From 1dd1c2d1abf95f307412c4e704ea7cf58e4fc046 Mon Sep 17 00:00:00 2001 From: alehane Date: Thu, 25 Apr 2019 13:19:06 +0100 Subject: [PATCH 01/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" goal. --- .../AbstractFromConfigurationMojo.java | 115 +++++++++++++++++- .../fromConfiguration/TestUnpackMojo.java | 90 +++++++++++++- 2 files changed, 202 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java index 377923c123..f0ccffb13a 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java @@ -26,6 +26,10 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; +import org.apache.maven.artifact.versioning.ComparableVersion; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -40,6 +44,10 @@ import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate; import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver; import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolverException; +import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResult; +import org.apache.maven.shared.transfer.dependencies.DefaultDependableCoordinate; +import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolver; +import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolverException; import org.apache.maven.shared.transfer.repository.RepositoryManager; import org.codehaus.plexus.util.StringUtils; @@ -106,6 +114,9 @@ public abstract class AbstractFromConfigurationMojo @Component private ArtifactResolver artifactResolver; + @Component + private DependencyResolver dependencyResolver; + @Component private RepositoryManager repositoryManager; @@ -116,7 +127,7 @@ public abstract class AbstractFromConfigurationMojo /** * artifactItems is filled by either field injection or by setArtifact(). - * + * * @throws MojoFailureException in case of an error. */ protected void verifyRequirements() @@ -156,6 +167,8 @@ protected List getProcessedArtifactItems( ProcessArtifactItemsRequ { this.getLog().info( "Configured Artifact: " + artifactItem.toString() ); + resolveArtifactRanges( artifactItem ); + if ( artifactItem.getOutputDirectory() == null ) { artifactItem.setOutputDirectory( this.outputDirectory ); @@ -189,6 +202,106 @@ protected List getProcessedArtifactItems( ProcessArtifactItemsRequ return artifactItems; } + /** + * If the artifact item has a version range, rather than a version, this + * method attempts to resolve this range by inspecting the list of resolved dependencies + * in the project for a match, before using the maven dependency resolver to resolve + * the range. + * + * If the dependency can be found and the version fits the artifact item's range + * then the artifact item is updated with the found version. + * + * If the dependency is not found or the range does not match, then the version + * is not changed. + * + * @param artifactItem The artifact item to update, if required. + * + * @throws MojoExecutionException if + */ + private void resolveArtifactRanges( final ArtifactItem artifactItem ) + { + VersionRange range; + try + { + range = VersionRange.createFromVersionSpec( artifactItem.getVersion() ); + } + catch ( InvalidVersionSpecificationException ivse ) + { + this.getLog().warn( "Found invalid version range on artifact: " + artifactItem ); + range = null; + } + + if ( range != null && range.hasRestrictions() ) + { + // First, try and find the artifact in the projects list of already, resolved + // dependencies: + ComparableVersion foundVersion = null; + + for ( Artifact a : getProject().getDependencyArtifacts() ) + { + if ( artifactItem.getArtifactId().equals( a.getArtifactId() ) + && artifactItem.getGroupId().equals( a.getGroupId() ) + && range.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) ) + { + + ComparableVersion v = new ComparableVersion( a.getVersion() ); + if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) + { + foundVersion = v; + } + } + } + + if ( foundVersion == null ) + { + // If we've not found the artifact in the resolved list of project dependencies, + // then attempt to use the dependency resolver to resolve the version range: + + ProjectBuildingRequest request = newResolveArtifactProjectBuildingRequest(); + + DefaultDependableCoordinate searchDep = new DefaultDependableCoordinate(); + searchDep.setGroupId( artifactItem.getGroupId() ); + searchDep.setArtifactId( artifactItem.getArtifactId() ); + searchDep.setVersion( artifactItem.getVersion() ); + searchDep.setType( artifactItem.getType() ); + searchDep.setClassifier( artifactItem.getClassifier() ); + + Iterable result; + try + { + result = dependencyResolver.resolveDependencies( request, searchDep, null ); + } + catch ( DependencyResolverException are ) + { + result = null; + // Do something else! + } + + if ( result != null ) + { + for ( ArtifactResult artifact : result ) + { + + this.getLog().info( "Resolved version from: " + artifactItem.getVersion() + ", to: " + + artifact.getArtifact().getVersion() ); + + ComparableVersion v = new ComparableVersion( artifact.getArtifact().getVersion() ); + if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) + { + foundVersion = v; + } + } + } + } + + if ( foundVersion != null ) + { + this.getLog().info( "Resolved version from: " + range.toString() + ", to: " + foundVersion ); + artifactItem.setVersion( foundVersion.toString() ); + } + } + } + private boolean checkIfProcessingNeeded( ArtifactItem item ) throws MojoExecutionException, ArtifactFilterException { diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java index 5a27484992..81004193f0 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java @@ -1,6 +1,6 @@ package org.apache.maven.plugins.dependency.fromConfiguration; -/* +/* * 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 @@ -16,7 +16,7 @@ * "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. + * under the License. */ import java.io.File; @@ -24,10 +24,18 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; +import org.apache.maven.artifact.handler.ArtifactHandler; +import org.apache.maven.artifact.handler.DefaultArtifactHandler; +import org.apache.maven.artifact.handler.manager.DefaultArtifactHandlerManager; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; @@ -36,6 +44,7 @@ import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.apache.maven.project.MavenProject; +import org.junit.Ignore; import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; import org.sonatype.aether.util.DefaultRepositorySystemSession; @@ -44,6 +53,7 @@ public class TestUnpackMojo { UnpackMojo mojo; + DefaultArtifactHandlerManager artifactHandlerManager; public TestUnpackMojo() { @@ -80,8 +90,25 @@ protected void setUp() DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) session.getRepositorySession(); repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( stubFactory.getWorkingDir() ) ); + + artifactHandlerManager = new DefaultArtifactHandlerManager(); + + Map handlerMap = new HashMap<>(); + handlerMap.put("", new DefaultArtifactHandler("")); + handlerMap.put("jar", new DefaultArtifactHandler("jar")); + artifactHandlerManager.addHandlers(handlerMap); + } + + @Override + protected void tearDown() + { + super.tearDown(); + + artifactHandlerManager = null; + mojo = null; } + public ArtifactItem getSingleArtifactItem( boolean removeVersion ) throws MojoExecutionException { @@ -573,6 +600,41 @@ public void testUnpackOverWriteIfNewer() + ": should be different", marker.lastModified() != unpackedFile.lastModified() ); } +// @Ignore +// public void testVersionRangeFromResolvedFromDependencies() +// throws Exception +// { +// ArtifactItem item = new ArtifactItem(); +// +// item.setArtifactId( "artifactId" ); +// item.setClassifier( "" ); +// item.setGroupId( "groupId" ); +// item.setType( "jar" ); +// item.setVersion( "[0,)" ); +// +// List list = new ArrayList(); +// list.add( item ); +// mojo.setArtifactItems( list ); +// +// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, +// "jar", "classifier", false ); +// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", +// "classifier", false ); +// +// MavenProject project = mojo.getProject(); +// project.setDependencies( createArtifacts( getDependencyList( item ) ) ); +// project.setDependencyArtifacts( createArtifactSet( getDependencyList( item ) ) ); +// +//// project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); +// +// mojo.execute(); +// assertMarkerFile( true, item ); +// assertEquals( "2.1", item.getVersion() ); +// } + + + + private void displayFile( String description, File file ) { System.out.println( description + ' ' + DateFormatUtils.ISO_DATETIME_FORMAT.format( file.lastModified() ) + ' ' @@ -628,6 +690,30 @@ private List createArtifacts( List items ) return items; } + // respects the createUnpackableFile flag of the ArtifactStubFactory + private Set createArtifactSet( List items ) + throws IOException + { + + Set set = new HashSet<>(); + + for ( Dependency item : items ) + { + set.add( + new DefaultArtifact( + item.getGroupId(), + item.getArtifactId(), + item.getVersion(), + item.getScope(), + item.getType(), + item.getClassifier(), + artifactHandlerManager.getArtifactHandler(item.getType()) + ) + ); + } + return set; + } + private Artifact createArtifact( Artifact art ) throws IOException { From 155cd72e3459ec8d2d25abfbe27fb08ead02e90a Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Thu, 25 Apr 2019 15:05:56 +0100 Subject: [PATCH 02/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" --- .../AbstractFromConfigurationMojo.java | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java index f0ccffb13a..f839b17d12 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java @@ -237,17 +237,20 @@ private void resolveArtifactRanges( final ArtifactItem artifactItem ) // dependencies: ComparableVersion foundVersion = null; - for ( Artifact a : getProject().getDependencyArtifacts() ) + if ( getProject().getDependencyArtifacts() != null ) { - if ( artifactItem.getArtifactId().equals( a.getArtifactId() ) - && artifactItem.getGroupId().equals( a.getGroupId() ) - && range.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) ) + for ( Artifact a : getProject().getDependencyArtifacts() ) { - - ComparableVersion v = new ComparableVersion( a.getVersion() ); - if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) + if ( artifactItem.getArtifactId().equals( a.getArtifactId() ) + && artifactItem.getGroupId().equals( a.getGroupId() ) + && range.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) ) { - foundVersion = v; + + ComparableVersion v = new ComparableVersion( a.getVersion() ); + if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) + { + foundVersion = v; + } } } } @@ -274,17 +277,13 @@ private void resolveArtifactRanges( final ArtifactItem artifactItem ) catch ( DependencyResolverException are ) { result = null; - // Do something else! + this.getLog().warn( are ); } if ( result != null ) { for ( ArtifactResult artifact : result ) { - - this.getLog().info( "Resolved version from: " + artifactItem.getVersion() + ", to: " - + artifact.getArtifact().getVersion() ); - ComparableVersion v = new ComparableVersion( artifact.getArtifact().getVersion() ); if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) { From 27e4685905879599a8274a9eee29cdf9a64d15ba Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Thu, 25 Apr 2019 15:06:50 +0100 Subject: [PATCH 03/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" --- .../AbstractFromConfigurationMojo.java | 1059 ++++++++++------- 1 file changed, 628 insertions(+), 431 deletions(-) diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java index f839b17d12..741d9d9f05 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java @@ -20,538 +20,735 @@ */ import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang.time.DateFormatUtils; import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; -import org.apache.maven.artifact.versioning.ComparableVersion; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.handler.DefaultArtifactHandler; +import org.apache.maven.artifact.handler.manager.DefaultArtifactHandlerManager; import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.dependency.AbstractDependencyMojo; -import org.apache.maven.plugins.dependency.utils.DependencyUtil; -import org.apache.maven.plugins.dependency.utils.filters.ArtifactItemFilter; +import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; +import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; +import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuildingRequest; -import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; -import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate; -import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver; -import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolverException; -import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResult; -import org.apache.maven.shared.transfer.dependencies.DefaultDependableCoordinate; -import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolver; -import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolverException; -import org.apache.maven.shared.transfer.repository.RepositoryManager; -import org.codehaus.plexus.util.StringUtils; - -/** - * Abstract parent class used by mojos that get Artifact information from the plugin configuration as an ArrayList of - * ArtifactItems - * - * @author Brian Fox - * @see ArtifactItem - */ -public abstract class AbstractFromConfigurationMojo - extends AbstractDependencyMojo +import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; +import org.sonatype.aether.util.DefaultRepositorySystemSession; + +public class TestUnpackMojo + extends AbstractDependencyMojoTestCase { - /** - * Default output location used for mojo, unless overridden in ArtifactItem. - * - * @since 1.0 - */ - @Parameter( property = "outputDirectory", defaultValue = "${project.build.directory}/dependency" ) - private File outputDirectory; - - /** - * Overwrite release artifacts - * - * @since 1.0 - */ - @Parameter( property = "mdep.overWriteReleases", defaultValue = "false" ) - private boolean overWriteReleases; - - /** - * Overwrite snapshot artifacts - * - * @since 1.0 - */ - @Parameter( property = "mdep.overWriteSnapshots", defaultValue = "false" ) - private boolean overWriteSnapshots; - - /** - * Overwrite if newer - * - * @since 2.0 - */ - @Parameter( property = "mdep.overIfNewer", defaultValue = "true" ) - private boolean overWriteIfNewer; - - /** - * Collection of ArtifactItems to work on. (ArtifactItem contains groupId, artifactId, version, type, classifier, - * outputDirectory, destFileName, overWrite and encoding.) See Usage for details. - * - * @since 1.0 - */ - @Parameter - private List artifactItems; - - /** - * Path to override default local repository during plugin's execution. To remove all downloaded artifacts as part - * of the build, set this value to a location under your project's target directory - * - * @since 2.2 - */ - @Parameter - private File localRepositoryDirectory; - - @Component - private ArtifactResolver artifactResolver; - - @Component - private DependencyResolver dependencyResolver; - - @Component - private RepositoryManager repositoryManager; - - @Component - private ArtifactHandlerManager artifactHandlerManager; - - abstract ArtifactItemFilter getMarkedArtifactFilter( ArtifactItem item ); - - /** - * artifactItems is filled by either field injection or by setArtifact(). - * - * @throws MojoFailureException in case of an error. - */ - protected void verifyRequirements() - throws MojoFailureException - { - if ( artifactItems == null || artifactItems.isEmpty() ) - { - throw new MojoFailureException( "Either artifact or artifactItems is required " ); - } + + UnpackMojo mojo; + DefaultArtifactHandlerManager artifactHandlerManager; + + public TestUnpackMojo() + { + super(); } - /** - * Preprocesses the list of ArtifactItems. This method defaults the outputDirectory if not set and creates the - * output Directory if it doesn't exist. - * - * @param processArtifactItemsRequest preprocessing instructions - * @return An ArrayList of preprocessed ArtifactItems - * @throws MojoExecutionException with a message if an error occurs. - * @see ArtifactItem - */ - protected List getProcessedArtifactItems( ProcessArtifactItemsRequest processArtifactItemsRequest ) - throws MojoExecutionException + protected void setUp() + throws Exception { + super.setUp( "unpack", true, false ); - boolean removeVersion = processArtifactItemsRequest.isRemoveVersion(), - prependGroupId = processArtifactItemsRequest.isPrependGroupId(), - useBaseVersion = processArtifactItemsRequest.isUseBaseVersion(); + File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-test/plugin-config.xml" ); + mojo = (UnpackMojo) lookupMojo( "unpack", testPom ); + mojo.setOutputDirectory( new File( this.testDir, "outputDirectory" ) ); + mojo.setMarkersDirectory( new File( this.testDir, "markers" ) ); + mojo.setSilent( true ); - boolean removeClassifier = processArtifactItemsRequest.isRemoveClassifier(); + assertNotNull( mojo ); + assertNotNull( mojo.getProject() ); + // MavenProject project = mojo.getProject(); + // init classifier things + // it needs to get the archivermanager + stubFactory.setUnpackableFile( mojo.getArchiverManager() ); + // i'm using one file repeatedly to archive so I can test the name + // programmatically. + stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar + + "target/test-classes/unit/unpack-dependencies-test/test.txt" ) ); - if ( artifactItems == null || artifactItems.size() < 1 ) - { - throw new MojoExecutionException( "There are no artifactItems configured." ); - } + mojo.setUseJvmChmod( true ); - for ( ArtifactItem artifactItem : artifactItems ) - { - this.getLog().info( "Configured Artifact: " + artifactItem.toString() ); + MavenSession session = newMavenSession( mojo.getProject() ); + setVariableValueToObject( mojo, "session", session ); - resolveArtifactRanges( artifactItem ); + DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) session.getRepositorySession(); - if ( artifactItem.getOutputDirectory() == null ) - { - artifactItem.setOutputDirectory( this.outputDirectory ); - } - artifactItem.getOutputDirectory().mkdirs(); + repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( stubFactory.getWorkingDir() ) ); - // make sure we have a version. - if ( StringUtils.isEmpty( artifactItem.getVersion() ) ) - { - fillMissingArtifactVersion( artifactItem ); - } + artifactHandlerManager = new DefaultArtifactHandlerManager(); - artifactItem.setArtifact( this.getArtifact( artifactItem ) ); + Map handlerMap = new HashMap<>(); + handlerMap.put("", new DefaultArtifactHandler("")); + handlerMap.put("jar", new DefaultArtifactHandler("jar")); + artifactHandlerManager.addHandlers(handlerMap); + } - if ( StringUtils.isEmpty( artifactItem.getDestFileName() ) ) - { - artifactItem.setDestFileName( DependencyUtil.getFormattedFileName( artifactItem.getArtifact(), - removeVersion, prependGroupId, - useBaseVersion, removeClassifier ) ); - } + @Override + protected void tearDown() + { + super.tearDown(); - try - { - artifactItem.setNeedsProcessing( checkIfProcessingNeeded( artifactItem ) ); - } - catch ( ArtifactFilterException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); - } + artifactHandlerManager = null; + mojo = null; + } + + + public ArtifactItem getSingleArtifactItem( boolean removeVersion ) + throws MojoExecutionException + { + List list = mojo.getProcessedArtifactItems( removeVersion ); + return list.get( 0 ); + } + + public void testGetArtifactItems() + throws Exception + { + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "1.0", null, null ); + + ArrayList list = new ArrayList( 1 ); + list.add( createArtifact( item ) ); + + mojo.setArtifactItems( list ); + + ArtifactItem result = getSingleArtifactItem( false ); + assertEquals( mojo.getOutputDirectory(), result.getOutputDirectory() ); + + File output = new File( mojo.getOutputDirectory(), "override" ); + item.setOutputDirectory( output ); + result = getSingleArtifactItem( false ); + assertEquals( output, result.getOutputDirectory() ); + } + + public void assertMarkerFiles( Collection items, boolean exist ) + { + for ( ArtifactItem item : items ) + { + assertMarkerFile( exist, item ); } - return artifactItems; - } - - /** - * If the artifact item has a version range, rather than a version, this - * method attempts to resolve this range by inspecting the list of resolved dependencies - * in the project for a match, before using the maven dependency resolver to resolve - * the range. - * - * If the dependency can be found and the version fits the artifact item's range - * then the artifact item is updated with the found version. - * - * If the dependency is not found or the range does not match, then the version - * is not changed. - * - * @param artifactItem The artifact item to update, if required. - * - * @throws MojoExecutionException if - */ - private void resolveArtifactRanges( final ArtifactItem artifactItem ) - { - VersionRange range; + } + + public void assertMarkerFile( boolean val, ArtifactItem item ) + { + UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler( item, mojo.getMarkersDirectory() ); try { - range = VersionRange.createFromVersionSpec( artifactItem.getVersion() ); + assertEquals( val, handle.isMarkerSet() ); } - catch ( InvalidVersionSpecificationException ivse ) + catch ( MojoExecutionException e ) { - this.getLog().warn( "Found invalid version range on artifact: " + artifactItem ); - range = null; + fail( e.getLongMessage() ); } + } - if ( range != null && range.hasRestrictions() ) - { - // First, try and find the artifact in the projects list of already, resolved - // dependencies: - ComparableVersion foundVersion = null; + public void testUnpackFile() + throws Exception + { + List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - if ( getProject().getDependencyArtifacts() != null ) - { - for ( Artifact a : getProject().getDependencyArtifacts() ) - { - if ( artifactItem.getArtifactId().equals( a.getArtifactId() ) - && artifactItem.getGroupId().equals( a.getGroupId() ) - && range.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) ) - { - - ComparableVersion v = new ComparableVersion( a.getVersion() ); - if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) - { - foundVersion = v; - } - } - } - } + mojo.setArtifactItems( list ); - if ( foundVersion == null ) - { - // If we've not found the artifact in the resolved list of project dependencies, - // then attempt to use the dependency resolver to resolve the version range: - - ProjectBuildingRequest request = newResolveArtifactProjectBuildingRequest(); - - DefaultDependableCoordinate searchDep = new DefaultDependableCoordinate(); - searchDep.setGroupId( artifactItem.getGroupId() ); - searchDep.setArtifactId( artifactItem.getArtifactId() ); - searchDep.setVersion( artifactItem.getVersion() ); - searchDep.setType( artifactItem.getType() ); - searchDep.setClassifier( artifactItem.getClassifier() ); - - Iterable result; - try - { - result = dependencyResolver.resolveDependencies( request, searchDep, null ); - } - catch ( DependencyResolverException are ) - { - result = null; - this.getLog().warn( are ); - } - - if ( result != null ) - { - for ( ArtifactResult artifact : result ) - { - ComparableVersion v = new ComparableVersion( artifact.getArtifact().getVersion() ); - if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) - { - foundVersion = v; - } - } - } - } + mojo.execute(); - if ( foundVersion != null ) - { - this.getLog().info( "Resolved version from: " + range.toString() + ", to: " + foundVersion ); - artifactItem.setVersion( foundVersion.toString() ); - } - } + assertMarkerFiles( list, true ); } - private boolean checkIfProcessingNeeded( ArtifactItem item ) - throws MojoExecutionException, ArtifactFilterException + public void testSkip() + throws Exception { - return StringUtils.equalsIgnoreCase( item.getOverWrite(), "true" ) - || getMarkedArtifactFilter( item ).isArtifactIncluded( item ); + List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + + mojo.setSkip( true ); + mojo.setArtifactItems( list ); + + mojo.execute(); + + assertMarkerFiles( list, false ); } - /** - * Resolves the Artifact from the remote repository if necessary. If no version is specified, it will be retrieved - * from the dependency list or from the DependencyManagement section of the pom. - * - * @param artifactItem containing information about artifact from plugin configuration. - * @return Artifact object representing the specified file. - * @throws MojoExecutionException with a message if the version can't be found in DependencyManagement. - */ - protected Artifact getArtifact( ArtifactItem artifactItem ) - throws MojoExecutionException + public void testUnpackToLocation() + throws Exception { - Artifact artifact; + List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + ArtifactItem item = list.get( 0 ); + item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); - try + mojo.setArtifactItems( list ); + + mojo.execute(); + + assertMarkerFiles( list, true ); + } + + public void testUnpackToLocationWhereLocationCannotBeCreatedThrowsException() + throws Exception + { + List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); + ArtifactItem item = list.get( 0 ); + item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); + + mojo.setArtifactItems( list ); + final File currentFile = mojo.getOutputDirectory(); + + // pretend that the output directory cannot be found event after mkdirs has been called by the mojo + // ifor instance in the case when the outputDirectory cannot be created because of permissions on the + // parent of the output directory + mojo.setOutputDirectory( new File( currentFile.getAbsolutePath() ) { - // mdep-50 - rolledback for now because it's breaking some functionality. - /* - * List listeners = new ArrayList(); Set theSet = new HashSet(); theSet.add( artifact ); - * ArtifactResolutionResult artifactResolutionResult = artifactCollector.collect( theSet, project - * .getArtifact(), managedVersions, this.local, project.getRemoteArtifactRepositories(), - * artifactMetadataSource, null, listeners ); Iterator iter = - * artifactResolutionResult.getArtifactResolutionNodes().iterator(); while ( iter.hasNext() ) { - * ResolutionNode node = (ResolutionNode) iter.next(); artifact = node.getArtifact(); } - */ - - ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); - - if ( localRepositoryDirectory != null ) - { - buildingRequest = - repositoryManager.setLocalRepositoryBasedir( buildingRequest, localRepositoryDirectory ); - } - // Map dependency to artifact coordinate - DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); - coordinate.setGroupId( artifactItem.getGroupId() ); - coordinate.setArtifactId( artifactItem.getArtifactId() ); - coordinate.setVersion( artifactItem.getVersion() ); - coordinate.setClassifier( artifactItem.getClassifier() ); + private static final long serialVersionUID = -8559876942040177020L; - final String extension; - ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler( artifactItem.getType() ); - if ( artifactHandler != null ) - { - extension = artifactHandler.getExtension(); - } - else + @Override + public boolean exists() { - extension = artifactItem.getType(); + // this file will always report that it does not exist + return false; } - coordinate.setExtension( extension ); + } ); + try + { + mojo.execute(); + fail( "Expected Exception Here." ); + } + catch ( MojoExecutionException e ) + { + // caught the expected exception. + } + } - artifact = artifactResolver.resolveArtifact( buildingRequest, coordinate ).getArtifact(); + public void testMissingVersionNotFound() + throws Exception + { + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "type"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + try + { + mojo.execute(); + fail( "Expected Exception Here." ); } - catch ( ArtifactResolverException e ) + catch ( MojoExecutionException e ) { - throw new MojoExecutionException( "Unable to find/resolve artifact.", e ); + // caught the expected exception. } + } - return artifact; + public List getDependencyList( ArtifactItem item ) + { + Dependency dep = new Dependency(); + dep.setArtifactId( item.getArtifactId() ); + dep.setClassifier( item.getClassifier() ); + dep.setGroupId( item.getGroupId() ); + dep.setType( item.getType() ); + dep.setVersion( "2.0-SNAPSHOT" ); + + Dependency dep2 = new Dependency(); + dep2.setArtifactId( item.getArtifactId() ); + dep2.setClassifier( "classifier" ); + dep2.setGroupId( item.getGroupId() ); + dep2.setType( item.getType() ); + dep2.setVersion( "2.1" ); + + List list = new ArrayList( 2 ); + list.add( dep2 ); + list.add( dep ); + + return list; } - /** - * Tries to find missing version from dependency list and dependency management. If found, the artifact is updated - * with the correct version. It will first look for an exact match on artifactId/groupId/classifier/type and if it - * doesn't find a match, it will try again looking for artifactId and groupId only. - * - * @param artifact representing configured file. - * @throws MojoExecutionException - */ - private void fillMissingArtifactVersion( ArtifactItem artifact ) - throws MojoExecutionException + public void testMissingVersionFromDependencies() + throws Exception { - MavenProject project = getProject(); - List deps = project.getDependencies(); - List depMngt = project.getDependencyManagement() == null ? Collections.emptyList() - : project.getDependencyManagement().getDependencies(); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "jar"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.0-SNAPSHOT", item.getVersion() ); + } + + public void testMissingVersionFromDependenciesWithClassifier() + throws Exception + { + + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "classifier", "war"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.1", item.getVersion() ); + } + + public List getDependencyMgtList( ArtifactItem item ) + { + Dependency dep = new Dependency(); + dep.setArtifactId( item.getArtifactId() ); + dep.setClassifier( item.getClassifier() ); + dep.setGroupId( item.getGroupId() ); + dep.setType( item.getType() ); + dep.setVersion( "3.0-SNAPSHOT" ); + + Dependency dep2 = new Dependency(); + dep2.setArtifactId( item.getArtifactId() ); + dep2.setClassifier( "classifier" ); + dep2.setGroupId( item.getGroupId() ); + dep2.setType( item.getType() ); + dep2.setVersion( "3.1" ); + + List list = new ArrayList( 2 ); + list.add( dep2 ); + list.add( dep ); + + return list; + } + + public void testMissingVersionFromDependencyMgt() + throws Exception + { + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "jar"); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - if ( !findDependencyVersion( artifact, deps, false ) - && ( project.getDependencyManagement() == null || !findDependencyVersion( artifact, depMngt, false ) ) - && !findDependencyVersion( artifact, deps, true ) - && ( project.getDependencyManagement() == null || !findDependencyVersion( artifact, depMngt, true ) ) ) + item = createArtifactItem( "groupId", "artifactId-2", null, "", "jar"); + + List list = new ArrayList(); + list.add( item ); + + mojo.setArtifactItems( list ); + + project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "3.0-SNAPSHOT", item.getVersion() ); + } + + public void testMissingVersionFromDependencyMgtWithClassifier() + throws Exception + { + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "classifier", "jar"); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + + item = createArtifactItem( "groupId", "artifactId-2", null, "classifier", "jar"); + + stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.0-SNAPSHOT" ), null, + "jar", "classifier", false ); + stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.1" ), null, "jar", + "classifier", false ); + + List list = new ArrayList(); + list.add( item ); + + mojo.setArtifactItems( list ); + + project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); + + mojo.execute(); + + assertMarkerFile( true, item ); + assertEquals( "3.1", item.getVersion() ); + } + + public void testArtifactNotFound() + throws Exception + { + dotestArtifactExceptions( false, true ); + } + + public void testArtifactResolutionException() + throws Exception + { + dotestArtifactExceptions( true, false ); + } + + public void dotestArtifactExceptions( boolean are, boolean anfe ) + throws Exception + { + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "1.0", "", "type" ); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + try + { + mojo.execute(); + fail( "ExpectedException" ); + } + catch ( MojoExecutionException e ) { - throw new MojoExecutionException( "Unable to find artifact version of " + artifact.getGroupId() + ":" - + artifact.getArtifactId() + " in either dependency list or in project's dependency management." ); + assertEquals( "Unable to find/resolve artifact.", e.getMessage() ); } } - /** - * Tries to find missing version from a list of dependencies. If found, the artifact is updated with the correct - * version. - * - * @param artifact representing configured file. - * @param dependencies list of dependencies to search. - * @param looseMatch only look at artifactId and groupId - * @return the found dependency - */ - private boolean findDependencyVersion( ArtifactItem artifact, List dependencies, boolean looseMatch ) + public void testNoArtifactItems() { - for ( Dependency dependency : dependencies ) + try { - if ( StringUtils.equals( dependency.getArtifactId(), artifact.getArtifactId() ) - && StringUtils.equals( dependency.getGroupId(), artifact.getGroupId() ) - && ( looseMatch || StringUtils.equals( dependency.getClassifier(), artifact.getClassifier() ) ) - && ( looseMatch || StringUtils.equals( dependency.getType(), artifact.getType() ) ) ) - { - artifact.setVersion( dependency.getVersion() ); - - return true; - } + mojo.getProcessedArtifactItems( false ); + fail( "Expected Exception" ); + } + catch ( MojoExecutionException e ) + { + assertEquals( "There are no artifactItems configured.", e.getMessage() ); } - return false; } - /** - * @return Returns the artifactItems. - */ - public List getArtifactItems() + public void testUnpackDontOverWriteReleases() + throws Exception { - return this.artifactItems; + stubFactory.setCreateFiles( true ); + Artifact release = stubFactory.getReleaseArtifact(); + assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + + ArtifactItem item = new ArtifactItem( createArtifact( release ) ); + + List list = new ArrayList( 1 ); + list.add( item ); + mojo.setArtifactItems( list ); + + mojo.setOverWriteIfNewer( false ); + + mojo.execute(); + + assertUnpacked( item, false ); } - /** - * @param theArtifactItems The artifactItems to set. - */ - public void setArtifactItems( List theArtifactItems ) + public void testUnpackDontOverWriteSnapshots() + throws Exception { - this.artifactItems = theArtifactItems; + stubFactory.setCreateFiles( true ); + Artifact artifact = stubFactory.getSnapshotArtifact(); + assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + + ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); + + List list = new ArrayList( 1 ); + list.add( item ); + mojo.setArtifactItems( list ); + + mojo.setOverWriteIfNewer( false ); + + mojo.execute(); + + assertUnpacked( item, false ); } - /** - * @return Returns the outputDirectory. - */ - public File getOutputDirectory() + public void testUnpackOverWriteReleases() + throws Exception { - return this.outputDirectory; + stubFactory.setCreateFiles( true ); + Artifact release = stubFactory.getReleaseArtifact(); + assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + + ArtifactItem item = new ArtifactItem( createArtifact( release ) ); + + List list = new ArrayList( 1 ); + list.add( item ); + mojo.setArtifactItems( list ); + + mojo.setOverWriteIfNewer( false ); + mojo.setOverWriteReleases( true ); + mojo.execute(); + + assertUnpacked( item, true ); } - /** - * @param theOutputDirectory The outputDirectory to set. - */ - public void setOutputDirectory( File theOutputDirectory ) + public void testUnpackOverWriteSnapshot() + throws Exception { - this.outputDirectory = theOutputDirectory; + stubFactory.setCreateFiles( true ); + Artifact artifact = stubFactory.getSnapshotArtifact(); + assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); + + ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); + + List list = new ArrayList( 1 ); + list.add( item ); + mojo.setArtifactItems( list ); + + mojo.setOverWriteIfNewer( false ); + mojo.setOverWriteReleases( false ); + mojo.setOverWriteSnapshots( true ); + mojo.execute(); + + assertUnpacked( item, true ); } - /** - * @return Returns the overWriteIfNewer. - */ - public boolean isOverWriteIfNewer() + public void testUnpackOverWriteIfNewer() + throws Exception { - return this.overWriteIfNewer; + final long now = System.currentTimeMillis(); + + mojo.setSilent( false ); + stubFactory.setCreateFiles( true ); + Artifact artifact = stubFactory.getSnapshotArtifact(); + assertTrue( artifact.getFile().setLastModified( now - 20000 ) ); + + ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); + + List list = Collections.singletonList( item ); + mojo.setArtifactItems( list ); + mojo.setOverWriteIfNewer( true ); + mojo.execute(); + File unpackedFile = getUnpackedFile( item ); + + // round down to the last second + long time = now; + time = time - ( time % 1000 ); + // go back 10 more seconds for linux + time -= 10000; + // set to known value + assertTrue( unpackedFile.setLastModified( time ) ); + // set source to be newer was 4s but test is brittle on MacOS if less than 5s + assertTrue( artifact.getFile().setLastModified( time + 5000 ) ); + + // manually set markerfile (must match getMarkerFile in DefaultMarkerFileHandler) + File marker = new File( mojo.getMarkersDirectory(), artifact.getId().replace( ':', '-' ) + ".marker" ); + assertTrue( marker.setLastModified( time ) ); + + displayFile( "unpackedFile", unpackedFile ); + displayFile( "artifact ", artifact.getFile() ); + displayFile( "marker ", marker ); + System.out.println( "mojo.execute()" ); + mojo.execute(); + displayFile( "unpackedFile", unpackedFile ); + displayFile( "artifact ", artifact.getFile() ); + displayFile( "marker ", marker ); + System.out.println( "marker.lastModified() = " + marker.lastModified() ); + System.out.println( "unpackedFile.lastModified() = " + unpackedFile.lastModified() ); + assertTrue( "unpackedFile '" + unpackedFile + "' lastModified() == " + marker.lastModified() + + ": should be different", marker.lastModified() != unpackedFile.lastModified() ); } - /** - * @param theOverWriteIfNewer The overWriteIfNewer to set. - */ - public void setOverWriteIfNewer( boolean theOverWriteIfNewer ) + public void testVersionRangeFromResolvedProjectDependencies() + throws Exception { - this.overWriteIfNewer = theOverWriteIfNewer; + stubFactory.setCreateFiles( true ); + + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, + "jar", "", false ); + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", + "", false ); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + project.setDependencyArtifacts( createArtifactSet( getDependencyList( item ) ) ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.1", item.getVersion() ); } - /** - * @return Returns the overWriteReleases. - */ - public boolean isOverWriteReleases() + public void testVersionRangeFromResolvedProjectDependenciesWithMultipleDependencies() + throws Exception { - return this.overWriteReleases; + stubFactory.setCreateFiles( true ); + + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, + "jar", "", false ); + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", + "", false ); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + + Set dependencySet = createArtifactSet( getDependencyList( item ) ); + dependencySet.addAll( createArtifactSet( getDependencyList( createArtifactItem( "groupId", "differentArtifactId", "1.0", "", "jar") ) ) ); + dependencySet.addAll( createArtifactSet( getDependencyList( createArtifactItem( "differentGroupId", "artifactId", "1.0", "", "jar") ) ) ); + + project.setDependencyArtifacts( dependencySet ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.1", item.getVersion() ); } - /** - * @param theOverWriteReleases The overWriteReleases to set. - */ - public void setOverWriteReleases( boolean theOverWriteReleases ) +// +// public void testVersionRangeNoResolvedProjectDependencies() +// throws Exception +// { +// stubFactory.setCreateFiles( true ); +// +// ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); +// +// List list = new ArrayList(); +// list.add( item ); +// mojo.setArtifactItems( list ); +// +// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, +// "jar", "", false ); +// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", +// "", false ); +// +// mojo.execute(); +// assertMarkerFile( true, item ); +// assertEquals( "2.1", item.getVersion() ); +// } + + + private void displayFile( String description, File file ) { - this.overWriteReleases = theOverWriteReleases; + System.out.println( description + ' ' + DateFormatUtils.ISO_DATETIME_FORMAT.format( file.lastModified() ) + ' ' + + file.getPath().substring( getBasedir().length() ) ); } - /** - * @return Returns the overWriteSnapshots. - */ - public boolean isOverWriteSnapshots() + public void assertUnpacked( ArtifactItem item, boolean overWrite ) + throws Exception { - return this.overWriteSnapshots; + + File unpackedFile = getUnpackedFile( item ); + + Thread.sleep( 100 ); + // round down to the last second + long time = System.currentTimeMillis(); + time = time - ( time % 1000 ); + assertTrue( unpackedFile.setLastModified( time ) ); + + assertEquals( time, unpackedFile.lastModified() ); + mojo.execute(); + + if ( overWrite ) + { + assertTrue( time != unpackedFile.lastModified() ); + } + else + { + assertEquals( time, unpackedFile.lastModified() ); + } } - /** - * @param theOverWriteSnapshots The overWriteSnapshots to set. - */ - public void setOverWriteSnapshots( boolean theOverWriteSnapshots ) + public File getUnpackedFile( ArtifactItem item ) { - this.overWriteSnapshots = theOverWriteSnapshots; + File unpackedFile = new File( item.getOutputDirectory(), + DependencyArtifactStubFactory.getUnpackableFileName( item.getArtifact() ) ); + + assertTrue( unpackedFile.exists() ); + return unpackedFile; + } - /** - * @param localRepositoryDirectory {@link #localRepositoryDirectory} - */ - public void setLocalRepositoryDirectory( File localRepositoryDirectory ) + private ArtifactItem createArtifactItem( + final String groupId, + final String artifactId, + final String version, + final String classifier, + final String type ) { - this.localRepositoryDirectory = localRepositoryDirectory; + + ArtifactItem item = new ArtifactItem(); + + item.setArtifactId( artifactId ); + item.setClassifier( classifier ); + item.setGroupId( groupId ); + + if ( type != null ) { + item.setType( type ); + } + item.setVersion( version ); + + return item; } - /** - * @param artifact The artifact. - * @throws MojoFailureException in case of an error. - */ - public void setArtifact( String artifact ) - throws MojoFailureException + // respects the createUnpackableFile flag of the ArtifactStubFactory + private List createArtifacts( List items ) + throws IOException { - if ( artifact != null ) + for ( Dependency item : items ) { - String packaging = "jar"; - String classifier; - String[] tokens = StringUtils.split( artifact, ":" ); - if ( tokens.length < 3 || tokens.length > 5 ) - { - throw new MojoFailureException( "Invalid artifact, " - + "you must specify groupId:artifactId:version[:packaging[:classifier]] " + artifact ); - } - String groupId = tokens[0]; - String artifactId = tokens[1]; - String version = tokens[2]; - if ( tokens.length >= 4 ) - { - packaging = tokens[3]; - } - if ( tokens.length == 5 ) - { - classifier = tokens[4]; - } - else - { - classifier = null; - } + String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); + stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), + VersionRange.createFromVersion( item.getVersion() ), null, item.getType(), + classifier, item.isOptional() ); + } + return items; + } - ArtifactItem artifactItem = new ArtifactItem(); - artifactItem.setGroupId( groupId ); - artifactItem.setArtifactId( artifactId ); - artifactItem.setVersion( version ); - artifactItem.setType( packaging ); - artifactItem.setClassifier( classifier ); + // respects the createUnpackableFile flag of the ArtifactStubFactory + private Set createArtifactSet( List items ) + throws IOException + { + + Set set = new HashSet<>(); - setArtifactItems( Collections.singletonList( artifactItem ) ); + for ( Dependency item : items ) + { + set.add( + new DefaultArtifact( + item.getGroupId(), + item.getArtifactId(), + item.getVersion(), + item.getScope(), + item.getType(), + item.getClassifier(), + artifactHandlerManager.getArtifactHandler(item.getType()) + ) + ); } + return set; + } + + private Artifact createArtifact( Artifact art ) + throws IOException + { + String classifier = "".equals( art.getClassifier() ) ? null : art.getClassifier(); + stubFactory.createArtifact( art.getGroupId(), art.getArtifactId(), + VersionRange.createFromVersion( art.getVersion() ), null, art.getType(), classifier, + art.isOptional() ); + return art; + } + + private ArtifactItem createArtifact( ArtifactItem item ) + throws IOException + { + String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); + stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), item.getVersion(), null, item.getType(), + classifier ); + return item; } } From c84ff87a6c730d70d619df88e9feceefc1ce048f Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Thu, 25 Apr 2019 15:17:32 +0100 Subject: [PATCH 04/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" --- .../AbstractFromConfigurationMojo.java | 1059 +++++++---------- 1 file changed, 431 insertions(+), 628 deletions(-) diff --git a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java index 741d9d9f05..f839b17d12 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/AbstractFromConfigurationMojo.java @@ -20,735 +20,538 @@ */ import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.commons.lang.time.DateFormatUtils; import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.artifact.handler.DefaultArtifactHandler; -import org.apache.maven.artifact.handler.manager.DefaultArtifactHandlerManager; +import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; +import org.apache.maven.artifact.versioning.ComparableVersion; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; -import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; -import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.dependency.AbstractDependencyMojo; +import org.apache.maven.plugins.dependency.utils.DependencyUtil; +import org.apache.maven.plugins.dependency.utils.filters.ArtifactItemFilter; import org.apache.maven.project.MavenProject; -import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; -import org.sonatype.aether.util.DefaultRepositorySystemSession; - -public class TestUnpackMojo - extends AbstractDependencyMojoTestCase +import org.apache.maven.project.ProjectBuildingRequest; +import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; +import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate; +import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver; +import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolverException; +import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResult; +import org.apache.maven.shared.transfer.dependencies.DefaultDependableCoordinate; +import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolver; +import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolverException; +import org.apache.maven.shared.transfer.repository.RepositoryManager; +import org.codehaus.plexus.util.StringUtils; + +/** + * Abstract parent class used by mojos that get Artifact information from the plugin configuration as an ArrayList of + * ArtifactItems + * + * @author Brian Fox + * @see ArtifactItem + */ +public abstract class AbstractFromConfigurationMojo + extends AbstractDependencyMojo { - - UnpackMojo mojo; - DefaultArtifactHandlerManager artifactHandlerManager; - - public TestUnpackMojo() - { - super(); - } - - protected void setUp() - throws Exception - { - super.setUp( "unpack", true, false ); - - File testPom = new File( getBasedir(), "target/test-classes/unit/unpack-test/plugin-config.xml" ); - mojo = (UnpackMojo) lookupMojo( "unpack", testPom ); - mojo.setOutputDirectory( new File( this.testDir, "outputDirectory" ) ); - mojo.setMarkersDirectory( new File( this.testDir, "markers" ) ); - mojo.setSilent( true ); - - assertNotNull( mojo ); - assertNotNull( mojo.getProject() ); - // MavenProject project = mojo.getProject(); - // init classifier things - // it needs to get the archivermanager - stubFactory.setUnpackableFile( mojo.getArchiverManager() ); - // i'm using one file repeatedly to archive so I can test the name - // programmatically. - stubFactory.setSrcFile( new File( getBasedir() + File.separatorChar - + "target/test-classes/unit/unpack-dependencies-test/test.txt" ) ); - - mojo.setUseJvmChmod( true ); - - MavenSession session = newMavenSession( mojo.getProject() ); - setVariableValueToObject( mojo, "session", session ); - - DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) session.getRepositorySession(); - - repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( stubFactory.getWorkingDir() ) ); - - artifactHandlerManager = new DefaultArtifactHandlerManager(); - - Map handlerMap = new HashMap<>(); - handlerMap.put("", new DefaultArtifactHandler("")); - handlerMap.put("jar", new DefaultArtifactHandler("jar")); - artifactHandlerManager.addHandlers(handlerMap); - } - - @Override - protected void tearDown() - { - super.tearDown(); - - artifactHandlerManager = null; - mojo = null; + /** + * Default output location used for mojo, unless overridden in ArtifactItem. + * + * @since 1.0 + */ + @Parameter( property = "outputDirectory", defaultValue = "${project.build.directory}/dependency" ) + private File outputDirectory; + + /** + * Overwrite release artifacts + * + * @since 1.0 + */ + @Parameter( property = "mdep.overWriteReleases", defaultValue = "false" ) + private boolean overWriteReleases; + + /** + * Overwrite snapshot artifacts + * + * @since 1.0 + */ + @Parameter( property = "mdep.overWriteSnapshots", defaultValue = "false" ) + private boolean overWriteSnapshots; + + /** + * Overwrite if newer + * + * @since 2.0 + */ + @Parameter( property = "mdep.overIfNewer", defaultValue = "true" ) + private boolean overWriteIfNewer; + + /** + * Collection of ArtifactItems to work on. (ArtifactItem contains groupId, artifactId, version, type, classifier, + * outputDirectory, destFileName, overWrite and encoding.) See Usage for details. + * + * @since 1.0 + */ + @Parameter + private List artifactItems; + + /** + * Path to override default local repository during plugin's execution. To remove all downloaded artifacts as part + * of the build, set this value to a location under your project's target directory + * + * @since 2.2 + */ + @Parameter + private File localRepositoryDirectory; + + @Component + private ArtifactResolver artifactResolver; + + @Component + private DependencyResolver dependencyResolver; + + @Component + private RepositoryManager repositoryManager; + + @Component + private ArtifactHandlerManager artifactHandlerManager; + + abstract ArtifactItemFilter getMarkedArtifactFilter( ArtifactItem item ); + + /** + * artifactItems is filled by either field injection or by setArtifact(). + * + * @throws MojoFailureException in case of an error. + */ + protected void verifyRequirements() + throws MojoFailureException + { + if ( artifactItems == null || artifactItems.isEmpty() ) + { + throw new MojoFailureException( "Either artifact or artifactItems is required " ); + } } - - public ArtifactItem getSingleArtifactItem( boolean removeVersion ) + /** + * Preprocesses the list of ArtifactItems. This method defaults the outputDirectory if not set and creates the + * output Directory if it doesn't exist. + * + * @param processArtifactItemsRequest preprocessing instructions + * @return An ArrayList of preprocessed ArtifactItems + * @throws MojoExecutionException with a message if an error occurs. + * @see ArtifactItem + */ + protected List getProcessedArtifactItems( ProcessArtifactItemsRequest processArtifactItemsRequest ) throws MojoExecutionException { - List list = mojo.getProcessedArtifactItems( removeVersion ); - return list.get( 0 ); - } - - public void testGetArtifactItems() - throws Exception - { - ArtifactItem item = createArtifactItem( "groupId", "artifactId", "1.0", null, null ); - ArrayList list = new ArrayList( 1 ); - list.add( createArtifact( item ) ); + boolean removeVersion = processArtifactItemsRequest.isRemoveVersion(), + prependGroupId = processArtifactItemsRequest.isPrependGroupId(), + useBaseVersion = processArtifactItemsRequest.isUseBaseVersion(); - mojo.setArtifactItems( list ); + boolean removeClassifier = processArtifactItemsRequest.isRemoveClassifier(); - ArtifactItem result = getSingleArtifactItem( false ); - assertEquals( mojo.getOutputDirectory(), result.getOutputDirectory() ); - - File output = new File( mojo.getOutputDirectory(), "override" ); - item.setOutputDirectory( output ); - result = getSingleArtifactItem( false ); - assertEquals( output, result.getOutputDirectory() ); - } - - public void assertMarkerFiles( Collection items, boolean exist ) - { - for ( ArtifactItem item : items ) + if ( artifactItems == null || artifactItems.size() < 1 ) { - assertMarkerFile( exist, item ); + throw new MojoExecutionException( "There are no artifactItems configured." ); } - } - public void assertMarkerFile( boolean val, ArtifactItem item ) - { - UnpackFileMarkerHandler handle = new UnpackFileMarkerHandler( item, mojo.getMarkersDirectory() ); - try - { - assertEquals( val, handle.isMarkerSet() ); - } - catch ( MojoExecutionException e ) + for ( ArtifactItem artifactItem : artifactItems ) { - fail( e.getLongMessage() ); - } - } - - public void testUnpackFile() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - - mojo.setArtifactItems( list ); - - mojo.execute(); - - assertMarkerFiles( list, true ); - } - - public void testSkip() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - - mojo.setSkip( true ); - mojo.setArtifactItems( list ); - - mojo.execute(); - - assertMarkerFiles( list, false ); - } + this.getLog().info( "Configured Artifact: " + artifactItem.toString() ); - public void testUnpackToLocation() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); - - mojo.setArtifactItems( list ); + resolveArtifactRanges( artifactItem ); - mojo.execute(); - - assertMarkerFiles( list, true ); - } - - public void testUnpackToLocationWhereLocationCannotBeCreatedThrowsException() - throws Exception - { - List list = stubFactory.getArtifactItems( stubFactory.getClassifiedArtifacts() ); - ArtifactItem item = list.get( 0 ); - item.setOutputDirectory( new File( mojo.getOutputDirectory(), "testOverride" ) ); + if ( artifactItem.getOutputDirectory() == null ) + { + artifactItem.setOutputDirectory( this.outputDirectory ); + } + artifactItem.getOutputDirectory().mkdirs(); - mojo.setArtifactItems( list ); - final File currentFile = mojo.getOutputDirectory(); + // make sure we have a version. + if ( StringUtils.isEmpty( artifactItem.getVersion() ) ) + { + fillMissingArtifactVersion( artifactItem ); + } - // pretend that the output directory cannot be found event after mkdirs has been called by the mojo - // ifor instance in the case when the outputDirectory cannot be created because of permissions on the - // parent of the output directory - mojo.setOutputDirectory( new File( currentFile.getAbsolutePath() ) - { + artifactItem.setArtifact( this.getArtifact( artifactItem ) ); - private static final long serialVersionUID = -8559876942040177020L; + if ( StringUtils.isEmpty( artifactItem.getDestFileName() ) ) + { + artifactItem.setDestFileName( DependencyUtil.getFormattedFileName( artifactItem.getArtifact(), + removeVersion, prependGroupId, + useBaseVersion, removeClassifier ) ); + } - @Override - public boolean exists() + try { - // this file will always report that it does not exist - return false; + artifactItem.setNeedsProcessing( checkIfProcessingNeeded( artifactItem ) ); + } + catch ( ArtifactFilterException e ) + { + throw new MojoExecutionException( e.getMessage(), e ); } - } ); - try - { - mojo.execute(); - fail( "Expected Exception Here." ); - } - catch ( MojoExecutionException e ) - { - // caught the expected exception. } - } - - public void testMissingVersionNotFound() - throws Exception - { - ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "type"); - - List list = new ArrayList(); - list.add( item ); - mojo.setArtifactItems( list ); - + return artifactItems; + } + + /** + * If the artifact item has a version range, rather than a version, this + * method attempts to resolve this range by inspecting the list of resolved dependencies + * in the project for a match, before using the maven dependency resolver to resolve + * the range. + * + * If the dependency can be found and the version fits the artifact item's range + * then the artifact item is updated with the found version. + * + * If the dependency is not found or the range does not match, then the version + * is not changed. + * + * @param artifactItem The artifact item to update, if required. + * + * @throws MojoExecutionException if + */ + private void resolveArtifactRanges( final ArtifactItem artifactItem ) + { + VersionRange range; try { - mojo.execute(); - fail( "Expected Exception Here." ); + range = VersionRange.createFromVersionSpec( artifactItem.getVersion() ); } - catch ( MojoExecutionException e ) + catch ( InvalidVersionSpecificationException ivse ) { - // caught the expected exception. + this.getLog().warn( "Found invalid version range on artifact: " + artifactItem ); + range = null; } - } - public List getDependencyList( ArtifactItem item ) - { - Dependency dep = new Dependency(); - dep.setArtifactId( item.getArtifactId() ); - dep.setClassifier( item.getClassifier() ); - dep.setGroupId( item.getGroupId() ); - dep.setType( item.getType() ); - dep.setVersion( "2.0-SNAPSHOT" ); - - Dependency dep2 = new Dependency(); - dep2.setArtifactId( item.getArtifactId() ); - dep2.setClassifier( "classifier" ); - dep2.setGroupId( item.getGroupId() ); - dep2.setType( item.getType() ); - dep2.setVersion( "2.1" ); - - List list = new ArrayList( 2 ); - list.add( dep2 ); - list.add( dep ); - - return list; - } - - public void testMissingVersionFromDependencies() - throws Exception - { - ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "jar"); - - List list = new ArrayList(); - list.add( item ); - mojo.setArtifactItems( list ); - - MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - - mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "2.0-SNAPSHOT", item.getVersion() ); - } - - public void testMissingVersionFromDependenciesWithClassifier() - throws Exception - { - - ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "classifier", "war"); + if ( range != null && range.hasRestrictions() ) + { + // First, try and find the artifact in the projects list of already, resolved + // dependencies: + ComparableVersion foundVersion = null; - List list = new ArrayList(); - list.add( item ); - mojo.setArtifactItems( list ); + if ( getProject().getDependencyArtifacts() != null ) + { + for ( Artifact a : getProject().getDependencyArtifacts() ) + { + if ( artifactItem.getArtifactId().equals( a.getArtifactId() ) + && artifactItem.getGroupId().equals( a.getGroupId() ) + && range.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) ) + { + + ComparableVersion v = new ComparableVersion( a.getVersion() ); + if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) + { + foundVersion = v; + } + } + } + } - MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + if ( foundVersion == null ) + { + // If we've not found the artifact in the resolved list of project dependencies, + // then attempt to use the dependency resolver to resolve the version range: + + ProjectBuildingRequest request = newResolveArtifactProjectBuildingRequest(); + + DefaultDependableCoordinate searchDep = new DefaultDependableCoordinate(); + searchDep.setGroupId( artifactItem.getGroupId() ); + searchDep.setArtifactId( artifactItem.getArtifactId() ); + searchDep.setVersion( artifactItem.getVersion() ); + searchDep.setType( artifactItem.getType() ); + searchDep.setClassifier( artifactItem.getClassifier() ); + + Iterable result; + try + { + result = dependencyResolver.resolveDependencies( request, searchDep, null ); + } + catch ( DependencyResolverException are ) + { + result = null; + this.getLog().warn( are ); + } + + if ( result != null ) + { + for ( ArtifactResult artifact : result ) + { + ComparableVersion v = new ComparableVersion( artifact.getArtifact().getVersion() ); + if ( foundVersion == null || v.compareTo( foundVersion ) > 0 ) + { + foundVersion = v; + } + } + } + } - mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "2.1", item.getVersion() ); + if ( foundVersion != null ) + { + this.getLog().info( "Resolved version from: " + range.toString() + ", to: " + foundVersion ); + artifactItem.setVersion( foundVersion.toString() ); + } + } } - public List getDependencyMgtList( ArtifactItem item ) + private boolean checkIfProcessingNeeded( ArtifactItem item ) + throws MojoExecutionException, ArtifactFilterException { - Dependency dep = new Dependency(); - dep.setArtifactId( item.getArtifactId() ); - dep.setClassifier( item.getClassifier() ); - dep.setGroupId( item.getGroupId() ); - dep.setType( item.getType() ); - dep.setVersion( "3.0-SNAPSHOT" ); - - Dependency dep2 = new Dependency(); - dep2.setArtifactId( item.getArtifactId() ); - dep2.setClassifier( "classifier" ); - dep2.setGroupId( item.getGroupId() ); - dep2.setType( item.getType() ); - dep2.setVersion( "3.1" ); - - List list = new ArrayList( 2 ); - list.add( dep2 ); - list.add( dep ); - - return list; + return StringUtils.equalsIgnoreCase( item.getOverWrite(), "true" ) + || getMarkedArtifactFilter( item ).isArtifactIncluded( item ); } - public void testMissingVersionFromDependencyMgt() - throws Exception - { - ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "jar"); - - MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - - item = createArtifactItem( "groupId", "artifactId-2", null, "", "jar"); - - List list = new ArrayList(); - list.add( item ); - - mojo.setArtifactItems( list ); - - project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); - - mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "3.0-SNAPSHOT", item.getVersion() ); - } - - public void testMissingVersionFromDependencyMgtWithClassifier() - throws Exception + /** + * Resolves the Artifact from the remote repository if necessary. If no version is specified, it will be retrieved + * from the dependency list or from the DependencyManagement section of the pom. + * + * @param artifactItem containing information about artifact from plugin configuration. + * @return Artifact object representing the specified file. + * @throws MojoExecutionException with a message if the version can't be found in DependencyManagement. + */ + protected Artifact getArtifact( ArtifactItem artifactItem ) + throws MojoExecutionException { - ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "classifier", "jar"); - - MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - - item = createArtifactItem( "groupId", "artifactId-2", null, "classifier", "jar"); - - stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.0-SNAPSHOT" ), null, - "jar", "classifier", false ); - stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.1" ), null, "jar", - "classifier", false ); + Artifact artifact; - List list = new ArrayList(); - list.add( item ); - - mojo.setArtifactItems( list ); - - project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); + try + { + // mdep-50 - rolledback for now because it's breaking some functionality. + /* + * List listeners = new ArrayList(); Set theSet = new HashSet(); theSet.add( artifact ); + * ArtifactResolutionResult artifactResolutionResult = artifactCollector.collect( theSet, project + * .getArtifact(), managedVersions, this.local, project.getRemoteArtifactRepositories(), + * artifactMetadataSource, null, listeners ); Iterator iter = + * artifactResolutionResult.getArtifactResolutionNodes().iterator(); while ( iter.hasNext() ) { + * ResolutionNode node = (ResolutionNode) iter.next(); artifact = node.getArtifact(); } + */ + + ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(); + + if ( localRepositoryDirectory != null ) + { + buildingRequest = + repositoryManager.setLocalRepositoryBasedir( buildingRequest, localRepositoryDirectory ); + } - mojo.execute(); + // Map dependency to artifact coordinate + DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); + coordinate.setGroupId( artifactItem.getGroupId() ); + coordinate.setArtifactId( artifactItem.getArtifactId() ); + coordinate.setVersion( artifactItem.getVersion() ); + coordinate.setClassifier( artifactItem.getClassifier() ); - assertMarkerFile( true, item ); - assertEquals( "3.1", item.getVersion() ); - } + final String extension; + ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler( artifactItem.getType() ); + if ( artifactHandler != null ) + { + extension = artifactHandler.getExtension(); + } + else + { + extension = artifactItem.getType(); + } + coordinate.setExtension( extension ); - public void testArtifactNotFound() - throws Exception - { - dotestArtifactExceptions( false, true ); - } + artifact = artifactResolver.resolveArtifact( buildingRequest, coordinate ).getArtifact(); + } + catch ( ArtifactResolverException e ) + { + throw new MojoExecutionException( "Unable to find/resolve artifact.", e ); + } - public void testArtifactResolutionException() - throws Exception - { - dotestArtifactExceptions( true, false ); + return artifact; } - public void dotestArtifactExceptions( boolean are, boolean anfe ) - throws Exception + /** + * Tries to find missing version from dependency list and dependency management. If found, the artifact is updated + * with the correct version. It will first look for an exact match on artifactId/groupId/classifier/type and if it + * doesn't find a match, it will try again looking for artifactId and groupId only. + * + * @param artifact representing configured file. + * @throws MojoExecutionException + */ + private void fillMissingArtifactVersion( ArtifactItem artifact ) + throws MojoExecutionException { - ArtifactItem item = createArtifactItem( "groupId", "artifactId", "1.0", "", "type" ); + MavenProject project = getProject(); + List deps = project.getDependencies(); + List depMngt = project.getDependencyManagement() == null ? Collections.emptyList() + : project.getDependencyManagement().getDependencies(); - List list = new ArrayList(); - list.add( item ); - mojo.setArtifactItems( list ); - - try - { - mojo.execute(); - fail( "ExpectedException" ); - } - catch ( MojoExecutionException e ) + if ( !findDependencyVersion( artifact, deps, false ) + && ( project.getDependencyManagement() == null || !findDependencyVersion( artifact, depMngt, false ) ) + && !findDependencyVersion( artifact, deps, true ) + && ( project.getDependencyManagement() == null || !findDependencyVersion( artifact, depMngt, true ) ) ) { - assertEquals( "Unable to find/resolve artifact.", e.getMessage() ); + throw new MojoExecutionException( "Unable to find artifact version of " + artifact.getGroupId() + ":" + + artifact.getArtifactId() + " in either dependency list or in project's dependency management." ); } } - public void testNoArtifactItems() + /** + * Tries to find missing version from a list of dependencies. If found, the artifact is updated with the correct + * version. + * + * @param artifact representing configured file. + * @param dependencies list of dependencies to search. + * @param looseMatch only look at artifactId and groupId + * @return the found dependency + */ + private boolean findDependencyVersion( ArtifactItem artifact, List dependencies, boolean looseMatch ) { - try - { - mojo.getProcessedArtifactItems( false ); - fail( "Expected Exception" ); - } - catch ( MojoExecutionException e ) + for ( Dependency dependency : dependencies ) { - assertEquals( "There are no artifactItems configured.", e.getMessage() ); + if ( StringUtils.equals( dependency.getArtifactId(), artifact.getArtifactId() ) + && StringUtils.equals( dependency.getGroupId(), artifact.getGroupId() ) + && ( looseMatch || StringUtils.equals( dependency.getClassifier(), artifact.getClassifier() ) ) + && ( looseMatch || StringUtils.equals( dependency.getType(), artifact.getType() ) ) ) + { + artifact.setVersion( dependency.getVersion() ); + + return true; + } } + return false; } - public void testUnpackDontOverWriteReleases() - throws Exception + /** + * @return Returns the artifactItems. + */ + public List getArtifactItems() { - stubFactory.setCreateFiles( true ); - Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); - - ArtifactItem item = new ArtifactItem( createArtifact( release ) ); - - List list = new ArrayList( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - - mojo.setOverWriteIfNewer( false ); - - mojo.execute(); - - assertUnpacked( item, false ); + return this.artifactItems; } - public void testUnpackDontOverWriteSnapshots() - throws Exception + /** + * @param theArtifactItems The artifactItems to set. + */ + public void setArtifactItems( List theArtifactItems ) { - stubFactory.setCreateFiles( true ); - Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); - - ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); - - List list = new ArrayList( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - - mojo.setOverWriteIfNewer( false ); - - mojo.execute(); - - assertUnpacked( item, false ); + this.artifactItems = theArtifactItems; } - public void testUnpackOverWriteReleases() - throws Exception + /** + * @return Returns the outputDirectory. + */ + public File getOutputDirectory() { - stubFactory.setCreateFiles( true ); - Artifact release = stubFactory.getReleaseArtifact(); - assertTrue( release.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); - - ArtifactItem item = new ArtifactItem( createArtifact( release ) ); - - List list = new ArrayList( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - - mojo.setOverWriteIfNewer( false ); - mojo.setOverWriteReleases( true ); - mojo.execute(); - - assertUnpacked( item, true ); + return this.outputDirectory; } - public void testUnpackOverWriteSnapshot() - throws Exception + /** + * @param theOutputDirectory The outputDirectory to set. + */ + public void setOutputDirectory( File theOutputDirectory ) { - stubFactory.setCreateFiles( true ); - Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 ) ); - - ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); - - List list = new ArrayList( 1 ); - list.add( item ); - mojo.setArtifactItems( list ); - - mojo.setOverWriteIfNewer( false ); - mojo.setOverWriteReleases( false ); - mojo.setOverWriteSnapshots( true ); - mojo.execute(); - - assertUnpacked( item, true ); + this.outputDirectory = theOutputDirectory; } - public void testUnpackOverWriteIfNewer() - throws Exception + /** + * @return Returns the overWriteIfNewer. + */ + public boolean isOverWriteIfNewer() { - final long now = System.currentTimeMillis(); - - mojo.setSilent( false ); - stubFactory.setCreateFiles( true ); - Artifact artifact = stubFactory.getSnapshotArtifact(); - assertTrue( artifact.getFile().setLastModified( now - 20000 ) ); - - ArtifactItem item = new ArtifactItem( createArtifact( artifact ) ); - - List list = Collections.singletonList( item ); - mojo.setArtifactItems( list ); - mojo.setOverWriteIfNewer( true ); - mojo.execute(); - File unpackedFile = getUnpackedFile( item ); - - // round down to the last second - long time = now; - time = time - ( time % 1000 ); - // go back 10 more seconds for linux - time -= 10000; - // set to known value - assertTrue( unpackedFile.setLastModified( time ) ); - // set source to be newer was 4s but test is brittle on MacOS if less than 5s - assertTrue( artifact.getFile().setLastModified( time + 5000 ) ); - - // manually set markerfile (must match getMarkerFile in DefaultMarkerFileHandler) - File marker = new File( mojo.getMarkersDirectory(), artifact.getId().replace( ':', '-' ) + ".marker" ); - assertTrue( marker.setLastModified( time ) ); - - displayFile( "unpackedFile", unpackedFile ); - displayFile( "artifact ", artifact.getFile() ); - displayFile( "marker ", marker ); - System.out.println( "mojo.execute()" ); - mojo.execute(); - displayFile( "unpackedFile", unpackedFile ); - displayFile( "artifact ", artifact.getFile() ); - displayFile( "marker ", marker ); - System.out.println( "marker.lastModified() = " + marker.lastModified() ); - System.out.println( "unpackedFile.lastModified() = " + unpackedFile.lastModified() ); - assertTrue( "unpackedFile '" + unpackedFile + "' lastModified() == " + marker.lastModified() - + ": should be different", marker.lastModified() != unpackedFile.lastModified() ); + return this.overWriteIfNewer; } - public void testVersionRangeFromResolvedProjectDependencies() - throws Exception + /** + * @param theOverWriteIfNewer The overWriteIfNewer to set. + */ + public void setOverWriteIfNewer( boolean theOverWriteIfNewer ) { - stubFactory.setCreateFiles( true ); - - ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); - - List list = new ArrayList(); - list.add( item ); - mojo.setArtifactItems( list ); - - stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, - "jar", "", false ); - stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", - "", false ); - - MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - project.setDependencyArtifacts( createArtifactSet( getDependencyList( item ) ) ); - - mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "2.1", item.getVersion() ); + this.overWriteIfNewer = theOverWriteIfNewer; } - public void testVersionRangeFromResolvedProjectDependenciesWithMultipleDependencies() - throws Exception + /** + * @return Returns the overWriteReleases. + */ + public boolean isOverWriteReleases() { - stubFactory.setCreateFiles( true ); - - ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); - - List list = new ArrayList(); - list.add( item ); - mojo.setArtifactItems( list ); - - stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, - "jar", "", false ); - stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", - "", false ); - - MavenProject project = mojo.getProject(); - project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - - Set dependencySet = createArtifactSet( getDependencyList( item ) ); - dependencySet.addAll( createArtifactSet( getDependencyList( createArtifactItem( "groupId", "differentArtifactId", "1.0", "", "jar") ) ) ); - dependencySet.addAll( createArtifactSet( getDependencyList( createArtifactItem( "differentGroupId", "artifactId", "1.0", "", "jar") ) ) ); - - project.setDependencyArtifacts( dependencySet ); - - mojo.execute(); - assertMarkerFile( true, item ); - assertEquals( "2.1", item.getVersion() ); + return this.overWriteReleases; } -// -// public void testVersionRangeNoResolvedProjectDependencies() -// throws Exception -// { -// stubFactory.setCreateFiles( true ); -// -// ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); -// -// List list = new ArrayList(); -// list.add( item ); -// mojo.setArtifactItems( list ); -// -// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, -// "jar", "", false ); -// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", -// "", false ); -// -// mojo.execute(); -// assertMarkerFile( true, item ); -// assertEquals( "2.1", item.getVersion() ); -// } - - - private void displayFile( String description, File file ) + /** + * @param theOverWriteReleases The overWriteReleases to set. + */ + public void setOverWriteReleases( boolean theOverWriteReleases ) { - System.out.println( description + ' ' + DateFormatUtils.ISO_DATETIME_FORMAT.format( file.lastModified() ) + ' ' - + file.getPath().substring( getBasedir().length() ) ); + this.overWriteReleases = theOverWriteReleases; } - public void assertUnpacked( ArtifactItem item, boolean overWrite ) - throws Exception + /** + * @return Returns the overWriteSnapshots. + */ + public boolean isOverWriteSnapshots() { - - File unpackedFile = getUnpackedFile( item ); - - Thread.sleep( 100 ); - // round down to the last second - long time = System.currentTimeMillis(); - time = time - ( time % 1000 ); - assertTrue( unpackedFile.setLastModified( time ) ); - - assertEquals( time, unpackedFile.lastModified() ); - mojo.execute(); - - if ( overWrite ) - { - assertTrue( time != unpackedFile.lastModified() ); - } - else - { - assertEquals( time, unpackedFile.lastModified() ); - } + return this.overWriteSnapshots; } - public File getUnpackedFile( ArtifactItem item ) + /** + * @param theOverWriteSnapshots The overWriteSnapshots to set. + */ + public void setOverWriteSnapshots( boolean theOverWriteSnapshots ) { - File unpackedFile = new File( item.getOutputDirectory(), - DependencyArtifactStubFactory.getUnpackableFileName( item.getArtifact() ) ); - - assertTrue( unpackedFile.exists() ); - return unpackedFile; - + this.overWriteSnapshots = theOverWriteSnapshots; } - private ArtifactItem createArtifactItem( - final String groupId, - final String artifactId, - final String version, - final String classifier, - final String type ) + /** + * @param localRepositoryDirectory {@link #localRepositoryDirectory} + */ + public void setLocalRepositoryDirectory( File localRepositoryDirectory ) { - - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( artifactId ); - item.setClassifier( classifier ); - item.setGroupId( groupId ); - - if ( type != null ) { - item.setType( type ); - } - item.setVersion( version ); - - return item; + this.localRepositoryDirectory = localRepositoryDirectory; } - // respects the createUnpackableFile flag of the ArtifactStubFactory - private List createArtifacts( List items ) - throws IOException + /** + * @param artifact The artifact. + * @throws MojoFailureException in case of an error. + */ + public void setArtifact( String artifact ) + throws MojoFailureException { - for ( Dependency item : items ) + if ( artifact != null ) { - String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); - stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), - VersionRange.createFromVersion( item.getVersion() ), null, item.getType(), - classifier, item.isOptional() ); - } - return items; - } - - // respects the createUnpackableFile flag of the ArtifactStubFactory - private Set createArtifactSet( List items ) - throws IOException - { + String packaging = "jar"; + String classifier; + String[] tokens = StringUtils.split( artifact, ":" ); + if ( tokens.length < 3 || tokens.length > 5 ) + { + throw new MojoFailureException( "Invalid artifact, " + + "you must specify groupId:artifactId:version[:packaging[:classifier]] " + artifact ); + } + String groupId = tokens[0]; + String artifactId = tokens[1]; + String version = tokens[2]; + if ( tokens.length >= 4 ) + { + packaging = tokens[3]; + } + if ( tokens.length == 5 ) + { + classifier = tokens[4]; + } + else + { + classifier = null; + } - Set set = new HashSet<>(); + ArtifactItem artifactItem = new ArtifactItem(); + artifactItem.setGroupId( groupId ); + artifactItem.setArtifactId( artifactId ); + artifactItem.setVersion( version ); + artifactItem.setType( packaging ); + artifactItem.setClassifier( classifier ); - for ( Dependency item : items ) - { - set.add( - new DefaultArtifact( - item.getGroupId(), - item.getArtifactId(), - item.getVersion(), - item.getScope(), - item.getType(), - item.getClassifier(), - artifactHandlerManager.getArtifactHandler(item.getType()) - ) - ); + setArtifactItems( Collections.singletonList( artifactItem ) ); } - return set; - } - - private Artifact createArtifact( Artifact art ) - throws IOException - { - String classifier = "".equals( art.getClassifier() ) ? null : art.getClassifier(); - stubFactory.createArtifact( art.getGroupId(), art.getArtifactId(), - VersionRange.createFromVersion( art.getVersion() ), null, art.getType(), classifier, - art.isOptional() ); - return art; - } - - private ArtifactItem createArtifact( ArtifactItem item ) - throws IOException - { - String classifier = "".equals( item.getClassifier() ) ? null : item.getClassifier(); - stubFactory.createArtifact( item.getGroupId(), item.getArtifactId(), item.getVersion(), null, item.getType(), - classifier ); - return item; } } From 295f50f0d24b71653156df8f22f45d9c58c71ac5 Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Thu, 25 Apr 2019 15:19:17 +0100 Subject: [PATCH 05/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" --- .../fromConfiguration/TestUnpackMojo.java | 165 ++++++++++-------- 1 file changed, 92 insertions(+), 73 deletions(-) diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java index 81004193f0..741d9d9f05 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java @@ -44,7 +44,6 @@ import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.apache.maven.project.MavenProject; -import org.junit.Ignore; import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; import org.sonatype.aether.util.DefaultRepositorySystemSession; @@ -119,12 +118,7 @@ public ArtifactItem getSingleArtifactItem( boolean removeVersion ) public void testGetArtifactItems() throws Exception { - - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( "artifact" ); - item.setGroupId( "groupId" ); - item.setVersion( "1.0" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "1.0", null, null ); ArrayList list = new ArrayList( 1 ); list.add( createArtifact( item ) ); @@ -239,12 +233,7 @@ public boolean exists() public void testMissingVersionNotFound() throws Exception { - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "type"); List list = new ArrayList(); list.add( item ); @@ -287,12 +276,7 @@ public List getDependencyList( ArtifactItem item ) public void testMissingVersionFromDependencies() throws Exception { - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "jar"); List list = new ArrayList(); list.add( item ); @@ -309,12 +293,8 @@ public void testMissingVersionFromDependencies() public void testMissingVersionFromDependenciesWithClassifier() throws Exception { - ArtifactItem item = new ArtifactItem(); - item.setArtifactId( "artifactId" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "war" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "classifier", "war"); List list = new ArrayList(); list.add( item ); @@ -354,22 +334,12 @@ public List getDependencyMgtList( ArtifactItem item ) public void testMissingVersionFromDependencyMgt() throws Exception { - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "", "jar"); MavenProject project = mojo.getProject(); project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - item = new ArtifactItem(); - - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + item = createArtifactItem( "groupId", "artifactId-2", null, "", "jar"); List list = new ArrayList(); list.add( item ); @@ -386,22 +356,12 @@ public void testMissingVersionFromDependencyMgt() public void testMissingVersionFromDependencyMgtWithClassifier() throws Exception { - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( "artifactId" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", null, "classifier", "jar"); MavenProject project = mojo.getProject(); project.setDependencies( createArtifacts( getDependencyList( item ) ) ); - item = new ArtifactItem(); - - item.setArtifactId( "artifactId-2" ); - item.setClassifier( "classifier" ); - item.setGroupId( "groupId" ); - item.setType( "jar" ); + item = createArtifactItem( "groupId", "artifactId-2", null, "classifier", "jar"); stubFactory.createArtifact( "groupId", "artifactId-2", VersionRange.createFromVersion( "3.0-SNAPSHOT" ), null, "jar", "classifier", false ); @@ -436,13 +396,7 @@ public void testArtifactResolutionException() public void dotestArtifactExceptions( boolean are, boolean anfe ) throws Exception { - ArtifactItem item = new ArtifactItem(); - - item.setArtifactId( "artifactId" ); - item.setClassifier( "" ); - item.setGroupId( "groupId" ); - item.setType( "type" ); - item.setVersion( "1.0" ); + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "1.0", "", "type" ); List list = new ArrayList(); list.add( item ); @@ -600,32 +554,77 @@ public void testUnpackOverWriteIfNewer() + ": should be different", marker.lastModified() != unpackedFile.lastModified() ); } -// @Ignore -// public void testVersionRangeFromResolvedFromDependencies() + public void testVersionRangeFromResolvedProjectDependencies() + throws Exception + { + stubFactory.setCreateFiles( true ); + + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, + "jar", "", false ); + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", + "", false ); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + project.setDependencyArtifacts( createArtifactSet( getDependencyList( item ) ) ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.1", item.getVersion() ); + } + + public void testVersionRangeFromResolvedProjectDependenciesWithMultipleDependencies() + throws Exception + { + stubFactory.setCreateFiles( true ); + + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, + "jar", "", false ); + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", + "", false ); + + MavenProject project = mojo.getProject(); + project.setDependencies( createArtifacts( getDependencyList( item ) ) ); + + Set dependencySet = createArtifactSet( getDependencyList( item ) ); + dependencySet.addAll( createArtifactSet( getDependencyList( createArtifactItem( "groupId", "differentArtifactId", "1.0", "", "jar") ) ) ); + dependencySet.addAll( createArtifactSet( getDependencyList( createArtifactItem( "differentGroupId", "artifactId", "1.0", "", "jar") ) ) ); + + project.setDependencyArtifacts( dependencySet ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.1", item.getVersion() ); + } + +// +// public void testVersionRangeNoResolvedProjectDependencies() // throws Exception // { -// ArtifactItem item = new ArtifactItem(); +// stubFactory.setCreateFiles( true ); // -// item.setArtifactId( "artifactId" ); -// item.setClassifier( "" ); -// item.setGroupId( "groupId" ); -// item.setType( "jar" ); -// item.setVersion( "[0,)" ); +// ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); // // List list = new ArrayList(); // list.add( item ); // mojo.setArtifactItems( list ); // // stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, -// "jar", "classifier", false ); +// "jar", "", false ); // stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", -// "classifier", false ); -// -// MavenProject project = mojo.getProject(); -// project.setDependencies( createArtifacts( getDependencyList( item ) ) ); -// project.setDependencyArtifacts( createArtifactSet( getDependencyList( item ) ) ); -// -//// project.getDependencyManagement().setDependencies( createArtifacts( getDependencyMgtList( item ) ) ); +// "", false ); // // mojo.execute(); // assertMarkerFile( true, item ); @@ -633,8 +632,6 @@ public void testUnpackOverWriteIfNewer() // } - - private void displayFile( String description, File file ) { System.out.println( description + ' ' + DateFormatUtils.ISO_DATETIME_FORMAT.format( file.lastModified() ) + ' ' @@ -676,6 +673,28 @@ public File getUnpackedFile( ArtifactItem item ) } + private ArtifactItem createArtifactItem( + final String groupId, + final String artifactId, + final String version, + final String classifier, + final String type ) + { + + ArtifactItem item = new ArtifactItem(); + + item.setArtifactId( artifactId ); + item.setClassifier( classifier ); + item.setGroupId( groupId ); + + if ( type != null ) { + item.setType( type ); + } + item.setVersion( version ); + + return item; + } + // respects the createUnpackableFile flag of the ArtifactStubFactory private List createArtifacts( List items ) throws IOException From e321ea7353970f7c1088501614f5a6d7a2522948 Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Thu, 25 Apr 2019 16:02:49 +0100 Subject: [PATCH 06/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" goal - add tests and improve error handling --- .../testUtils/stubs/DependencyResolverStub | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub new file mode 100644 index 0000000000..e2c76ece7e --- /dev/null +++ b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub @@ -0,0 +1,98 @@ +package org.apache.maven.plugins.dependency.testUtils.stubs; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Dependency; +import org.apache.maven.model.Model; +import org.apache.maven.project.ProjectBuildingRequest; +import org.apache.maven.shared.artifact.filter.resolve.TransformableFilter; +import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResult; +import org.apache.maven.shared.transfer.dependencies.DependableCoordinate; +import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolver; +import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolverException; + +/** + * A very simple stub to use for whiteboxing the a Maven DependencyResolver + * class. + */ +public class DependencyResolverStub implements DependencyResolver { + + private Map coordCache = new HashMap<>(); + + public void addDependableCoordinateLookup( + final DependableCoordinate coord, + final Artifact artifact ) + { + coordCache.put( coord.toString(), artifact ); + } + + @Override + public Iterable resolveDependencies( + final ProjectBuildingRequest buildingRequest, + final DependableCoordinate coordinate, + final TransformableFilter filter ) throws DependencyResolverException + { + + + if ( coordCache.get( coordinate.toString() ) != null ) { + ArtifactResult result = new ArtifactResult() + { + + @Override + public Artifact getArtifact() + { + // TODO Auto-generated method stub + return coordCache.get( coordinate.toString() ); + } + }; + + return Arrays.asList( result ); + } else { + throw new DependencyResolverException( "Cannot resolve coordinates: " + coordinate, new IOException() ); + } + } + + @Override + public Iterable resolveDependencies( + ProjectBuildingRequest buildingRequest, + Model model, + TransformableFilter filter ) throws DependencyResolverException { + + throw new UnsupportedOperationException( "Method not implemented" ); + } + + @Override + public Iterable resolveDependencies( + ProjectBuildingRequest buildingRequest, + Collection dependencies, + Collection managedDependencies, + TransformableFilter filter ) throws DependencyResolverException { + + throw new UnsupportedOperationException( "Method not implemented" ); + } + +} From 93c2b4c9d1eaf86b49707db1778ba03cf30a922b Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Thu, 25 Apr 2019 16:03:50 +0100 Subject: [PATCH 07/10] MDEP-650 - Add ability to resolve version ranges when using the "unpack" goal - add tests and improve error handling --- .../fromConfiguration/TestUnpackMojo.java | 56 ++++++++++++------- 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java index 741d9d9f05..b935d106b1 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java @@ -609,27 +609,41 @@ public void testVersionRangeFromResolvedProjectDependenciesWithMultipleDependenc assertEquals( "2.1", item.getVersion() ); } -// -// public void testVersionRangeNoResolvedProjectDependencies() -// throws Exception -// { -// stubFactory.setCreateFiles( true ); -// -// ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar"); -// -// List list = new ArrayList(); -// list.add( item ); -// mojo.setArtifactItems( list ); -// -// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, -// "jar", "", false ); -// stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", -// "", false ); -// -// mojo.execute(); -// assertMarkerFile( true, item ); -// assertEquals( "2.1", item.getVersion() ); -// } + public void testVersionRangeNoResolvedProjectDependencies() + throws Exception + { + stubFactory.setCreateFiles( true ); + + DependencyResolverStub stubResolver = new DependencyResolverStub(); + ReflectionUtils.setVariableValueInObject(mojo, "dependencyResolver", stubResolver); + + DefaultDependableCoordinate coord = new DefaultDependableCoordinate(); + coord.setArtifactId( "artifactId" ); + coord.setGroupId( "groupId" ); + coord.setVersion( "[0,)" ); + coord.setType( "jar" ); + + DefaultArtifact depArtifact = new DefaultArtifact( + "groupId", "artifactId", "2.1", null, "jar", "", artifactHandlerManager.getArtifactHandler( "jar" ) + ); + + stubResolver.addDependableCoordinateLookup(coord, depArtifact); + + ArtifactItem item = createArtifactItem( "groupId", "artifactId", "[0,)", "", "jar" ); + + List list = new ArrayList(); + list.add( item ); + mojo.setArtifactItems( list ); + + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.0-SNAPSHOT" ), null, + "jar", "", false ); + stubFactory.createArtifact( "groupId", "artifactId", VersionRange.createFromVersion( "2.1" ), null, "jar", + "", false ); + + mojo.execute(); + assertMarkerFile( true, item ); + assertEquals( "2.1", item.getVersion() ); + } private void displayFile( String description, File file ) From 20a862842c54425bd956e8f06a732b15acd33ff6 Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Fri, 26 Apr 2019 11:31:20 +0100 Subject: [PATCH 08/10] MDEP-650 - dependency:unpack doesn't seem to handle version ranges - Correct imports --- .../plugins/dependency/fromConfiguration/TestUnpackMojo.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java index b935d106b1..cca7f94115 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java +++ b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestUnpackMojo.java @@ -42,11 +42,15 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.dependency.AbstractDependencyMojoTestCase; import org.apache.maven.plugins.dependency.testUtils.DependencyArtifactStubFactory; +import org.apache.maven.plugins.dependency.testUtils.stubs.DependencyResolverStub; import org.apache.maven.plugins.dependency.utils.markers.UnpackFileMarkerHandler; import org.apache.maven.project.MavenProject; +import org.apache.maven.shared.transfer.dependencies.DefaultDependableCoordinate; +import org.codehaus.plexus.util.ReflectionUtils; import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; import org.sonatype.aether.util.DefaultRepositorySystemSession; + public class TestUnpackMojo extends AbstractDependencyMojoTestCase { From a35c269e162f20db0844c7944edaa25ba590d73b Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Fri, 26 Apr 2019 11:36:13 +0100 Subject: [PATCH 09/10] [MDEP-650] - dependency:unpack doesn't seem to handle version ranges - correct file name --- .../stubs/{DependencyResolverStub => DependencyResolverStub.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/{DependencyResolverStub => DependencyResolverStub.java} (100%) diff --git a/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub b/src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub.java similarity index 100% rename from src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub rename to src/test/java/org/apache/maven/plugins/dependency/testUtils/stubs/DependencyResolverStub.java From bab35d753eab9a5dcdb549137dbde2d4907bf02f Mon Sep 17 00:00:00 2001 From: Andy Lehane Date: Fri, 26 Apr 2019 11:43:28 +0100 Subject: [PATCH 10/10] Change snapshot version to allow for internal use. Change the snapshot version in the pom.xml file to allow for internal use while the pull request is considered. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ca53726c17..53150191e4 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ under the License. maven-dependency-plugin - 3.1.2-SNAPSHOT + 3.1.1.alehane-SNAPSHOT maven-plugin Apache Maven Dependency Plugin