From cb05873dd55059082d54ed255715914fe484aad6 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Sun, 11 Dec 2022 22:03:53 +0100 Subject: [PATCH 1/2] Enable Spotless plugin - automatic code formatting --- pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pom.xml b/pom.xml index fcebe8d5e1..122f136dbf 100644 --- a/pom.xml +++ b/pom.xml @@ -213,9 +213,16 @@ + + com.diffplug.spotless + spotless-maven-plugin + org.apache.maven.plugins maven-checkstyle-plugin + + ${checkstyle.spotless.config} + org.codehaus.mojo From a65464deec062dca4a0960b7f414a59b76f63a04 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Sun, 11 Dec 2022 22:11:51 +0100 Subject: [PATCH 2/2] Enable Spotless plugin - code reformat --- pom.xml | 16 +- versions-api/pom.xml | 4 +- .../versions/api/change/VersionChange.java | 4 +- .../versions/api/recording/ChangeRecord.java | 24 +- .../api/recording/ChangeRecorder.java | 7 +- versions-common/pom.xml | 238 ++- .../versions/api/AbstractVersionDetails.java | 480 +++--- .../versions/api/ArtifactAssociation.java | 3 +- .../mojo/versions/api/ArtifactVersions.java | 121 +- .../versions/api/ArtifactVersionsCache.java | 18 +- .../api/DefaultArtifactAssociation.java | 71 +- .../versions/api/DefaultVersionsHelper.java | 976 +++++------ .../versions/api/PluginUpdatesDetails.java | 37 +- .../codehaus/mojo/versions/api/PomHelper.java | 1444 +++++++---------- .../codehaus/mojo/versions/api/Property.java | 57 +- .../mojo/versions/api/PropertyVersions.java | 398 ++--- .../versions/api/PropertyVersionsBuilder.java | 196 +-- .../mojo/versions/api/ReportRenderer.java | 3 +- .../codehaus/mojo/versions/api/Segment.java | 25 +- .../mojo/versions/api/VersionDetails.java | 79 +- .../api/VersionRetrievalException.java | 21 +- .../mojo/versions/api/VersionsHelper.java | 106 +- .../change/AbstractVersionChanger.java | 18 +- .../change/CompositeVersionChanger.java | 23 +- .../versions/change/DefaultVersionChange.java | 50 +- .../change/DependencyVersionChanger.java | 28 +- .../versions/change/ParentVersionChanger.java | 27 +- .../versions/change/PluginVersionChanger.java | 26 +- .../change/ProjectVersionChanger.java | 26 +- .../mojo/versions/change/VersionChanger.java | 6 +- .../change/VersionChangerFactory.java | 99 +- .../versions/filtering/DependencyFilter.java | 84 +- .../filtering/NullAwareWildcardMatcher.java | 16 +- .../versions/filtering/TokenizedMatcher.java | 110 +- .../versions/filtering/WildcardMatcher.java | 71 +- .../ordering/AbstractVersionComparator.java | 31 +- .../ordering/BoundArtifactVersion.java | 98 +- .../versions/ordering/ComparableVersion.java | 290 ++-- .../ordering/InvalidSegmentException.java | 20 +- .../ordering/MavenVersionComparator.java | 142 +- .../ordering/MercuryVersionComparator.java | 106 +- .../ordering/NumericVersionComparator.java | 302 ++-- .../ordering/ReactorDepthComparator.java | 27 +- .../versions/ordering/VersionComparator.java | 6 +- .../versions/ordering/VersionComparators.java | 130 +- .../recording/ChangeRecorderNull.java | 17 +- .../versions/recording/ChangeRecorderXML.java | 70 +- .../recording/DefaultChangeRecord.java | 53 +- .../rewriting/ModifiedPomXMLEventReader.java | 273 ++-- .../mojo/versions/utils/ContextualLog.java | 6 +- .../utils/DelegatingContextualLog.java | 150 +- .../versions/utils/DependencyBuilder.java | 95 +- .../versions/utils/DependencyComparator.java | 25 +- .../versions/utils/MavenProjectUtils.java | 113 +- .../mojo/versions/utils/MiscUtils.java | 12 +- .../mojo/versions/utils/PluginComparator.java | 47 +- .../utils/PropertiesVersionsFileReader.java | 42 +- .../versions/utils/PropertyComparator.java | 17 +- .../mojo/versions/utils/RegexUtils.java | 103 +- .../mojo/versions/utils/SegmentUtils.java | 34 +- .../utils/VersionsExpressionEvaluator.java | 10 +- .../versions/api/ArtifactVersionsTest.java | 260 +-- .../api/DefaultVersionsHelperTest.java | 363 +++-- .../mojo/versions/api/PomHelperTest.java | 197 +-- .../filtering/DependencyFilterTest.java | 191 +-- .../versions/filtering/HasGAVMatcher.java | 30 +- .../filtering/TokenizedMatcherTest.java | 151 +- .../filtering/WildcardMatcherTest.java | 319 ++-- .../ordering/BoundArtifactVersionTest.java | 83 +- .../ordering/MavenVersionComparatorTest.java | 63 +- .../MercuryVersionComparatorTest.java | 25 +- .../NumericVersionComparatorTest.java | 104 +- .../ordering/VersionComparatorTestBase.java | 72 +- .../recording/ChangeRecorderXMLTest.java | 125 +- .../ModifiedPomXMLEventReaderTest.java | 85 +- .../utils/ModifiedPomXMLEventReaderUtils.java | 29 +- .../PropertiesVersionsFileReaderTest.java | 28 +- .../mojo/versions/utils/SegmentUtilsTest.java | 36 +- .../mojo/versions/utils/VersionStub.java | 30 +- versions-enforcer/pom.xml | 354 ++-- .../enforcer/MaxDependencyUpdates.java | 207 +-- .../enforcer/MaxDependencyUpdatesTest.java | 359 ++-- versions-maven-plugin/pom.xml | 18 +- .../AbstractDependencyUpdatesReportMojo.java | 259 ++- .../AbstractPluginUpdatesReportMojo.java | 158 +- .../AbstractPropertyUpdatesReportMojo.java | 130 +- ...AbstractVersionsDependencyUpdaterMojo.java | 364 ++--- .../versions/AbstractVersionsDisplayMojo.java | 136 +- .../mojo/versions/AbstractVersionsReport.java | 128 +- .../versions/AbstractVersionsUpdaterMojo.java | 295 ++-- .../codehaus/mojo/versions/CommitMojo.java | 30 +- .../versions/CompareDependenciesMojo.java | 413 ++--- .../DependencyUpdatesAggregateReportMojo.java | 54 +- .../versions/DependencyUpdatesReportMojo.java | 50 +- .../DisplayDependencyUpdatesMojo.java | 336 ++-- .../versions/DisplayParentUpdatesMojo.java | 138 +- .../versions/DisplayPluginUpdatesMojo.java | 1245 ++++++-------- .../versions/DisplayPropertyUpdatesMojo.java | 181 +-- .../mojo/versions/ForceReleasesMojo.java | 124 +- .../mojo/versions/LockSnapshotsMojo.java | 176 +- .../MinimalMavenBuildVersionFinder.java | 194 +-- .../versions/ParentUpdatesReportMojo.java | 92 +- .../PluginUpdatesAggregateReportMojo.java | 53 +- .../versions/PluginUpdatesReportMojo.java | 44 +- .../PropertyUpdatesAggregateReportMojo.java | 48 +- .../versions/PropertyUpdatesReportMojo.java | 34 +- .../mojo/versions/ResolveRangesMojo.java | 252 ++- .../codehaus/mojo/versions/RevertMojo.java | 66 +- .../org/codehaus/mojo/versions/SetMojo.java | 478 +++--- .../mojo/versions/SetPropertyMojo.java | 127 +- .../codehaus/mojo/versions/SetScmTagMojo.java | 117 +- .../mojo/versions/UnlockSnapshotsMojo.java | 158 +- .../mojo/versions/UpdateChildModulesMojo.java | 178 +- .../mojo/versions/UpdateParentMojo.java | 170 +- .../mojo/versions/UpdatePropertiesMojo.java | 56 +- .../versions/UpdatePropertiesMojoBase.java | 116 +- .../mojo/versions/UpdatePropertyMojo.java | 63 +- .../mojo/versions/UseDepVersionMojo.java | 115 +- .../mojo/versions/UseLatestReleasesMojo.java | 128 +- .../mojo/versions/UseLatestSnapshotsMojo.java | 99 +- .../mojo/versions/UseLatestVersionsMojo.java | 109 +- .../versions/UseLatestVersionsMojoBase.java | 73 +- .../mojo/versions/UseNextReleasesMojo.java | 73 +- .../mojo/versions/UseNextSnapshotsMojo.java | 96 +- .../mojo/versions/UseNextVersionsMojo.java | 70 +- .../mojo/versions/UseReactorMojo.java | 109 +- .../mojo/versions/UseReleasesMojo.java | 145 +- .../AbstractVersionsReportRenderer.java | 287 ++-- .../DependencyUpdatesReportRenderer.java | 58 +- .../versions/reporting/OverviewStats.java | 71 +- .../ParentUpdatesReportRenderer.java | 18 +- .../reporting/PluginOverviewStats.java | 41 +- .../PluginUpdatesReportRenderer.java | 145 +- .../PropertyUpdatesReportRenderer.java | 138 +- .../reporting/ReportRendererFactory.java | 5 +- .../reporting/ReportRendererFactoryImpl.java | 41 +- .../reporting/VersionsReportRendererBase.java | 138 +- .../reporting/model/AbstractUpdatesModel.java | 42 +- .../model/DependencyUpdatesModel.java | 11 +- .../reporting/model/ParentUpdatesModel.java | 8 +- .../reporting/model/PluginUpdatesModel.java | 19 +- .../reporting/model/PropertyUpdatesModel.java | 15 +- .../reporting/util/AggregateReportUtils.java | 15 +- .../xml/CommonXmlReportRendererUtils.java | 23 +- .../DependencyUpdatesXmlReportRenderer.java | 93 +- .../xml/PluginUpdatesXmlReportRenderer.java | 95 +- .../xml/PropertyUpdatesXmlReportRenderer.java | 106 +- .../AbstractVersionsUpdaterMojoTest.java | 27 +- .../DependencyUpdatesReportMojoTest.java | 343 ++-- .../DependencyUpdatesXmlRendererTest.java | 87 +- .../DisplayDependencyUpdatesMojoTest.java | 561 ++++--- .../DisplayPropertyUpdatesMojoTest.java | 64 +- .../mojo/versions/ForceReleasesMojoTest.java | 247 +-- .../MinimalMavenBuildVersionFinderTest.java | 52 +- .../versions/ParentUpdatesReportMojoTest.java | 82 +- .../versions/PluginUpdatesReportMojoTest.java | 194 +-- .../PluginUpdatesXmlRendererTest.java | 99 +- .../PropertyUpdatesReportMojoTest.java | 58 +- .../mojo/versions/RevertMojoTest.java | 53 +- .../mojo/versions/RewriteWithStAXTest.java | 366 ++--- ...ratePatternsForIncludesAnExcludesTest.java | 87 +- .../codehaus/mojo/versions/SetMojoTest.java | 159 +- .../mojo/versions/SetPropertyMojoTest.java | 98 +- .../mojo/versions/SetScmTagMojoTest.java | 31 +- .../mojo/versions/UpdateParentMojoTest.java | 494 +++--- .../versions/UpdatePropertiesMojoTest.java | 73 +- .../UpdatePropertiesMojoTestBase.java | 48 +- .../mojo/versions/UpdatePropertyMojoTest.java | 52 +- .../mojo/versions/UseDepVersionMojoTest.java | 23 +- .../versions/UseLatestReleasesMojoTest.java | 124 +- .../versions/UseLatestVersionsMojoTest.java | 484 +++--- .../mojo/versions/UseReleasesMojoTest.java | 163 +- .../versions/model/TestIgnoreVersions.java | 37 +- versions-model-report/pom.xml | 144 +- versions-model/pom.xml | 136 +- versions-test/pom.xml | 105 +- .../mojo/versions/utils/MockUtils.java | 140 +- .../versions/utils/TestChangeRecorder.java | 22 +- .../mojo/versions/utils/TestUtils.java | 49 +- .../mojo/versions/utils/VersionStub.java | 30 +- 180 files changed, 10393 insertions(+), 13448 deletions(-) diff --git a/pom.xml b/pom.xml index 122f136dbf..67eb0fe9d4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,5 @@ - + + 4.0.0 @@ -108,8 +107,8 @@ scm:git:https://github.com/mojohaus/versions.git scm:git:ssh://git@github.com/mojohaus/versions.git - https://github.com/mojohaus/versions/tree/master HEAD + https://github.com/mojohaus/versions/tree/master @@ -133,7 +132,8 @@ 3.7 2.1.0 2.0.0 - ${project.build.directory}/staging + ${project.build.directory}/staging + 2022-10-23T15:41:47Z 0.9.0.M1 @@ -230,10 +230,10 @@ check-java18 - test check + test org.codehaus.mojo.signature @@ -251,11 +251,11 @@ default-site - site site stage + site @@ -270,7 +270,7 @@ maven-plugin-report-plugin - + diff --git a/versions-api/pom.xml b/versions-api/pom.xml index 72458be0d6..748c3a4296 100644 --- a/versions-api/pom.xml +++ b/versions-api/pom.xml @@ -1,7 +1,5 @@ - + 4.0.0 diff --git a/versions-api/src/main/java/org/codehaus/mojo/versions/api/change/VersionChange.java b/versions-api/src/main/java/org/codehaus/mojo/versions/api/change/VersionChange.java index 656d42aa0b..c8b6f63216 100644 --- a/versions-api/src/main/java/org/codehaus/mojo/versions/api/change/VersionChange.java +++ b/versions-api/src/main/java/org/codehaus/mojo/versions/api/change/VersionChange.java @@ -23,8 +23,7 @@ * @author Slawomir Jaranowski * @since 2.14.0 */ -public interface VersionChange -{ +public interface VersionChange { /** * @return a groupId of changed item * @since 2.14.0 @@ -48,5 +47,4 @@ public interface VersionChange * @since 2.14.0 */ String getNewVersion(); - } diff --git a/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecord.java b/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecord.java index 18ab668071..9328aac507 100644 --- a/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecord.java +++ b/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecord.java @@ -25,29 +25,25 @@ * @author Slawomir Jaranowski * @since 2.14.0 */ -public interface ChangeRecord -{ +public interface ChangeRecord { /** * Describe where version item is updated. */ - enum ChangeKind - { - DEPENDENCY( "dependency-update" ), - DEPENDENCY_MANAGEMENT( "dependency-management-update" ), - PARENT( "parent-update" ), - PLUGIN( "plugin-update" ), - PLUGIN_MANAGEMENT( "plugin-management-update" ), - PROPERTY( "property-update" ); + enum ChangeKind { + DEPENDENCY("dependency-update"), + DEPENDENCY_MANAGEMENT("dependency-management-update"), + PARENT("parent-update"), + PLUGIN("plugin-update"), + PLUGIN_MANAGEMENT("plugin-management-update"), + PROPERTY("property-update"); private final String label; - ChangeKind( String label ) - { + ChangeKind(String label) { this.label = label; } - public String getLabel() - { + public String getLabel() { return label; } } diff --git a/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecorder.java b/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecorder.java index 42d961357c..4618818250 100644 --- a/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecorder.java +++ b/versions-api/src/main/java/org/codehaus/mojo/versions/api/recording/ChangeRecorder.java @@ -26,15 +26,14 @@ * @author Slawomir Jaranowski * @since 2.14.0 */ -public interface ChangeRecorder -{ +public interface ChangeRecorder { /** * Record that a dependency was updated. * * @param changeRecord a record described change * @since 2.14.0 */ - void recordChange( ChangeRecord changeRecord ); + void recordChange(ChangeRecord changeRecord); /** * Write the current set of changes to the given output path. @@ -48,5 +47,5 @@ public interface ChangeRecorder * @throws IOException On write and/or I/O errors * @since 2.14.0 */ - void writeReport( Path outputPath ) throws IOException; + void writeReport(Path outputPath) throws IOException; } diff --git a/versions-common/pom.xml b/versions-common/pom.xml index 5f40995b25..a566ae9d93 100644 --- a/versions-common/pom.xml +++ b/versions-common/pom.xml @@ -1,129 +1,127 @@ - - - versions - org.codehaus.mojo.versions - 2.14.0-SNAPSHOT - - 4.0.0 + + 4.0.0 + + org.codehaus.mojo.versions + versions + 2.14.0-SNAPSHOT + - versions-common + versions-common - Versions Common - Common components for the Versions Maven Plugin + Versions Common + Common components for the Versions Maven Plugin - - - org.codehaus.mojo.versions - versions-api - 2.14.0-SNAPSHOT - - - org.codehaus.mojo.versions - versions-model - ${project.version} - + + + org.codehaus.mojo.versions + versions-api + 2.14.0-SNAPSHOT + + + org.codehaus.mojo.versions + versions-model + ${project.version} + - - org.apache.maven - maven-artifact - ${mavenVersion} - provided - + + org.apache.maven + maven-artifact + ${mavenVersion} + provided + - - org.apache.maven - maven-core - ${mavenVersion} - provided - - - org.apache.maven.wagon - wagon-provider-api - 3.5.2 - - - org.apache.maven - maven-model - ${mavenVersion} - provided - - - org.apache.maven - maven-plugin-api - ${mavenVersion} - provided - - - org.apache.maven - maven-settings - ${mavenVersion} - provided - - - - com.fasterxml.woodstox - woodstox-core - test - - - org.apache.commons - commons-lang3 - + + org.apache.maven + maven-core + ${mavenVersion} + provided + + + org.apache.maven.wagon + wagon-provider-api + 3.5.2 + + + org.apache.maven + maven-model + ${mavenVersion} + provided + + + org.apache.maven + maven-plugin-api + ${mavenVersion} + provided + + + org.apache.maven + maven-settings + ${mavenVersion} + provided + + + + com.fasterxml.woodstox + woodstox-core + test + + + org.apache.commons + commons-lang3 + - - org.apache.maven.plugin-testing - maven-plugin-testing-harness - test - - - org.junit.jupiter - junit-jupiter - test - - - org.junit.vintage - junit-vintage-engine - test - - - org.hamcrest - hamcrest-core - - - - - org.mockito - mockito-inline - test - - - org.hamcrest - hamcrest - test - - - org.slf4j - slf4j-simple - test - - - - org.apache.maven - maven-compat - ${mavenVersion} - test - - + + org.apache.maven.plugin-testing + maven-plugin-testing-harness + test + + + org.junit.jupiter + junit-jupiter + test + + + org.junit.vintage + junit-vintage-engine + test + + + org.hamcrest + hamcrest-core + + + + + org.mockito + mockito-inline + test + + + org.hamcrest + hamcrest + test + + + org.slf4j + slf4j-simple + test + + + + org.apache.maven + maven-compat + ${mavenVersion} + test + + - - - - org.eclipse.sisu - sisu-maven-plugin - - - + + + + org.eclipse.sisu + sisu-maven-plugin + + + diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java index 13e8966c88..3ba86c0a7d 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java @@ -51,13 +51,11 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -public abstract class AbstractVersionDetails - implements VersionDetails -{ +public abstract class AbstractVersionDetails implements VersionDetails { private static final Pattern PREVIEW_PATTERN = - Pattern.compile( "(?i)(?:.*[-.](alpha|a|beta|b|milestone|m|preview|rc)" - + "[-.]?(\\d{0,2}[a-z]?|\\d{6}\\.\\d{4})|\\d{8}(?:\\.?\\d{6})?)$" ); + Pattern.compile("(?i)(?:.*[-.](alpha|a|beta|b|milestone|m|preview|rc)" + + "[-.]?(\\d{0,2}[a-z]?|\\d{6}\\.\\d{4})|\\d{8}(?:\\.?\\d{6})?)$"); /** * The current version. Guarded by {@link #currentVersionLock}. @@ -83,359 +81,299 @@ public abstract class AbstractVersionDetails */ private final Object currentVersionLock = new Object(); - protected AbstractVersionDetails() - { - } + protected AbstractVersionDetails() {} @Override - public Restriction restrictionFor( Optional scope ) - throws InvalidSegmentException - { + public Restriction restrictionFor(Optional scope) throws InvalidSegmentException { // one range spec can have multiple restrictions, and multiple 'lower bound', we want the highest one. // [1.0,2.0),[3.0,4.0) -> 3.0 ArtifactVersion highestLowerBound = currentVersion; - if ( currentVersion != null ) - { - try - { - highestLowerBound = VersionRange.createFromVersionSpec( currentVersion.toString() ) - .getRestrictions().stream().map( Restriction::getLowerBound ).filter( Objects::nonNull ) - .max( getVersionComparator() ).orElse( currentVersion ); - } - catch ( InvalidVersionSpecificationException ignored ) - { - ignored.printStackTrace( System.err ); + if (currentVersion != null) { + try { + highestLowerBound = + VersionRange.createFromVersionSpec(currentVersion.toString()).getRestrictions().stream() + .map(Restriction::getLowerBound) + .filter(Objects::nonNull) + .max(getVersionComparator()) + .orElse(currentVersion); + } catch (InvalidVersionSpecificationException ignored) { + ignored.printStackTrace(System.err); } } final ArtifactVersion currentVersion = highestLowerBound; - ArtifactVersion nextVersion = scope - .filter( s -> s.isMajorTo( SUBINCREMENTAL ) ) - .map( s -> (ArtifactVersion) - new BoundArtifactVersion( currentVersion, Segment.of( s.value() + 1 ) ) ) - .orElse( currentVersion ); - return new Restriction( nextVersion, false, scope.filter( MAJOR::isMajorTo ) - .map( s -> (ArtifactVersion) new BoundArtifactVersion( currentVersion, s ) ).orElse( null ), - false ); + ArtifactVersion nextVersion = scope.filter(s -> s.isMajorTo(SUBINCREMENTAL)) + .map(s -> (ArtifactVersion) new BoundArtifactVersion(currentVersion, Segment.of(s.value() + 1))) + .orElse(currentVersion); + return new Restriction( + nextVersion, + false, + scope.filter(MAJOR::isMajorTo) + .map(s -> (ArtifactVersion) new BoundArtifactVersion(currentVersion, s)) + .orElse(null), + false); } @Override - public Restriction restrictionForIgnoreScope( Optional ignored ) - { - ArtifactVersion nextVersion = ignored - .map( s -> (ArtifactVersion) new BoundArtifactVersion( currentVersion, s ) ) - .orElse( currentVersion ); - return new Restriction( nextVersion, false, null, false ); + public Restriction restrictionForIgnoreScope(Optional ignored) { + ArtifactVersion nextVersion = ignored.map(s -> (ArtifactVersion) new BoundArtifactVersion(currentVersion, s)) + .orElse(currentVersion); + return new Restriction(nextVersion, false, null, false); } @Override - public final boolean isCurrentVersionDefined() - { + public final boolean isCurrentVersionDefined() { return getCurrentVersion() != null; } @Override - public final ArtifactVersion getCurrentVersion() - { - synchronized ( currentVersionLock ) - { + public final ArtifactVersion getCurrentVersion() { + synchronized (currentVersionLock) { return currentVersion; } } @Override - public final void setCurrentVersion( ArtifactVersion currentVersion ) - { - synchronized ( currentVersionLock ) - { + public final void setCurrentVersion(ArtifactVersion currentVersion) { + synchronized (currentVersionLock) { this.currentVersion = currentVersion; } } @Override - public final void setCurrentVersion( String currentVersion ) - { - setCurrentVersion( currentVersion == null ? null : new DefaultArtifactVersion( currentVersion ) ); + public final void setCurrentVersion(String currentVersion) { + setCurrentVersion(currentVersion == null ? null : new DefaultArtifactVersion(currentVersion)); } @Override - public final boolean isIncludeSnapshots() - { - synchronized ( currentVersionLock ) - { + public final boolean isIncludeSnapshots() { + synchronized (currentVersionLock) { return includeSnapshots; } } @Override - public final void setIncludeSnapshots( boolean includeSnapshots ) - { - synchronized ( currentVersionLock ) - { + public final void setIncludeSnapshots(boolean includeSnapshots) { + synchronized (currentVersionLock) { this.includeSnapshots = includeSnapshots; } } @Override - public final ArtifactVersion[] getVersions() - { - return getVersions( isIncludeSnapshots() ); + public final ArtifactVersion[] getVersions() { + return getVersions(isIncludeSnapshots()); } @Override - public abstract ArtifactVersion[] getVersions( boolean includeSnapshots ); + public abstract ArtifactVersion[] getVersions(boolean includeSnapshots); @Override - public final ArtifactVersion[] getVersions( VersionRange versionRange, boolean includeSnapshots ) - { - return getVersions( versionRange, null, includeSnapshots ); + public final ArtifactVersion[] getVersions(VersionRange versionRange, boolean includeSnapshots) { + return getVersions(versionRange, null, includeSnapshots); } @Override - public final ArtifactVersion[] getVersions( ArtifactVersion lowerBound, ArtifactVersion upperBound ) - { - return getVersions( lowerBound, upperBound, isIncludeSnapshots() ); + public final ArtifactVersion[] getVersions(ArtifactVersion lowerBound, ArtifactVersion upperBound) { + return getVersions(lowerBound, upperBound, isIncludeSnapshots()); } @Override - public final ArtifactVersion[] getVersions( ArtifactVersion lowerBound, ArtifactVersion upperBound, - boolean includeSnapshots ) - { - Restriction restriction = new Restriction( lowerBound, false, upperBound, false ); - return getVersions( restriction, includeSnapshots ); + public final ArtifactVersion[] getVersions( + ArtifactVersion lowerBound, ArtifactVersion upperBound, boolean includeSnapshots) { + Restriction restriction = new Restriction(lowerBound, false, upperBound, false); + return getVersions(restriction, includeSnapshots); } @Override - public final ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion upperBound ) - { - return getNewestVersion( lowerBound, upperBound, isIncludeSnapshots() ); + public final ArtifactVersion getNewestVersion(ArtifactVersion lowerBound, ArtifactVersion upperBound) { + return getNewestVersion(lowerBound, upperBound, isIncludeSnapshots()); } @Override - public final ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion upperBound, - boolean includeSnapshots ) - { - Restriction restriction = new Restriction( lowerBound, false, upperBound, false ); - return getNewestVersion( restriction, includeSnapshots ); + public final ArtifactVersion getNewestVersion( + ArtifactVersion lowerBound, ArtifactVersion upperBound, boolean includeSnapshots) { + Restriction restriction = new Restriction(lowerBound, false, upperBound, false); + return getNewestVersion(restriction, includeSnapshots); } @Override - public final ArtifactVersion getNewestVersion( VersionRange versionRange, Restriction restriction, - boolean includeSnapshots ) - { - return getNewestVersion( versionRange, restriction, includeSnapshots, false ); + public final ArtifactVersion getNewestVersion( + VersionRange versionRange, Restriction restriction, boolean includeSnapshots) { + return getNewestVersion(versionRange, restriction, includeSnapshots, false); } @Override - public final ArtifactVersion getNewestVersion( VersionRange versionRange, Restriction restriction, - boolean includeSnapshots, boolean allowDowngrade ) - { + public final ArtifactVersion getNewestVersion( + VersionRange versionRange, Restriction restriction, boolean includeSnapshots, boolean allowDowngrade) { // reverseOrder( getVersions( ... ) ) will contain versions sorted from latest to oldest, // so we only need to find the first candidate fulfilling the criteria - return Arrays.stream( getVersions( includeSnapshots ) ) - .sorted( reverseOrder() ) - .filter( candidate -> allowDowngrade || versionRange == null - || ArtifactVersions.isVersionInRange( candidate, versionRange ) ) - .filter( candidate -> restriction == null || isVersionInRestriction( restriction, candidate ) ) - .filter( candidate -> includeSnapshots || !ArtifactUtils.isSnapshot( candidate.toString() ) ) + return Arrays.stream(getVersions(includeSnapshots)) + .sorted(reverseOrder()) + .filter(candidate -> allowDowngrade + || versionRange == null + || ArtifactVersions.isVersionInRange(candidate, versionRange)) + .filter(candidate -> restriction == null || isVersionInRestriction(restriction, candidate)) + .filter(candidate -> includeSnapshots || !ArtifactUtils.isSnapshot(candidate.toString())) .findAny() - .orElse( null ); + .orElse(null); } @Override - public final ArtifactVersion getNewestVersion( Restriction restriction, boolean includeSnapshots ) - { - return getNewestVersion( null, restriction, includeSnapshots ); + public final ArtifactVersion getNewestVersion(Restriction restriction, boolean includeSnapshots) { + return getNewestVersion(null, restriction, includeSnapshots); } @Override - public final ArtifactVersion getNewestVersion( VersionRange versionRange, boolean includeSnapshots ) - { - return getNewestVersion( versionRange, null, includeSnapshots ); + public final ArtifactVersion getNewestVersion(VersionRange versionRange, boolean includeSnapshots) { + return getNewestVersion(versionRange, null, includeSnapshots); } @Override - public final boolean containsVersion( String version ) - { - for ( ArtifactVersion candidate : getVersions( true ) ) - { - if ( version.equals( candidate.toString() ) ) - { + public final boolean containsVersion(String version) { + for (ArtifactVersion candidate : getVersions(true)) { + if (version.equals(candidate.toString())) { return true; } } return false; } - private ArtifactVersion[] getNewerVersions( ArtifactVersion version, boolean includeSnapshots ) - { - Restriction restriction = new Restriction( version, false, null, false ); - return getVersions( restriction, includeSnapshots ); + private ArtifactVersion[] getNewerVersions(ArtifactVersion version, boolean includeSnapshots) { + Restriction restriction = new Restriction(version, false, null, false); + return getVersions(restriction, includeSnapshots); } @Override - public final ArtifactVersion[] getNewerVersions( String version, boolean includeSnapshots ) - { - return getNewerVersions( new DefaultArtifactVersion( version ), includeSnapshots ); + public final ArtifactVersion[] getNewerVersions(String version, boolean includeSnapshots) { + return getNewerVersions(new DefaultArtifactVersion(version), includeSnapshots); } @Deprecated @Override - public final ArtifactVersion[] getNewerVersions( String version, Optional upperBoundSegment, - boolean includeSnapshots ) - throws InvalidSegmentException - { - return getNewerVersions( version, upperBoundSegment, includeSnapshots, false ); + public final ArtifactVersion[] getNewerVersions( + String version, Optional upperBoundSegment, boolean includeSnapshots) + throws InvalidSegmentException { + return getNewerVersions(version, upperBoundSegment, includeSnapshots, false); } @Override - public final ArtifactVersion[] getNewerVersions( String versionString, Optional unchangedSegment, - boolean includeSnapshots, boolean allowDowngrade ) - throws InvalidSegmentException - { - ArtifactVersion currentVersion = new DefaultArtifactVersion( versionString ); + public final ArtifactVersion[] getNewerVersions( + String versionString, Optional unchangedSegment, boolean includeSnapshots, boolean allowDowngrade) + throws InvalidSegmentException { + ArtifactVersion currentVersion = new DefaultArtifactVersion(versionString); ArtifactVersion lowerBound = allowDowngrade - ? getLowerBound( currentVersion, unchangedSegment ) - .map( DefaultArtifactVersion::new ) - .orElse( null ) + ? getLowerBound(currentVersion, unchangedSegment) + .map(DefaultArtifactVersion::new) + .orElse(null) : currentVersion; - ArtifactVersion upperBound = - unchangedSegment - .map( s -> (ArtifactVersion) new BoundArtifactVersion( currentVersion, - s.isMajorTo( SUBINCREMENTAL ) - ? Segment.of( s.value() + 1 ) - : s ) ) - .orElse( null ); + ArtifactVersion upperBound = unchangedSegment + .map(s -> (ArtifactVersion) new BoundArtifactVersion( + currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.of(s.value() + 1) : s)) + .orElse(null); - Restriction restriction = new Restriction( lowerBound, allowDowngrade, upperBound, allowDowngrade ); - return getVersions( restriction, includeSnapshots ); + Restriction restriction = new Restriction(lowerBound, allowDowngrade, upperBound, allowDowngrade); + return getVersions(restriction, includeSnapshots); } @Override - public Optional getNewestVersion( String versionString, Optional upperBoundSegment, - boolean includeSnapshots, boolean allowDowngrade ) - throws InvalidSegmentException - { - ArtifactVersion currentVersion = new DefaultArtifactVersion( versionString ); + public Optional getNewestVersion( + String versionString, Optional upperBoundSegment, boolean includeSnapshots, boolean allowDowngrade) + throws InvalidSegmentException { + ArtifactVersion currentVersion = new DefaultArtifactVersion(versionString); ArtifactVersion lowerBound = allowDowngrade - ? getLowerBound( currentVersion, upperBoundSegment ) - .map( DefaultArtifactVersion::new ) - .orElse( null ) + ? getLowerBound(currentVersion, upperBoundSegment) + .map(DefaultArtifactVersion::new) + .orElse(null) : currentVersion; - ArtifactVersion upperBound = - upperBoundSegment - .map( s -> (ArtifactVersion) new BoundArtifactVersion( currentVersion, - s.isMajorTo( SUBINCREMENTAL ) - ? Segment.of( s.value() + 1 ) - : s ) ) - .orElse( null ); + ArtifactVersion upperBound = upperBoundSegment + .map(s -> (ArtifactVersion) new BoundArtifactVersion( + currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.of(s.value() + 1) : s)) + .orElse(null); - Restriction restriction = new Restriction( lowerBound, allowDowngrade, upperBound, allowDowngrade ); - return Arrays.stream( getVersions( includeSnapshots ) ) - .filter( candidate -> isVersionInRestriction( restriction, candidate ) ) - .filter( candidate -> includeSnapshots || !ArtifactUtils.isSnapshot( candidate.toString() ) ) - .max( getVersionComparator() ); + Restriction restriction = new Restriction(lowerBound, allowDowngrade, upperBound, allowDowngrade); + return Arrays.stream(getVersions(includeSnapshots)) + .filter(candidate -> isVersionInRestriction(restriction, candidate)) + .filter(candidate -> includeSnapshots || !ArtifactUtils.isSnapshot(candidate.toString())) + .max(getVersionComparator()); } @Override - public final ArtifactVersion[] getVersions( Restriction restriction, boolean includeSnapshots ) - { - return getVersions( null, restriction, includeSnapshots ); + public final ArtifactVersion[] getVersions(Restriction restriction, boolean includeSnapshots) { + return getVersions(null, restriction, includeSnapshots); } @Override - public final ArtifactVersion[] getVersions( VersionRange versionRange, Restriction restriction, - boolean includeSnapshots ) - { - return Arrays.stream( getVersions( includeSnapshots ) ) - .filter( candidate -> - versionRange == null || ArtifactVersions.isVersionInRange( candidate, versionRange ) ) - .filter( candidate -> restriction == null || isVersionInRestriction( restriction, candidate ) ) - .filter( candidate -> includeSnapshots || !ArtifactUtils.isSnapshot( candidate.toString() ) ) - .sorted( getVersionComparator() ) + public final ArtifactVersion[] getVersions( + VersionRange versionRange, Restriction restriction, boolean includeSnapshots) { + return Arrays.stream(getVersions(includeSnapshots)) + .filter(candidate -> versionRange == null || ArtifactVersions.isVersionInRange(candidate, versionRange)) + .filter(candidate -> restriction == null || isVersionInRestriction(restriction, candidate)) + .filter(candidate -> includeSnapshots || !ArtifactUtils.isSnapshot(candidate.toString())) + .sorted(getVersionComparator()) .distinct() - .toArray( ArtifactVersion[]::new ); + .toArray(ArtifactVersion[]::new); } @Override - public final ArtifactVersion getNewestUpdate( ArtifactVersion currentVersion, Optional updateScope, - boolean includeSnapshots ) - { - try - { - return getNewestVersion( restrictionFor( updateScope ), - includeSnapshots ); - } - catch ( InvalidSegmentException e ) - { + public final ArtifactVersion getNewestUpdate( + ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) { + try { + return getNewestVersion(restrictionFor(updateScope), includeSnapshots); + } catch (InvalidSegmentException e) { return null; } } @Override - public final ArtifactVersion[] getAllUpdates( ArtifactVersion currentVersion, Optional updateScope, - boolean includeSnapshots ) - { - try - { - return getVersions( restrictionFor( updateScope ), - includeSnapshots ); - } - catch ( InvalidSegmentException e ) - { + public final ArtifactVersion[] getAllUpdates( + ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) { + try { + return getVersions(restrictionFor(updateScope), includeSnapshots); + } catch (InvalidSegmentException e) { return null; } } @Override - public final ArtifactVersion getNewestUpdate( Optional updateScope ) - { - return getNewestUpdate( updateScope, isIncludeSnapshots() ); + public final ArtifactVersion getNewestUpdate(Optional updateScope) { + return getNewestUpdate(updateScope, isIncludeSnapshots()); } @Override - public final ArtifactVersion[] getAllUpdates( Optional updateScope ) - { - return getAllUpdates( updateScope, isIncludeSnapshots() ); + public final ArtifactVersion[] getAllUpdates(Optional updateScope) { + return getAllUpdates(updateScope, isIncludeSnapshots()); } @Override - public final ArtifactVersion getNewestUpdate( Optional updateScope, boolean includeSnapshots ) - { - if ( isCurrentVersionDefined() ) - { - return getNewestUpdate( getCurrentVersion(), updateScope, includeSnapshots ); + public final ArtifactVersion getNewestUpdate(Optional updateScope, boolean includeSnapshots) { + if (isCurrentVersionDefined()) { + return getNewestUpdate(getCurrentVersion(), updateScope, includeSnapshots); } return null; } @Override - public final ArtifactVersion[] getAllUpdates( Optional updateScope, boolean includeSnapshots ) - { - if ( isCurrentVersionDefined() ) - { - return getAllUpdates( getCurrentVersion(), updateScope, includeSnapshots ); + public final ArtifactVersion[] getAllUpdates(Optional updateScope, boolean includeSnapshots) { + if (isCurrentVersionDefined()) { + return getAllUpdates(getCurrentVersion(), updateScope, includeSnapshots); } return null; } @Override - public final ArtifactVersion[] getAllUpdates() - { - return getAllUpdates( (VersionRange) null, isIncludeSnapshots() ); + public final ArtifactVersion[] getAllUpdates() { + return getAllUpdates((VersionRange) null, isIncludeSnapshots()); } @Override - public final ArtifactVersion[] getAllUpdates( VersionRange versionRange ) - { - return getAllUpdates( versionRange, isIncludeSnapshots() ); + public final ArtifactVersion[] getAllUpdates(VersionRange versionRange) { + return getAllUpdates(versionRange, isIncludeSnapshots()); } @Override - public ArtifactVersion[] getAllUpdates( VersionRange versionRange, boolean includeSnapshots ) - { - Restriction restriction = new Restriction( getCurrentVersion(), false, null, false ); - return getVersions( versionRange, restriction, includeSnapshots ); + public ArtifactVersion[] getAllUpdates(VersionRange versionRange, boolean includeSnapshots) { + Restriction restriction = new Restriction(getCurrentVersion(), false, null, false); + return getVersions(versionRange, restriction, includeSnapshots); } /** @@ -449,44 +387,34 @@ public ArtifactVersion[] getAllUpdates( VersionRange versionRange, boolean inclu * @throws InvalidSegmentException if the requested segment is outside of the bounds (less than 1 or greater than * the segment count) */ - protected Optional getLowerBound( ArtifactVersion version, Optional unchangedSegment ) - throws InvalidSegmentException - { - if ( !unchangedSegment.isPresent() ) - { + protected Optional getLowerBound(ArtifactVersion version, Optional unchangedSegment) + throws InvalidSegmentException { + if (!unchangedSegment.isPresent()) { return empty(); } - int segmentCount = getVersionComparator().getSegmentCount( version ); - if ( unchangedSegment.get().value() > segmentCount ) - { - throw new InvalidSegmentException( unchangedSegment.get(), segmentCount, version ); + int segmentCount = getVersionComparator().getSegmentCount(version); + if (unchangedSegment.get().value() > segmentCount) { + throw new InvalidSegmentException(unchangedSegment.get(), segmentCount, version); } StringBuilder newVersion = new StringBuilder(); - newVersion.append( version.getMajorVersion() ); + newVersion.append(version.getMajorVersion()); - if ( segmentCount > 0 ) - { - newVersion.append( "." ).append( unchangedSegment.get().value() >= 1 ? version.getMinorVersion() : 0 ); + if (segmentCount > 0) { + newVersion.append(".").append(unchangedSegment.get().value() >= 1 ? version.getMinorVersion() : 0); } - if ( segmentCount > 1 ) - { - newVersion.append( "." ) - .append( unchangedSegment.get().value() >= 2 ? version.getIncrementalVersion() : 0 ); + if (segmentCount > 1) { + newVersion.append(".").append(unchangedSegment.get().value() >= 2 ? version.getIncrementalVersion() : 0); } - if ( segmentCount > 2 ) - { - if ( version.getQualifier() != null ) - { - newVersion.append( "-" ).append( unchangedSegment.get().value() >= 3 ? version.getQualifier() : "0" ); - } - else - { - newVersion.append( "-" ).append( unchangedSegment.get().value() >= 3 ? version.getBuildNumber() : "0" ); + if (segmentCount > 2) { + if (version.getQualifier() != null) { + newVersion.append("-").append(unchangedSegment.get().value() >= 3 ? version.getQualifier() : "0"); + } else { + newVersion.append("-").append(unchangedSegment.get().value() >= 3 ? version.getBuildNumber() : "0"); } } - return of( newVersion.toString() ); + return of(newVersion.toString()); } /** @@ -497,20 +425,18 @@ protected Optional getLowerBound( ArtifactVersion version, Optional 0 || upper < 0 ) - { + int lower = lowerBound == null ? -1 : versionComparator.compare(lowerBound, candidate); + int upper = upperBound == null ? +1 : versionComparator.compare(upperBound, candidate); + if (lower > 0 || upper < 0) { return false; } - return ( includeLower || lower != 0 ) && ( includeUpper || upper != 0 ); + return (includeLower || lower != 0) && (includeUpper || upper != 0); } /** @@ -520,10 +446,10 @@ public boolean isVersionInRestriction( Restriction restriction, ArtifactVersion * @return the newest version after currentVersion within the specified update scope, * or null if no version is available. */ - public final ArtifactVersion getReportNewestUpdate( Optional updateScope ) - { - return getArtifactVersionStream( updateScope ) - .min( Collections.reverseOrder( getVersionComparator() ) ).orElse( null ); + public final ArtifactVersion getReportNewestUpdate(Optional updateScope) { + return getArtifactVersionStream(updateScope) + .min(Collections.reverseOrder(getVersionComparator())) + .orElse(null); } /** @@ -531,26 +457,21 @@ public final ArtifactVersion getReportNewestUpdate( Optional updateScop * @param updateScope the scope of updates to include. * @return all versions after currentVersion within the specified update scope. */ - public final ArtifactVersion[] getReportUpdates( Optional updateScope ) - { - TreeSet versions = getArtifactVersionStream( updateScope ) - .collect( Collectors.toCollection( () -> new TreeSet<>( getVersionComparator() ) ) ); + public final ArtifactVersion[] getReportUpdates(Optional updateScope) { + TreeSet versions = getArtifactVersionStream(updateScope) + .collect(Collectors.toCollection(() -> new TreeSet<>(getVersionComparator()))); // filter out intermediate minor versions. - if ( !verboseDetail ) - { + if (!verboseDetail) { int major = 0; int minor = 0; boolean needOneMore = false; - for ( Iterator it = versions.descendingIterator(); it.hasNext(); ) - { + for (Iterator it = versions.descendingIterator(); it.hasNext(); ) { ArtifactVersion version = it.next(); - boolean isPreview = PREVIEW_PATTERN.matcher( version.toString() ).matches(); + boolean isPreview = PREVIEW_PATTERN.matcher(version.toString()).matches(); // encountered a version in same Major.Minor version, remove it. - if ( version.getMajorVersion() == major && version.getMinorVersion() == minor ) - { - if ( needOneMore && !isPreview ) - { + if (version.getMajorVersion() == major && version.getMinorVersion() == minor) { + if (needOneMore && !isPreview) { needOneMore = false; continue; } @@ -564,10 +485,9 @@ public final ArtifactVersion[] getReportUpdates( Optional updateScope ) // if version is a pre-release, also search for the last release. needOneMore = isPreview; - } } - return versions.toArray( new ArtifactVersion[0] ); + return versions.toArray(new ArtifactVersion[0]); } /** @@ -575,24 +495,18 @@ public final ArtifactVersion[] getReportUpdates( Optional updateScope ) * @param updateScope the scope of updates to include. * @return all versions after currentVersion within the specified update scope. */ - private Stream getArtifactVersionStream( Optional updateScope ) - { - if ( isCurrentVersionDefined() ) - { - try - { - Restriction restriction = restrictionFor( updateScope ); - - return Arrays.stream( getVersions() ).filter( - candidate -> ( isIncludeSnapshots() || !ArtifactUtils.isSnapshot( candidate.toString() ) ) - && isVersionInRestriction( restriction, candidate ) ); - } - catch ( InvalidSegmentException ignored ) - { - ignored.printStackTrace( System.err ); + private Stream getArtifactVersionStream(Optional updateScope) { + if (isCurrentVersionDefined()) { + try { + Restriction restriction = restrictionFor(updateScope); + + return Arrays.stream(getVersions()) + .filter(candidate -> (isIncludeSnapshots() || !ArtifactUtils.isSnapshot(candidate.toString())) + && isVersionInRestriction(restriction, candidate)); + } catch (InvalidSegmentException ignored) { + ignored.printStackTrace(System.err); } } return Stream.empty(); } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactAssociation.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactAssociation.java index 71043e9694..794db9d4a8 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactAssociation.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactAssociation.java @@ -27,8 +27,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public interface ArtifactAssociation extends Comparable -{ +public interface ArtifactAssociation extends Comparable { String getGroupId(); String getArtifactId(); diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersions.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersions.java index 6a398891b1..a31ce9171e 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersions.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersions.java @@ -40,9 +40,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public class ArtifactVersions - extends AbstractVersionDetails implements Comparable -{ +public class ArtifactVersions extends AbstractVersionDetails implements Comparable { /** * The artifact that who's versions we hold details of. * @@ -72,15 +70,13 @@ public class ArtifactVersions * @param versionComparator The version comparison rule. * @since 1.0-alpha-3 */ - public ArtifactVersions( Artifact artifact, List versions, VersionComparator versionComparator ) - { + public ArtifactVersions(Artifact artifact, List versions, VersionComparator versionComparator) { this.artifact = artifact; this.versionComparator = versionComparator; - this.versions = new TreeSet<>( versionComparator ); - this.versions.addAll( versions ); - if ( artifact.getVersion() != null ) - { - setCurrentVersion( artifact.getVersion() ); + this.versions = new TreeSet<>(versionComparator); + this.versions.addAll(versions); + if (artifact.getVersion() != null) { + setCurrentVersion(artifact.getVersion()); } } @@ -90,59 +86,53 @@ public ArtifactVersions( Artifact artifact, List versions, Vers * @param other other object to be linked to * @since 2.13.0 */ - public ArtifactVersions( ArtifactVersions other ) - { + public ArtifactVersions(ArtifactVersions other) { artifact = other.artifact; versionComparator = other.versionComparator; versions = other.versions; - setCurrentVersion( other.getCurrentVersion() ); - setIncludeSnapshots( other.isIncludeSnapshots() ); + setCurrentVersion(other.getCurrentVersion()); + setIncludeSnapshots(other.isIncludeSnapshots()); } - @SuppressWarnings( "checkstyle:InnerAssignment" ) - public int compareTo( ArtifactVersions that ) - { + @SuppressWarnings("checkstyle:InnerAssignment") + public int compareTo(ArtifactVersions that) { int rv; return this == that ? 0 : that == null || getClass() != that.getClass() - ? 1 - : ( rv = compare( getGroupId(), that.getGroupId() ) ) != 0 - ? rv - : ( rv = compare( getArtifactId(), that.getArtifactId() ) ) != 0 - ? rv - : compare( getVersion(), that.getVersion() ); + ? 1 + : (rv = compare(getGroupId(), that.getGroupId())) != 0 + ? rv + : (rv = compare(getArtifactId(), that.getArtifactId())) != 0 + ? rv + : compare(getVersion(), that.getVersion()); } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof ArtifactVersions ) ) - { + if (!(o instanceof ArtifactVersions)) { return false; } ArtifactVersions that = (ArtifactVersions) o; return new EqualsBuilder() - .append( getArtifact(), that.getArtifact() ) - .append( getVersions(), that.getVersions() ) - .append( getVersionComparator(), that.getVersionComparator() ) + .append(getArtifact(), that.getArtifact()) + .append(getVersions(), that.getVersions()) + .append(getVersionComparator(), that.getVersionComparator()) .isEquals(); } @Override - public int hashCode() - { - return new HashCodeBuilder( 17, 37 ) - .append( getArtifact() ) - .append( getVersions() ) - .append( getVersionComparator() ) + public int hashCode() { + return new HashCodeBuilder(17, 37) + .append(getArtifact()) + .append(getVersions()) + .append(getVersionComparator()) .toHashCode(); } @@ -155,31 +145,23 @@ public int hashCode() * @return true if and only if the version is in the range. * @since 1.3 */ - public static boolean isVersionInRange( ArtifactVersion version, VersionRange range ) - { - if ( !range.containsVersion( version ) ) - { + public static boolean isVersionInRange(ArtifactVersion version, VersionRange range) { + if (!range.containsVersion(version)) { return false; } - for ( Restriction r : range.getRestrictions() ) - { - if ( r.containsVersion( version ) ) - { + for (Restriction r : range.getRestrictions()) { + if (r.containsVersion(version)) { // check for the -! syntax - if ( !r.isLowerBoundInclusive() && r.getLowerBound() != null ) - { + if (!r.isLowerBoundInclusive() && r.getLowerBound() != null) { String s = r.getLowerBound().toString(); - if ( s.endsWith( "-!" ) && version.toString().startsWith( s.substring( 0, s.length() - 2 ) ) ) - { + if (s.endsWith("-!") && version.toString().startsWith(s.substring(0, s.length() - 2))) { return false; } } - if ( !r.isUpperBoundInclusive() && r.getUpperBound() != null ) - { + if (!r.isUpperBoundInclusive() && r.getUpperBound() != null) { String s = r.getUpperBound().toString(); - if ( s.endsWith( "-!" ) && version.toString().startsWith( s.substring( 0, s.length() - 2 ) ) ) - { + if (s.endsWith("-!") && version.toString().startsWith(s.substring(0, s.length() - 2))) { return false; } } @@ -194,8 +176,7 @@ public static boolean isVersionInRange( ArtifactVersion version, VersionRange ra * @return the artifact who's version information we are holding. * @since 1.0-alpha-3 */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } @@ -205,8 +186,7 @@ public Artifact getArtifact() * @return the groupId. * @since 1.0-alpha-3 */ - public String getGroupId() - { + public String getGroupId() { return getArtifact().getGroupId(); } @@ -216,8 +196,7 @@ public String getGroupId() * @return the artifactId. * @since 1.0-alpha-3 */ - public String getArtifactId() - { + public String getArtifactId() { return getArtifact().getArtifactId(); } @@ -227,31 +206,27 @@ public String getArtifactId() * @return current version * @since 2.13.0 */ - public String getVersion() - { + public String getVersion() { return getArtifact().getVersion(); } - public ArtifactVersion[] getVersions( boolean includeSnapshots ) - { + public ArtifactVersion[] getVersions(boolean includeSnapshots) { return includeSnapshots - ? versions.toArray( new ArtifactVersion[0] ) - : versions.stream().filter( v -> !ArtifactUtils.isSnapshot( v.toString() ) ) - .toArray( ArtifactVersion[]::new ); + ? versions.toArray(new ArtifactVersion[0]) + : versions.stream() + .filter(v -> !ArtifactUtils.isSnapshot(v.toString())) + .toArray(ArtifactVersion[]::new); } - public VersionComparator getVersionComparator() - { + public VersionComparator getVersionComparator() { return versionComparator; } /** * {@inheritDoc} */ - public String toString() - { + public String toString() { return "ArtifactVersions" + "{artifact=" + artifact + ", versions=" + versions + ", versionComparator=" - + versionComparator + '}'; + + versionComparator + '}'; } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java index 9966d9a1c2..e51e91938b 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java @@ -1,6 +1,5 @@ package org.codehaus.mojo.versions.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -30,8 +29,7 @@ /** * Utility providing a cached {@link ArtifactVersions#getNewestUpdate(Optional)} API */ -public class ArtifactVersionsCache -{ +public class ArtifactVersionsCache { private BiFunction, ?> cachedFunction; private Map>, Object> updateCache = new HashMap<>(); @@ -41,9 +39,7 @@ public class ArtifactVersionsCache * * @param cachedFunction reference to the function computing the required information */ - public ArtifactVersionsCache( BiFunction, ?> - cachedFunction ) - { + public ArtifactVersionsCache(BiFunction, ?> cachedFunction) { this.cachedFunction = cachedFunction; } @@ -58,11 +54,9 @@ public ArtifactVersionsCache( BiFunction R get( V artifactVersions, - Optional updateScope ) - { - return (R) updateCache.computeIfAbsent( Pair.of( artifactVersions, updateScope ), - pair -> cachedFunction.apply( pair.getLeft(), pair.getRight() ) ); + @SuppressWarnings("unchecked") + public R get(V artifactVersions, Optional updateScope) { + return (R) updateCache.computeIfAbsent( + Pair.of(artifactVersions, updateScope), pair -> cachedFunction.apply(pair.getLeft(), pair.getRight())); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultArtifactAssociation.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultArtifactAssociation.java index e75ee3525b..69e281ef00 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultArtifactAssociation.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultArtifactAssociation.java @@ -30,104 +30,83 @@ * @author connollys * @since Aug 6, 2009 9:23:13 AM */ -final class DefaultArtifactAssociation - implements ArtifactAssociation -{ +final class DefaultArtifactAssociation implements ArtifactAssociation { private final Artifact artifact; private final boolean usePluginRepositories; - DefaultArtifactAssociation( Artifact artifact, boolean usePluginRepositories ) - { - Objects.requireNonNull( artifact ); + DefaultArtifactAssociation(Artifact artifact, boolean usePluginRepositories) { + Objects.requireNonNull(artifact); this.artifact = artifact; this.usePluginRepositories = usePluginRepositories; } - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } - - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public boolean isUsePluginRepositories() - { + public boolean isUsePluginRepositories() { return usePluginRepositories; } - public int compareTo( ArtifactAssociation o ) - { - if ( this == o ) - { + public int compareTo(ArtifactAssociation o) { + if (this == o) { return 0; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return 1; } DefaultArtifactAssociation that = (DefaultArtifactAssociation) o; - int rv = getGroupId().compareTo( that.getGroupId() ); - if ( rv != 0 ) - { + int rv = getGroupId().compareTo(that.getGroupId()); + if (rv != 0) { return rv; } - rv = getArtifactId().compareTo( that.getArtifactId() ); - if ( rv != 0 ) - { + rv = getArtifactId().compareTo(that.getArtifactId()); + if (rv != 0) { return rv; } - if ( usePluginRepositories != that.usePluginRepositories ) - { + if (usePluginRepositories != that.usePluginRepositories) { return usePluginRepositories ? 1 : -1; } return 0; } - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } DefaultArtifactAssociation that = (DefaultArtifactAssociation) o; - if ( usePluginRepositories != that.usePluginRepositories ) - { + if (usePluginRepositories != that.usePluginRepositories) { return false; } - if ( !getArtifactId().equals( that.getArtifactId() ) ) - { + if (!getArtifactId().equals(that.getArtifactId())) { return false; } - return getGroupId().equals( that.getGroupId() ); + return getGroupId().equals(that.getGroupId()); } - public int hashCode() - { + public int hashCode() { int result = getGroupId().hashCode(); result = 31 * result + getArtifactId().hashCode(); - result = 31 * result + ( usePluginRepositories ? 1 : 0 ); + result = 31 * result + (usePluginRepositories ? 1 : 0); return result; } - public String toString() - { - return ( usePluginRepositories ? "plugin:" : "artifact:" ) + ArtifactUtils.versionlessKey( artifact ); + public String toString() { + return (usePluginRepositories ? "plugin:" : "artifact:") + ArtifactUtils.versionlessKey(artifact); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java index cc55e3f379..f2b0687859 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java @@ -100,9 +100,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public class DefaultVersionsHelper - implements VersionsHelper -{ +public class DefaultVersionsHelper implements VersionsHelper { private static final String CLASSPATH_PROTOCOL = "classpath"; private static final String TYPE_EXACT = "exact"; @@ -148,105 +146,94 @@ public class DefaultVersionsHelper /** * Private constructor used by the builder */ - private DefaultVersionsHelper() - { - } + private DefaultVersionsHelper() {} - static boolean exactMatch( String wildcardRule, String value ) - { - Pattern p = Pattern.compile( RegexUtils.convertWildcardsToRegex( wildcardRule, true ) ); - return p.matcher( value ).matches(); + static boolean exactMatch(String wildcardRule, String value) { + Pattern p = Pattern.compile(RegexUtils.convertWildcardsToRegex(wildcardRule, true)); + return p.matcher(value).matches(); } - static boolean match( String wildcardRule, String value ) - { - Pattern p = Pattern.compile( RegexUtils.convertWildcardsToRegex( wildcardRule, false ) ); - return p.matcher( value ).matches(); + static boolean match(String wildcardRule, String value) { + Pattern p = Pattern.compile(RegexUtils.convertWildcardsToRegex(wildcardRule, false)); + return p.matcher(value).matches(); } - static boolean isClasspathUri( String uri ) - { - return ( uri != null && uri.startsWith( CLASSPATH_PROTOCOL + ":" ) ); + static boolean isClasspathUri(String uri) { + return (uri != null && uri.startsWith(CLASSPATH_PROTOCOL + ":")); } @Override - public Log getLog() - { + public Log getLog() { return log; } @Override - public ArtifactVersions lookupArtifactVersions( Artifact artifact, VersionRange versionRange, - boolean usePluginRepositories ) - throws VersionRetrievalException - { - try - { - Collection ignoredVersions = getIgnoredVersions( artifact ); - if ( !ignoredVersions.isEmpty() && getLog().isDebugEnabled() ) - { - getLog().debug( "Found ignored versions: " + ignoredVersions.stream() - .map( IgnoreVersion::toString ).collect( Collectors.joining( ", " ) ) ); - } - return new ArtifactVersions( artifact, - aetherRepositorySystem.resolveVersionRange( mavenSession.getRepositorySession(), + public ArtifactVersions lookupArtifactVersions( + Artifact artifact, VersionRange versionRange, boolean usePluginRepositories) + throws VersionRetrievalException { + try { + Collection ignoredVersions = getIgnoredVersions(artifact); + if (!ignoredVersions.isEmpty() && getLog().isDebugEnabled()) { + getLog().debug("Found ignored versions: " + + ignoredVersions.stream().map(IgnoreVersion::toString).collect(Collectors.joining(", "))); + } + return new ArtifactVersions( + artifact, + aetherRepositorySystem + .resolveVersionRange( + mavenSession.getRepositorySession(), new VersionRangeRequest( - toArtifact( artifact ).setVersion( - versionRange != null - ? versionRange.toString() - : "(,)" ), + toArtifact(artifact) + .setVersion(versionRange != null ? versionRange.toString() : "(,)"), usePluginRepositories - ? mavenSession.getCurrentProject().getRemotePluginRepositories() - : mavenSession.getCurrentProject().getRemoteProjectRepositories(), - "lookupArtifactVersions" ) ) + ? mavenSession + .getCurrentProject() + .getRemotePluginRepositories() + : mavenSession + .getCurrentProject() + .getRemoteProjectRepositories(), + "lookupArtifactVersions")) .getVersions() .parallelStream() - .filter( v -> ignoredVersions.stream() - .noneMatch( i -> - { - if ( TYPE_REGEX.equals( i.getType() ) - && Pattern.compile( i.getVersion() ).matcher( v.toString() ).matches() ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Version " + v + " for artifact " - + ArtifactUtils.versionlessKey( artifact ) - + " found on ignore list: " - + i ); - } - return true; - } - - if ( TYPE_EXACT.equals( i.getType() ) - && i.getVersion().equals( v.toString() ) ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Version " + v + " for artifact " - + ArtifactUtils.versionlessKey( artifact ) - + " found on ignore list: " - + i ); - } - return true; - } - - return false; - } ) ) - .map( v -> new DefaultArtifactVersion( v.toString() ) ) - .collect( Collectors.toList() ), - getVersionComparator( artifact ) ); - } - catch ( VersionRangeResolutionException e ) - { - throw new VersionRetrievalException( e.getMessage(), e ); + .filter(v -> ignoredVersions.stream().noneMatch(i -> { + if (TYPE_REGEX.equals(i.getType()) + && Pattern.compile(i.getVersion()) + .matcher(v.toString()) + .matches()) { + if (getLog().isDebugEnabled()) { + getLog().debug("Version " + v + " for artifact " + + ArtifactUtils.versionlessKey(artifact) + + " found on ignore list: " + + i); + } + return true; + } + + if (TYPE_EXACT.equals(i.getType()) + && i.getVersion().equals(v.toString())) { + if (getLog().isDebugEnabled()) { + getLog().debug("Version " + v + " for artifact " + + ArtifactUtils.versionlessKey(artifact) + + " found on ignore list: " + + i); + } + return true; + } + + return false; + })) + .map(v -> new DefaultArtifactVersion(v.toString())) + .collect(Collectors.toList()), + getVersionComparator(artifact)); + } catch (VersionRangeResolutionException e) { + throw new VersionRetrievalException(e.getMessage(), e); } } @Override - public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories ) - throws VersionRetrievalException - { - return lookupArtifactVersions( artifact, null, usePluginRepositories ); + public ArtifactVersions lookupArtifactVersions(Artifact artifact, boolean usePluginRepositories) + throws VersionRetrievalException { + return lookupArtifactVersions(artifact, null, usePluginRepositories); } /** @@ -255,39 +242,29 @@ public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePl * @param artifact The artifact * @return List of ignored version */ - private List getIgnoredVersions( Artifact artifact ) - { + private List getIgnoredVersions(Artifact artifact) { final List ret = new ArrayList<>(); - for ( final IgnoreVersion ignoreVersion : ruleSet.getIgnoreVersions() ) - { - if ( !TYPE_EXACT.equals( ignoreVersion.getType() ) && !TYPE_REGEX.equals( ignoreVersion.getType() ) ) - { - getLog().warn( "The type attribute '" + ignoreVersion.getType() + "' for global ignoreVersion[" - + ignoreVersion + "] is not valid." + " Please use either '" + TYPE_EXACT + "' or '" - + TYPE_REGEX - + "'." ); - } - else - { - ret.add( ignoreVersion ); + for (final IgnoreVersion ignoreVersion : ruleSet.getIgnoreVersions()) { + if (!TYPE_EXACT.equals(ignoreVersion.getType()) && !TYPE_REGEX.equals(ignoreVersion.getType())) { + getLog().warn("The type attribute '" + ignoreVersion.getType() + "' for global ignoreVersion[" + + ignoreVersion + "] is not valid." + " Please use either '" + TYPE_EXACT + "' or '" + + TYPE_REGEX + + "'."); + } else { + ret.add(ignoreVersion); } } - final Rule rule = getBestFitRule( artifact.getGroupId(), artifact.getArtifactId() ); + final Rule rule = getBestFitRule(artifact.getGroupId(), artifact.getArtifactId()); - if ( rule != null ) - { - for ( IgnoreVersion ignoreVersion : rule.getIgnoreVersions() ) - { - if ( !TYPE_EXACT.equals( ignoreVersion.getType() ) && !TYPE_REGEX.equals( ignoreVersion.getType() ) ) - { - getLog().warn( "The type attribute '" + ignoreVersion.getType() + "' for " + rule + " is not valid." - + " Please use either '" + TYPE_EXACT + "' or '" + TYPE_REGEX + "'." ); - } - else - { - ret.add( ignoreVersion ); + if (rule != null) { + for (IgnoreVersion ignoreVersion : rule.getIgnoreVersions()) { + if (!TYPE_EXACT.equals(ignoreVersion.getType()) && !TYPE_REGEX.equals(ignoreVersion.getType())) { + getLog().warn("The type attribute '" + ignoreVersion.getType() + "' for " + rule + " is not valid." + + " Please use either '" + TYPE_EXACT + "' or '" + TYPE_REGEX + "'."); + } else { + ret.add(ignoreVersion); } } } @@ -296,39 +273,34 @@ private List getIgnoredVersions( Artifact artifact ) } @Override - public void resolveArtifact( Artifact artifact, boolean usePluginRepositories ) - throws ArtifactResolutionException - { - try - { - ArtifactResult artifactResult = aetherRepositorySystem.resolveArtifact( mavenSession.getRepositorySession(), - new ArtifactRequest( toArtifact( artifact ), + public void resolveArtifact(Artifact artifact, boolean usePluginRepositories) throws ArtifactResolutionException { + try { + ArtifactResult artifactResult = aetherRepositorySystem.resolveArtifact( + mavenSession.getRepositorySession(), + new ArtifactRequest( + toArtifact(artifact), usePluginRepositories ? mavenSession.getCurrentProject().getRemotePluginRepositories() : mavenSession.getCurrentProject().getRemoteProjectRepositories(), - getClass().getName() ) ); - artifact.setFile( artifactResult.getArtifact().getFile() ); - artifact.setVersion( artifactResult.getArtifact().getVersion() ); - artifact.setResolved( artifactResult.isResolved() ); - } - catch ( org.eclipse.aether.resolution.ArtifactResolutionException e ) - { - throw new ArtifactResolutionException( e.getMessage(), artifact ); + getClass().getName())); + artifact.setFile(artifactResult.getArtifact().getFile()); + artifact.setVersion(artifactResult.getArtifact().getVersion()); + artifact.setResolved(artifactResult.isResolved()); + } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) { + throw new ArtifactResolutionException(e.getMessage(), artifact); } } @Override - public VersionComparator getVersionComparator( Artifact artifact ) - { - return getVersionComparator( artifact.getGroupId(), artifact.getArtifactId() ); + public VersionComparator getVersionComparator(Artifact artifact) { + return getVersionComparator(artifact.getGroupId(), artifact.getArtifactId()); } @Override - public VersionComparator getVersionComparator( String groupId, String artifactId ) - { - Rule rule = getBestFitRule( groupId, artifactId ); + public VersionComparator getVersionComparator(String groupId, String artifactId) { + Rule rule = getBestFitRule(groupId, artifactId); final String comparisonMethod = rule == null ? ruleSet.getComparisonMethod() : rule.getComparisonMethod(); - return VersionComparators.getVersionComparator( comparisonMethod ); + return VersionComparators.getVersionComparator(comparisonMethod); } /** @@ -338,12 +310,10 @@ public VersionComparator getVersionComparator( String groupId, String artifactId * @param artifactId Artifact id of the artifact * @return Rule which best describes the given artifact */ - protected Rule getBestFitRule( String groupId, String artifactId ) - { + protected Rule getBestFitRule(String groupId, String artifactId) { String groupArtifactId = groupId + ':' + artifactId; - if ( artifactBestFitRule.containsKey( groupArtifactId ) ) - { - return artifactBestFitRule.get( groupArtifactId ); + if (artifactBestFitRule.containsKey(groupArtifactId)) { + return artifactBestFitRule.get(groupArtifactId); } Rule bestFit = null; @@ -352,114 +322,104 @@ protected Rule getBestFitRule( String groupId, String artifactId ) int bestArtifactIdScore = Integer.MAX_VALUE; boolean exactGroupId = false; boolean exactArtifactId = false; - for ( Rule rule : rules ) - { - int groupIdScore = RegexUtils.getWildcardScore( rule.getGroupId() ); - if ( groupIdScore > bestGroupIdScore ) - { + for (Rule rule : rules) { + int groupIdScore = RegexUtils.getWildcardScore(rule.getGroupId()); + if (groupIdScore > bestGroupIdScore) { continue; } - boolean exactMatch = exactMatch( rule.getGroupId(), groupId ); - boolean match = exactMatch || match( rule.getGroupId(), groupId ); - if ( !match || ( exactGroupId && !exactMatch ) ) - { + boolean exactMatch = exactMatch(rule.getGroupId(), groupId); + boolean match = exactMatch || match(rule.getGroupId(), groupId); + if (!match || (exactGroupId && !exactMatch)) { continue; } - if ( bestGroupIdScore > groupIdScore ) - { + if (bestGroupIdScore > groupIdScore) { bestArtifactIdScore = Integer.MAX_VALUE; exactArtifactId = false; } bestGroupIdScore = groupIdScore; - if ( exactMatch && !exactGroupId ) - { + if (exactMatch && !exactGroupId) { exactGroupId = true; bestArtifactIdScore = Integer.MAX_VALUE; exactArtifactId = false; } - int artifactIdScore = RegexUtils.getWildcardScore( rule.getArtifactId() ); - if ( artifactIdScore > bestArtifactIdScore ) - { + int artifactIdScore = RegexUtils.getWildcardScore(rule.getArtifactId()); + if (artifactIdScore > bestArtifactIdScore) { continue; } - exactMatch = exactMatch( rule.getArtifactId(), artifactId ); - match = exactMatch || match( rule.getArtifactId(), artifactId ); - if ( !match || ( exactArtifactId && !exactMatch ) ) - { + exactMatch = exactMatch(rule.getArtifactId(), artifactId); + match = exactMatch || match(rule.getArtifactId(), artifactId); + if (!match || (exactArtifactId && !exactMatch)) { continue; } bestArtifactIdScore = artifactIdScore; - if ( exactMatch && !exactArtifactId ) - { + if (exactMatch && !exactArtifactId) { exactArtifactId = true; } bestFit = rule; } - artifactBestFitRule.put( groupArtifactId, bestFit ); + artifactBestFitRule.put(groupArtifactId, bestFit); return bestFit; } @Override - public Artifact createPluginArtifact( String groupId, String artifactId, String version ) - { + public Artifact createPluginArtifact(String groupId, String artifactId, String version) { Plugin plugin = new Plugin(); - plugin.setGroupId( groupId ); - plugin.setArtifactId( artifactId ); - plugin.setVersion( StringUtils.isNotBlank( version ) ? version : "[0,]" ); - return repositorySystem.createPluginArtifact( plugin ); + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); + plugin.setVersion(StringUtils.isNotBlank(version) ? version : "[0,]"); + return repositorySystem.createPluginArtifact(plugin); } @Override - public Artifact createDependencyArtifact( String groupId, String artifactId, String version, String type, - String classifier, String scope, boolean optional ) - { - return repositorySystem.createDependencyArtifact( DependencyBuilder.newBuilder() - .withGroupId( groupId ) - .withArtifactId( artifactId ) - .withType( type ) - .withClassifier( classifier ) - .withScope( scope ) - .withOptional( optional ) - .withVersion( StringUtils.isNotBlank( version ) ? version : "[0,]" ) - .build() ); + public Artifact createDependencyArtifact( + String groupId, + String artifactId, + String version, + String type, + String classifier, + String scope, + boolean optional) { + return repositorySystem.createDependencyArtifact(DependencyBuilder.newBuilder() + .withGroupId(groupId) + .withArtifactId(artifactId) + .withType(type) + .withClassifier(classifier) + .withScope(scope) + .withOptional(optional) + .withVersion(StringUtils.isNotBlank(version) ? version : "[0,]") + .build()); } @Override - public Artifact createDependencyArtifact( String groupId, String artifactId, String version, String type, - String classifier, String scope ) - { - return createDependencyArtifact( groupId, artifactId, version, type, classifier, scope, false ); + public Artifact createDependencyArtifact( + String groupId, String artifactId, String version, String type, String classifier, String scope) { + return createDependencyArtifact(groupId, artifactId, version, type, classifier, scope, false); } @Override - public Artifact createDependencyArtifact( Dependency dependency ) - { - if ( StringUtils.isBlank( dependency.getVersion() ) ) - { + public Artifact createDependencyArtifact(Dependency dependency) { + if (StringUtils.isBlank(dependency.getVersion())) { dependency = dependency.clone(); - dependency.setVersion( "[,0]" ); + dependency.setVersion("[,0]"); } - return repositorySystem.createDependencyArtifact( dependency ); + return repositorySystem.createDependencyArtifact(dependency); } @Override - public Set extractArtifacts( Collection mavenProjects ) - { + public Set extractArtifacts(Collection mavenProjects) { Set result = new HashSet<>(); - for ( MavenProject project : mavenProjects ) - { - result.add( project.getArtifact() ); + for (MavenProject project : mavenProjects) { + result.add(project.getArtifact()); } return result; } @Override - public ArtifactVersion createArtifactVersion( String version ) - { - return new DefaultArtifactVersion( version ); + public ArtifactVersion createArtifactVersion(String version) { + return new DefaultArtifactVersion(version); } /** @@ -471,219 +431,179 @@ public ArtifactVersion createArtifactVersion( String version ) * @return map containing the ArtifactVersions object per dependency */ @Override - public Map lookupDependenciesUpdates( Set dependencies, - boolean usePluginRepositories ) - throws VersionRetrievalException - { - ExecutorService executor = Executors.newFixedThreadPool( LOOKUP_PARALLEL_THREADS ); - try - { - Map dependencyUpdates = new TreeMap<>( DependencyComparator.INSTANCE ); + public Map lookupDependenciesUpdates( + Set dependencies, boolean usePluginRepositories) throws VersionRetrievalException { + ExecutorService executor = Executors.newFixedThreadPool(LOOKUP_PARALLEL_THREADS); + try { + Map dependencyUpdates = new TreeMap<>(DependencyComparator.INSTANCE); List>> futures = dependencies.stream() - .map( dependency -> executor.submit( () -> new ImmutablePair<> - ( dependency, lookupDependencyUpdates( dependency, usePluginRepositories ) ) ) ) - .collect( Collectors.toList() ); - for ( Future> details : futures ) - { + .map(dependency -> executor.submit(() -> new ImmutablePair<>( + dependency, lookupDependencyUpdates(dependency, usePluginRepositories)))) + .collect(Collectors.toList()); + for (Future> details : futures) { Pair pair = details.get(); - dependencyUpdates.put( pair.getKey(), pair.getValue() ); + dependencyUpdates.put(pair.getKey(), pair.getValue()); } return dependencyUpdates; - } - catch ( ExecutionException | InterruptedException ie ) - { - throw new VersionRetrievalException( "Unable to acquire metadata for dependencies " - + dependencies + ": " + ie.getMessage(), ie ); - } - finally - { + } catch (ExecutionException | InterruptedException ie) { + throw new VersionRetrievalException( + "Unable to acquire metadata for dependencies " + dependencies + ": " + ie.getMessage(), ie); + } finally { executor.shutdown(); } } @Override - public ArtifactVersions lookupDependencyUpdates( Dependency dependency, boolean usePluginRepositories ) - throws VersionRetrievalException - { - ArtifactVersions allVersions = lookupArtifactVersions( createDependencyArtifact( dependency ), - usePluginRepositories ); - return new ArtifactVersions( allVersions.getArtifact(), Arrays.stream( allVersions.getAllUpdates() ) - .collect( Collectors.toList() ), allVersions.getVersionComparator() ); + public ArtifactVersions lookupDependencyUpdates(Dependency dependency, boolean usePluginRepositories) + throws VersionRetrievalException { + ArtifactVersions allVersions = + lookupArtifactVersions(createDependencyArtifact(dependency), usePluginRepositories); + return new ArtifactVersions( + allVersions.getArtifact(), + Arrays.stream(allVersions.getAllUpdates()).collect(Collectors.toList()), + allVersions.getVersionComparator()); } @Override - public Map lookupPluginsUpdates( Set plugins, boolean allowSnapshots ) - throws VersionRetrievalException - { - ExecutorService executor = Executors.newFixedThreadPool( LOOKUP_PARALLEL_THREADS ); - try - { - Map pluginUpdates = new TreeMap<>( PluginComparator.INSTANCE ); + public Map lookupPluginsUpdates(Set plugins, boolean allowSnapshots) + throws VersionRetrievalException { + ExecutorService executor = Executors.newFixedThreadPool(LOOKUP_PARALLEL_THREADS); + try { + Map pluginUpdates = new TreeMap<>(PluginComparator.INSTANCE); List>> futures = plugins.stream() - .map( p -> executor.submit( () -> new ImmutablePair<> - ( p, lookupPluginUpdates( p, allowSnapshots ) ) ) ) - .collect( Collectors.toList() ); - for ( Future> details : futures ) - { + .map(p -> executor.submit(() -> new ImmutablePair<>(p, lookupPluginUpdates(p, allowSnapshots)))) + .collect(Collectors.toList()); + for (Future> details : futures) { Pair pair = details.get(); - pluginUpdates.put( pair.getKey(), pair.getValue() ); + pluginUpdates.put(pair.getKey(), pair.getValue()); } return pluginUpdates; - } - catch ( ExecutionException | InterruptedException ie ) - { - throw new VersionRetrievalException( "Unable to acquire metadata for plugins " + plugins + ": " - + ie.getMessage(), ie ); - } - finally - { + } catch (ExecutionException | InterruptedException ie) { + throw new VersionRetrievalException( + "Unable to acquire metadata for plugins " + plugins + ": " + ie.getMessage(), ie); + } finally { executor.shutdown(); } } @Override - public PluginUpdatesDetails lookupPluginUpdates( Plugin plugin, boolean allowSnapshots ) - throws VersionRetrievalException - { - String version = plugin.getVersion() != null - ? plugin.getVersion() - : "LATEST"; - - Set pluginDependencies = new TreeSet<>( DependencyComparator.INSTANCE ); - if ( plugin.getDependencies() != null ) - { - pluginDependencies.addAll( plugin.getDependencies() ); + public PluginUpdatesDetails lookupPluginUpdates(Plugin plugin, boolean allowSnapshots) + throws VersionRetrievalException { + String version = plugin.getVersion() != null ? plugin.getVersion() : "LATEST"; + + Set pluginDependencies = new TreeSet<>(DependencyComparator.INSTANCE); + if (plugin.getDependencies() != null) { + pluginDependencies.addAll(plugin.getDependencies()); } Map pluginDependencyDetails = - lookupDependenciesUpdates( pluginDependencies, false ); - - ArtifactVersions allVersions = - lookupArtifactVersions( createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), version ), - true ); - ArtifactVersions updatedVersions = new ArtifactVersions( allVersions.getArtifact(), - Arrays.stream( allVersions.getAllUpdates() ).collect( Collectors.toList() ), - allVersions.getVersionComparator() ); - return new PluginUpdatesDetails( updatedVersions, pluginDependencyDetails, allowSnapshots ); + lookupDependenciesUpdates(pluginDependencies, false); + + ArtifactVersions allVersions = lookupArtifactVersions( + createPluginArtifact(plugin.getGroupId(), plugin.getArtifactId(), version), true); + ArtifactVersions updatedVersions = new ArtifactVersions( + allVersions.getArtifact(), + Arrays.stream(allVersions.getAllUpdates()).collect(Collectors.toList()), + allVersions.getVersionComparator()); + return new PluginUpdatesDetails(updatedVersions, pluginDependencyDetails, allowSnapshots); } @Override - public ExpressionEvaluator getExpressionEvaluator( MavenProject project ) - { - return new VersionsExpressionEvaluator( mavenSession, mojoExecution ); + public ExpressionEvaluator getExpressionEvaluator(MavenProject project) { + return new VersionsExpressionEvaluator(mavenSession, mojoExecution); } @Override - public Map getVersionPropertiesMap( VersionPropertiesMapRequest request ) - throws MojoExecutionException - { + public Map getVersionPropertiesMap(VersionPropertiesMapRequest request) + throws MojoExecutionException { Map properties = new HashMap<>(); - if ( request.getPropertyDefinitions() != null ) - { - Arrays.stream( request.getPropertyDefinitions() ).forEach( p -> properties.put( p.getName(), p ) ); + if (request.getPropertyDefinitions() != null) { + Arrays.stream(request.getPropertyDefinitions()).forEach(p -> properties.put(p.getName(), p)); } Map builders = new HashMap<>(); - if ( request.isAutoLinkItems() ) - { + if (request.isAutoLinkItems()) { final PropertyVersionsBuilder[] propertyVersionsBuilders; - try - { - propertyVersionsBuilders = PomHelper.getPropertyVersionsBuilders( this, request.getMavenProject(), - request.isIncludeParent() ); - } - catch ( ExpressionEvaluationException | IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + propertyVersionsBuilders = PomHelper.getPropertyVersionsBuilders( + this, request.getMavenProject(), request.isIncludeParent()); + } catch (ExpressionEvaluationException | IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } - for ( PropertyVersionsBuilder propertyVersionsBuilder : propertyVersionsBuilders ) - { + for (PropertyVersionsBuilder propertyVersionsBuilder : propertyVersionsBuilders) { final String name = propertyVersionsBuilder.getName(); - builders.put( name, propertyVersionsBuilder ); - if ( !properties.containsKey( name ) ) - { - final Property value = new Property( name ); - getLog().debug( "Property ${" + name + "}: Adding inferred version range of " - + propertyVersionsBuilder.getVersionRange() ); - value.setVersion( propertyVersionsBuilder.getVersionRange() ); - properties.put( name, value ); + builders.put(name, propertyVersionsBuilder); + if (!properties.containsKey(name)) { + final Property value = new Property(name); + getLog().debug("Property ${" + name + "}: Adding inferred version range of " + + propertyVersionsBuilder.getVersionRange()); + value.setVersion(propertyVersionsBuilder.getVersionRange()); + properties.put(name, value); } } } List includePropertiesList = request.getIncludeProperties() != null - ? Arrays.asList( request.getIncludeProperties().split( "\\s*,\\s*" ) ) - : Collections.emptyList(); + ? Arrays.asList(request.getIncludeProperties().split("\\s*,\\s*")) + : Collections.emptyList(); List excludePropertiesList = request.getExcludeProperties() != null - ? Arrays.asList( request.getExcludeProperties().split( "\\s*,\\s*" ) ) + ? Arrays.asList(request.getExcludeProperties().split("\\s*,\\s*")) : Collections.emptyList(); - getLog().debug( "Searching for properties associated with builders" ); + getLog().debug("Searching for properties associated with builders"); Iterator i = properties.values().iterator(); - while ( i.hasNext() ) - { + while (i.hasNext()) { Property property = i.next(); - getLog().debug( "includePropertiesList:" + includePropertiesList + " property: " + property.getName() ); - getLog().debug( "excludePropertiesList:" + excludePropertiesList + " property: " + property.getName() ); - if ( !includePropertiesList.isEmpty() && !includePropertiesList.contains( property.getName() ) ) - { - getLog().debug( "Skipping property ${" + property.getName() + "}" ); + getLog().debug("includePropertiesList:" + includePropertiesList + " property: " + property.getName()); + getLog().debug("excludePropertiesList:" + excludePropertiesList + " property: " + property.getName()); + if (!includePropertiesList.isEmpty() && !includePropertiesList.contains(property.getName())) { + getLog().debug("Skipping property ${" + property.getName() + "}"); i.remove(); - } - else if ( !excludePropertiesList.isEmpty() && excludePropertiesList.contains( property.getName() ) ) - { - getLog().debug( "Ignoring property ${" + property.getName() + "}" ); + } else if (!excludePropertiesList.isEmpty() && excludePropertiesList.contains(property.getName())) { + getLog().debug("Ignoring property ${" + property.getName() + "}"); i.remove(); } } i = properties.values().iterator(); - Map propertyVersions = new LinkedHashMap<>( properties.size() ); - while ( i.hasNext() ) - { + Map propertyVersions = new LinkedHashMap<>(properties.size()); + while (i.hasNext()) { Property property = i.next(); - getLog().debug( "Property ${" + property.getName() + "}" ); - PropertyVersionsBuilder builder = builders.get( property.getName() ); - if ( builder == null || !builder.isAssociated() ) - { - getLog().debug( "Property ${" + property.getName() + "}: Looks like this property is not " - + "associated with any dependency..." ); - builder = new PropertyVersionsBuilder( null, property.getName(), this ); - } - if ( !property.isAutoLinkDependencies() ) - { - getLog().debug( "Property ${" + property.getName() + "}: Removing any autoLinkDependencies" ); + getLog().debug("Property ${" + property.getName() + "}"); + PropertyVersionsBuilder builder = builders.get(property.getName()); + if (builder == null || !builder.isAssociated()) { + getLog().debug("Property ${" + property.getName() + "}: Looks like this property is not " + + "associated with any dependency..."); + builder = new PropertyVersionsBuilder(null, property.getName(), this); + } + if (!property.isAutoLinkDependencies()) { + getLog().debug("Property ${" + property.getName() + "}: Removing any autoLinkDependencies"); builder.clearAssociations(); } Dependency[] dependencies = property.getDependencies(); - if ( dependencies != null ) - { - for ( Dependency dependency : dependencies ) - { - getLog().debug( "Property ${" + property.getName() + "}: Adding association to " + dependency ); - builder.addAssociation( this.createDependencyArtifact( dependency ), false ); + if (dependencies != null) { + for (Dependency dependency : dependencies) { + getLog().debug("Property ${" + property.getName() + "}: Adding association to " + dependency); + builder.addAssociation(this.createDependencyArtifact(dependency), false); } } - try - { + try { final PropertyVersions versions = builder.newPropertyVersions(); - if ( property.isAutoLinkDependencies() && StringUtils.isEmpty( property.getVersion() ) - && !StringUtils.isEmpty( builder.getVersionRange() ) ) - { - getLog().debug( "Property ${" + property.getName() + "}: Adding inferred version range of " - + builder.getVersionRange() ); - property.setVersion( builder.getVersionRange() ); + if (property.isAutoLinkDependencies() + && StringUtils.isEmpty(property.getVersion()) + && !StringUtils.isEmpty(builder.getVersionRange())) { + getLog().debug("Property ${" + property.getName() + "}: Adding inferred version range of " + + builder.getVersionRange()); + property.setVersion(builder.getVersionRange()); } - final String currentVersion = request.getMavenProject().getProperties() - .getProperty( property.getName() ); - versions.setCurrentVersion( currentVersion ); - property.setValue( currentVersion ); - propertyVersions.put( property, versions ); - } - catch ( VersionRetrievalException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + final String currentVersion = + request.getMavenProject().getProperties().getProperty(property.getName()); + versions.setCurrentVersion(currentVersion); + property.setValue(currentVersion); + propertyVersions.put(property, versions); + } catch (VersionRetrievalException e) { + throw new MojoExecutionException(e.getMessage(), e); } } return propertyVersions; @@ -692,8 +612,7 @@ else if ( !excludePropertiesList.isEmpty() && excludePropertiesList.contains( pr /** * Builder class for {@linkplain DefaultVersionsHelper} */ - public static class Builder - { + public static class Builder { private RepositorySystem repositorySystem; private Collection ignoredVersions; private RuleSet ruleSet; @@ -705,30 +624,22 @@ public static class Builder private org.eclipse.aether.RepositorySystem aetherRepositorySystem; private Map wagonMap; - public Builder() - { - } + public Builder() {} - private static RuleSet getRulesFromClasspath( String uri, Log logger ) - throws MojoExecutionException - { - logger.debug( "Going to load rules from \"" + uri + "\"" ); - String choppedUrl = uri.substring( CLASSPATH_PROTOCOL.length() + 3 ); - URL url = DefaultVersionsHelper.class.getResource( choppedUrl ); - if ( url == null ) - { - throw new MojoExecutionException( "Resource \"" + uri + "\" not found in classpath." ); + private static RuleSet getRulesFromClasspath(String uri, Log logger) throws MojoExecutionException { + logger.debug("Going to load rules from \"" + uri + "\""); + String choppedUrl = uri.substring(CLASSPATH_PROTOCOL.length() + 3); + URL url = DefaultVersionsHelper.class.getResource(choppedUrl); + if (url == null) { + throw new MojoExecutionException("Resource \"" + uri + "\" not found in classpath."); } - try ( BufferedInputStream bis = new BufferedInputStream( url.openStream() ) ) - { - RuleSet result = new RuleXpp3Reader().read( bis ); - logger.debug( "Loaded rules from \"" + uri + "\" successfully" ); + try (BufferedInputStream bis = new BufferedInputStream(url.openStream())) { + RuleSet result = new RuleXpp3Reader().read(bis); + logger.debug("Loaded rules from \"" + uri + "\" successfully"); return result; - } - catch ( IOException | XmlPullParserException e ) - { - throw new MojoExecutionException( "Could not load specified rules from " + uri, e ); + } catch (IOException | XmlPullParserException e) { + throw new MojoExecutionException("Could not load specified rules from " + uri, e); } } @@ -746,257 +657,217 @@ private static RuleSet getRulesFromClasspath( String uri, Log logger ) * @return new RuleSet object containing the (if passed) cloned version of the rule set, enriched with * the given set of ignored versions */ - @SuppressWarnings( "checkstyle:AvoidNestedBlocks" ) - private static RuleSet enrichRuleSet( Collection ignoredVersions, RuleSet originalRuleSet ) - { + @SuppressWarnings("checkstyle:AvoidNestedBlocks") + private static RuleSet enrichRuleSet(Collection ignoredVersions, RuleSet originalRuleSet) { RuleSet ruleSet = new RuleSet(); - if ( originalRuleSet != null ) - { - ruleSet.setComparisonMethod( originalRuleSet.getComparisonMethod() ); - if ( originalRuleSet.getRules() != null ) - { - ruleSet.setRules( new ArrayList<>( originalRuleSet.getRules() ) ); + if (originalRuleSet != null) { + ruleSet.setComparisonMethod(originalRuleSet.getComparisonMethod()); + if (originalRuleSet.getRules() != null) { + ruleSet.setRules(new ArrayList<>(originalRuleSet.getRules())); } - if ( originalRuleSet.getIgnoreVersions() != null ) - { - ruleSet.setIgnoreVersions( new ArrayList<>( originalRuleSet.getIgnoreVersions() ) ); + if (originalRuleSet.getIgnoreVersions() != null) { + ruleSet.setIgnoreVersions(new ArrayList<>(originalRuleSet.getIgnoreVersions())); } } - if ( ruleSet.getIgnoreVersions() == null ) - { - ruleSet.setIgnoreVersions( new ArrayList<>() ); + if (ruleSet.getIgnoreVersions() == null) { + ruleSet.setIgnoreVersions(new ArrayList<>()); } - ruleSet.getIgnoreVersions().addAll( ignoredVersions.stream().map( v -> - { - IgnoreVersion ignoreVersion = new IgnoreVersion(); - ignoreVersion.setType( TYPE_REGEX ); - ignoreVersion.setVersion( v ); - return ignoreVersion; - } ).collect( Collectors.toList() ) ); + ruleSet.getIgnoreVersions() + .addAll(ignoredVersions.stream() + .map(v -> { + IgnoreVersion ignoreVersion = new IgnoreVersion(); + ignoreVersion.setType(TYPE_REGEX); + ignoreVersion.setVersion(v); + return ignoreVersion; + }) + .collect(Collectors.toList())); return ruleSet; } - private static class RulesUri - { + private static class RulesUri { String basePath; String resource; - private RulesUri( String basePath, String resource ) - { + private RulesUri(String basePath, String resource) { this.basePath = basePath; this.resource = resource; } - static RulesUri build( String rulesUri ) throws URISyntaxException - { - int split = rulesUri.lastIndexOf( '/' ); + static RulesUri build(String rulesUri) throws URISyntaxException { + int split = rulesUri.lastIndexOf('/'); return split == -1 - ? new RulesUri( rulesUri, "" ) - : new RulesUri( rulesUri.substring( 0, split ) + '/', - split + 1 < rulesUri.length() - ? rulesUri.substring( split + 1 ) - : "" ) ; - } - } - - private RemoteRepository remoteRepository( RulesUri uri ) - { - RemoteRepository prototype = new RemoteRepository.Builder( serverId, null, uri.basePath ).build(); - RemoteRepository.Builder builder = new RemoteRepository.Builder( prototype ); - ofNullable( mavenSession.getRepositorySession().getProxySelector().getProxy( prototype ) ) - .ifPresent( builder::setProxy ); - ofNullable( mavenSession.getRepositorySession().getAuthenticationSelector().getAuthentication( prototype ) ) - .ifPresent( builder::setAuthentication ); - ofNullable( mavenSession.getRepositorySession().getMirrorSelector().getMirror( prototype ) ) - .ifPresent( mirror -> builder.setMirroredRepositories( singletonList( mirror ) ) ); + ? new RulesUri(rulesUri, "") + : new RulesUri( + rulesUri.substring(0, split) + '/', + split + 1 < rulesUri.length() ? rulesUri.substring(split + 1) : ""); + } + } + + private RemoteRepository remoteRepository(RulesUri uri) { + RemoteRepository prototype = new RemoteRepository.Builder(serverId, null, uri.basePath).build(); + RemoteRepository.Builder builder = new RemoteRepository.Builder(prototype); + ofNullable(mavenSession.getRepositorySession().getProxySelector().getProxy(prototype)) + .ifPresent(builder::setProxy); + ofNullable(mavenSession + .getRepositorySession() + .getAuthenticationSelector() + .getAuthentication(prototype)) + .ifPresent(builder::setAuthentication); + ofNullable(mavenSession.getRepositorySession().getMirrorSelector().getMirror(prototype)) + .ifPresent(mirror -> builder.setMirroredRepositories(singletonList(mirror))); return builder.build(); } - private Optional getProxyInfo( RemoteRepository repository ) - { - return ofNullable( repository.getProxy() ) - .map( proxy -> new ProxyInfo() - {{ - setHost( proxy.getHost() ); - setPort( proxy.getPort() ); - setType( proxy.getType() ); - ofNullable( proxy.getAuthentication() ) - .ifPresent( auth -> - { - try ( AuthenticationContext authCtx = AuthenticationContext - .forProxy( mavenSession.getRepositorySession(), repository ) ) - { - ofNullable( authCtx.get( AuthenticationContext.USERNAME ) ) - .ifPresent( this::setUserName ); - ofNullable( authCtx.get( AuthenticationContext.PASSWORD ) ) - .ifPresent( this::setPassword ); - ofNullable( authCtx.get( AuthenticationContext.NTLM_DOMAIN ) ) - .ifPresent( this::setNtlmDomain ); - ofNullable( authCtx.get( AuthenticationContext - .NTLM_WORKSTATION ) ).ifPresent( this::setNtlmHost ); - } - } ); - }} ); + private Optional getProxyInfo(RemoteRepository repository) { + return ofNullable(repository.getProxy()).map(proxy -> new ProxyInfo() { + { + setHost(proxy.getHost()); + setPort(proxy.getPort()); + setType(proxy.getType()); + ofNullable(proxy.getAuthentication()).ifPresent(auth -> { + try (AuthenticationContext authCtx = + AuthenticationContext.forProxy(mavenSession.getRepositorySession(), repository)) { + ofNullable(authCtx.get(AuthenticationContext.USERNAME)) + .ifPresent(this::setUserName); + ofNullable(authCtx.get(AuthenticationContext.PASSWORD)) + .ifPresent(this::setPassword); + ofNullable(authCtx.get(AuthenticationContext.NTLM_DOMAIN)) + .ifPresent(this::setNtlmDomain); + ofNullable(authCtx.get(AuthenticationContext.NTLM_WORKSTATION)) + .ifPresent(this::setNtlmHost); + } + }); + } + }); } - private Optional getAuthenticationInfo( RemoteRepository repository ) - { - return ofNullable( repository.getAuthentication() ) - .map( authentication -> new AuthenticationInfo() - {{ - try ( AuthenticationContext authCtx = AuthenticationContext - .forRepository( mavenSession.getRepositorySession(), repository ) ) - { - ofNullable( authCtx.get( AuthenticationContext.USERNAME ) ) - .ifPresent( this::setUserName ); - ofNullable( authCtx.get( AuthenticationContext.PASSWORD ) ) - .ifPresent( this::setPassword ); - ofNullable( authCtx.get( AuthenticationContext.PRIVATE_KEY_PASSPHRASE ) ) - .ifPresent( this::setPassphrase ); - ofNullable( authCtx.get( AuthenticationContext.PRIVATE_KEY_PATH ) ) - .ifPresent( this::setPrivateKey ); - } - }} ); + private Optional getAuthenticationInfo(RemoteRepository repository) { + return ofNullable(repository.getAuthentication()).map(authentication -> new AuthenticationInfo() { + { + try (AuthenticationContext authCtx = + AuthenticationContext.forRepository(mavenSession.getRepositorySession(), repository)) { + ofNullable(authCtx.get(AuthenticationContext.USERNAME)).ifPresent(this::setUserName); + ofNullable(authCtx.get(AuthenticationContext.PASSWORD)).ifPresent(this::setPassword); + ofNullable(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE)) + .ifPresent(this::setPassphrase); + ofNullable(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH)) + .ifPresent(this::setPrivateKey); + } + } + }); } - private org.apache.maven.wagon.repository.Repository wagonRepository( RemoteRepository repository ) - { - return new org.apache.maven.wagon.repository.Repository( repository.getId(), repository.getUrl() ); + private org.apache.maven.wagon.repository.Repository wagonRepository(RemoteRepository repository) { + return new org.apache.maven.wagon.repository.Repository(repository.getId(), repository.getUrl()); } - private RuleSet getRulesUsingWagon() throws MojoExecutionException - { + private RuleSet getRulesUsingWagon() throws MojoExecutionException { RulesUri uri; - try - { - uri = RulesUri.build( rulesUri ); - } - catch ( URISyntaxException e ) - { - log.warn( "Invalid rulesUri protocol: " + e.getMessage() ); + try { + uri = RulesUri.build(rulesUri); + } catch (URISyntaxException e) { + log.warn("Invalid rulesUri protocol: " + e.getMessage()); return null; } - RemoteRepository repository = remoteRepository( uri ); - return ofNullable( wagonMap.get( repository.getProtocol() ) ) - .map( wagon -> - { - if ( log.isDebugEnabled() ) - { + RemoteRepository repository = remoteRepository(uri); + return ofNullable(wagonMap.get(repository.getProtocol())) + .map(wagon -> { + if (log.isDebugEnabled()) { Debug debug = new Debug(); - wagon.addSessionListener( debug ); - wagon.addTransferListener( debug ); + wagon.addSessionListener(debug); + wagon.addTransferListener(debug); } - try - { - Optional proxyInfo = getProxyInfo( repository ); - Optional authenticationInfo = getAuthenticationInfo( repository ); - if ( log.isDebugEnabled() ) - { - log.debug( "Connecting to remote repository \"" + repository.getId() + "\"" - + proxyInfo.map( pi -> " using proxy " + pi.getHost() + ":" - + pi.getPort() ).orElse( "" ) - + authenticationInfo.map( ai -> " as " + ai.getUserName() ).orElse( "" ) ); + try { + Optional proxyInfo = getProxyInfo(repository); + Optional authenticationInfo = getAuthenticationInfo(repository); + if (log.isDebugEnabled()) { + log.debug("Connecting to remote repository \"" + repository.getId() + "\"" + + proxyInfo + .map(pi -> " using proxy " + pi.getHost() + ":" + pi.getPort()) + .orElse("") + + authenticationInfo + .map(ai -> " as " + ai.getUserName()) + .orElse("")); } - wagon.connect( wagonRepository( repository ), getAuthenticationInfo( repository ) - .orElse( null ), getProxyInfo( repository ).orElse( null ) ); - try - { - Path tempFile = Files.createTempFile( "rules-", ".xml" ); - wagon.get( uri.resource, tempFile.toFile() ); - try ( BufferedInputStream is = new BufferedInputStream( - Files.newInputStream( tempFile ) ) ) - { - return new RuleXpp3Reader().read( is ); - } - finally - { - Files.deleteIfExists( tempFile ); + wagon.connect( + wagonRepository(repository), + getAuthenticationInfo(repository).orElse(null), + getProxyInfo(repository).orElse(null)); + try { + Path tempFile = Files.createTempFile("rules-", ".xml"); + wagon.get(uri.resource, tempFile.toFile()); + try (BufferedInputStream is = new BufferedInputStream(Files.newInputStream(tempFile))) { + return new RuleXpp3Reader().read(is); + } finally { + Files.deleteIfExists(tempFile); } - } - finally - { + } finally { wagon.disconnect(); } - } - catch ( Exception e ) - { - log.warn( e.getMessage() ); + } catch (Exception e) { + log.warn(e.getMessage()); return null; } - } ) - .orElseThrow( () -> new MojoExecutionException( "Could not load specified rules from " - + rulesUri ) ); + }) + .orElseThrow(() -> new MojoExecutionException("Could not load specified rules from " + rulesUri)); } - public static Optional protocol( final String url ) - { - int pos = url.indexOf( ":" ); - return pos == -1 - ? empty() - : of( url.substring( 0, pos ).trim() ); + public static Optional protocol(final String url) { + int pos = url.indexOf(":"); + return pos == -1 ? empty() : of(url.substring(0, pos).trim()); } - public Builder withRepositorySystem( RepositorySystem repositorySystem ) - { + public Builder withRepositorySystem(RepositorySystem repositorySystem) { this.repositorySystem = repositorySystem; return this; } - public Builder withIgnoredVersions( Collection ignoredVersions ) - { + public Builder withIgnoredVersions(Collection ignoredVersions) { this.ignoredVersions = ignoredVersions; return this; } - public Builder withRuleSet( RuleSet ruleSet ) - { + public Builder withRuleSet(RuleSet ruleSet) { this.ruleSet = ruleSet; return this; } - public Builder withServerId( String serverId ) - { + public Builder withServerId(String serverId) { this.serverId = serverId; return this; } - public Builder withRulesUri( String rulesUri ) - { + public Builder withRulesUri(String rulesUri) { this.rulesUri = rulesUri; return this; } - public Builder withLog( Log log ) - { + public Builder withLog(Log log) { this.log = log; return this; } - public Builder withMavenSession( MavenSession mavenSession ) - { + public Builder withMavenSession(MavenSession mavenSession) { this.mavenSession = mavenSession; return this; } - public Builder withMojoExecution( MojoExecution mojoExecution ) - { + public Builder withMojoExecution(MojoExecution mojoExecution) { this.mojoExecution = mojoExecution; return this; } - public Builder withAetherRepositorySystem( org.eclipse.aether.RepositorySystem aetherRepositorySystem ) - { + public Builder withAetherRepositorySystem(org.eclipse.aether.RepositorySystem aetherRepositorySystem) { this.aetherRepositorySystem = aetherRepositorySystem; return this; } - public Builder withWagonMap( Map wagonMap ) - { + public Builder withWagonMap(Map wagonMap) { this.wagonMap = wagonMap; return this; } @@ -1006,39 +877,30 @@ public Builder withWagonMap( Map wagonMap ) * @return constructed {@linkplain DefaultVersionsHelper} * @throws MojoExecutionException should the constructor with the RuleSet retrieval doesn't succeed */ - public DefaultVersionsHelper build() throws MojoExecutionException - { + public DefaultVersionsHelper build() throws MojoExecutionException { DefaultVersionsHelper instance = new DefaultVersionsHelper(); instance.repositorySystem = repositorySystem; instance.mavenSession = mavenSession; instance.mojoExecution = mojoExecution; - if ( ruleSet != null ) - { - if ( !isBlank( rulesUri ) ) - { - log.warn( "rulesUri is ignored if rules are specified in pom or as parameters" ); + if (ruleSet != null) { + if (!isBlank(rulesUri)) { + log.warn("rulesUri is ignored if rules are specified in pom or as parameters"); } instance.ruleSet = ruleSet; - } - else - { - instance.ruleSet = isBlank( rulesUri ) + } else { + instance.ruleSet = isBlank(rulesUri) ? new RuleSet() - : isClasspathUri( rulesUri ) - ? getRulesFromClasspath( rulesUri, log ) - : getRulesUsingWagon(); + : isClasspathUri(rulesUri) ? getRulesFromClasspath(rulesUri, log) : getRulesUsingWagon(); } - if ( ignoredVersions != null && !ignoredVersions.isEmpty() ) - { - instance.ruleSet = enrichRuleSet( ignoredVersions, instance.ruleSet ); + if (ignoredVersions != null && !ignoredVersions.isEmpty()) { + instance.ruleSet = enrichRuleSet(ignoredVersions, instance.ruleSet); } instance.aetherRepositorySystem = aetherRepositorySystem; instance.log = log; return instance; } - private static boolean isBlank( String s ) - { + private static boolean isBlank(String s) { return s == null || s.trim().isEmpty(); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PluginUpdatesDetails.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PluginUpdatesDetails.java index 6376f5c2d6..ca7b3cbe73 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PluginUpdatesDetails.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PluginUpdatesDetails.java @@ -30,25 +30,24 @@ /** * Details of a plugin's updates. */ -public class PluginUpdatesDetails extends ArtifactVersions -{ +public class PluginUpdatesDetails extends ArtifactVersions { private final Map dependencyVersions; private final boolean includeSnapshots; - public PluginUpdatesDetails( ArtifactVersions artifactVersions, - Map dependencyVersions, boolean includeSnapshots ) - { - super( artifactVersions ); - Objects.requireNonNull( artifactVersions ); - Objects.requireNonNull( dependencyVersions ); + public PluginUpdatesDetails( + ArtifactVersions artifactVersions, + Map dependencyVersions, + boolean includeSnapshots) { + super(artifactVersions); + Objects.requireNonNull(artifactVersions); + Objects.requireNonNull(dependencyVersions); this.dependencyVersions = dependencyVersions; this.includeSnapshots = includeSnapshots; } - public Map getDependencyVersions() - { + public Map getDependencyVersions() { return dependencyVersions; } @@ -57,9 +56,8 @@ public Map getDependencyVersions() * * @return true if a new version can be found */ - public boolean isArtifactUpdateAvailable() - { - ArtifactVersion[] updates = getAllUpdates( empty(), includeSnapshots ); + public boolean isArtifactUpdateAvailable() { + ArtifactVersion[] updates = getAllUpdates(empty(), includeSnapshots); return updates != null && updates.length > 0; } @@ -68,13 +66,11 @@ public boolean isArtifactUpdateAvailable() * * @return true if a new version can be found */ - public boolean isDependencyUpdateAvailable() - { - return dependencyVersions.values().stream().anyMatch( versions -> - { - ArtifactVersion[] dependencyUpdates = versions.getAllUpdates( empty(), includeSnapshots ); + public boolean isDependencyUpdateAvailable() { + return dependencyVersions.values().stream().anyMatch(versions -> { + ArtifactVersion[] dependencyUpdates = versions.getAllUpdates(empty(), includeSnapshots); return dependencyUpdates != null && dependencyUpdates.length > 0; - } ); + }); } /** @@ -82,8 +78,7 @@ public boolean isDependencyUpdateAvailable() * * @return true if a new version can be found */ - public boolean isUpdateAvailable() - { + public boolean isUpdateAvailable() { return isArtifactUpdateAvailable() || isDependencyUpdateAvailable(); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java index cc1d1126c1..9583bf28c7 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java @@ -82,8 +82,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public class PomHelper -{ +public class PomHelper { public static final String APACHE_MAVEN_PLUGINS_GROUPID = "org.apache.maven.plugins"; /** @@ -93,10 +92,8 @@ public class PomHelper * @return The raw model. * @throws IOException if the file is not found or if the file does not parse. */ - public static Model getRawModel( MavenProject project ) - throws IOException - { - return getRawModel( project.getFile() ); + public static Model getRawModel(MavenProject project) throws IOException { + return getRawModel(project.getFile()); } /** @@ -106,13 +103,10 @@ public static Model getRawModel( MavenProject project ) * @return The raw model. * @throws IOException if the file is not found or if the file does not parse. */ - public static Model getRawModel( File moduleProjectFile ) - throws IOException - { - try ( Reader reader = new BufferedReader( new InputStreamReader( Files.newInputStream( moduleProjectFile - .toPath() ) ) ) ) - { - return getRawModel( reader ); + public static Model getRawModel(File moduleProjectFile) throws IOException { + try (Reader reader = + new BufferedReader(new InputStreamReader(Files.newInputStream(moduleProjectFile.toPath())))) { + return getRawModel(reader); } } @@ -123,12 +117,10 @@ public static Model getRawModel( File moduleProjectFile ) * @return The raw model. * @throws IOException if the file is not found or if the file does not parse. */ - public static Model getRawModel( ModifiedPomXMLEventReader modifiedPomXMLEventReader ) - throws IOException - { - try ( Reader reader = new StringReader( modifiedPomXMLEventReader.asStringBuilder().toString() ) ) - { - return getRawModel( reader ); + public static Model getRawModel(ModifiedPomXMLEventReader modifiedPomXMLEventReader) throws IOException { + try (Reader reader = + new StringReader(modifiedPomXMLEventReader.asStringBuilder().toString())) { + return getRawModel(reader); } } @@ -139,16 +131,11 @@ public static Model getRawModel( ModifiedPomXMLEventReader modifiedPomXMLEventRe * @return The raw model. * @throws IOException if the file is not found or if the file does not parse. */ - public static Model getRawModel( Reader reader ) - throws IOException - { - try - { - return new MavenXpp3Reader().read( reader ); - } - catch ( XmlPullParserException e ) - { - throw new IOException( e.getMessage(), e ); + public static Model getRawModel(Reader reader) throws IOException { + try { + return new MavenXpp3Reader().read(reader); + } catch (XmlPullParserException e) { + throw new IOException(e.getMessage(), e); } } @@ -162,10 +149,9 @@ public static Model getRawModel( Reader reader ) * @return true if a replacement was made. * @throws XMLStreamException if somethinh went wrong. */ - public static boolean setPropertyVersion( final ModifiedPomXMLEventReader pom, final String profileId, - final String property, final String value ) - throws XMLStreamException - { + public static boolean setPropertyVersion( + final ModifiedPomXMLEventReader pom, final String profileId, final String property, final String value) + throws XMLStreamException { Stack stack = new Stack<>(); String path = ""; final Pattern propertyRegex; @@ -173,64 +159,49 @@ public static boolean setPropertyVersion( final ModifiedPomXMLEventReader pom, f final Pattern projectProfileId; boolean inMatchScope = false; boolean madeReplacement = false; - if ( profileId == null ) - { - propertyRegex = Pattern.compile( "/project/properties/" + RegexUtils.quote( property ) ); - matchScopeRegex = Pattern.compile( "/project/properties" ); + if (profileId == null) { + propertyRegex = Pattern.compile("/project/properties/" + RegexUtils.quote(property)); + matchScopeRegex = Pattern.compile("/project/properties"); projectProfileId = null; - } - else - { - propertyRegex = Pattern.compile( "/project/profiles/profile/properties/" + RegexUtils.quote( property ) ); - matchScopeRegex = Pattern.compile( "/project/profiles/profile" ); - projectProfileId = Pattern.compile( "/project/profiles/profile/id" ); + } else { + propertyRegex = Pattern.compile("/project/profiles/profile/properties/" + RegexUtils.quote(property)); + matchScopeRegex = Pattern.compile("/project/profiles/profile"); + projectProfileId = Pattern.compile("/project/profiles/profile/id"); } pom.rewind(); - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); path = path + "/" + event.asStartElement().getName().getLocalPart(); - if ( propertyRegex.matcher( path ).matches() ) - { - pom.mark( 0 ); - } - else if ( matchScopeRegex.matcher( path ).matches() ) - { + if (propertyRegex.matcher(path).matches()) { + pom.mark(0); + } else if (matchScopeRegex.matcher(path).matches()) { // we're in a new match scope // reset any previous partial matches inMatchScope = profileId == null; - pom.clearMark( 0 ); - pom.clearMark( 1 ); - } - else if ( profileId != null && projectProfileId.matcher( path ).matches() ) - { + pom.clearMark(0); + pom.clearMark(1); + } else if (profileId != null && projectProfileId.matcher(path).matches()) { String candidateId = pom.getElementText(); path = stack.pop(); // since getElementText will be after the end element - inMatchScope = profileId.trim().equals( candidateId.trim() ); + inMatchScope = profileId.trim().equals(candidateId.trim()); } } - if ( event.isEndElement() ) - { - if ( propertyRegex.matcher( path ).matches() ) - { - pom.mark( 1 ); - } - else if ( matchScopeRegex.matcher( path ).matches() ) - { - if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) ) - { - pom.replaceBetween( 0, 1, value ); + if (event.isEndElement()) { + if (propertyRegex.matcher(path).matches()) { + pom.mark(1); + } else if (matchScopeRegex.matcher(path).matches()) { + if (inMatchScope && pom.hasMark(0) && pom.hasMark(1)) { + pom.replaceBetween(0, 1, value); madeReplacement = true; } - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); inMatchScope = false; } path = stack.pop(); @@ -247,10 +218,9 @@ else if ( matchScopeRegex.matcher( path ).matches() ) * @return true if a replacement was made. * @throws XMLStreamException if somethinh went wrong. */ - public static boolean setProjectVersion( final ModifiedPomXMLEventReader pom, final String value ) - throws XMLStreamException - { - return setElementValue( pom, "/project", "version", value, false ); + public static boolean setProjectVersion(final ModifiedPomXMLEventReader pom, final String value) + throws XMLStreamException { + return setElementValue(pom, "/project", "version", value, false); } /** @@ -265,12 +235,11 @@ public static boolean setProjectVersion( final ModifiedPomXMLEventReader pom, fi * @return {@code true} if the element was created or replaced * @throws XMLStreamException if something went wrong */ - public static boolean setElementValue( ModifiedPomXMLEventReader pom, String parentPath, - String elementName, String value ) - throws XMLStreamException - { + public static boolean setElementValue( + ModifiedPomXMLEventReader pom, String parentPath, String elementName, String value) + throws XMLStreamException { pom.rewind(); - return setElementValue( pom, parentPath, elementName, value, true ); + return setElementValue(pom, parentPath, elementName, value, true); } /** @@ -288,12 +257,10 @@ public static boolean setElementValue( ModifiedPomXMLEventReader pom, String par * @return {@code true} if the element was created or replaced * @throws XMLStreamException if something went wrong */ - public static boolean setElementValue( ModifiedPomXMLEventReader pom, String parentPath, - String elementName, String value, boolean shouldCreate ) - throws XMLStreamException - { - class ElementValueInternal - { + public static boolean setElementValue( + ModifiedPomXMLEventReader pom, String parentPath, String elementName, String value, boolean shouldCreate) + throws XMLStreamException { + class ElementValueInternal { private final String parentName; private final String superParentPath; @@ -301,52 +268,39 @@ class ElementValueInternal private static final int MARK_OPTION = 1; private static final int PARENT_BEGIN = 2; - ElementValueInternal() - { - int lastDelimeterIndex = parentPath.lastIndexOf( '/' ); - parentName = parentPath.substring( lastDelimeterIndex + 1 ); - superParentPath = parentPath.substring( 0, lastDelimeterIndex ); + ElementValueInternal() { + int lastDelimeterIndex = parentPath.lastIndexOf('/'); + parentName = parentPath.substring(lastDelimeterIndex + 1); + superParentPath = parentPath.substring(0, lastDelimeterIndex); } - boolean process( String currentPath ) throws XMLStreamException - { + boolean process(String currentPath) throws XMLStreamException { boolean replacementMade = false; - while ( !replacementMade && pom.hasNext() ) - { + while (!replacementMade && pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - String currentElementName = event.asStartElement().getName().getLocalPart(); + if (event.isStartElement()) { + String currentElementName = + event.asStartElement().getName().getLocalPart(); // here, we will only mark the beginning of the child or the parent element - if ( currentPath.equals( parentPath ) && elementName.equals( currentElementName ) ) - { - pom.mark( MARK_CHILD_BEGIN ); - } - else if ( currentPath.equals( superParentPath ) && currentElementName.equals( parentName ) ) - { - pom.mark( PARENT_BEGIN ); + if (currentPath.equals(parentPath) && elementName.equals(currentElementName)) { + pom.mark(MARK_CHILD_BEGIN); + } else if (currentPath.equals(superParentPath) && currentElementName.equals(parentName)) { + pom.mark(PARENT_BEGIN); } // process child element - replacementMade = process( currentPath + "/" + currentElementName ); - } - else if ( event.isEndElement() ) - { + replacementMade = process(currentPath + "/" + currentElementName); + } else if (event.isEndElement()) { // here we're doing the replacement - if ( currentPath.equals( parentPath + "/" + elementName ) ) - { + if (currentPath.equals(parentPath + "/" + elementName)) { // end of the child replaceValueInChild(); replacementMade = true; - } - else if ( shouldCreate && currentPath.equals( parentPath ) ) - { + } else if (shouldCreate && currentPath.equals(parentPath)) { // end of the parent replaceValueInParent(); replacementMade = true; - } - else - { + } else { return false; } } @@ -354,51 +308,34 @@ else if ( shouldCreate && currentPath.equals( parentPath ) ) return replacementMade; } - private void replaceValueInChild() - { - pom.mark( MARK_OPTION ); - if ( pom.getBetween( MARK_CHILD_BEGIN, MARK_OPTION ).length() > 0 ) - { - pom.replaceBetween( 0, 1, value ); - } - else - { - pom.replace( String.format( "<%1$s>%2$s", elementName, value ) ); + private void replaceValueInChild() { + pom.mark(MARK_OPTION); + if (pom.getBetween(MARK_CHILD_BEGIN, MARK_OPTION).length() > 0) { + pom.replaceBetween(0, 1, value); + } else { + pom.replace(String.format("<%1$s>%2$s", elementName, value)); } } - private void replaceValueInParent() - { - pom.mark( MARK_OPTION ); - if ( pom.hasMark( PARENT_BEGIN ) ) - { - if ( pom.getBetween( PARENT_BEGIN, MARK_OPTION ).length() > 0 ) - { - pom.replace( String.format( "<%2$s>%3$s", - parentName, elementName, value ) ); - } - else - { - pom.replace( String.format( "<%1$s><%2$s>%3$s", - parentName, elementName, value ) ); + private void replaceValueInParent() { + pom.mark(MARK_OPTION); + if (pom.hasMark(PARENT_BEGIN)) { + if (pom.getBetween(PARENT_BEGIN, MARK_OPTION).length() > 0) { + pom.replace(String.format("<%2$s>%3$s", parentName, elementName, value)); + } else { + pom.replace(String.format("<%1$s><%2$s>%3$s", parentName, elementName, value)); } - } - else - { - pom.replace( String.format( "<%1$s><%2$s>%3$s", - parentName, elementName, value ) ); + } else { + pom.replace(String.format("<%1$s><%2$s>%3$s", parentName, elementName, value)); } } } - try - { + try { pom.rewind(); - return new ElementValueInternal().process( "" ); - } - finally - { - range( 0, 3 ).forEach( pom::clearMark ); + return new ElementValueInternal().process(""); + } finally { + range(0, 3).forEach(pom::clearMark); } } @@ -410,39 +347,31 @@ private void replaceValueInParent() * parent version). * @throws XMLStreamException if something went wrong. */ - public static String getProjectVersion( final ModifiedPomXMLEventReader pom ) - throws XMLStreamException - { + public static String getProjectVersion(final ModifiedPomXMLEventReader pom) throws XMLStreamException { Stack stack = new Stack<>(); String path = ""; - final Pattern matchScopeRegex = Pattern.compile( "/project/version" ); + final Pattern matchScopeRegex = Pattern.compile("/project/version"); pom.rewind(); - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); path = path + "/" + event.asStartElement().getName().getLocalPart(); - if ( matchScopeRegex.matcher( path ).matches() ) - { - pom.mark( 0 ); + if (matchScopeRegex.matcher(path).matches()) { + pom.mark(0); } } - if ( event.isEndElement() ) - { - if ( matchScopeRegex.matcher( path ).matches() ) - { - pom.mark( 1 ); - if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) ) - { - return pom.getBetween( 0, 1 ).trim(); + if (event.isEndElement()) { + if (matchScopeRegex.matcher(path).matches()) { + pom.mark(1); + if (pom.hasMark(0) && pom.hasMark(1)) { + return pom.getBetween(0, 1).trim(); } - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); } path = stack.pop(); } @@ -458,42 +387,35 @@ public static String getProjectVersion( final ModifiedPomXMLEventReader pom ) * @return true if a replacement was made. * @throws XMLStreamException if somethinh went wrong. */ - public static boolean setProjectParentVersion( final ModifiedPomXMLEventReader pom, final String value ) - throws XMLStreamException - { + public static boolean setProjectParentVersion(final ModifiedPomXMLEventReader pom, final String value) + throws XMLStreamException { Stack stack = new Stack<>(); String path = ""; final Pattern matchScopeRegex; boolean madeReplacement = false; - matchScopeRegex = Pattern.compile( "/project/parent/version" ); + matchScopeRegex = Pattern.compile("/project/parent/version"); pom.rewind(); - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); path = path + "/" + event.asStartElement().getName().getLocalPart(); - if ( matchScopeRegex.matcher( path ).matches() ) - { - pom.mark( 0 ); + if (matchScopeRegex.matcher(path).matches()) { + pom.mark(0); } } - if ( event.isEndElement() ) - { - if ( matchScopeRegex.matcher( path ).matches() ) - { - pom.mark( 1 ); - if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) ) - { - pom.replaceBetween( 0, 1, value ); + if (event.isEndElement()) { + if (matchScopeRegex.matcher(path).matches()) { + pom.mark(1); + if (pom.hasMark(0) && pom.hasMark(1)) { + pom.replaceBetween(0, 1, value); madeReplacement = true; } - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); } path = stack.pop(); } @@ -513,65 +435,58 @@ public static boolean setProjectParentVersion( final ModifiedPomXMLEventReader p * @return true if a replacement was made. * @throws XMLStreamException if something went wrong. */ - @SuppressWarnings( "checkstyle:MethodLength" ) - public static boolean setDependencyVersion( final ModifiedPomXMLEventReader pom, final String groupId, - final String artifactId, final String oldVersion, - final String newVersion, final Model model ) - throws XMLStreamException - { + @SuppressWarnings("checkstyle:MethodLength") + public static boolean setDependencyVersion( + final ModifiedPomXMLEventReader pom, + final String groupId, + final String artifactId, + final String oldVersion, + final String newVersion, + final Model model) + throws XMLStreamException { Stack stack = new Stack<>(); String path = ""; - Set implicitPaths = - new HashSet<>( Arrays.asList( "/project/parent/groupId", "/project/parent/artifactId", - "/project/parent/version", "/project/groupId", - "/project/artifactId", "/project/version" ) ); + Set implicitPaths = new HashSet<>(Arrays.asList( + "/project/parent/groupId", "/project/parent/artifactId", + "/project/parent/version", "/project/groupId", + "/project/artifactId", "/project/version")); Map implicitProperties = new HashMap<>(); - for ( Map.Entry entry : model.getProperties().entrySet() ) - { - implicitProperties.put( (String) entry.getKey(), (String) entry.getValue() ); + for (Map.Entry entry : model.getProperties().entrySet()) { + implicitProperties.put((String) entry.getKey(), (String) entry.getValue()); } pom.rewind(); - while ( pom.hasNext() ) - { - while ( pom.hasNext() ) - { + while (pom.hasNext()) { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); final String elementName = event.asStartElement().getName().getLocalPart(); path = path + "/" + elementName; - if ( implicitPaths.contains( path ) ) - { + if (implicitPaths.contains(path)) { final String elementText = pom.getElementText().trim(); - implicitProperties.put( path.substring( 1 ).replace( '/', '.' ), elementText ); + implicitProperties.put(path.substring(1).replace('/', '.'), elementText); path = stack.pop(); } } - if ( event.isEndElement() ) - { + if (event.isEndElement()) { path = stack.pop(); } } } boolean modified = true; - while ( modified ) - { + while (modified) { modified = false; - for ( Map.Entry entry : implicitProperties.entrySet() ) - { - if ( entry.getKey().contains( ".parent" ) ) - { - String child = entry.getKey().replace( ".parent", "" ); - if ( !implicitProperties.containsKey( child ) ) - { - implicitProperties.put( child, entry.getValue() ); + for (Map.Entry entry : implicitProperties.entrySet()) { + if (entry.getKey().contains(".parent")) { + String child = entry.getKey().replace(".parent", ""); + if (!implicitProperties.containsKey(child)) { + implicitProperties.put(child, entry.getValue()); modified = true; break; } @@ -587,88 +502,74 @@ public static boolean setDependencyVersion( final ModifiedPomXMLEventReader pom, boolean haveArtifactId = false; boolean haveOldVersion = false; - final Pattern matchScopeRegex = Pattern.compile( - "/project" + "(/profiles/profile)?" + final Pattern matchScopeRegex = Pattern.compile("/project" + "(/profiles/profile)?" + "((/dependencyManagement)|(/build(/pluginManagement)?/plugins/plugin))?" - + "/dependencies/dependency" ); + + "/dependencies/dependency"); - final Pattern matchTargetRegex = Pattern.compile( - "/project" + "(/profiles/profile)?" + final Pattern matchTargetRegex = Pattern.compile("/project" + "(/profiles/profile)?" + "((/dependencyManagement)|(/build(/pluginManagement)?/plugins/plugin))?" + "/dependencies/dependency" - + "((/groupId)|(/artifactId)|(/version))" ); + + "((/groupId)|(/artifactId)|(/version))"); pom.rewind(); - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); final String elementName = event.asStartElement().getName().getLocalPart(); path = path + "/" + elementName; - if ( matchScopeRegex.matcher( path ).matches() ) - { + if (matchScopeRegex.matcher(path).matches()) { // we're in a new match scope // reset any previous partial matches inMatchScope = true; - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); haveGroupId = false; haveArtifactId = false; haveOldVersion = false; - } - else if ( inMatchScope && matchTargetRegex.matcher( path ).matches() ) - { - if ( "groupId".equals( elementName ) ) - { - haveGroupId = groupId.equals( evaluate( pom.getElementText().trim(), implicitProperties ) ); + } else if (inMatchScope && matchTargetRegex.matcher(path).matches()) { + if ("groupId".equals(elementName)) { + haveGroupId = + groupId.equals(evaluate(pom.getElementText().trim(), implicitProperties)); path = stack.pop(); - } - else if ( "artifactId".equals( elementName ) ) - { + } else if ("artifactId".equals(elementName)) { haveArtifactId = - artifactId.equals( evaluate( pom.getElementText().trim(), implicitProperties ) ); + artifactId.equals(evaluate(pom.getElementText().trim(), implicitProperties)); path = stack.pop(); - } - else if ( "version".equals( elementName ) ) - { - pom.mark( 0 ); + } else if ("version".equals(elementName)) { + pom.mark(0); } } } - if ( event.isEndElement() ) - { - if ( matchTargetRegex.matcher( path ).matches() - && "version".equals( event.asEndElement().getName().getLocalPart() ) ) - { - pom.mark( 1 ); - String compressedPomVersion = StringUtils.deleteWhitespace( pom.getBetween( 0, 1 ).trim() ); - String compressedOldVersion = StringUtils.deleteWhitespace( oldVersion ); - - try - { - haveOldVersion = isVersionOverlap( compressedOldVersion, compressedPomVersion ); - } - catch ( InvalidVersionSpecificationException e ) - { + if (event.isEndElement()) { + if (matchTargetRegex.matcher(path).matches() + && "version".equals(event.asEndElement().getName().getLocalPart())) { + pom.mark(1); + String compressedPomVersion = + StringUtils.deleteWhitespace(pom.getBetween(0, 1).trim()); + String compressedOldVersion = StringUtils.deleteWhitespace(oldVersion); + + try { + haveOldVersion = isVersionOverlap(compressedOldVersion, compressedPomVersion); + } catch (InvalidVersionSpecificationException e) { // fall back to string comparison - haveOldVersion = compressedOldVersion.equals( compressedPomVersion ); + haveOldVersion = compressedOldVersion.equals(compressedPomVersion); } - } - else if ( matchScopeRegex.matcher( path ).matches() ) - { - if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) && haveGroupId && haveArtifactId - && haveOldVersion ) - { - pom.replaceBetween( 0, 1, newVersion ); + } else if (matchScopeRegex.matcher(path).matches()) { + if (inMatchScope + && pom.hasMark(0) + && pom.hasMark(1) + && haveGroupId + && haveArtifactId + && haveOldVersion) { + pom.replaceBetween(0, 1, newVersion); madeReplacement = true; } - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); haveArtifactId = false; haveGroupId = false; haveOldVersion = false; @@ -687,73 +588,55 @@ else if ( matchScopeRegex.matcher( path ).matches() ) * @param properties The properties to substitute. * @return The evaluated expression. */ - public static String evaluate( String expr, Map properties ) - { - if ( expr == null ) - { + public static String evaluate(String expr, Map properties) { + if (expr == null) { return null; } - String expression = stripTokens( expr ); - if ( expression.equals( expr ) ) - { - int index = expr.indexOf( "${" ); - if ( index >= 0 ) - { - int lastIndex = expr.indexOf( "}", index ); - if ( lastIndex >= 0 ) - { - String retVal = expr.substring( 0, index ); - - if ( index > 0 && expr.charAt( index - 1 ) == '$' ) - { - retVal += expr.substring( index + 1, lastIndex + 1 ); - } - else - { - retVal += evaluate( expr.substring( index, lastIndex + 1 ), properties ); + String expression = stripTokens(expr); + if (expression.equals(expr)) { + int index = expr.indexOf("${"); + if (index >= 0) { + int lastIndex = expr.indexOf("}", index); + if (lastIndex >= 0) { + String retVal = expr.substring(0, index); + + if (index > 0 && expr.charAt(index - 1) == '$') { + retVal += expr.substring(index + 1, lastIndex + 1); + } else { + retVal += evaluate(expr.substring(index, lastIndex + 1), properties); } - retVal += evaluate( expr.substring( lastIndex + 1 ), properties ); + retVal += evaluate(expr.substring(lastIndex + 1), properties); return retVal; } } // Was not an expression - if ( expression.contains( "$$" ) ) - { - return expression.replaceAll( "\\$\\$", "\\$" ); - } - else - { + if (expression.contains("$$")) { + return expression.replaceAll("\\$\\$", "\\$"); + } else { return expression; } } - String value = properties.get( expression ); + String value = properties.get(expression); - if ( value != null ) - { - int exprStartDelimiter = value.indexOf( "${" ); + if (value != null) { + int exprStartDelimiter = value.indexOf("${"); - if ( exprStartDelimiter >= 0 ) - { - if ( exprStartDelimiter > 0 ) - { - value = value.substring( 0, exprStartDelimiter ) - + evaluate( value.substring( exprStartDelimiter ), properties ); - } - else - { - value = evaluate( value.substring( exprStartDelimiter ), properties ); + if (exprStartDelimiter >= 0) { + if (exprStartDelimiter > 0) { + value = value.substring(0, exprStartDelimiter) + + evaluate(value.substring(exprStartDelimiter), properties); + } else { + value = evaluate(value.substring(exprStartDelimiter), properties); } } - } - else - { + } else { // TODO find a way to log that and not use this System.out!! // this class could be a component with logger injected !! - System.out.println( "expression: " + expression + " no value " ); + System.out.println("expression: " + expression + " no value "); } return value == null ? expr : value; } @@ -764,11 +647,9 @@ public static String evaluate( String expr, Map properties ) * @param expr the string (perhaps with token markers) * @return the string (definately without token markers) */ - private static String stripTokens( String expr ) - { - if ( expr.startsWith( "${" ) && expr.indexOf( "}" ) == expr.length() - 1 ) - { - expr = expr.substring( 2, expr.length() - 1 ); + private static String stripTokens(String expr) { + if (expr.startsWith("${") && expr.indexOf("}") == expr.length() - 1) { + expr = expr.substring(2, expr.length() - 1); } return expr; } @@ -781,32 +662,26 @@ private static String stripTokens( String expr ) * @return true if both versions have an overlap * @throws InvalidVersionSpecificationException if the versions can't be parsed to a range */ - public static boolean isVersionOverlap( String leftVersionOrRange, String rightVersionOrRange ) - throws InvalidVersionSpecificationException - { - VersionRange pomVersionRange = createVersionRange( leftVersionOrRange ); - if ( !pomVersionRange.hasRestrictions() ) - { + public static boolean isVersionOverlap(String leftVersionOrRange, String rightVersionOrRange) + throws InvalidVersionSpecificationException { + VersionRange pomVersionRange = createVersionRange(leftVersionOrRange); + if (!pomVersionRange.hasRestrictions()) { return true; } - VersionRange oldVersionRange = createVersionRange( rightVersionOrRange ); - if ( !oldVersionRange.hasRestrictions() ) - { + VersionRange oldVersionRange = createVersionRange(rightVersionOrRange); + if (!oldVersionRange.hasRestrictions()) { return true; } - VersionRange result = oldVersionRange.restrict( pomVersionRange ); + VersionRange result = oldVersionRange.restrict(pomVersionRange); return result.hasRestrictions(); } - private static VersionRange createVersionRange( String versionOrRange ) - throws InvalidVersionSpecificationException - { - VersionRange versionRange = VersionRange.createFromVersionSpec( versionOrRange ); - if ( versionRange.getRecommendedVersion() != null ) - { - versionRange = VersionRange.createFromVersionSpec( "[" + versionOrRange + "]" ); + private static VersionRange createVersionRange(String versionOrRange) throws InvalidVersionSpecificationException { + VersionRange versionRange = VersionRange.createFromVersionSpec(versionOrRange); + if (versionRange.getRecommendedVersion() != null) { + versionRange = VersionRange.createFromVersionSpec("[" + versionOrRange + "]"); } return versionRange; } @@ -822,10 +697,13 @@ private static VersionRange createVersionRange( String versionOrRange ) * @return true if a replacement was made. * @throws XMLStreamException if somethinh went wrong. */ - public static boolean setPluginVersion( final ModifiedPomXMLEventReader pom, final String groupId, - final String artifactId, final String oldVersion, final String newVersion ) - throws XMLStreamException - { + public static boolean setPluginVersion( + final ModifiedPomXMLEventReader pom, + final String groupId, + final String artifactId, + final String oldVersion, + final String newVersion) + throws XMLStreamException { Stack stack = new Stack<>(); String path = ""; final Pattern matchScopeRegex; @@ -833,84 +711,71 @@ public static boolean setPluginVersion( final ModifiedPomXMLEventReader pom, fin boolean inMatchScope = false; boolean madeReplacement = false; boolean haveGroupId = false; - boolean needGroupId = groupId != null && !APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ); + boolean needGroupId = groupId != null && !APACHE_MAVEN_PLUGINS_GROUPID.equals(groupId); boolean haveArtifactId = false; boolean haveOldVersion = false; - matchScopeRegex = Pattern.compile( "/project" + "(/profiles/profile)?" - + "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin" ); + matchScopeRegex = Pattern.compile( + "/project" + "(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin"); - matchTargetRegex = Pattern.compile( "/project" + "(/profiles/profile)?" - + "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin" - + "((/groupId)|(/artifactId)|(/version))" ); + matchTargetRegex = Pattern.compile("/project" + "(/profiles/profile)?" + + "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin" + + "((/groupId)|(/artifactId)|(/version))"); pom.rewind(); - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); final String elementName = event.asStartElement().getName().getLocalPart(); path = path + "/" + elementName; - if ( matchScopeRegex.matcher( path ).matches() ) - { + if (matchScopeRegex.matcher(path).matches()) { // we're in a new match scope // reset any previous partial matches inMatchScope = true; - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); haveGroupId = false; haveArtifactId = false; haveOldVersion = false; - } - else if ( inMatchScope && matchTargetRegex.matcher( path ).matches() ) - { - if ( "groupId".equals( elementName ) ) - { - haveGroupId = pom.getElementText().trim().equals( groupId ); + } else if (inMatchScope && matchTargetRegex.matcher(path).matches()) { + if ("groupId".equals(elementName)) { + haveGroupId = pom.getElementText().trim().equals(groupId); path = stack.pop(); - } - else if ( "artifactId".equals( elementName ) ) - { - haveArtifactId = artifactId.equals( pom.getElementText().trim() ); + } else if ("artifactId".equals(elementName)) { + haveArtifactId = artifactId.equals(pom.getElementText().trim()); path = stack.pop(); - } - else if ( "version".equals( elementName ) ) - { - pom.mark( 0 ); + } else if ("version".equals(elementName)) { + pom.mark(0); } } } - if ( event.isEndElement() ) - { - if ( matchTargetRegex.matcher( path ).matches() - && "version".equals( event.asEndElement().getName().getLocalPart() ) ) - { - pom.mark( 1 ); - - try - { - haveOldVersion = isVersionOverlap( oldVersion, pom.getBetween( 0, 1 ).trim() ); - } - catch ( InvalidVersionSpecificationException e ) - { + if (event.isEndElement()) { + if (matchTargetRegex.matcher(path).matches() + && "version".equals(event.asEndElement().getName().getLocalPart())) { + pom.mark(1); + + try { + haveOldVersion = isVersionOverlap( + oldVersion, pom.getBetween(0, 1).trim()); + } catch (InvalidVersionSpecificationException e) { // fall back to string comparison - haveOldVersion = oldVersion.equals( pom.getBetween( 0, 1 ).trim() ); + haveOldVersion = oldVersion.equals(pom.getBetween(0, 1).trim()); } - } - else if ( matchScopeRegex.matcher( path ).matches() ) - { - if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) && ( haveGroupId || !needGroupId ) - && haveArtifactId && haveOldVersion ) - { - pom.replaceBetween( 0, 1, newVersion ); + } else if (matchScopeRegex.matcher(path).matches()) { + if (inMatchScope + && pom.hasMark(0) + && pom.hasMark(1) + && (haveGroupId || !needGroupId) + && haveArtifactId + && haveOldVersion) { + pom.replaceBetween(0, 1, newVersion); madeReplacement = true; - pom.clearMark( 0 ); - pom.clearMark( 1 ); + pom.clearMark(0); + pom.clearMark(1); haveArtifactId = false; haveGroupId = false; haveOldVersion = false; @@ -929,27 +794,19 @@ else if ( matchScopeRegex.matcher( path ).matches() ) * @param project maven project of the child for which the models need to be gathered * @return gathered map of raw models per project */ - private static Map getRawModelWithParents( MavenProject project ) throws IOException - { + private static Map getRawModelWithParents(MavenProject project) throws IOException { // constructs a tree sorted from children to parents - Map models = new TreeMap<>( ( p1, p2 ) -> - { - for ( MavenProject p = p1; p != null; p = p.getParent() ) - { - if ( p == p2 ) // meaning p2 is an ancestor to p1 or p1 == p2 + Map models = new TreeMap<>((p1, p2) -> { + for (MavenProject p = p1; p != null; p = p.getParent()) { + if (p == p2) // meaning p2 is an ancestor to p1 or p1 == p2 { - return p == p1 - ? 0 - : -1; // p1 is the child + return p == p1 ? 0 : -1; // p1 is the child } } return 1; - } ); - for ( MavenProject p = project; p != null; p = p.getParent() ) - { - models.put( p, p.getFile() != null - ? getRawModel( p ) - : p.getOriginalModel() ); + }); + for (MavenProject p = project; p != null; p = p.getParent()) { + models.put(p, p.getFile() != null ? getRawModel(p) : p.getOriginalModel()); } return models; } @@ -965,130 +822,145 @@ private static Map getRawModelWithParents( MavenProject pro * @throws IOException if the project's pom file cannot be parsed. * @since 1.0-alpha-3 */ - public static PropertyVersionsBuilder[] getPropertyVersionsBuilders( VersionsHelper helper, MavenProject project, - boolean includeParent ) - throws ExpressionEvaluationException, IOException - { - ExpressionEvaluator expressionEvaluator = helper.getExpressionEvaluator( project ); - Map reactorModels = includeParent - ? getRawModelWithParents( project ) - : singletonMap( project, getRawModel( project ) ); + public static PropertyVersionsBuilder[] getPropertyVersionsBuilders( + VersionsHelper helper, MavenProject project, boolean includeParent) + throws ExpressionEvaluationException, IOException { + ExpressionEvaluator expressionEvaluator = helper.getExpressionEvaluator(project); + Map reactorModels = + includeParent ? getRawModelWithParents(project) : singletonMap(project, getRawModel(project)); Map propertiesMap = new TreeMap<>(); Set activeProfiles = new TreeSet<>(); - for ( Profile profile : project.getActiveProfiles() ) - { - activeProfiles.add( profile.getId() ); + for (Profile profile : project.getActiveProfiles()) { + activeProfiles.add(profile.getId()); } // add any properties from profiles first (as they override properties from the project - for ( Iterator it = reactorModels.values().stream() - .flatMap( model -> model.getProfiles().stream() ) - .filter( profile -> activeProfiles.contains( profile.getId() ) ) - .iterator(); it.hasNext(); ) - { + for (Iterator it = reactorModels.values().stream() + .flatMap(model -> model.getProfiles().stream()) + .filter(profile -> activeProfiles.contains(profile.getId())) + .iterator(); + it.hasNext(); ) { Profile profile = it.next(); - try - { - addProperties( helper, propertiesMap, profile.getId(), profile.getProperties() ); - if ( profile.getDependencyManagement() != null ) - { - addDependencyAssocations( helper, expressionEvaluator, propertiesMap, - profile.getDependencyManagement().getDependencies(), false ); + try { + addProperties(helper, propertiesMap, profile.getId(), profile.getProperties()); + if (profile.getDependencyManagement() != null) { + addDependencyAssocations( + helper, + expressionEvaluator, + propertiesMap, + profile.getDependencyManagement().getDependencies(), + false); } - addDependencyAssocations( helper, expressionEvaluator, propertiesMap, - profile.getDependencies(), - false ); - if ( profile.getBuild() != null ) - { - if ( profile.getBuild().getPluginManagement() != null ) - { - addPluginAssociations( helper, expressionEvaluator, propertiesMap, - profile.getBuild().getPluginManagement().getPlugins() ); + addDependencyAssocations(helper, expressionEvaluator, propertiesMap, profile.getDependencies(), false); + if (profile.getBuild() != null) { + if (profile.getBuild().getPluginManagement() != null) { + addPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + profile.getBuild().getPluginManagement().getPlugins()); } - addPluginAssociations( helper, expressionEvaluator, propertiesMap, - profile.getBuild().getPlugins() ); + addPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + profile.getBuild().getPlugins()); } - if ( profile.getReporting() != null ) - { - addReportPluginAssociations( helper, expressionEvaluator, propertiesMap, - profile.getReporting().getPlugins() ); + if (profile.getReporting() != null) { + addReportPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + profile.getReporting().getPlugins()); } - } - catch ( ExpressionEvaluationException e ) - { - throw new RuntimeException( e ); + } catch (ExpressionEvaluationException e) { + throw new RuntimeException(e); } } // second, we add all the properties in the pom - reactorModels.values().forEach( model -> addProperties( helper, propertiesMap, null, model.getProperties() ) ); - - - for ( MavenProject currentPrj = project; currentPrj != null; currentPrj = includeParent - ? currentPrj.getParent() - : null ) - { - Model model = reactorModels.get( currentPrj ); - - if ( model.getDependencyManagement() != null ) - { - addDependencyAssocations( helper, expressionEvaluator, propertiesMap, - model.getDependencyManagement().getDependencies(), false ); + reactorModels.values().forEach(model -> addProperties(helper, propertiesMap, null, model.getProperties())); + + for (MavenProject currentPrj = project; + currentPrj != null; + currentPrj = includeParent ? currentPrj.getParent() : null) { + Model model = reactorModels.get(currentPrj); + + if (model.getDependencyManagement() != null) { + addDependencyAssocations( + helper, + expressionEvaluator, + propertiesMap, + model.getDependencyManagement().getDependencies(), + false); } - addDependencyAssocations( helper, expressionEvaluator, propertiesMap, model.getDependencies(), false ); - if ( model.getBuild() != null ) - { - if ( model.getBuild().getPluginManagement() != null ) - { - addPluginAssociations( helper, expressionEvaluator, propertiesMap, - model.getBuild().getPluginManagement().getPlugins() ); + addDependencyAssocations(helper, expressionEvaluator, propertiesMap, model.getDependencies(), false); + if (model.getBuild() != null) { + if (model.getBuild().getPluginManagement() != null) { + addPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + model.getBuild().getPluginManagement().getPlugins()); } - addPluginAssociations( helper, expressionEvaluator, propertiesMap, model.getBuild().getPlugins() ); + addPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + model.getBuild().getPlugins()); } - if ( model.getReporting() != null ) - { - addReportPluginAssociations( helper, expressionEvaluator, propertiesMap, - model.getReporting().getPlugins() ); + if (model.getReporting() != null) { + addReportPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + model.getReporting().getPlugins()); } // third, we add any associations from the active profiles - for ( Profile profile : model.getProfiles() ) - { - if ( !activeProfiles.contains( profile.getId() ) ) - { + for (Profile profile : model.getProfiles()) { + if (!activeProfiles.contains(profile.getId())) { continue; } - if ( profile.getDependencyManagement() != null ) - { - addDependencyAssocations( helper, expressionEvaluator, propertiesMap, - profile.getDependencyManagement().getDependencies(), false ); + if (profile.getDependencyManagement() != null) { + addDependencyAssocations( + helper, + expressionEvaluator, + propertiesMap, + profile.getDependencyManagement().getDependencies(), + false); } - addDependencyAssocations( helper, expressionEvaluator, propertiesMap, profile.getDependencies(), - false ); - if ( profile.getBuild() != null ) - { - if ( profile.getBuild().getPluginManagement() != null ) - { - addPluginAssociations( helper, expressionEvaluator, propertiesMap, - profile.getBuild().getPluginManagement().getPlugins() ); + addDependencyAssocations(helper, expressionEvaluator, propertiesMap, profile.getDependencies(), false); + if (profile.getBuild() != null) { + if (profile.getBuild().getPluginManagement() != null) { + addPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + profile.getBuild().getPluginManagement().getPlugins()); } - addPluginAssociations( helper, expressionEvaluator, propertiesMap, - profile.getBuild().getPlugins() ); + addPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + profile.getBuild().getPlugins()); } - if ( profile.getReporting() != null ) - { - addReportPluginAssociations( helper, expressionEvaluator, propertiesMap, - profile.getReporting().getPlugins() ); + if (profile.getReporting() != null) { + addReportPluginAssociations( + helper, + expressionEvaluator, + propertiesMap, + profile.getReporting().getPlugins()); } } } // finally, remove any properties without associations - purgeProperties( propertiesMap ); + purgeProperties(propertiesMap); - return propertiesMap.values().toArray( new PropertyVersionsBuilder[0] ); + return propertiesMap.values().toArray(new PropertyVersionsBuilder[0]); } /** @@ -1102,109 +974,88 @@ public static PropertyVersionsBuilder[] getPropertyVersionsBuilders( VersionsHel * @param plugins The list of {@link org.apache.maven.model.Plugin}. * @throws ExpressionEvaluationException if an expression cannot be evaluated. */ - private static void addPluginAssociations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator, - Map result, List plugins ) - throws ExpressionEvaluationException - { - if ( plugins == null ) - { + private static void addPluginAssociations( + VersionsHelper helper, + ExpressionEvaluator expressionEvaluator, + Map result, + List plugins) + throws ExpressionEvaluationException { + if (plugins == null) { return; } - for ( Plugin plugin : plugins ) - { + for (Plugin plugin : plugins) { String version = plugin.getVersion(); - if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 ) - { - version = StringUtils.deleteWhitespace( version ); - for ( PropertyVersionsBuilder property : result.values() ) - { + if (version != null && version.contains("${") && version.indexOf('}') != -1) { + version = StringUtils.deleteWhitespace(version); + for (PropertyVersionsBuilder property : result.values()) { // any of these could be defined by a property final String propertyRef = "${" + property.getName() + "}"; - if ( version.contains( propertyRef ) ) - { + if (version.contains(propertyRef)) { String groupId = plugin.getGroupId(); - if ( groupId == null || groupId.trim().length() == 0 ) - { + if (groupId == null || groupId.trim().length() == 0) { // group Id has a special default groupId = APACHE_MAVEN_PLUGINS_GROUPID; - } - else - { - groupId = (String) expressionEvaluator.evaluate( groupId ); + } else { + groupId = (String) expressionEvaluator.evaluate(groupId); } String artifactId = plugin.getArtifactId(); - if ( artifactId == null || artifactId.trim().length() == 0 ) - { + if (artifactId == null || artifactId.trim().length() == 0) { // malformed pom continue; - } - else - { - artifactId = (String) expressionEvaluator.evaluate( artifactId ); + } else { + artifactId = (String) expressionEvaluator.evaluate(artifactId); } // might as well capture the current value - String evaluatedVersion = (String) expressionEvaluator.evaluate( plugin.getVersion() ); - property.addAssociation( helper.createPluginArtifact( groupId, artifactId, evaluatedVersion ), - true ); - if ( !propertyRef.equals( version ) ) - { - addBounds( property, version, propertyRef ); + String evaluatedVersion = (String) expressionEvaluator.evaluate(plugin.getVersion()); + property.addAssociation( + helper.createPluginArtifact(groupId, artifactId, evaluatedVersion), true); + if (!propertyRef.equals(version)) { + addBounds(property, version, propertyRef); } } } } - addDependencyAssocations( helper, expressionEvaluator, result, plugin.getDependencies(), true ); + addDependencyAssocations(helper, expressionEvaluator, result, plugin.getDependencies(), true); } } - private static void addReportPluginAssociations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator, - Map result, - List reportPlugins ) - throws ExpressionEvaluationException - { - if ( reportPlugins == null ) - { + private static void addReportPluginAssociations( + VersionsHelper helper, + ExpressionEvaluator expressionEvaluator, + Map result, + List reportPlugins) + throws ExpressionEvaluationException { + if (reportPlugins == null) { return; } - for ( ReportPlugin plugin : reportPlugins ) - { + for (ReportPlugin plugin : reportPlugins) { String version = plugin.getVersion(); - if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 ) - { - version = StringUtils.deleteWhitespace( version ); - for ( PropertyVersionsBuilder property : result.values() ) - { + if (version != null && version.contains("${") && version.indexOf('}') != -1) { + version = StringUtils.deleteWhitespace(version); + for (PropertyVersionsBuilder property : result.values()) { final String propertyRef = "${" + property.getName() + "}"; - if ( version.contains( propertyRef ) ) - { + if (version.contains(propertyRef)) { // any of these could be defined by a property String groupId = plugin.getGroupId(); - if ( groupId == null || groupId.trim().length() == 0 ) - { + if (groupId == null || groupId.trim().length() == 0) { // group Id has a special default groupId = APACHE_MAVEN_PLUGINS_GROUPID; - } - else - { - groupId = (String) expressionEvaluator.evaluate( groupId ); + } else { + groupId = (String) expressionEvaluator.evaluate(groupId); } String artifactId = plugin.getArtifactId(); - if ( artifactId == null || artifactId.trim().length() == 0 ) - { + if (artifactId == null || artifactId.trim().length() == 0) { // malformed pom continue; - } - else - { - artifactId = (String) expressionEvaluator.evaluate( artifactId ); + } else { + artifactId = (String) expressionEvaluator.evaluate(artifactId); } // might as well capture the current value - String versionEvaluated = (String) expressionEvaluator.evaluate( plugin.getVersion() ); - property.addAssociation( helper.createPluginArtifact( groupId, artifactId, versionEvaluated ), - true ); - if ( !propertyRef.equals( version ) ) - { - addBounds( property, version, propertyRef ); + String versionEvaluated = (String) expressionEvaluator.evaluate(plugin.getVersion()); + property.addAssociation( + helper.createPluginArtifact(groupId, artifactId, versionEvaluated), true); + if (!propertyRef.equals(version)) { + addBounds(property, version, propertyRef); } } } @@ -1212,58 +1063,52 @@ private static void addReportPluginAssociations( VersionsHelper helper, Expressi } } - private static void addDependencyAssocations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator, - Map result, - List dependencies, boolean usePluginRepositories ) - throws ExpressionEvaluationException - { - if ( dependencies == null ) - { + private static void addDependencyAssocations( + VersionsHelper helper, + ExpressionEvaluator expressionEvaluator, + Map result, + List dependencies, + boolean usePluginRepositories) + throws ExpressionEvaluationException { + if (dependencies == null) { return; } - for ( Dependency dependency : dependencies ) - { + for (Dependency dependency : dependencies) { String version = dependency.getVersion(); - if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 ) - { - version = StringUtils.deleteWhitespace( version ); - for ( PropertyVersionsBuilder property : result.values() ) - { + if (version != null && version.contains("${") && version.indexOf('}') != -1) { + version = StringUtils.deleteWhitespace(version); + for (PropertyVersionsBuilder property : result.values()) { final String propertyRef = "${" + property.getName() + "}"; - if ( version.contains( propertyRef ) ) - { + if (version.contains(propertyRef)) { // Any of these could be defined by a property String groupId = dependency.getGroupId(); - if ( groupId == null || groupId.trim().length() == 0 ) - { + if (groupId == null || groupId.trim().length() == 0) { // malformed pom continue; - } - else - { - groupId = (String) expressionEvaluator.evaluate( groupId ); + } else { + groupId = (String) expressionEvaluator.evaluate(groupId); } String artifactId = dependency.getArtifactId(); - if ( artifactId == null || artifactId.trim().length() == 0 ) - { + if (artifactId == null || artifactId.trim().length() == 0) { // malformed pom continue; - } - else - { - artifactId = (String) expressionEvaluator.evaluate( artifactId ); + } else { + artifactId = (String) expressionEvaluator.evaluate(artifactId); } // might as well capture the current value - String versionEvaluated = (String) expressionEvaluator.evaluate( dependency.getVersion() ); - property.addAssociation( helper.createDependencyArtifact( groupId, artifactId, versionEvaluated, - dependency.getType(), - dependency.getClassifier(), - dependency.getScope(), - dependency.isOptional() ), - usePluginRepositories ); - if ( !propertyRef.equals( version ) ) - { - addBounds( property, version, propertyRef ); + String versionEvaluated = (String) expressionEvaluator.evaluate(dependency.getVersion()); + property.addAssociation( + helper.createDependencyArtifact( + groupId, + artifactId, + versionEvaluated, + dependency.getType(), + dependency.getClassifier(), + dependency.getScope(), + dependency.isOptional()), + usePluginRepositories); + if (!propertyRef.equals(version)) { + addBounds(property, version, propertyRef); } } } @@ -1271,51 +1116,44 @@ private static void addDependencyAssocations( VersionsHelper helper, ExpressionE } } - private static void addBounds( PropertyVersionsBuilder builder, String rawVersionRange, String propertyRef ) - { - Pattern lowerBound = Pattern.compile( "([(\\[])([^,]*)," + RegexUtils.quote( propertyRef ) + "([)\\]])" ); - Pattern upperBound = Pattern.compile( "([(\\[])" + RegexUtils.quote( propertyRef ) + ",([^,]*)([)\\]])" ); - Matcher m = lowerBound.matcher( rawVersionRange ); - if ( m.find() ) - { - boolean includeLower = "[".equals( m.group( 1 ) ); - String lowerLimit = m.group( 2 ); - if ( StringUtils.isNotEmpty( lowerLimit ) ) - { - builder.addLowerBound( lowerLimit, includeLower ); + private static void addBounds(PropertyVersionsBuilder builder, String rawVersionRange, String propertyRef) { + Pattern lowerBound = Pattern.compile("([(\\[])([^,]*)," + RegexUtils.quote(propertyRef) + "([)\\]])"); + Pattern upperBound = Pattern.compile("([(\\[])" + RegexUtils.quote(propertyRef) + ",([^,]*)([)\\]])"); + Matcher m = lowerBound.matcher(rawVersionRange); + if (m.find()) { + boolean includeLower = "[".equals(m.group(1)); + String lowerLimit = m.group(2); + if (StringUtils.isNotEmpty(lowerLimit)) { + builder.addLowerBound(lowerLimit, includeLower); } } - m = upperBound.matcher( rawVersionRange ); - if ( m.find() ) - { - boolean includeUpper = "[".equals( m.group( 3 ) ); - String upperLimit = m.group( 2 ); - if ( StringUtils.isNotEmpty( upperLimit ) ) - { - builder.addUpperBound( upperLimit, includeUpper ); + m = upperBound.matcher(rawVersionRange); + if (m.find()) { + boolean includeUpper = "[".equals(m.group(3)); + String upperLimit = m.group(2); + if (StringUtils.isNotEmpty(upperLimit)) { + builder.addUpperBound(upperLimit, includeUpper); } } } - private static void addProperties( VersionsHelper helper, Map result, - String profileId, Properties properties ) - { - if ( properties == null ) - { + private static void addProperties( + VersionsHelper helper, + Map result, + String profileId, + Properties properties) { + if (properties == null) { return; } - for ( String propertyName : properties.stringPropertyNames() ) - { - if ( !result.containsKey( propertyName ) ) - { - result.put( propertyName, new PropertyVersionsBuilder( profileId, propertyName, helper ) ); + for (String propertyName : properties.stringPropertyNames()) { + if (!result.containsKey(propertyName)) { + result.put(propertyName, new PropertyVersionsBuilder(profileId, propertyName, helper)); } } } - private static void purgeProperties( Map result ) - { - result.values().removeIf( versions -> versions.getAssociations().length == 0 ); + private static void purgeProperties(Map result) { + result.values().removeIf(versions -> versions.getAssociations().length == 0); } /** @@ -1326,9 +1164,8 @@ private static void purgeProperties( Map result * @param logger The logger to use. * @return the set of all child modules of the project. */ - public static Set getAllChildModules( MavenProject project, Log logger ) - { - return getAllChildModules( project.getOriginalModel(), logger ); + public static Set getAllChildModules(MavenProject project, Log logger) { + return getAllChildModules(project.getOriginalModel(), logger); } /** @@ -1339,12 +1176,11 @@ public static Set getAllChildModules( MavenProject project, Log logger ) * @param logger The logger to use. * @return the set of all child modules of the project. */ - public static Set getAllChildModules( Model model, Log logger ) - { - logger.debug( "Finding child modules..." ); - Set childModules = new TreeSet<>( model.getModules() ); - model.getProfiles().forEach( profile -> childModules.addAll( profile.getModules() ) ); - debugModules( logger, "Child modules:", childModules ); + public static Set getAllChildModules(Model model, Log logger) { + logger.debug("Finding child modules..."); + Set childModules = new TreeSet<>(model.getModules()); + model.getProfiles().forEach(profile -> childModules.addAll(profile.getModules())); + debugModules(logger, "Child modules:", childModules); return childModules; } @@ -1355,20 +1191,14 @@ public static Set getAllChildModules( Model model, Log logger ) * @param message The message to display. * @param modules The modules to append to the message. */ - public static void debugModules( Log logger, String message, Collection modules ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( message ); - if ( modules.isEmpty() ) - { - logger.debug( "None." ); - } - else - { - modules.forEach( module -> logger.debug( " " + module ) ); + public static void debugModules(Log logger, String message, Collection modules) { + if (logger.isDebugEnabled()) { + logger.debug(message); + if (modules.isEmpty()) { + logger.debug("None."); + } else { + modules.forEach(module -> logger.debug(" " + module)); } - } } @@ -1379,31 +1209,27 @@ public static void debugModules( Log logger, String message, Collection * @param basedir the project basedir. * @param childModules the child modules. */ - public static void removeMissingChildModules( Log logger, File basedir, Collection childModules ) - { - logger.debug( "Removing child modules which are missing..." ); + public static void removeMissingChildModules(Log logger, File basedir, Collection childModules) { + logger.debug("Removing child modules which are missing..."); Iterator i = childModules.iterator(); - while ( i.hasNext() ) - { + while (i.hasNext()) { String modulePath = i.next(); - File moduleFile = new File( basedir, modulePath ); + File moduleFile = new File(basedir, modulePath); - if ( moduleFile.isDirectory() && new File( moduleFile, "pom.xml" ).isFile() ) - { + if (moduleFile.isDirectory() && new File(moduleFile, "pom.xml").isFile()) { // it's a directory that exists continue; } - if ( moduleFile.isFile() ) - { + if (moduleFile.isFile()) { // it's the pom.xml file directly referenced and it exists. continue; } - logger.debug( "Removing missing child module " + modulePath ); + logger.debug("Removing missing child module " + modulePath); i.remove(); } - debugModules( logger, "After removing missing", childModules ); + debugModules(logger, "After removing missing", childModules); } /** @@ -1412,11 +1238,9 @@ public static void removeMissingChildModules( Log logger, File basedir, Collecti * @param model The model. * @return The version. */ - public static String getVersion( Model model ) - { + public static String getVersion(Model model) { String targetVersion = model.getVersion(); - if ( targetVersion == null && model.getParent() != null ) - { + if (targetVersion == null && model.getParent() != null) { targetVersion = model.getParent().getVersion(); } return targetVersion; @@ -1428,8 +1252,7 @@ public static String getVersion( Model model ) * @param model The model. * @return {@code true} if the model explicitly specifies the project version, i.e. /project/version */ - public static boolean isExplicitVersion( Model model ) - { + public static boolean isExplicitVersion(Model model) { return model.getVersion() != null; } @@ -1439,11 +1262,9 @@ public static boolean isExplicitVersion( Model model ) * @param model The model. * @return The artifactId. */ - public static String getArtifactId( Model model ) - { + public static String getArtifactId(Model model) { String sourceArtifactId = model.getArtifactId(); - if ( sourceArtifactId == null && model.getParent() != null ) - { + if (sourceArtifactId == null && model.getParent() != null) { sourceArtifactId = model.getParent().getArtifactId(); } return sourceArtifactId; @@ -1455,11 +1276,9 @@ public static String getArtifactId( Model model ) * @param model The model. * @return The groupId. */ - public static String getGroupId( Model model ) - { + public static String getGroupId(Model model) { String targetGroupId = model.getGroupId(); - if ( targetGroupId == null && model.getParent() != null ) - { + if (targetGroupId == null && model.getParent() != null) { targetGroupId = model.getParent().getGroupId(); } return targetGroupId; @@ -1473,50 +1292,36 @@ public static String getGroupId( Model model ) * @param logger The logger to log tog * @return The local root (note this may be the project passed as an argument). */ - public static MavenProject getLocalRoot( ProjectBuilder projectBuilder, - MavenSession mavenSession, - Log logger ) - { - logger.info( "Searching for local aggregator root..." ); + public static MavenProject getLocalRoot(ProjectBuilder projectBuilder, MavenSession mavenSession, Log logger) { + logger.info("Searching for local aggregator root..."); MavenProject project = mavenSession.getCurrentProject(); - while ( true ) - { + while (true) { final File parentDir = project.getBasedir().getParentFile(); - if ( parentDir != null && parentDir.isDirectory() ) - { - logger.debug( "Checking to see if " + parentDir + " is an aggregator parent" ); - File parentFile = new File( parentDir, "pom.xml" ); - if ( parentFile.isFile() ) - { - try - { - ProjectBuildingResult result = projectBuilder.build( parentFile, - createProjectBuilderRequest( mavenSession ) ); - if ( !result.getProblems().isEmpty() ) - { - logger.warn( "Problems encountered during the computation of the local aggregation root." ); - result.getProblems().forEach( p -> - logger.warn( "\t" + p.getMessage() ) ); + if (parentDir != null && parentDir.isDirectory()) { + logger.debug("Checking to see if " + parentDir + " is an aggregator parent"); + File parentFile = new File(parentDir, "pom.xml"); + if (parentFile.isFile()) { + try { + ProjectBuildingResult result = + projectBuilder.build(parentFile, createProjectBuilderRequest(mavenSession)); + if (!result.getProblems().isEmpty()) { + logger.warn("Problems encountered during the computation of the local aggregation root."); + result.getProblems().forEach(p -> logger.warn("\t" + p.getMessage())); } - if ( getAllChildModules( result.getProject(), logger ) - .contains( project.getBasedir().getName() ) ) - { - logger.debug( parentDir + " is an aggregator parent" ); + if (getAllChildModules(result.getProject(), logger) + .contains(project.getBasedir().getName())) { + logger.debug(parentDir + " is an aggregator parent"); project = result.getProject(); continue; + } else { + logger.debug(parentDir + " is not an aggregator parent"); } - else - { - logger.debug( parentDir + " is not an aggregator parent" ); - } - } - catch ( ProjectBuildingException e ) - { - logger.warn( e ); + } catch (ProjectBuildingException e) { + logger.warn(e); } } } - logger.debug( "Local aggregation root is " + project.getBasedir() ); + logger.debug("Local aggregation root is " + project.getBasedir()); return project; } } @@ -1530,23 +1335,23 @@ public static MavenProject getLocalRoot( ProjectBuilder projectBuilder, * @return constructed builder request */ @SafeVarargs - public static ProjectBuildingRequest createProjectBuilderRequest( MavenSession mavenSession, - Consumer... initializers ) - { - return new DefaultProjectBuildingRequest() - {{ - setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); - setResolveDependencies( false ); - setLocalRepository( mavenSession.getLocalRepository() ); - setRemoteRepositories( mavenSession.getCurrentProject().getRemoteArtifactRepositories() ); - setBuildStartTime( mavenSession.getStartTime() ); - setUserProperties( mavenSession.getUserProperties() ); - setSystemProperties( mavenSession.getSystemProperties() ); - setActiveProfileIds( mavenSession.getRequest().getActiveProfiles() ); - setInactiveProfileIds( mavenSession.getRequest().getInactiveProfiles() ); - setRepositorySession( mavenSession.getRepositorySession() ); - Arrays.stream( initializers ).forEach( i -> i.accept( this ) ); - }}; + public static ProjectBuildingRequest createProjectBuilderRequest( + MavenSession mavenSession, Consumer... initializers) { + return new DefaultProjectBuildingRequest() { + { + setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); + setResolveDependencies(false); + setLocalRepository(mavenSession.getLocalRepository()); + setRemoteRepositories(mavenSession.getCurrentProject().getRemoteArtifactRepositories()); + setBuildStartTime(mavenSession.getStartTime()); + setUserProperties(mavenSession.getUserProperties()); + setSystemProperties(mavenSession.getSystemProperties()); + setActiveProfileIds(mavenSession.getRequest().getActiveProfiles()); + setInactiveProfileIds(mavenSession.getRequest().getInactiveProfiles()); + setRepositorySession(mavenSession.getRepositorySession()); + Arrays.stream(initializers).forEach(i -> i.accept(this)); + } + }; } /** @@ -1557,14 +1362,12 @@ public static ProjectBuildingRequest createProjectBuilderRequest( MavenSession m * @return A map of raw models keyed by path relative to the project's basedir. * @throws IOException if things go wrong. */ - public static Map getReactorModels( MavenProject project, Log logger ) - throws IOException - { + public static Map getReactorModels(MavenProject project, Log logger) throws IOException { Map result = new LinkedHashMap<>(); - final Model model = getRawModel( project ); + final Model model = getRawModel(project); final String path = ""; - result.put( path, model ); - result.putAll( getReactorModels( path, model, project, logger ) ); + result.put(path, model); + result.putAll(getReactorModels(path, model, project, logger)); return result; } @@ -1578,46 +1381,35 @@ public static Map getReactorModels( MavenProject project, Log log * @return A map of raw models keyed by path relative to the project's basedir. * @throws IOException if things go wrong. */ - private static Map getReactorModels( String path, Model model, MavenProject project, Log logger ) - throws IOException - { + private static Map getReactorModels(String path, Model model, MavenProject project, Log logger) + throws IOException { Map result = new LinkedHashMap<>(); Map childResults = new LinkedHashMap<>(); - Set childModules = getAllChildModules( model, logger ); + Set childModules = getAllChildModules(model, logger); - File baseDir = path.length() > 0 - ? new File( project.getBasedir(), path ) - : project.getBasedir(); - removeMissingChildModules( logger, baseDir, childModules ); + File baseDir = path.length() > 0 ? new File(project.getBasedir(), path) : project.getBasedir(); + removeMissingChildModules(logger, baseDir, childModules); childModules.stream() - .map( moduleName -> new File( baseDir, moduleName ) ) - .filter( File::exists ) - .forEach( moduleFile -> - { - File pomFile = moduleFile.isDirectory() - ? new File( moduleFile, "/pom.xml" ) - : moduleFile; - String modulePath = ( !path.isEmpty() && !path.endsWith( "/" ) - ? path + "/" - : path ) + .map(moduleName -> new File(baseDir, moduleName)) + .filter(File::exists) + .forEach(moduleFile -> { + File pomFile = moduleFile.isDirectory() ? new File(moduleFile, "/pom.xml") : moduleFile; + String modulePath = (!path.isEmpty() && !path.endsWith("/") ? path + "/" : path) + pomFile.getParentFile().getName(); - try - { + try { // the aim of this goal is to fix problems when the project cannot be parsed by Maven, // so we have to work with the raw model and not the interpolated parsed model from maven - Model moduleModel = getRawModel( pomFile ); - result.put( modulePath, moduleModel ); - childResults.putAll( getReactorModels( modulePath, moduleModel, project, logger ) ); - } - catch ( IOException e ) - { - logger.debug( "Could not parse " + pomFile.getPath(), e ); + Model moduleModel = getRawModel(pomFile); + result.put(modulePath, moduleModel); + childResults.putAll(getReactorModels(modulePath, moduleModel, project, logger)); + } catch (IOException e) { + logger.debug("Could not parse " + pomFile.getPath(), e); } - } ); + }); - result.putAll( childResults ); // more efficient update order if all children are added after siblings + result.putAll(childResults); // more efficient update order if all children are added after siblings return result; } @@ -1629,18 +1421,14 @@ private static Map getReactorModels( String path, Model model, Ma * @param artifactId The artifactId of the parent. * @return a map of models that have a specified groupId and artifactId as parent keyed by path. */ - public static Map getChildModels( Map reactor, String groupId, String artifactId ) - { + public static Map getChildModels(Map reactor, String groupId, String artifactId) { final Map result = new LinkedHashMap<>(); - for ( Map.Entry entry : reactor.entrySet() ) - { + for (Map.Entry entry : reactor.entrySet()) { final String path = entry.getKey(); final Model model = entry.getValue(); final Parent parent = model.getParent(); - if ( parent != null && groupId.equals( parent.getGroupId() ) - && artifactId.equals( parent.getArtifactId() ) ) - { - result.put( path, model ); + if (parent != null && groupId.equals(parent.getGroupId()) && artifactId.equals(parent.getArtifactId())) { + result.put(path, model); } } return result; @@ -1654,11 +1442,12 @@ public static Map getChildModels( Map reactor, Str * @param artifactId The artifactId to match. * @return The model or null if the model was not in the reactor. */ - public static Model getModel( Map reactor, String groupId, String artifactId ) - { - return reactor.values().stream().filter( - model -> ( groupId == null || groupId.equals( getGroupId( model ) ) ) && artifactId.equals( - getArtifactId( model ) ) ).findAny().orElse( null ); + public static Model getModel(Map reactor, String groupId, String artifactId) { + return reactor.values().stream() + .filter(model -> (groupId == null || groupId.equals(getGroupId(model))) + && artifactId.equals(getArtifactId(model))) + .findAny() + .orElse(null); } /** @@ -1670,12 +1459,13 @@ public static Model getModel( Map reactor, String groupId, String * @param artifactId The artifactId to match. * @return The model entry or null if the model was not in the reactor. */ - public static Map.Entry getModelEntry( Map reactor, String groupId, - String artifactId ) - { - return reactor.entrySet().stream().filter( - e -> ( groupId == null || groupId.equals( PomHelper.getGroupId( e.getValue() ) ) ) && artifactId.equals( - PomHelper.getArtifactId( e.getValue() ) ) ).findAny().orElse( null ); + public static Map.Entry getModelEntry( + Map reactor, String groupId, String artifactId) { + return reactor.entrySet().stream() + .filter(e -> (groupId == null || groupId.equals(PomHelper.getGroupId(e.getValue()))) + && artifactId.equals(PomHelper.getArtifactId(e.getValue()))) + .findAny() + .orElse(null); } /** @@ -1685,18 +1475,16 @@ public static Map.Entry getModelEntry( Map reactor * @param model The model. * @return The number of parents of this model in the reactor. */ - public static int getReactorParentCount( Map reactor, Model model ) - { - if ( model.getParent() == null ) - { + public static int getReactorParentCount(Map reactor, Model model) { + if (model.getParent() == null) { return 0; } - Model parentModel = getModel( reactor, model.getParent().getGroupId(), model.getParent().getArtifactId() ); - if ( parentModel == null ) - { + Model parentModel = getModel( + reactor, model.getParent().getGroupId(), model.getParent().getArtifactId()); + if (parentModel == null) { return 0; } - return getReactorParentCount( reactor, parentModel ) + 1; + return getReactorParentCount(reactor, parentModel) + 1; } /** @@ -1706,12 +1494,9 @@ public static int getReactorParentCount( Map reactor, Model model * @return String The content of the file. * @throws java.io.IOException when things go wrong. */ - public static StringBuilder readXmlFile( File outFile ) - throws IOException - { - try ( Reader reader = ReaderFactory.newXmlReader( outFile ) ) - { - return new StringBuilder( IOUtil.toString( reader ) ); + public static StringBuilder readXmlFile(File outFile) throws IOException { + try (Reader reader = ReaderFactory.newXmlReader(outFile)) { + return new StringBuilder(IOUtil.toString(reader)); } } @@ -1721,8 +1506,7 @@ public static StringBuilder readXmlFile( File outFile ) * @param model the model. * @return the GAV coordinates of a model. */ - public static String getGAV( Model model ) - { - return getGroupId( model ) + ":" + getArtifactId( model ) + ":" + getVersion( model ); + public static String getGAV(Model model) { + return getGroupId(model) + ":" + getArtifactId(model) + ":" + getVersion(model); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/Property.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/Property.java index 395121df9f..e7263939c1 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/Property.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/Property.java @@ -27,8 +27,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public class Property -{ +public class Property { /** * The property that defines the version of the artifact to use. * @@ -98,13 +97,11 @@ public class Property private static final Dependency[] EMPTY_DEPENDENCY_ARRAY = new Dependency[0]; - public Property() - { + public Property() { this.autoLinkDependencies = true; } - public Property( String name ) - { + public Property(String name) { this.name = name; this.autoLinkDependencies = true; this.dependencies = EMPTY_DEPENDENCY_ARRAY; @@ -115,83 +112,67 @@ public Property( String name ) this.value = null; } - public String getName() - { + public String getName() { return name; } - public void setName( String name ) - { + public void setName(String name) { this.name = name; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public boolean isAutoLinkDependencies() - { + public boolean isAutoLinkDependencies() { return autoLinkDependencies; } - public void setAutoLinkDependencies( boolean autoLinkDependencies ) - { + public void setAutoLinkDependencies(boolean autoLinkDependencies) { this.autoLinkDependencies = autoLinkDependencies; } - public Dependency[] getDependencies() - { + public Dependency[] getDependencies() { return dependencies; } - public void setDependencies( Dependency[] dependencies ) - { + public void setDependencies(Dependency[] dependencies) { this.dependencies = dependencies; } - public boolean isSearchReactor() - { + public boolean isSearchReactor() { return searchReactor; } - public void setSearchReactor( boolean searchReactor ) - { + public void setSearchReactor(boolean searchReactor) { this.searchReactor = searchReactor; } - public boolean isPreferReactor() - { + public boolean isPreferReactor() { return preferReactor; } - public void setPreferReactor( boolean preferReactor ) - { + public void setPreferReactor(boolean preferReactor) { this.preferReactor = preferReactor; } - public boolean isBanSnapshots() - { + public boolean isBanSnapshots() { return banSnapshots; } - public void setBanSnapshots( boolean banSnapshots ) - { + public void setBanSnapshots(boolean banSnapshots) { this.banSnapshots = banSnapshots; } - public String getValue() - { + public String getValue() { return value; } - public void setValue( String value ) - { + public void setValue(String value) { this.value = value; } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java index cfef7f9cd4..eecff4b98a 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java @@ -52,9 +52,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public class PropertyVersions - extends AbstractVersionDetails -{ +public class PropertyVersions extends AbstractVersionDetails { private final String name; private final String profileId; @@ -72,63 +70,50 @@ public class PropertyVersions private final PropertyVersions.PropertyVersionComparator comparator; - PropertyVersions( String profileId, String name, VersionsHelper helper, Set associations ) - throws VersionRetrievalException - { + PropertyVersions(String profileId, String name, VersionsHelper helper, Set associations) + throws VersionRetrievalException { this.profileId = profileId; this.name = name; this.helper = helper; - this.associations = new TreeSet<>( associations ); + this.associations = new TreeSet<>(associations); this.comparator = new PropertyVersionComparator(); - this.versions = resolveAssociatedVersions( helper, associations, comparator ); - + this.versions = resolveAssociatedVersions(helper, associations, comparator); } - private static SortedSet resolveAssociatedVersions( VersionsHelper helper, - Set associations, - VersionComparator versionComparator ) - throws VersionRetrievalException - { + private static SortedSet resolveAssociatedVersions( + VersionsHelper helper, Set associations, VersionComparator versionComparator) + throws VersionRetrievalException { SortedSet versions = null; - for ( ArtifactAssociation association : associations ) - { + for (ArtifactAssociation association : associations) { final ArtifactVersions associatedVersions = - helper.lookupArtifactVersions( association.getArtifact(), association.isUsePluginRepositories() ); - if ( versions != null ) - { - final ArtifactVersion[] artifactVersions = associatedVersions.getVersions( true ); + helper.lookupArtifactVersions(association.getArtifact(), association.isUsePluginRepositories()); + if (versions != null) { + final ArtifactVersion[] artifactVersions = associatedVersions.getVersions(true); // since ArtifactVersion does not override equals, we have to do this the hard way // result.retainAll( Arrays.asList( artifactVersions ) ); Iterator j = versions.iterator(); - while ( j.hasNext() ) - { + while (j.hasNext()) { boolean contains = false; ArtifactVersion version = j.next(); - for ( ArtifactVersion artifactVersion : artifactVersions ) - { - if ( version.compareTo( artifactVersion ) == 0 ) - { + for (ArtifactVersion artifactVersion : artifactVersions) { + if (version.compareTo(artifactVersion) == 0) { contains = true; break; } } - if ( !contains ) - { + if (!contains) { j.remove(); } } - } - else - { - versions = new TreeSet<>( versionComparator ); - versions.addAll( Arrays.asList( associatedVersions.getVersions( true ) ) ); + } else { + versions = new TreeSet<>(versionComparator); + versions.addAll(Arrays.asList(associatedVersions.getVersions(true))); } } - if ( versions == null ) - { - versions = new TreeSet<>( versionComparator ); + if (versions == null) { + versions = new TreeSet<>(versionComparator); } - return Collections.unmodifiableSortedSet( versions ); + return Collections.unmodifiableSortedSet(versions); } /** @@ -137,20 +122,19 @@ private static SortedSet resolveAssociatedVersions( VersionsHel * @return the rule for version comparison of this artifact. * @since 1.0-beta-1 */ - public VersionComparator getVersionComparator() - { + public VersionComparator getVersionComparator() { return comparator; } - public ArtifactAssociation[] getAssociations() - { - return associations.toArray( new ArtifactAssociation[0] ); + public ArtifactAssociation[] getAssociations() { + return associations.toArray(new ArtifactAssociation[0]); } - private VersionComparator[] lookupComparators() - { - return associations.stream().map( association -> helper.getVersionComparator( association.getArtifact() ) ) - .distinct().toArray( VersionComparator[]::new ); + private VersionComparator[] lookupComparators() { + return associations.stream() + .map(association -> helper.getVersionComparator(association.getArtifact())) + .distinct() + .toArray(VersionComparator[]::new); } /** @@ -162,27 +146,20 @@ private VersionComparator[] lookupComparators() * is also associated to an artifact that has not been provided). * @since 1.0-alpha-3 */ - public ArtifactVersion[] getVersions( Collection artifacts ) - { + public ArtifactVersion[] getVersions(Collection artifacts) { List result = new ArrayList<>(); // go through all the associations // see if they are met from the collection // add the version if they are // go through all the versions // see if the version is available for all associations - for ( ArtifactAssociation association : associations ) - { - for ( Artifact artifact : artifacts ) - { - if ( association.getGroupId().equals( artifact.getGroupId() ) - && association.getArtifactId().equals( artifact.getArtifactId() ) ) - { - try - { - result.add( artifact.getSelectedVersion() ); - } - catch ( OverConstrainedVersionException e ) - { + for (ArtifactAssociation association : associations) { + for (Artifact artifact : artifacts) { + if (association.getGroupId().equals(artifact.getGroupId()) + && association.getArtifactId().equals(artifact.getArtifactId())) { + try { + result.add(artifact.getSelectedVersion()); + } catch (OverConstrainedVersionException e) { // ignore this one as we cannot resolve a valid version } } @@ -191,27 +168,21 @@ public ArtifactVersion[] getVersions( Collection artifacts ) // we now have a list of all the versions that partially satisfy the association requirements Iterator k = result.iterator(); versions: - while ( k.hasNext() ) - { + while (k.hasNext()) { ArtifactVersion candidate = k.next(); associations: - for ( ArtifactAssociation association : associations ) - { - for ( Artifact artifact : artifacts ) - { - if ( association.getGroupId().equals( artifact.getGroupId() ) - && association.getArtifactId().equals( artifact.getArtifactId() ) ) - { - try - { - if ( candidate.toString().equals( artifact.getSelectedVersion().toString() ) ) - { + for (ArtifactAssociation association : associations) { + for (Artifact artifact : artifacts) { + if (association.getGroupId().equals(artifact.getGroupId()) + && association.getArtifactId().equals(artifact.getArtifactId())) { + try { + if (candidate + .toString() + .equals(artifact.getSelectedVersion().toString())) { // this association can be met, try the next continue associations; } - } - catch ( OverConstrainedVersionException e ) - { + } catch (OverConstrainedVersionException e) { // ignore this one again } } @@ -221,7 +192,7 @@ public ArtifactVersion[] getVersions( Collection artifacts ) continue versions; } } - return asArtifactVersionArray( result ); + return asArtifactVersionArray(result); } /** @@ -231,90 +202,74 @@ public ArtifactVersion[] getVersions( Collection artifacts ) * @param includeSnapshots Whether to include snapshot versions in our search. * @return The (possibly empty) array of versions. */ - public synchronized ArtifactVersion[] getVersions( boolean includeSnapshots ) - { + public synchronized ArtifactVersion[] getVersions(boolean includeSnapshots) { Set result; - if ( includeSnapshots ) - { + if (includeSnapshots) { result = versions; - } - else - { - result = new TreeSet<>( getVersionComparator() ); - for ( ArtifactVersion candidate : versions ) - { - if ( ArtifactUtils.isSnapshot( candidate.toString() ) ) - { + } else { + result = new TreeSet<>(getVersionComparator()); + for (ArtifactVersion candidate : versions) { + if (ArtifactUtils.isSnapshot(candidate.toString())) { continue; } - result.add( candidate ); + result.add(candidate); } } - return asArtifactVersionArray( result ); + return asArtifactVersionArray(result); } - private ArtifactVersion[] asArtifactVersionArray( Collection result ) - { - if ( result == null || result.isEmpty() ) - { + private ArtifactVersion[] asArtifactVersionArray(Collection result) { + if (result == null || result.isEmpty()) { return new ArtifactVersion[0]; - } - else - { - final ArtifactVersion[] answer = result.toArray( new ArtifactVersion[0] ); + } else { + final ArtifactVersion[] answer = result.toArray(new ArtifactVersion[0]); VersionComparator[] rules = lookupComparators(); assert rules.length > 0; - Arrays.sort( answer, rules[0] ); - if ( rules.length == 1 || answer.length == 1 ) - { + Arrays.sort(answer, rules[0]); + if (rules.length == 1 || answer.length == 1) { // only one rule... return answer; } ArtifactVersion[] alt = answer.clone(); - for ( int j = 1; j < rules.length; j++ ) - { - Arrays.sort( alt, rules[j] ); - if ( !Arrays.equals( alt, answer ) ) - { - throw new IllegalStateException( - "Property " + name + " is associated with multiple artifacts" + for (int j = 1; j < rules.length; j++) { + Arrays.sort(alt, rules[j]); + if (!Arrays.equals(alt, answer)) { + throw new IllegalStateException("Property " + name + " is associated with multiple artifacts" + " and these artifacts use different version sorting rules and these rules are effectively" + " incompatible for the set of versions available to this property.\nFirst rule says: " - + Arrays.asList( answer ) + "\nSecond rule says: " - + Arrays.asList( alt ) ); + + Arrays.asList(answer) + "\nSecond rule says: " + + Arrays.asList(alt)); } } return answer; } } - public String getName() - { + public String getName() { return name; } - public String getProfileId() - { + public String getProfileId() { return profileId; } - public boolean isAssociated() - { + public boolean isAssociated() { return !associations.isEmpty(); } - public String toString() - { - return "PropertyVersions{" + ( profileId == null ? "" : "profileId='" + profileId + "', " ) + "name='" + name - + '\'' + ", associations=" + associations + '}'; + public String toString() { + return "PropertyVersions{" + (profileId == null ? "" : "profileId='" + profileId + "', ") + "name='" + name + + '\'' + ", associations=" + associations + '}'; } - public ArtifactVersion getNewestVersion( String currentVersion, Property property, boolean allowSnapshots, - List reactorProjects, VersionsHelper helper ) - throws InvalidVersionSpecificationException, InvalidSegmentException - { - return getNewestVersion( currentVersion, property, allowSnapshots, reactorProjects, helper, - false, empty() ); + public ArtifactVersion getNewestVersion( + String currentVersion, + Property property, + boolean allowSnapshots, + List reactorProjects, + VersionsHelper helper) + throws InvalidVersionSpecificationException, InvalidSegmentException { + return getNewestVersion(currentVersion, property, allowSnapshots, reactorProjects, helper, false, empty()); } /** @@ -333,96 +288,84 @@ public ArtifactVersion getNewestVersion( String currentVersion, Property propert * of segments in the version string) * @throws InvalidVersionSpecificationException thrown if the version string in the property is not valid */ - public ArtifactVersion getNewestVersion( String versionString, Property property, boolean allowSnapshots, - Collection reactorProjects, VersionsHelper helper, - boolean allowDowngrade, Optional upperBoundSegment ) - throws InvalidSegmentException, InvalidVersionSpecificationException - { + public ArtifactVersion getNewestVersion( + String versionString, + Property property, + boolean allowSnapshots, + Collection reactorProjects, + VersionsHelper helper, + boolean allowDowngrade, + Optional upperBoundSegment) + throws InvalidSegmentException, InvalidVersionSpecificationException { final boolean includeSnapshots = !property.isBanSnapshots() && allowSnapshots; - helper.getLog().debug( "getNewestVersion(): includeSnapshots='" + includeSnapshots + "'" ); - helper.getLog().debug( "Property ${" + property.getName() + "}: Set of valid available versions is " - + Arrays.asList( getVersions( includeSnapshots ) ) ); - VersionRange range = property.getVersion() != null - ? VersionRange.createFromVersionSpec( property.getVersion() ) : null; - helper.getLog().debug( "Property ${" + property.getName() + "}: Restricting results to " + range ); - - - ArtifactVersion currentVersion = new DefaultArtifactVersion( versionString ); + helper.getLog().debug("getNewestVersion(): includeSnapshots='" + includeSnapshots + "'"); + helper.getLog() + .debug("Property ${" + property.getName() + "}: Set of valid available versions is " + + Arrays.asList(getVersions(includeSnapshots))); + VersionRange range = + property.getVersion() != null ? VersionRange.createFromVersionSpec(property.getVersion()) : null; + helper.getLog().debug("Property ${" + property.getName() + "}: Restricting results to " + range); + + ArtifactVersion currentVersion = new DefaultArtifactVersion(versionString); ArtifactVersion lowerBound = allowDowngrade - ? getLowerBound( currentVersion, upperBoundSegment ) - .map( DefaultArtifactVersion::new ) - .orElse( null ) + ? getLowerBound(currentVersion, upperBoundSegment) + .map(DefaultArtifactVersion::new) + .orElse(null) : currentVersion; - if ( helper.getLog().isDebugEnabled() ) - { - helper.getLog().debug( "lowerBoundArtifactVersion: " + lowerBound ); + if (helper.getLog().isDebugEnabled()) { + helper.getLog().debug("lowerBoundArtifactVersion: " + lowerBound); } - ArtifactVersion upperBound = - !upperBoundSegment.isPresent() - ? null - : upperBoundSegment - .map( s -> (ArtifactVersion) new BoundArtifactVersion( currentVersion, - s.isMajorTo( SUBINCREMENTAL ) - ? Segment.of( s.value() + 1 ) - : s ) ) - .orElse( null ); - if ( helper.getLog().isDebugEnabled() ) - { - helper.getLog().debug( "Property ${" + property.getName() + "}: upperBound is: " + upperBound ); + ArtifactVersion upperBound = !upperBoundSegment.isPresent() + ? null + : upperBoundSegment + .map(s -> (ArtifactVersion) new BoundArtifactVersion( + currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.of(s.value() + 1) : s)) + .orElse(null); + if (helper.getLog().isDebugEnabled()) { + helper.getLog().debug("Property ${" + property.getName() + "}: upperBound is: " + upperBound); } - Restriction restriction = new Restriction( lowerBound, allowDowngrade, upperBound, allowDowngrade ); - ArtifactVersion result = getNewestVersion( range, restriction, includeSnapshots ); + Restriction restriction = new Restriction(lowerBound, allowDowngrade, upperBound, allowDowngrade); + ArtifactVersion result = getNewestVersion(range, restriction, includeSnapshots); - helper.getLog().debug( "Property ${" + property.getName() + "}: Current winner is: " + result ); + helper.getLog().debug("Property ${" + property.getName() + "}: Current winner is: " + result); - if ( property.isSearchReactor() ) - { - helper.getLog().debug( "Property ${" + property.getName() + "}: Searching reactor for a valid version..." ); - Set reactorArtifacts = helper.extractArtifacts( reactorProjects ); - ArtifactVersion[] reactorVersions = getVersions( reactorArtifacts ); - helper.getLog().debug( "Property ${" + property.getName() - + "}: Set of valid available versions from the reactor is " + Arrays.asList( - reactorVersions ) ); + if (property.isSearchReactor()) { + helper.getLog().debug("Property ${" + property.getName() + "}: Searching reactor for a valid version..."); + Set reactorArtifacts = helper.extractArtifacts(reactorProjects); + ArtifactVersion[] reactorVersions = getVersions(reactorArtifacts); + helper.getLog() + .debug("Property ${" + property.getName() + + "}: Set of valid available versions from the reactor is " + + Arrays.asList(reactorVersions)); ArtifactVersion fromReactor = null; - if ( reactorVersions.length > 0 ) - { - for ( int j = reactorVersions.length - 1; j >= 0; j-- ) - { - if ( range == null || ArtifactVersions.isVersionInRange( reactorVersions[j], range ) ) - { + if (reactorVersions.length > 0) { + for (int j = reactorVersions.length - 1; j >= 0; j--) { + if (range == null || ArtifactVersions.isVersionInRange(reactorVersions[j], range)) { fromReactor = reactorVersions[j]; - helper.getLog().debug( "Property ${" + property.getName() + "}: Reactor has version " - + fromReactor ); + helper.getLog() + .debug("Property ${" + property.getName() + "}: Reactor has version " + fromReactor); break; } } } - if ( fromReactor != null && ( result != null || !currentVersion.equals( fromReactor.toString() ) ) ) - { - if ( property.isPreferReactor() ) - { - helper.getLog().debug( "Property ${" + property.getName() - + "}: Reactor has a version and we prefer the reactor" ); + if (fromReactor != null && (result != null || !currentVersion.equals(fromReactor.toString()))) { + if (property.isPreferReactor()) { + helper.getLog() + .debug("Property ${" + property.getName() + + "}: Reactor has a version and we prefer the reactor"); result = fromReactor; - } - else - { - if ( result == null ) - { - helper.getLog().debug( "Property ${" + property.getName() + "}: Reactor has the only version" ); + } else { + if (result == null) { + helper.getLog().debug("Property ${" + property.getName() + "}: Reactor has the only version"); result = fromReactor; - } - else if ( getVersionComparator().compare( result, fromReactor ) < 0 ) - { - helper.getLog().debug( "Property ${" + property.getName() + "}: Reactor has a newer version" ); + } else if (getVersionComparator().compare(result, fromReactor) < 0) { + helper.getLog().debug("Property ${" + property.getName() + "}: Reactor has a newer version"); result = fromReactor; - } - else - { - helper.getLog().debug( "Property ${" + property.getName() - + "}: Reactor has the same or older version" ); + } else { + helper.getLog() + .debug("Property ${" + property.getName() + "}: Reactor has the same or older version"); } } } @@ -430,66 +373,53 @@ else if ( getVersionComparator().compare( result, fromReactor ) < 0 ) return result; } - private final class PropertyVersionComparator implements VersionComparator - { - public int compare( ArtifactVersion v1, ArtifactVersion v2 ) - { - return innerCompare( v1, v2 ); + private final class PropertyVersionComparator implements VersionComparator { + public int compare(ArtifactVersion v1, ArtifactVersion v2) { + return innerCompare(v1, v2); } - private int innerCompare( ArtifactVersion v1, ArtifactVersion v2 ) - { - if ( !isAssociated() ) - { - throw new IllegalStateException( "Cannot compare versions for a property with no associations" ); + private int innerCompare(ArtifactVersion v1, ArtifactVersion v2) { + if (!isAssociated()) { + throw new IllegalStateException("Cannot compare versions for a property with no associations"); } VersionComparator[] comparators = lookupComparators(); assert comparators.length >= 1 : "we have at least one association => at least one comparator"; - int result = comparators[0].compare( v1, v2 ); - for ( int i = 1; i < comparators.length; i++ ) - { - int alt = comparators[i].compare( v1, v2 ); - if ( result != alt && ( result >= 0 && alt < 0 ) || ( result <= 0 && alt > 0 ) ) - { - throw new IllegalStateException( - "Property " + name + " is associated with multiple artifacts" + int result = comparators[0].compare(v1, v2); + for (int i = 1; i < comparators.length; i++) { + int alt = comparators[i].compare(v1, v2); + if (result != alt && (result >= 0 && alt < 0) || (result <= 0 && alt > 0)) { + throw new IllegalStateException("Property " + name + " is associated with multiple artifacts" + " and these artifacts use different version sorting rules and these rules are effectively" + " incompatible for the two of versions being compared.\nFirst rule says compare(\"" + v1 + "\", \"" + v2 + "\") = " + result + "\nSecond rule says compare(\"" + v1 + "\", \"" + v2 - + "\") = " + alt ); + + "\") = " + alt); } } return result; } - public int getSegmentCount( ArtifactVersion v ) - { - if ( !isAssociated() ) - { - throw new IllegalStateException( "Cannot compare versions for a property with no associations" ); + public int getSegmentCount(ArtifactVersion v) { + if (!isAssociated()) { + throw new IllegalStateException("Cannot compare versions for a property with no associations"); } VersionComparator[] comparators = lookupComparators(); assert comparators.length >= 1 : "we have at least one association => at least one comparator"; - int result = comparators[0].getSegmentCount( v ); - for ( int i = 1; i < comparators.length; i++ ) - { - int alt = comparators[i].getSegmentCount( v ); - if ( result != alt ) - { - throw new IllegalStateException( - "Property " + name + " is associated with multiple artifacts" + int result = comparators[0].getSegmentCount(v); + for (int i = 1; i < comparators.length; i++) { + int alt = comparators[i].getSegmentCount(v); + if (result != alt) { + throw new IllegalStateException("Property " + name + " is associated with multiple artifacts" + " and these artifacts use different version sorting rules and these rules are effectively" + " incompatible for the two of versions being compared.\n" + "First rule says getSegmentCount(\"" + v + "\") = " + result + "\nSecond rule says getSegmentCount(\"" + v + "\") = " - + alt ); + + alt); } } return result; } } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersionsBuilder.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersionsBuilder.java index 2fe8963834..3e32efecf2 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersionsBuilder.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersionsBuilder.java @@ -35,8 +35,7 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -class PropertyVersionsBuilder -{ +class PropertyVersionsBuilder { private final String name; private final String profileId; @@ -56,202 +55,151 @@ class PropertyVersionsBuilder * @param name The property name. * @param helper The {@link org.codehaus.mojo.versions.api.DefaultVersionsHelper}. */ - PropertyVersionsBuilder( String profileId, String name, VersionsHelper helper ) - { + PropertyVersionsBuilder(String profileId, String name, VersionsHelper helper) { this.profileId = profileId; this.name = name; this.associations = new TreeSet<>(); this.helper = helper; } - public void addAssociation( Artifact artifact, boolean usePluginRepositories ) - { - associations.add( new DefaultArtifactAssociation( artifact, usePluginRepositories ) ); + public void addAssociation(Artifact artifact, boolean usePluginRepositories) { + associations.add(new DefaultArtifactAssociation(artifact, usePluginRepositories)); } - public void removeAssociation( Artifact artifact, boolean usePluginRepositories ) - { - associations.remove( new DefaultArtifactAssociation( artifact, usePluginRepositories ) ); + public void removeAssociation(Artifact artifact, boolean usePluginRepositories) { + associations.remove(new DefaultArtifactAssociation(artifact, usePluginRepositories)); } - public void clearAssociations() - { + public void clearAssociations() { associations.clear(); } - public boolean isAssociated() - { + public boolean isAssociated() { return !associations.isEmpty(); } - public ArtifactAssociation[] getAssociations() - { - return associations.toArray( new ArtifactAssociation[0] ); + public ArtifactAssociation[] getAssociations() { + return associations.toArray(new ArtifactAssociation[0]); } - public PropertyVersions newPropertyVersions() - throws VersionRetrievalException - { - return new PropertyVersions( profileId, name, helper, associations ); + public PropertyVersions newPropertyVersions() throws VersionRetrievalException { + return new PropertyVersions(profileId, name, helper, associations); } - public String getName() - { + public String getName() { return name; } - public String getVersionRange() - { + public String getVersionRange() { Comparator comparator = new PropertyVersionComparator(); - if ( lowerBounds.isEmpty() && upperBounds.isEmpty() ) - { + if (lowerBounds.isEmpty() && upperBounds.isEmpty()) { return null; } ArtifactVersion lowerBound = null; boolean includeLower = true; - for ( Map.Entry entry : lowerBounds.entrySet() ) - { - ArtifactVersion candidate = helper.createArtifactVersion( entry.getKey() ); - if ( lowerBound == null ) - { + for (Map.Entry entry : lowerBounds.entrySet()) { + ArtifactVersion candidate = helper.createArtifactVersion(entry.getKey()); + if (lowerBound == null) { lowerBound = candidate; includeLower = entry.getValue(); - } - else - { - final int result = comparator.compare( lowerBound, candidate ); - if ( result > 0 ) - { + } else { + final int result = comparator.compare(lowerBound, candidate); + if (result > 0) { lowerBound = candidate; includeLower = entry.getValue(); - } - else if ( result == 0 ) - { + } else if (result == 0) { includeLower = includeLower && entry.getValue(); } } } ArtifactVersion upperBound = null; boolean includeUpper = true; - for ( Map.Entry entry : upperBounds.entrySet() ) - { - ArtifactVersion candidate = helper.createArtifactVersion( entry.getKey() ); - if ( upperBound == null ) - { + for (Map.Entry entry : upperBounds.entrySet()) { + ArtifactVersion candidate = helper.createArtifactVersion(entry.getKey()); + if (upperBound == null) { upperBound = candidate; includeUpper = entry.getValue(); - } - else - { - final int result = comparator.compare( upperBound, candidate ); - if ( result < 0 ) - { + } else { + final int result = comparator.compare(upperBound, candidate); + if (result < 0) { upperBound = candidate; includeUpper = entry.getValue(); - } - else if ( result == 0 ) - { + } else if (result == 0) { includeUpper = includeUpper && entry.getValue(); } } } StringBuilder buf = new StringBuilder(); - if ( includeLower ) - { - buf.append( '[' ); - } - else - { - buf.append( '(' ); + if (includeLower) { + buf.append('['); + } else { + buf.append('('); } - if ( lowerBound != null ) - { - buf.append( lowerBound ); + if (lowerBound != null) { + buf.append(lowerBound); } - buf.append( ',' ); - if ( upperBound != null ) - { - buf.append( upperBound ); + buf.append(','); + if (upperBound != null) { + buf.append(upperBound); } - if ( includeUpper ) - { - buf.append( ']' ); - } - else - { - buf.append( ')' ); + if (includeUpper) { + buf.append(']'); + } else { + buf.append(')'); } return buf.toString(); } - public void addLowerBound( String lowerBound, boolean includeLower ) - { - Boolean value = lowerBounds.get( lowerBound ); - if ( value == null ) - { + public void addLowerBound(String lowerBound, boolean includeLower) { + Boolean value = lowerBounds.get(lowerBound); + if (value == null) { value = includeLower; - } - else - { + } else { value = includeLower && value; } - lowerBounds.put( lowerBound, value ); + lowerBounds.put(lowerBound, value); } - public void addUpperBound( String upperBound, boolean includeUpper ) - { - Boolean value = upperBounds.get( upperBound ); - if ( value == null ) - { + public void addUpperBound(String upperBound, boolean includeUpper) { + Boolean value = upperBounds.get(upperBound); + if (value == null) { value = includeUpper; - } - else - { + } else { value = includeUpper && value; } - upperBounds.put( upperBound, value ); + upperBounds.put(upperBound, value); } - private VersionComparator[] lookupComparators() - { - return associations.stream().map( - association -> helper.getVersionComparator( association.getArtifact() ) ) - .distinct() - .toArray( VersionComparator[]::new ); + private VersionComparator[] lookupComparators() { + return associations.stream() + .map(association -> helper.getVersionComparator(association.getArtifact())) + .distinct() + .toArray(VersionComparator[]::new); } - private final class PropertyVersionComparator - implements Comparator - { - public int compare( ArtifactVersion v1, ArtifactVersion v2 ) - { - return innerCompare( v1, v2 ); + private final class PropertyVersionComparator implements Comparator { + public int compare(ArtifactVersion v1, ArtifactVersion v2) { + return innerCompare(v1, v2); } - private int innerCompare( ArtifactVersion v1, ArtifactVersion v2 ) - { - if ( !isAssociated() ) - { - throw new IllegalStateException( "Cannot compare versions for a property with no associations" ); + private int innerCompare(ArtifactVersion v1, ArtifactVersion v2) { + if (!isAssociated()) { + throw new IllegalStateException("Cannot compare versions for a property with no associations"); } VersionComparator[] comparators = lookupComparators(); assert comparators.length >= 1 : "we have at least one association => at least one comparator"; - int result = comparators[0].compare( v1, v2 ); - for ( int i = 1; i < comparators.length; i++ ) - { - int alt = comparators[i].compare( v1, v2 ); - if ( result != alt && ( result >= 0 && alt < 0 ) || ( result <= 0 && alt > 0 ) ) - { - throw new IllegalStateException( "Property " + name + " is associated with multiple artifacts" - + " and these artifacts use different version sorting rules and these rules are effectively" - + " incompatible for the two of versions being compared.\nFirst rule says compare(\"" + v1 - + "\", \"" + v2 + "\") = " + result + "\nSecond rule says compare(\"" + v1 + "\", \"" + v2 - + "\") = " + alt ); + int result = comparators[0].compare(v1, v2); + for (int i = 1; i < comparators.length; i++) { + int alt = comparators[i].compare(v1, v2); + if (result != alt && (result >= 0 && alt < 0) || (result <= 0 && alt > 0)) { + throw new IllegalStateException("Property " + name + " is associated with multiple artifacts" + + " and these artifacts use different version sorting rules and these rules are effectively" + + " incompatible for the two of versions being compared.\nFirst rule says compare(\"" + v1 + + "\", \"" + v2 + "\") = " + result + "\nSecond rule says compare(\"" + v1 + "\", \"" + v2 + + "\") = " + alt); } } return result; } - } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ReportRenderer.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ReportRenderer.java index 376985ef93..37d8639af6 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ReportRenderer.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ReportRenderer.java @@ -22,8 +22,7 @@ /** * Common interface for reporting components */ -public interface ReportRenderer -{ +public interface ReportRenderer { /** * Renders the report */ diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java index f72acdf223..9aa90ca057 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java @@ -24,25 +24,24 @@ * * @author Andrzej Jarmoniuk */ -public enum Segment implements Comparable -{ - MAJOR, MINOR, INCREMENTAL, SUBINCREMENTAL; +public enum Segment implements Comparable { + MAJOR, + MINOR, + INCREMENTAL, + SUBINCREMENTAL; /** * Returns the 0-based sendex index * * @return 0-based sendex index */ - public int value() - { + public int value() { return ordinal(); } - public static Segment of( int index ) - { - if ( index < 0 || index > 3 ) - { - throw new IllegalArgumentException( "Wrong segment index: " + index ); + public static Segment of(int index) { + if (index < 0 || index > 3) { + throw new IllegalArgumentException("Wrong segment index: " + index); } return values()[index]; } @@ -52,14 +51,12 @@ public static Segment of( int index ) * @param other other segment to compare * @return true if the given segment is more major */ - public boolean isMajorTo( Segment other ) - { + public boolean isMajorTo(Segment other) { return value() < other.value(); } @Override - public String toString() - { + public String toString() { return name(); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java index 6acedce8df..d0365bfd80 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java @@ -33,8 +33,7 @@ * @author connollys * @since 1.0-beta-1 */ -public interface VersionDetails -{ +public interface VersionDetails { /** * Returns true if the specific version is in the list of versions. * @@ -42,7 +41,7 @@ public interface VersionDetails * @return true if the specific version is in the list of versions. * @since 1.0-beta-1 */ - boolean containsVersion( String version ); + boolean containsVersion(String version); /** * Returns true if and only if getCurrentVersion() != null. @@ -58,7 +57,7 @@ public interface VersionDetails * @param currentVersion The new current version. * @since 1.0-beta-1 */ - void setCurrentVersion( ArtifactVersion currentVersion ); + void setCurrentVersion(ArtifactVersion currentVersion); /** * Sets the current version. @@ -66,11 +65,11 @@ public interface VersionDetails * @param currentVersion The new current version. * @since 1.0-beta-1 */ - void setCurrentVersion( String currentVersion ); + void setCurrentVersion(String currentVersion); boolean isIncludeSnapshots(); - void setIncludeSnapshots( boolean includeSnapshots ); + void setIncludeSnapshots(boolean includeSnapshots); /** * Retrieves the current version. @@ -103,7 +102,7 @@ public interface VersionDetails * @return all available versions in increasing order. * @since 1.0-alpha-3 */ - ArtifactVersion[] getVersions( boolean includeSnapshots ); + ArtifactVersion[] getVersions(boolean includeSnapshots); /** * Returns all available versions within the specified version range. @@ -113,7 +112,7 @@ public interface VersionDetails * @return all available versions within the specified version range. * @since 1.0-alpha-3 */ - ArtifactVersion[] getVersions( VersionRange versionRange, boolean includeSnapshots ); + ArtifactVersion[] getVersions(VersionRange versionRange, boolean includeSnapshots); /** * Returns all available versions within the specified bounds. @@ -123,7 +122,7 @@ public interface VersionDetails * @return all available versions within the specified version range. * @since 1.0-beta-1 */ - ArtifactVersion[] getVersions( ArtifactVersion lowerBound, ArtifactVersion upperBound ); + ArtifactVersion[] getVersions(ArtifactVersion lowerBound, ArtifactVersion upperBound); /** * Returns all available versions within the specified bounds. @@ -134,7 +133,7 @@ public interface VersionDetails * @return all available versions within the specified version range. * @since 1.0-beta-1 */ - ArtifactVersion[] getVersions( ArtifactVersion lowerBound, ArtifactVersion upperBound, boolean includeSnapshots ); + ArtifactVersion[] getVersions(ArtifactVersion lowerBound, ArtifactVersion upperBound, boolean includeSnapshots); /** * Returns all available versions within the specified bounds. @@ -144,7 +143,7 @@ public interface VersionDetails * @return all available versions within the specified version range. * @since 1.0-beta-1 */ - ArtifactVersion[] getVersions( Restriction restriction, boolean includeSnapshots ); + ArtifactVersion[] getVersions(Restriction restriction, boolean includeSnapshots); /** * Returns all available versions within the specified bounds. @@ -156,7 +155,7 @@ public interface VersionDetails * @return all available versions within the specified version range. * @since 1.0-beta-1 */ - ArtifactVersion[] getVersions( VersionRange versionRange, Restriction restriction, boolean includeSnapshots ); + ArtifactVersion[] getVersions(VersionRange versionRange, Restriction restriction, boolean includeSnapshots); /** * Returns the latest version given the version range, restricition, whether to include snapshots and/or @@ -168,8 +167,8 @@ public interface VersionDetails * @param allowDowngrade whether downgrades are allowed * @return the latest version satisfying the conditions or null if no version is available. */ - ArtifactVersion getNewestVersion( VersionRange versionRange, Restriction restriction, - boolean includeSnapshots, boolean allowDowngrade ); + ArtifactVersion getNewestVersion( + VersionRange versionRange, Restriction restriction, boolean includeSnapshots, boolean allowDowngrade); /** * Returns the latest version newer than the specified lowerBound, but less than the specified upper bound or @@ -180,7 +179,7 @@ ArtifactVersion getNewestVersion( VersionRange versionRange, Restriction restric * @return the latest version between lowerBound and upperBound or null if no version is available. * @since 1.0-alpha-3 */ - ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion upperBound ); + ArtifactVersion getNewestVersion(ArtifactVersion lowerBound, ArtifactVersion upperBound); /** * Returns the latest version newer than the specified lowerBound, but less than the specified upper bound or @@ -192,8 +191,7 @@ ArtifactVersion getNewestVersion( VersionRange versionRange, Restriction restric * @return the latest version between currentVersion and upperBound or null if no version is available. * @since 1.0-alpha-3 */ - ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion upperBound, - boolean includeSnapshots ); + ArtifactVersion getNewestVersion(ArtifactVersion lowerBound, ArtifactVersion upperBound, boolean includeSnapshots); /** * Returns the latest version newer than the specified current version, but less than the specified upper bound or @@ -204,7 +202,7 @@ ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion up * @return the latest version between lowerBound and upperBound or null if no version is available. * @since 1.0-alpha-3 */ - ArtifactVersion getNewestVersion( Restriction restriction, boolean includeSnapshots ); + ArtifactVersion getNewestVersion(Restriction restriction, boolean includeSnapshots); /** * Returns the latest version newer than the specified current version, but less than the specified upper bound or @@ -217,7 +215,7 @@ ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion up * @return the latest version between lowerBound and upperBound or null if no version is available. * @since 1.0-alpha-3 */ - ArtifactVersion getNewestVersion( VersionRange versionRange, Restriction restriction, boolean includeSnapshots ); + ArtifactVersion getNewestVersion(VersionRange versionRange, Restriction restriction, boolean includeSnapshots); /** * Returns the latest version within the specified version range or null if no such version exists. @@ -227,7 +225,7 @@ ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion up * @return the latest version within the version range or null if no version is available. * @since 1.0-alpha-3 */ - ArtifactVersion getNewestVersion( VersionRange versionRange, boolean includeSnapshots ); + ArtifactVersion getNewestVersion(VersionRange versionRange, boolean includeSnapshots); /** * Returns the latest version, newer than the given version, given the upper bound segment and whether snapshots @@ -242,8 +240,8 @@ ArtifactVersion getNewestVersion( ArtifactVersion lowerBound, ArtifactVersion up * @throws InvalidSegmentException if the requested segment is outside the bounds (less than 1 or greater than * the segment count) */ - Optional getNewestVersion( String versionString, Optional upperBoundSegment, - boolean includeSnapshots, boolean allowDowngrade ) + Optional getNewestVersion( + String versionString, Optional upperBoundSegment, boolean includeSnapshots, boolean allowDowngrade) throws InvalidSegmentException; /** @@ -258,8 +256,9 @@ Optional getNewestVersion( String versionString, Optional updateScope, - boolean includeSnapshots ) throws InvalidSegmentException; + ArtifactVersion getNewestUpdate( + ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) + throws InvalidSegmentException; /** * Returns an array of newer versions than the given version, given whether snapshots @@ -269,7 +268,7 @@ ArtifactVersion getNewestUpdate( ArtifactVersion currentVersion, Optional upperBoundSegment, - boolean includeSnapshots ) throws InvalidSegmentException; + ArtifactVersion[] getNewerVersions(String version, Optional upperBoundSegment, boolean includeSnapshots) + throws InvalidSegmentException; /** * Returns an array of newer versions than the given version, given the upper bound segment and whether snapshots @@ -300,8 +299,8 @@ ArtifactVersion[] getNewerVersions( String version, Optional upperBound * @throws InvalidSegmentException if the requested segment is outside the bounds (less than 1 or greater than * the segment count) */ - ArtifactVersion[] getNewerVersions( String versionString, Optional upperBoundSegment, - boolean includeSnapshots, boolean allowDowngrade ) + ArtifactVersion[] getNewerVersions( + String versionString, Optional upperBoundSegment, boolean includeSnapshots, boolean allowDowngrade) throws InvalidSegmentException; /** @@ -314,8 +313,9 @@ ArtifactVersion[] getNewerVersions( String versionString, Optional uppe * @throws InvalidSegmentException thrown if the updateScope is greater than the number of segments * @since 1.0-beta-1 */ - ArtifactVersion[] getAllUpdates( ArtifactVersion currentVersion, Optional updateScope, - boolean includeSnapshots ) throws InvalidSegmentException; + ArtifactVersion[] getAllUpdates( + ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) + throws InvalidSegmentException; /** * Returns the newest version newer than the specified current version, but within the specified update scope or @@ -327,7 +327,7 @@ ArtifactVersion[] getAllUpdates( ArtifactVersion currentVersion, Optional updateScope ) throws InvalidSegmentException; + ArtifactVersion getNewestUpdate(Optional updateScope) throws InvalidSegmentException; /** * Returns the all versions newer than the specified current version, but within the specified update scope. @@ -337,7 +337,7 @@ ArtifactVersion[] getAllUpdates( ArtifactVersion currentVersion, Optional updateScope ) throws InvalidSegmentException; + ArtifactVersion[] getAllUpdates(Optional updateScope) throws InvalidSegmentException; /** * Returns the newest version newer than the specified current version, but within the specified update scope or @@ -350,7 +350,7 @@ ArtifactVersion[] getAllUpdates( ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots ) + ArtifactVersion getNewestUpdate(Optional updateScope, boolean includeSnapshots) throws InvalidSegmentException; /** @@ -362,7 +362,7 @@ ArtifactVersion getNewestUpdate( Optional updateScope, boolean includeS * @throws InvalidSegmentException thrown if the updateScope is greater than the number of segments * @since 1.0-beta-1 */ - ArtifactVersion[] getAllUpdates( Optional updateScope, boolean includeSnapshots ) + ArtifactVersion[] getAllUpdates(Optional updateScope, boolean includeSnapshots) throws InvalidSegmentException; /** @@ -380,7 +380,7 @@ ArtifactVersion[] getAllUpdates( Optional updateScope, boolean includeS * @return the all versions after currentVersion within the specified update scope. * @since 1.0-beta-1 */ - ArtifactVersion[] getAllUpdates( VersionRange versionRange ); + ArtifactVersion[] getAllUpdates(VersionRange versionRange); /** * Returns the all versions newer than the specified current version, but within the specified update scope. @@ -390,7 +390,7 @@ ArtifactVersion[] getAllUpdates( Optional updateScope, boolean includeS * @return the all versions after currentVersion within the specified update scope. * @since 1.0-beta-1 */ - ArtifactVersion[] getAllUpdates( VersionRange versionRange, boolean includeSnapshots ); + ArtifactVersion[] getAllUpdates(VersionRange versionRange, boolean includeSnapshots); /** *

Returns a {@linkplain Restriction} object for computing version upgrades @@ -406,8 +406,7 @@ ArtifactVersion[] getAllUpdates( Optional updateScope, boolean includeS * @param scope most major segment where updates are allowed Optional.empty() for no restriction * @return {@linkplain Restriction} object based on the arguments */ - Restriction restrictionFor( Optional scope ) throws InvalidSegmentException; - + Restriction restrictionFor(Optional scope) throws InvalidSegmentException; /** * Returns the {@link Restriction} objects for a segemnt scope which is to be ignored. @@ -415,5 +414,5 @@ ArtifactVersion[] getAllUpdates( Optional updateScope, boolean includeS * @param ignored most major segment where updates are to be ignored; Optional.empty() for no ignored segments * @return {@linkplain Restriction} object based on the arguments */ - Restriction restrictionForIgnoreScope( Optional ignored ); + Restriction restrictionForIgnoreScope(Optional ignored); } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionRetrievalException.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionRetrievalException.java index c1f1a4138e..483e57f82b 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionRetrievalException.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionRetrievalException.java @@ -22,15 +22,13 @@ /** * Exception thrown if version information cannot be retrieved */ -public class VersionRetrievalException extends Exception -{ +public class VersionRetrievalException extends Exception { /** * Constructs a new exception with {@code null} as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. */ - public VersionRetrievalException() - { + public VersionRetrievalException() { super(); } @@ -42,9 +40,8 @@ public VersionRetrievalException() * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ - public VersionRetrievalException( String message ) - { - super( message ); + public VersionRetrievalException(String message) { + super(message); } /** @@ -60,9 +57,8 @@ public VersionRetrievalException( String message ) * permitted, and indicates that the cause is nonexistent or * unknown.) */ - public VersionRetrievalException( Throwable cause ) - { - super( cause ); + public VersionRetrievalException(Throwable cause) { + super(cause); } /** @@ -78,8 +74,7 @@ public VersionRetrievalException( Throwable cause ) * permitted, and indicates that the cause is nonexistent or * unknown.) */ - public VersionRetrievalException( String message, Throwable cause ) - { - super( message, cause ); + public VersionRetrievalException(String message, Throwable cause) { + super(message, cause); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java index 8e66f93223..1004e11bee 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java @@ -42,8 +42,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public interface VersionsHelper -{ +public interface VersionsHelper { /** * Gets the logger used by this helper. * @@ -58,7 +57,7 @@ public interface VersionsHelper * @return the version comparator to use. * @since 1.0-alpha-3 */ - VersionComparator getVersionComparator( Artifact artifact ); + VersionComparator getVersionComparator(Artifact artifact); /** * Returns the version comparator to use for the specified groupId and artifactId. @@ -68,7 +67,7 @@ public interface VersionsHelper * @return the version comparator to use. * @since 1.0-alpha-3 */ - VersionComparator getVersionComparator( String groupId, String artifactId ); + VersionComparator getVersionComparator(String groupId, String artifactId); /** * Shorthand method for repositorySystem.createPluginArtifact(...). @@ -79,7 +78,7 @@ public interface VersionsHelper * @return the corresponding plugin artifact. * @since 1.0-alpha-3 */ - Artifact createPluginArtifact( String groupId, String artifactId, String version ); + Artifact createPluginArtifact(String groupId, String artifactId, String version); /** * Shorthand method for repositorySystem.createDependencyArtifact(...). @@ -94,8 +93,14 @@ public interface VersionsHelper * @return The corresponding dependency artifact. * @since 1.0-alpha-3 */ - Artifact createDependencyArtifact( String groupId, String artifactId, String version, String type, - String classifier, String scope, boolean optional ); + Artifact createDependencyArtifact( + String groupId, + String artifactId, + String version, + String type, + String classifier, + String scope, + boolean optional); /** * Shorthand method for getArtifactFactory().createDependencyArtifact(...). @@ -109,8 +114,8 @@ Artifact createDependencyArtifact( String groupId, String artifactId, String ver * @return The corresponding dependency artifact. * @since 1.0-beta-1 */ - Artifact createDependencyArtifact( String groupId, String artifactId, String version, String type, - String classifier, String scope ); + Artifact createDependencyArtifact( + String groupId, String artifactId, String version, String type, String classifier, String scope); /** * Shorthand method for repositorySystem.createDependencyArtifact(...) which extracts the @@ -120,7 +125,7 @@ Artifact createDependencyArtifact( String groupId, String artifactId, String ver * @return The corresponding dependency artifact. * @since 1.0-alpha-3 */ - Artifact createDependencyArtifact( Dependency dependency ); + Artifact createDependencyArtifact(Dependency dependency); /** * Takes a {@link List} of {@link org.apache.maven.project.MavenProject} instances and converts it into a @@ -130,7 +135,7 @@ Artifact createDependencyArtifact( String groupId, String artifactId, String ver * @return a {@link Set} of {@link Artifact} instances. * @since 1.0-alpha-3 */ - Set extractArtifacts( Collection mavenProjects ); + Set extractArtifacts(Collection mavenProjects); /** * Creates an {@link ArtifactVersion} instance from a string. @@ -139,7 +144,7 @@ Artifact createDependencyArtifact( String groupId, String artifactId, String ver * @return The artifact version. * @since 1.0-beta-1 */ - ArtifactVersion createArtifactVersion( String version ); + ArtifactVersion createArtifactVersion(String version); /** * Looks up the versions of the specified artifact that are available in either the local repository, or the @@ -152,7 +157,7 @@ Artifact createDependencyArtifact( String groupId, String artifactId, String ver * @throws VersionRetrievalException thrown if version resolution fails * @since 1.0-alpha-3 */ - ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories ) + ArtifactVersions lookupArtifactVersions(Artifact artifact, boolean usePluginRepositories) throws VersionRetrievalException; /** @@ -167,8 +172,7 @@ ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRep * @throws VersionRetrievalException thrown if version resolution fails * @since 1.0-alpha-3 */ - ArtifactVersions lookupArtifactVersions( Artifact artifact, VersionRange versionRange, - boolean usePluginRepositories ) + ArtifactVersions lookupArtifactVersions(Artifact artifact, VersionRange versionRange, boolean usePluginRepositories) throws VersionRetrievalException; /** @@ -180,9 +184,8 @@ ArtifactVersions lookupArtifactVersions( Artifact artifact, VersionRange version * @throws VersionRetrievalException thrown if version resolution fails * @since 1.0-beta-1 */ - Map lookupDependenciesUpdates( Set dependencies, - boolean usePluginRepositories ) - throws VersionRetrievalException; + Map lookupDependenciesUpdates( + Set dependencies, boolean usePluginRepositories) throws VersionRetrievalException; /** * Creates an {@link org.codehaus.mojo.versions.api.ArtifactVersions} instance from a dependency. @@ -193,7 +196,7 @@ Map lookupDependenciesUpdates( Set dep * @throws VersionRetrievalException thrown if version resolution fails * @since 1.0-beta-1 */ - ArtifactVersions lookupDependencyUpdates( Dependency dependency, boolean usePluginRepositories ) + ArtifactVersions lookupDependencyUpdates(Dependency dependency, boolean usePluginRepositories) throws VersionRetrievalException; /** @@ -205,7 +208,7 @@ ArtifactVersions lookupDependencyUpdates( Dependency dependency, boolean usePlug * @throws VersionRetrievalException thrown if version resolution fails * @since 1.0-beta-1 */ - Map lookupPluginsUpdates( Set plugins, boolean allowSnapshots ) + Map lookupPluginsUpdates(Set plugins, boolean allowSnapshots) throws VersionRetrievalException; /** @@ -216,7 +219,7 @@ Map lookupPluginsUpdates( Set plugins, boo * @return The plugin update details. * @since 1.0-beta-1 */ - PluginUpdatesDetails lookupPluginUpdates( Plugin plugin, boolean allowSnapshots ) throws VersionRetrievalException; + PluginUpdatesDetails lookupPluginUpdates(Plugin plugin, boolean allowSnapshots) throws VersionRetrievalException; /** * Returns an {@link ExpressionEvaluator} for the specified project. @@ -225,7 +228,7 @@ Map lookupPluginsUpdates( Set plugins, boo * @return an {@link ExpressionEvaluator} for the specified project. * @since 1.0-beta-1 */ - ExpressionEvaluator getExpressionEvaluator( MavenProject project ); + ExpressionEvaluator getExpressionEvaluator(MavenProject project); /** * Returns a map of {@link org.codehaus.mojo.versions.api.PropertyVersions} values keyed by @@ -237,15 +240,14 @@ Map lookupPluginsUpdates( Set plugins, boo * {@link Property} instances. * @throws MojoExecutionException if something goes wrong. */ - Map getVersionPropertiesMap( VersionPropertiesMapRequest request ) - throws MojoExecutionException; + Map getVersionPropertiesMap(VersionPropertiesMapRequest request) + throws MojoExecutionException; /** * Argument builder class for * {@link VersionsHelper#getVersionPropertiesMap(VersionPropertiesMapRequest)}. */ - class VersionPropertiesMapRequest - { + class VersionPropertiesMapRequest { private MavenProject mavenProject; private Property[] propertyDefinitions; private String includeProperties; @@ -257,8 +259,7 @@ class VersionPropertiesMapRequest * Returns the {@link MavenProject} object * @return {@link MavenProject} object */ - protected MavenProject getMavenProject() - { + protected MavenProject getMavenProject() { return mavenProject; } @@ -266,8 +267,7 @@ protected MavenProject getMavenProject() * Returns the {@link Property} array * @return {@link Property} array */ - protected Property[] getPropertyDefinitions() - { + protected Property[] getPropertyDefinitions() { return propertyDefinitions; } @@ -275,8 +275,7 @@ protected Property[] getPropertyDefinitions() * Returns the value of {@link #includeProperties} * @return value of {@link #includeProperties} */ - protected String getIncludeProperties() - { + protected String getIncludeProperties() { return includeProperties; } @@ -284,8 +283,7 @@ protected String getIncludeProperties() * Returns the value of {@link #excludeProperties} * @return value of {@link #excludeProperties} */ - protected String getExcludeProperties() - { + protected String getExcludeProperties() { return excludeProperties; } @@ -295,8 +293,7 @@ protected String getExcludeProperties() * * @return value of {@link #includeParent} */ - protected boolean isIncludeParent() - { + protected boolean isIncludeParent() { return includeParent; } @@ -305,8 +302,7 @@ protected boolean isIncludeParent() * If not set, it is assumed to be {@code true} * @return value of {@link #autoLinkItems} */ - protected boolean isAutoLinkItems() - { + protected boolean isAutoLinkItems() { return autoLinkItems; } @@ -314,16 +310,14 @@ protected boolean isAutoLinkItems() * Returns a new {@link Builder} instance * @return new {@link Builder} instance */ - public static Builder builder() - { + public static Builder builder() { return new Builder(); } /** * Builder class for {@link VersionPropertiesMapRequest} */ - public static class Builder - { + public static class Builder { private MavenProject mavenProject; private Property[] propertyDefinitions; private String includeProperties; @@ -331,17 +325,14 @@ public static class Builder private Boolean includeParent; private Boolean autoLinkItems; - private Builder() - { - } + private Builder() {} /** * Supplies the {@link MavenProject} instance * @param mavenProject {@link MavenProject} instance * @return {@link Builder} instance */ - public Builder withMavenProject( MavenProject mavenProject ) - { + public Builder withMavenProject(MavenProject mavenProject) { this.mavenProject = mavenProject; return this; } @@ -351,8 +342,7 @@ public Builder withMavenProject( MavenProject mavenProject ) * @param propertyDefinitions array of property definitions * @return {@link Builder} instance */ - public Builder withPropertyDefinitions( Property[] propertyDefinitions ) - { + public Builder withPropertyDefinitions(Property[] propertyDefinitions) { this.propertyDefinitions = propertyDefinitions; return this; } @@ -362,8 +352,7 @@ public Builder withPropertyDefinitions( Property[] propertyDefinitions ) * @param includeProperties comma-delimited properties to include * @return {@link Builder} instance */ - public Builder withIncludeProperties( String includeProperties ) - { + public Builder withIncludeProperties(String includeProperties) { this.includeProperties = includeProperties; return this; } @@ -373,8 +362,7 @@ public Builder withIncludeProperties( String includeProperties ) * @param excludeProperties comma-delimited properties to exclude * @return {@link Builder} instance */ - public Builder withExcludeProperties( String excludeProperties ) - { + public Builder withExcludeProperties(String excludeProperties) { this.excludeProperties = excludeProperties; return this; } @@ -384,8 +372,7 @@ public Builder withExcludeProperties( String excludeProperties ) * @param includeParent whether parent POMs should be included * @return {@link Builder} instance */ - public Builder withIncludeParent( boolean includeParent ) - { + public Builder withIncludeParent(boolean includeParent) { this.includeParent = includeParent; return this; } @@ -395,8 +382,7 @@ public Builder withIncludeParent( boolean includeParent ) * @param autoLinkItems whether to automatically infer associations * @return {@link Builder} instance */ - public Builder withAutoLinkItems( boolean autoLinkItems ) - { + public Builder withAutoLinkItems(boolean autoLinkItems) { this.autoLinkItems = autoLinkItems; return this; } @@ -405,8 +391,7 @@ public Builder withAutoLinkItems( boolean autoLinkItems ) * Returns the {@link VersionPropertiesMapRequest} instance * @return {@link VersionPropertiesMapRequest} instance */ - public VersionPropertiesMapRequest build() - { + public VersionPropertiesMapRequest build() { VersionPropertiesMapRequest instance = new VersionPropertiesMapRequest(); instance.mavenProject = this.mavenProject; instance.propertyDefinitions = propertyDefinitions; @@ -427,6 +412,5 @@ public VersionPropertiesMapRequest build() * @throws ArtifactResolutionException if resolution is unsuccessful * @since 1.3 */ - void resolveArtifact( Artifact artifact, boolean usePluginRepositories ) - throws ArtifactResolutionException; + void resolveArtifact(Artifact artifact, boolean usePluginRepositories) throws ArtifactResolutionException; } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/AbstractVersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/AbstractVersionChanger.java index 3dbcc8862c..c1a46f1694 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/AbstractVersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/AbstractVersionChanger.java @@ -29,34 +29,28 @@ * @author Stephen Connolly * @since 15-Sep-2010 15:59:46 */ -public abstract class AbstractVersionChanger - implements VersionChanger -{ +public abstract class AbstractVersionChanger implements VersionChanger { private final Model model; private final ModifiedPomXMLEventReader pom; private final Log log; - public AbstractVersionChanger( Model model, ModifiedPomXMLEventReader pom, Log log ) - { + public AbstractVersionChanger(Model model, ModifiedPomXMLEventReader pom, Log log) { this.model = model; this.pom = pom; this.log = log; } - public Model getModel() - { + public Model getModel() { return model; } - public ModifiedPomXMLEventReader getPom() - { + public ModifiedPomXMLEventReader getPom() { return pom; } - public void info( CharSequence charSequence ) - { - log.info( charSequence ); + public void info(CharSequence charSequence) { + log.info(charSequence); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/CompositeVersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/CompositeVersionChanger.java index b0bb3b9421..a3ad9c0b8a 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/CompositeVersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/CompositeVersionChanger.java @@ -33,27 +33,20 @@ * @author Stephen Connolly * @since 15-Sep-2010 16:01:35 */ -public class CompositeVersionChanger - implements VersionChanger -{ +public class CompositeVersionChanger implements VersionChanger { private final List composites; - public CompositeVersionChanger( VersionChanger[] composites ) - { - this.composites = new ArrayList<>( Arrays.asList( composites ) ); + public CompositeVersionChanger(VersionChanger[] composites) { + this.composites = new ArrayList<>(Arrays.asList(composites)); } - public CompositeVersionChanger( List composites ) - { - this.composites = new ArrayList<>( composites ); + public CompositeVersionChanger(List composites) { + this.composites = new ArrayList<>(composites); } - public void apply( VersionChange versionChange ) - throws XMLStreamException - { - for ( VersionChanger delegate : composites ) - { - delegate.apply( versionChange ); + public void apply(VersionChange versionChange) throws XMLStreamException { + for (VersionChanger delegate : composites) { + delegate.apply(versionChange); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/DefaultVersionChange.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/DefaultVersionChange.java index f0f43ba25e..105f67f902 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/DefaultVersionChange.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/DefaultVersionChange.java @@ -29,8 +29,7 @@ * @author Stephen Connolly * @since 15-Sep-2010 14:48:10 */ -public final class DefaultVersionChange implements VersionChange -{ +public final class DefaultVersionChange implements VersionChange { private final String groupId; private final String artifactId; @@ -39,73 +38,60 @@ public final class DefaultVersionChange implements VersionChange private final String newVersion; - public DefaultVersionChange( String groupId, String artifactId, String oldVersion, String newVersion ) - { + public DefaultVersionChange(String groupId, String artifactId, String oldVersion, String newVersion) { this.groupId = groupId; this.artifactId = artifactId; this.oldVersion = oldVersion; this.newVersion = newVersion; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getOldVersion() - { + public String getOldVersion() { return oldVersion; } - public String getNewVersion() - { + public String getNewVersion() { return newVersion; } - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } DefaultVersionChange versionChange = (DefaultVersionChange) o; - if ( !Objects.equals( artifactId, versionChange.artifactId ) ) - { + if (!Objects.equals(artifactId, versionChange.artifactId)) { return false; } - if ( !Objects.equals( groupId, versionChange.groupId ) ) - { + if (!Objects.equals(groupId, versionChange.groupId)) { return false; } - if ( !Objects.equals( newVersion, versionChange.newVersion ) ) - { + if (!Objects.equals(newVersion, versionChange.newVersion)) { return false; } - return Objects.equals( oldVersion, versionChange.oldVersion ); + return Objects.equals(oldVersion, versionChange.oldVersion); } - public int hashCode() - { + public int hashCode() { int result = groupId != null ? groupId.hashCode() : 0; - result = 31 * result + ( artifactId != null ? artifactId.hashCode() : 0 ); - result = 31 * result + ( oldVersion != null ? oldVersion.hashCode() : 0 ); - result = 31 * result + ( newVersion != null ? newVersion.hashCode() : 0 ); + result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0); + result = 31 * result + (oldVersion != null ? oldVersion.hashCode() : 0); + result = 31 * result + (newVersion != null ? newVersion.hashCode() : 0); return result; } - public String toString() - { + public String toString() { return "DefaultVersionChange(" + groupId + ':' + artifactId + ":" + oldVersion + "-->" + newVersion + ')'; } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/DependencyVersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/DependencyVersionChanger.java index a106150773..9995d47fce 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/DependencyVersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/DependencyVersionChanger.java @@ -33,24 +33,22 @@ * @author Stephen Connolly * @since 15-Sep-2010 16:00:32 */ -public class DependencyVersionChanger - extends AbstractVersionChanger -{ +public class DependencyVersionChanger extends AbstractVersionChanger { - public DependencyVersionChanger( Model model, ModifiedPomXMLEventReader pom, Log reporter ) - { - super( model, pom, reporter ); + public DependencyVersionChanger(Model model, ModifiedPomXMLEventReader pom, Log reporter) { + super(model, pom, reporter); } - public void apply( VersionChange versionChange ) - throws XMLStreamException - { - if ( PomHelper.setDependencyVersion( getPom(), versionChange.getGroupId(), versionChange.getArtifactId(), - versionChange.getOldVersion(), versionChange.getNewVersion(), - getModel() ) ) - { - info( " Updating dependency " + versionChange.getGroupId() + ":" + versionChange.getArtifactId() ); - info( " from version " + versionChange.getOldVersion() + " to " + versionChange.getNewVersion() ); + public void apply(VersionChange versionChange) throws XMLStreamException { + if (PomHelper.setDependencyVersion( + getPom(), + versionChange.getGroupId(), + versionChange.getArtifactId(), + versionChange.getOldVersion(), + versionChange.getNewVersion(), + getModel())) { + info(" Updating dependency " + versionChange.getGroupId() + ":" + versionChange.getArtifactId()); + info(" from version " + versionChange.getOldVersion() + " to " + versionChange.getNewVersion()); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/ParentVersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/ParentVersionChanger.java index a0220049b1..fea98f8649 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/ParentVersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/ParentVersionChanger.java @@ -30,26 +30,19 @@ /** * */ -public class ParentVersionChanger - extends AbstractVersionChanger -{ +public class ParentVersionChanger extends AbstractVersionChanger { - public ParentVersionChanger( Model model, ModifiedPomXMLEventReader pom, Log reporter ) - { - super( model, pom, reporter ); + public ParentVersionChanger(Model model, ModifiedPomXMLEventReader pom, Log reporter) { + super(model, pom, reporter); } - public void apply( VersionChange versionChange ) - throws XMLStreamException - { - if ( getModel().getParent() != null && versionChange.getGroupId().equals( getModel().getParent().getGroupId() ) - && versionChange.getArtifactId().equals( getModel().getParent().getArtifactId() ) ) - { - if ( PomHelper.setProjectParentVersion( getPom(), versionChange.getNewVersion() ) ) - { - info( " Updating parent " + versionChange.getGroupId() + ":" + versionChange.getArtifactId() ); - info( " from version " + versionChange.getOldVersion() + " to " - + versionChange.getNewVersion() ); + public void apply(VersionChange versionChange) throws XMLStreamException { + if (getModel().getParent() != null + && versionChange.getGroupId().equals(getModel().getParent().getGroupId()) + && versionChange.getArtifactId().equals(getModel().getParent().getArtifactId())) { + if (PomHelper.setProjectParentVersion(getPom(), versionChange.getNewVersion())) { + info(" Updating parent " + versionChange.getGroupId() + ":" + versionChange.getArtifactId()); + info(" from version " + versionChange.getOldVersion() + " to " + versionChange.getNewVersion()); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/PluginVersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/PluginVersionChanger.java index 60ddce5831..279fee78dd 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/PluginVersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/PluginVersionChanger.java @@ -33,23 +33,21 @@ * @author Stephen Connolly * @since 15-Sep-2010 16:00:54 */ -public class PluginVersionChanger - extends AbstractVersionChanger -{ +public class PluginVersionChanger extends AbstractVersionChanger { - public PluginVersionChanger( Model model, ModifiedPomXMLEventReader pom, Log reporter ) - { - super( model, pom, reporter ); + public PluginVersionChanger(Model model, ModifiedPomXMLEventReader pom, Log reporter) { + super(model, pom, reporter); } - public void apply( VersionChange versionChange ) - throws XMLStreamException - { - if ( PomHelper.setPluginVersion( getPom(), versionChange.getGroupId(), versionChange.getArtifactId(), - versionChange.getOldVersion(), versionChange.getNewVersion() ) ) - { - info( " Updating plugin " + versionChange.getGroupId() + ":" + versionChange.getArtifactId() ); - info( " from version " + versionChange.getOldVersion() + " to " + versionChange.getNewVersion() ); + public void apply(VersionChange versionChange) throws XMLStreamException { + if (PomHelper.setPluginVersion( + getPom(), + versionChange.getGroupId(), + versionChange.getArtifactId(), + versionChange.getOldVersion(), + versionChange.getNewVersion())) { + info(" Updating plugin " + versionChange.getGroupId() + ":" + versionChange.getArtifactId()); + info(" from version " + versionChange.getOldVersion() + " to " + versionChange.getNewVersion()); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/ProjectVersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/ProjectVersionChanger.java index 64e8a87605..f75013251e 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/ProjectVersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/ProjectVersionChanger.java @@ -33,26 +33,18 @@ * @author Stephen Connolly * @since 15-Sep-2010 16:00:17 */ -public class ProjectVersionChanger - extends AbstractVersionChanger -{ +public class ProjectVersionChanger extends AbstractVersionChanger { - public ProjectVersionChanger( Model model, ModifiedPomXMLEventReader pom, Log reporter ) - { - super( model, pom, reporter ); + public ProjectVersionChanger(Model model, ModifiedPomXMLEventReader pom, Log reporter) { + super(model, pom, reporter); } - public void apply( VersionChange versionChange ) - throws XMLStreamException - { - if ( versionChange.getGroupId().equals( PomHelper.getGroupId( getModel() ) ) - && versionChange.getArtifactId().equals( PomHelper.getArtifactId( getModel() ) ) ) - { - if ( PomHelper.setProjectVersion( getPom(), versionChange.getNewVersion() ) ) - { - info( " Updating project " + versionChange.getGroupId() + ":" + versionChange.getArtifactId() ); - info( " from version " + versionChange.getOldVersion() + " to " - + versionChange.getNewVersion() ); + public void apply(VersionChange versionChange) throws XMLStreamException { + if (versionChange.getGroupId().equals(PomHelper.getGroupId(getModel())) + && versionChange.getArtifactId().equals(PomHelper.getArtifactId(getModel()))) { + if (PomHelper.setProjectVersion(getPom(), versionChange.getNewVersion())) { + info(" Updating project " + versionChange.getGroupId() + ":" + versionChange.getArtifactId()); + info(" from version " + versionChange.getOldVersion() + " to " + versionChange.getNewVersion()); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChanger.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChanger.java index dd86e8e8b1..b2a91a68f1 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChanger.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChanger.java @@ -29,8 +29,6 @@ * @author Stephen Connolly * @since 15-Sep-2010 15:59:00 */ -public interface VersionChanger -{ - void apply( VersionChange versionChange ) - throws XMLStreamException; +public interface VersionChanger { + void apply(VersionChange versionChange) throws XMLStreamException; } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChangerFactory.java b/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChangerFactory.java index 1f1d543d6c..8e91d8fb64 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChangerFactory.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/change/VersionChangerFactory.java @@ -32,116 +32,99 @@ * @author Stephen Connolly * @since 15-Sep-2010 16:05:27 */ -public class VersionChangerFactory -{ +public class VersionChangerFactory { private Model model = null; private ModifiedPomXMLEventReader pom = null; private Log log = null; - public synchronized Model getModel() - { + public synchronized Model getModel() { return model; } - public synchronized void setModel( Model model ) - { + public synchronized void setModel(Model model) { this.model = model; } - public synchronized ModifiedPomXMLEventReader getPom() - { + public synchronized ModifiedPomXMLEventReader getPom() { return pom; } - public synchronized void setPom( ModifiedPomXMLEventReader pom ) - { + public synchronized void setPom(ModifiedPomXMLEventReader pom) { this.pom = pom; } - public synchronized Log getLog() - { + public synchronized Log getLog() { return log; } - public synchronized void setLog( Log log ) - { + public synchronized void setLog(Log log) { this.log = log; } - private synchronized void checkState() - { - if ( model == null ) - { - throw new IllegalStateException( "Model has not been specified" ); + private synchronized void checkState() { + if (model == null) { + throw new IllegalStateException("Model has not been specified"); } - if ( pom == null ) - { - throw new IllegalStateException( "Pom has not been specified" ); + if (pom == null) { + throw new IllegalStateException("Pom has not been specified"); } - if ( log == null ) - { - throw new IllegalStateException( "Log has not been specified" ); + if (log == null) { + throw new IllegalStateException("Log has not been specified"); } } - public synchronized VersionChanger newPluginVersionChanger() - { + public synchronized VersionChanger newPluginVersionChanger() { checkState(); - return new PluginVersionChanger( model, pom, log ); + return new PluginVersionChanger(model, pom, log); } - public synchronized VersionChanger newDependencyVersionChanger() - { + public synchronized VersionChanger newDependencyVersionChanger() { checkState(); - return new DependencyVersionChanger( model, pom, log ); + return new DependencyVersionChanger(model, pom, log); } - public synchronized VersionChanger newProjectVersionChanger() - { + public synchronized VersionChanger newProjectVersionChanger() { checkState(); - return new ProjectVersionChanger( model, pom, log ); + return new ProjectVersionChanger(model, pom, log); } - public synchronized VersionChanger newParentVersionChanger() - { + public synchronized VersionChanger newParentVersionChanger() { checkState(); - return new ParentVersionChanger( model, pom, log ); + return new ParentVersionChanger(model, pom, log); } - public synchronized VersionChanger newVersionChanger() - { + public synchronized VersionChanger newVersionChanger() { checkState(); - VersionChanger[] delegates = new VersionChanger[] { newParentVersionChanger(), newProjectVersionChanger(), - newDependencyVersionChanger(), newPluginVersionChanger() }; - return new CompositeVersionChanger( delegates ); + VersionChanger[] delegates = new VersionChanger[] { + newParentVersionChanger(), + newProjectVersionChanger(), + newDependencyVersionChanger(), + newPluginVersionChanger() + }; + return new CompositeVersionChanger(delegates); } - public synchronized VersionChanger newVersionChanger( boolean processParent, boolean processProject, - boolean processDependencies, boolean processPlugins ) - { + public synchronized VersionChanger newVersionChanger( + boolean processParent, boolean processProject, boolean processDependencies, boolean processPlugins) { checkState(); List delegates = new ArrayList<>(); - if ( processParent ) - { - delegates.add( newParentVersionChanger() ); + if (processParent) { + delegates.add(newParentVersionChanger()); } - if ( processProject ) - { - delegates.add( newProjectVersionChanger() ); + if (processProject) { + delegates.add(newProjectVersionChanger()); } - if ( processDependencies ) - { - delegates.add( newDependencyVersionChanger() ); + if (processDependencies) { + delegates.add(newDependencyVersionChanger()); } - if ( processPlugins ) - { - delegates.add( newPluginVersionChanger() ); + if (processPlugins) { + delegates.add(newPluginVersionChanger()); } - return new CompositeVersionChanger( delegates ); + return new CompositeVersionChanger(delegates); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java index 00f58cb00c..4af2a4fbfa 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java @@ -30,60 +30,50 @@ import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.versions.utils.DependencyComparator; -public class DependencyFilter -{ +public class DependencyFilter { private final String pattern; private final List matchers; - DependencyFilter( String pattern, List matchers ) - { + DependencyFilter(String pattern, List matchers) { this.pattern = pattern; this.matchers = matchers; } - public static DependencyFilter parseFrom( List dependencies ) - { - List matchers = dependencies.stream() - .map( TokenizedMatcher::parse ) - .collect( Collectors.toList() ); + public static DependencyFilter parseFrom(List dependencies) { + List matchers = + dependencies.stream().map(TokenizedMatcher::parse).collect(Collectors.toList()); - String debugPattern = String.join( ",", dependencies ); + String debugPattern = String.join(",", dependencies); - return new DependencyFilter( debugPattern, matchers ); + return new DependencyFilter(debugPattern, matchers); } - private static Predicate not( Predicate predicate ) - { - return x -> !predicate.test( x ); + private static Predicate not(Predicate predicate) { + return x -> !predicate.test(x); } @Override - public String toString() - { - return String.format( "%s{%s}", getClass().getSimpleName(), pattern ); + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), pattern); } - public Set retainingIn( Collection dependencies ) - { - return filterBy( dependencies, this::matchersMatch ); + public Set retainingIn(Collection dependencies) { + return filterBy(dependencies, this::matchersMatch); } - public Set removingFrom( Collection dependencies ) - { - return filterBy( dependencies, not( this::matchersMatch ) ); + public Set removingFrom(Collection dependencies) { + return filterBy(dependencies, not(this::matchersMatch)); } - private boolean matchersMatch( Dependency dependency ) - { - return matchers.stream().anyMatch( m -> m.test( dependency ) ); + private boolean matchersMatch(Dependency dependency) { + return matchers.stream().anyMatch(m -> m.test(dependency)); } - private TreeSet filterBy( Collection dependencies, Predicate predicate ) - { + private TreeSet filterBy(Collection dependencies, Predicate predicate) { return dependencies.stream() - .filter( predicate ) - .collect( Collectors.toCollection( () -> new TreeSet<>( DependencyComparator.INSTANCE ) ) ); + .filter(predicate) + .collect(Collectors.toCollection(() -> new TreeSet<>(DependencyComparator.INSTANCE))); } /** @@ -100,30 +90,26 @@ public static Set filterDependencies( List includes, List excludes, String section, - Log log - ) - { - DependencyFilter includeDeps = DependencyFilter.parseFrom( includes ); - DependencyFilter excludeDeps = DependencyFilter.parseFrom( excludes ); - - Set filtered = includeDeps.retainingIn( dependencies ); - filtered = excludeDeps.removingFrom( filtered ); - - if ( log != null && log.isDebugEnabled() ) - { - log.debug( String.format( "parsed includes in %s: %s -> %s", section, includes, includeDeps ) ); - log.debug( String.format( "parsed excludes in %s: %s -> %s", section, excludes, excludeDeps ) ); - log.debug( String.format( "Unfiltered %s: ", section ) + output( dependencies ) ); - log.debug( String.format( "Filtered %s: ", section ) + output( filtered ) ); + Log log) { + DependencyFilter includeDeps = DependencyFilter.parseFrom(includes); + DependencyFilter excludeDeps = DependencyFilter.parseFrom(excludes); + + Set filtered = includeDeps.retainingIn(dependencies); + filtered = excludeDeps.removingFrom(filtered); + + if (log != null && log.isDebugEnabled()) { + log.debug(String.format("parsed includes in %s: %s -> %s", section, includes, includeDeps)); + log.debug(String.format("parsed excludes in %s: %s -> %s", section, excludes, excludeDeps)); + log.debug(String.format("Unfiltered %s: ", section) + output(dependencies)); + log.debug(String.format("Filtered %s: ", section) + output(filtered)); } return filtered; } - private static String output( Collection dependencies ) - { + private static String output(Collection dependencies) { return dependencies.stream() - .map( d -> String.format( "%s:%s:%s", d.getGroupId(), d.getArtifactId(), d.getVersion() ) ) - .collect( Collectors.joining( ", " ) ); + .map(d -> String.format("%s:%s:%s", d.getGroupId(), d.getArtifactId(), d.getVersion())) + .collect(Collectors.joining(", ")); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/NullAwareWildcardMatcher.java b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/NullAwareWildcardMatcher.java index 1db96c0d99..f5c984af68 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/NullAwareWildcardMatcher.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/NullAwareWildcardMatcher.java @@ -19,23 +19,19 @@ * under the License. */ -public class NullAwareWildcardMatcher extends WildcardMatcher -{ +public class NullAwareWildcardMatcher extends WildcardMatcher { public static final String NULL_KEYWORD = "null"; - public NullAwareWildcardMatcher( String pattern ) - { - super( pattern ); + public NullAwareWildcardMatcher(String pattern) { + super(pattern); } @Override - public boolean test( String token ) - { - if ( NULL_KEYWORD.equals( getPattern() ) ) - { + public boolean test(String token) { + if (NULL_KEYWORD.equals(getPattern())) { return token == null; } - return super.test( token ); + return super.test(token); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/TokenizedMatcher.java b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/TokenizedMatcher.java index 336c9f7e82..b5cae8f60e 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/TokenizedMatcher.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/TokenizedMatcher.java @@ -8,49 +8,41 @@ import org.apache.maven.model.Dependency; -public class TokenizedMatcher implements Predicate -{ - public enum Tokens - { - GROUP_ID( Dependency::getGroupId ), - ARTIFACT_ID( Dependency::getArtifactId ), - VERSION( Dependency::getVersion ), - TYPE( Dependency::getType ), - CLASSIFIER( Dependency::getClassifier ), - SCOPE( Dependency::getScope ); +public class TokenizedMatcher implements Predicate { + public enum Tokens { + GROUP_ID(Dependency::getGroupId), + ARTIFACT_ID(Dependency::getArtifactId), + VERSION(Dependency::getVersion), + TYPE(Dependency::getType), + CLASSIFIER(Dependency::getClassifier), + SCOPE(Dependency::getScope); private final Function tokenExtractor; - Tokens( Function tokenExtractor ) - { + Tokens(Function tokenExtractor) { this.tokenExtractor = tokenExtractor; } - public Function getTokenExtractor() - { + public Function getTokenExtractor() { return tokenExtractor; } } private final Map> matchers; - private TokenizedMatcher( Map> matchers ) - { + private TokenizedMatcher(Map> matchers) { this.matchers = matchers; } @Override - public boolean test( Dependency dependency ) - { - for ( Tokens token : Tokens.values() ) - { - String tokenValue = token.getTokenExtractor().apply( dependency ); + public boolean test(Dependency dependency) { + for (Tokens token : Tokens.values()) { + String tokenValue = token.getTokenExtractor().apply(dependency); - Predicate matcher = matchers.get( token ); - boolean matches = matcher.test( tokenValue ); + Predicate matcher = matchers.get(token); + boolean matches = matcher.test(tokenValue); - if ( !matches ) - { + if (!matches) { return false; } } @@ -58,50 +50,34 @@ public boolean test( Dependency dependency ) return true; } - public static TokenizedMatcher parse( String pattern ) - { - EnumMap> matchers = new EnumMap<>( Tokens.class ); - - String[] split = pattern == null - ? new String[0] - : pattern.split( ":" ); - - String groupIdPattern = split.length >= 1 - ? split[0] - : WildcardMatcher.WILDCARD; - matchers.put( Tokens.GROUP_ID, WildcardMatcher.parse( groupIdPattern ) ); - - String artifactIdPattern = split.length >= 2 - ? split[1] - : WildcardMatcher.WILDCARD; - matchers.put( Tokens.ARTIFACT_ID, WildcardMatcher.parse( artifactIdPattern ) ); - - String versionPattern = split.length >= 3 - ? split[2] - : WildcardMatcher.WILDCARD; - matchers.put( Tokens.VERSION, WildcardMatcher.parse( versionPattern ) ); - - String typePattern = split.length >= 4 - ? split[3] - : WildcardMatcher.WILDCARD; - matchers.put( Tokens.TYPE, WildcardMatcher.parse( typePattern ) ); - - String classifierPattern = split.length >= 5 - ? split[4] - : WildcardMatcher.WILDCARD; - matchers.put( Tokens.CLASSIFIER, new NullAwareWildcardMatcher( classifierPattern ) ); - - String scopePattern = split.length >= 6 - ? split[5] - : WildcardMatcher.WILDCARD; - matchers.put( Tokens.SCOPE, new NullAwareWildcardMatcher( scopePattern ) ); - - return new TokenizedMatcher( Collections.unmodifiableMap( matchers ) ); + public static TokenizedMatcher parse(String pattern) { + EnumMap> matchers = new EnumMap<>(Tokens.class); + + String[] split = pattern == null ? new String[0] : pattern.split(":"); + + String groupIdPattern = split.length >= 1 ? split[0] : WildcardMatcher.WILDCARD; + matchers.put(Tokens.GROUP_ID, WildcardMatcher.parse(groupIdPattern)); + + String artifactIdPattern = split.length >= 2 ? split[1] : WildcardMatcher.WILDCARD; + matchers.put(Tokens.ARTIFACT_ID, WildcardMatcher.parse(artifactIdPattern)); + + String versionPattern = split.length >= 3 ? split[2] : WildcardMatcher.WILDCARD; + matchers.put(Tokens.VERSION, WildcardMatcher.parse(versionPattern)); + + String typePattern = split.length >= 4 ? split[3] : WildcardMatcher.WILDCARD; + matchers.put(Tokens.TYPE, WildcardMatcher.parse(typePattern)); + + String classifierPattern = split.length >= 5 ? split[4] : WildcardMatcher.WILDCARD; + matchers.put(Tokens.CLASSIFIER, new NullAwareWildcardMatcher(classifierPattern)); + + String scopePattern = split.length >= 6 ? split[5] : WildcardMatcher.WILDCARD; + matchers.put(Tokens.SCOPE, new NullAwareWildcardMatcher(scopePattern)); + + return new TokenizedMatcher(Collections.unmodifiableMap(matchers)); } @Override - public String toString() - { - return String.format( "%s{%s}", getClass().getSimpleName(), matchers ); + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), matchers); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/WildcardMatcher.java b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/WildcardMatcher.java index f63f5e88bc..5b4905636f 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/WildcardMatcher.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/filtering/WildcardMatcher.java @@ -6,90 +6,73 @@ import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; -public class WildcardMatcher implements Predicate -{ +public class WildcardMatcher implements Predicate { public static final String WILDCARD = "*"; private final String pattern; - protected WildcardMatcher( String pattern ) - { + protected WildcardMatcher(String pattern) { this.pattern = pattern; } - public static WildcardMatcher parse( String pattern ) - { - return new WildcardMatcher( pattern ); + public static WildcardMatcher parse(String pattern) { + return new WildcardMatcher(pattern); } @Override - public boolean test( String token ) - { - if ( token == null ) - { - return WILDCARD.equals( pattern ); + public boolean test(String token) { + if (token == null) { + return WILDCARD.equals(pattern); } boolean matches; // support full wildcard and implied wildcard - if ( WILDCARD.equals( pattern ) || pattern.isEmpty() ) - { + if (WILDCARD.equals(pattern) || pattern.isEmpty()) { matches = true; } // support contains wildcard - else if ( pattern.startsWith( WILDCARD ) && pattern.endsWith( WILDCARD ) ) - { - String contains = pattern.substring( 1, pattern.length() - 1 ); + else if (pattern.startsWith(WILDCARD) && pattern.endsWith(WILDCARD)) { + String contains = pattern.substring(1, pattern.length() - 1); - matches = token.contains( contains ); + matches = token.contains(contains); } // support leading wildcard - else if ( pattern.startsWith( WILDCARD ) ) - { - matches = token.endsWith( pattern.substring( 1 ) ); + else if (pattern.startsWith(WILDCARD)) { + matches = token.endsWith(pattern.substring(1)); } // support trailing wildcard - else if ( pattern.endsWith( WILDCARD ) ) - { - String prefix = pattern.substring( 0, pattern.length() - 1 ); + else if (pattern.endsWith(WILDCARD)) { + String prefix = pattern.substring(0, pattern.length() - 1); - matches = token.startsWith( prefix ); + matches = token.startsWith(prefix); } // support versions range - else if ( pattern.startsWith( "[" ) || pattern.startsWith( "(" ) ) - { - matches = isVersionIncludedInRange( token, pattern ); + else if (pattern.startsWith("[") || pattern.startsWith("(")) { + matches = isVersionIncludedInRange(token, pattern); } // support exact match - else - { - matches = token.equals( pattern ); + else { + matches = token.equals(pattern); } return matches; } - private boolean isVersionIncludedInRange( final String version, final String range ) - { - try - { - return VersionRange.createFromVersionSpec( range ).containsVersion( new DefaultArtifactVersion( version ) ); - } - catch ( InvalidVersionSpecificationException e ) - { + private boolean isVersionIncludedInRange(final String version, final String range) { + try { + return VersionRange.createFromVersionSpec(range).containsVersion(new DefaultArtifactVersion(version)); + } catch (InvalidVersionSpecificationException e) { return false; } } - public String getPattern() - { + public String getPattern() { return pattern; } @Override - public String toString() - { - return String.format( "%s{%s}", getClass().getSimpleName(), pattern ); + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), pattern); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/AbstractVersionComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/AbstractVersionComparator.java index 75b659e047..23ea3269fd 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/AbstractVersionComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/AbstractVersionComparator.java @@ -26,28 +26,22 @@ * * @since 1.0-beta-1 */ -public abstract class AbstractVersionComparator - implements VersionComparator -{ +public abstract class AbstractVersionComparator implements VersionComparator { @Override - public abstract int compare( ArtifactVersion o1, ArtifactVersion o2 ); + public abstract int compare(ArtifactVersion o1, ArtifactVersion o2); @Override - public final int getSegmentCount( ArtifactVersion v ) - { - if ( v == null ) - { + public final int getSegmentCount(ArtifactVersion v) { + if (v == null) { return 0; } - if ( VersionComparators.isSnapshot( v ) ) - { - return innerGetSegmentCount( VersionComparators.stripSnapshot( v ) ); + if (VersionComparators.isSnapshot(v)) { + return innerGetSegmentCount(VersionComparators.stripSnapshot(v)); } - return innerGetSegmentCount( v ); - + return innerGetSegmentCount(v); } - protected abstract int innerGetSegmentCount( ArtifactVersion v ); + protected abstract int innerGetSegmentCount(ArtifactVersion v); /** * Returns a hash code value for the comparator class. @@ -55,8 +49,7 @@ public final int getSegmentCount( ArtifactVersion v ) * @return the hash code. */ @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } @@ -69,9 +62,7 @@ public int hashCode() * @see java.util.Hashtable */ @Override - public boolean equals( Object obj ) - { - return obj == this || ( obj != null && getClass().equals( obj.getClass() ) ); + public boolean equals(Object obj) { + return obj == this || (obj != null && getClass().equals(obj.getClass())); } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersion.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersion.java index 49b043e82e..b98dc85118 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersion.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersion.java @@ -21,13 +21,13 @@ *

This is particularly helpful for -SNAPSHOT and other versions with qualifiers, which * are lower than version 0 in the Maven versioning system.

*/ -public class BoundArtifactVersion extends DefaultArtifactVersion -{ +public class BoundArtifactVersion extends DefaultArtifactVersion { /** * Most major segment that can change, i.e. not held in place. * All segments that are more major than this one are held in place. */ private final Segment segment; + private final BoundComparableVersion comparator; /** @@ -35,11 +35,10 @@ public class BoundArtifactVersion extends DefaultArtifactVersion * @param artifactVersion artifact version containing the segment version values * @param segment most major segment that can change, i.e. not held in place */ - public BoundArtifactVersion( ArtifactVersion artifactVersion, Segment segment ) - { - super( artifactVersion.toString() ); + public BoundArtifactVersion(ArtifactVersion artifactVersion, Segment segment) { + super(artifactVersion.toString()); this.segment = segment; - this.comparator = new BoundComparableVersion( this ); + this.comparator = new BoundComparableVersion(this); } /** @@ -47,104 +46,85 @@ public BoundArtifactVersion( ArtifactVersion artifactVersion, Segment segment ) * All segments that are more major than this one are held in place. * @return segment that can change */ - public Segment getSegment() - { + public Segment getSegment() { return segment; } @Override - public int compareTo( ArtifactVersion other ) - { - if ( other == null ) - { + public int compareTo(ArtifactVersion other) { + if (other == null) { return -1; } - return comparator.compareTo( new ComparableVersion( other.toString() ) ); + return comparator.compareTo(new ComparableVersion(other.toString())); } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof BoundArtifactVersion ) ) - { + if (!(o instanceof BoundArtifactVersion)) { return false; } BoundArtifactVersion that = (BoundArtifactVersion) o; return new EqualsBuilder() - .appendSuper( super.equals( o ) ) - .append( getSegment(), that.getSegment() ) - .append( comparator, that.comparator ) + .appendSuper(super.equals(o)) + .append(getSegment(), that.getSegment()) + .append(comparator, that.comparator) .isEquals(); } @Override - public int hashCode() - { - return new HashCodeBuilder( 17, 37 ) - .appendSuper( super.hashCode() ) - .append( getSegment() ) - .append( comparator ) + public int hashCode() { + return new HashCodeBuilder(17, 37) + .appendSuper(super.hashCode()) + .append(getSegment()) + .append(comparator) .toHashCode(); } - protected static class BoundComparableVersion extends ComparableVersion - { + protected static class BoundComparableVersion extends ComparableVersion { private BoundArtifactVersion artifactVersion; - protected BoundComparableVersion( BoundArtifactVersion artifactVersion ) - { - super( artifactVersion.toString() ); + protected BoundComparableVersion(BoundArtifactVersion artifactVersion) { + super(artifactVersion.toString()); this.artifactVersion = artifactVersion; } @Override - public int compareTo( ComparableVersion o ) - { + public int compareTo(ComparableVersion o) { // all segments more or equally major than artifactVersion.segment can change - return compareTo( ( (List) items ).iterator(), - ( (Iterable) o.items ).iterator(), artifactVersion.segment.value() ); - + return compareTo( + ((List) items).iterator(), + ((Iterable) o.items).iterator(), + artifactVersion.segment.value()); } - private int compareTo( Iterator left, Iterator right, int comparisonsLeft ) - { - if ( comparisonsLeft <= 0 ) - { + private int compareTo(Iterator left, Iterator right, int comparisonsLeft) { + if (comparisonsLeft <= 0) { // always greater than the other version if all more major segments are equal return 1; } int result = left.hasNext() && right.hasNext() - ? integerItemOrZero( left.next() ).compareTo( right.next() ) - : left.hasNext() || right.hasNext() - ? compareToZero( left, right ) - : 1; - - return result != 0 - ? result - : compareTo( left, right, comparisonsLeft - 1 ); + ? integerItemOrZero(left.next()).compareTo(right.next()) + : left.hasNext() || right.hasNext() ? compareToZero(left, right) : 1; + + return result != 0 ? result : compareTo(left, right, comparisonsLeft - 1); } - private static int compareToZero( Iterator left, Iterator right ) - { + private static int compareToZero(Iterator left, Iterator right) { return left.hasNext() - ? integerItemOrZero( left.next() ).compareTo( ZERO ) - : -right.next().compareTo( ZERO ); + ? integerItemOrZero(left.next()).compareTo(ZERO) + : -right.next().compareTo(ZERO); } - private static Item integerItemOrZero( Item item ) - { - return item instanceof IntegerItem - ? item - : ZERO; + private static Item integerItemOrZero(Item item) { + return item instanceof IntegerItem ? item : ZERO; } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ComparableVersion.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ComparableVersion.java index 55327cfaf3..38dcd79993 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ComparableVersion.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ComparableVersion.java @@ -36,24 +36,21 @@ * @author Herve Boutemy * Note: The implementation of the maven core should be used. */ -public class ComparableVersion - implements Comparable -{ +public class ComparableVersion implements Comparable { private String value; private String canonical; protected ListItem items; - protected interface Item - { + protected interface Item { int INTEGER_ITEM = 0; int STRING_ITEM = 1; int LIST_ITEM = 2; - int compareTo( Item item ); + int compareTo(Item item); int getType(); @@ -63,46 +60,37 @@ protected interface Item /** * Represents a numeric item in the version item list. */ - protected static class IntegerItem - implements Item - { - private static final BigInteger BIG_INTEGER_ZERO = new BigInteger( "0" ); + protected static class IntegerItem implements Item { + private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); private final BigInteger value; public static final IntegerItem ZERO = new IntegerItem(); - private IntegerItem() - { + private IntegerItem() { this.value = BIG_INTEGER_ZERO; } - IntegerItem( String str ) - { - this.value = new BigInteger( str ); + IntegerItem(String str) { + this.value = new BigInteger(str); } - public int getType() - { + public int getType() { return INTEGER_ITEM; } - public boolean isNull() - { - return BIG_INTEGER_ZERO.equals( value ); + public boolean isNull() { + return BIG_INTEGER_ZERO.equals(value); } - public int compareTo( Item item ) - { - if ( item == null ) - { - return BIG_INTEGER_ZERO.equals( value ) ? 0 : 1; // 1.0 == 1, 1.1 > 1 + public int compareTo(Item item) { + if (item == null) { + return BIG_INTEGER_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 } - switch ( item.getType() ) - { + switch (item.getType()) { case INTEGER_ITEM: - return value.compareTo( ( (IntegerItem) item ).value ); + return value.compareTo(((IntegerItem) item).value); case STRING_ITEM: return 1; // 1.1 > 1-sp @@ -111,12 +99,11 @@ public int compareTo( Item item ) return 1; // 1.1 > 1-1 default: - throw new RuntimeException( "invalid item: " + item.getClass() ); + throw new RuntimeException("invalid item: " + item.getClass()); } } - public String toString() - { + public String toString() { return value.toString(); } } @@ -124,39 +111,33 @@ public String toString() /** * Represents a string in the version item list, usually a qualifier. */ - private static class StringItem - implements Item - { - private static final String[] QUALIFIERS = { - "snapshot", "alpha", "beta", "milestone", "preview", "rc", "", "sp" }; + private static class StringItem implements Item { + private static final String[] QUALIFIERS = {"snapshot", "alpha", "beta", "milestone", "preview", "rc", "", "sp" + }; - private static final List QUALIFIERS_LIST = Arrays.asList( QUALIFIERS ); + private static final List QUALIFIERS_LIST = Arrays.asList(QUALIFIERS); private static final Properties ALIASES = new Properties(); - static - { - ALIASES.put( "mr", "milestone" ); - ALIASES.put( "cr", "rc" ); - ALIASES.put( "final", "" ); - ALIASES.put( "ga", "" ); + static { + ALIASES.put("mr", "milestone"); + ALIASES.put("cr", "rc"); + ALIASES.put("final", ""); + ALIASES.put("ga", ""); } /** * A comparable for the empty-string qualifier. This one is used to determine if a given qualifier makes the * version older than one without a qualifier, or more recent. */ - private static final Comparable RELEASE_VERSION_INDEX = String.valueOf( QUALIFIERS_LIST.indexOf( "" ) ); + private static final Comparable RELEASE_VERSION_INDEX = String.valueOf(QUALIFIERS_LIST.indexOf("")); private final String value; - StringItem( String value, boolean followedByDigit ) - { - if ( followedByDigit && value.length() == 1 ) - { + StringItem(String value, boolean followedByDigit) { + if (followedByDigit && value.length() == 1) { // a1 = alpha-1, b1 = beta-1, m1 = milestone-1 - switch ( value.charAt( 0 ) ) - { + switch (value.charAt(0)) { case 'a': value = "alpha"; break; @@ -171,17 +152,15 @@ private static class StringItem break; } } - this.value = ALIASES.getProperty( value, value ); + this.value = ALIASES.getProperty(value, value); } - public int getType() - { + public int getType() { return STRING_ITEM; } - public boolean isNull() - { - return ( comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX ) == 0 ); + public boolean isNull() { + return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); } /** @@ -197,38 +176,33 @@ public boolean isNull() * @param qualifier * @return */ - public static Comparable comparableQualifier( String qualifier ) - { - int i = QUALIFIERS_LIST.indexOf( qualifier ); + public static Comparable comparableQualifier(String qualifier) { + int i = QUALIFIERS_LIST.indexOf(qualifier); - return i == -1 ? QUALIFIERS_LIST.size() + "-" + qualifier : String.valueOf( i ); + return i == -1 ? QUALIFIERS_LIST.size() + "-" + qualifier : String.valueOf(i); } - public int compareTo( Item item ) - { - if ( item == null ) - { + public int compareTo(Item item) { + if (item == null) { // 1-rc < 1, 1-ga > 1 - return comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX ); + return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); } - switch ( item.getType() ) - { + switch (item.getType()) { case INTEGER_ITEM: return -1; // 1.any < 1.1 ? case STRING_ITEM: - return comparableQualifier( value ).compareTo( comparableQualifier( ( (StringItem) item ).value ) ); + return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value)); case LIST_ITEM: return -1; // 1.any < 1-1 default: - throw new RuntimeException( "invalid item: " + item.getClass() ); + throw new RuntimeException("invalid item: " + item.getClass()); } } - public String toString() - { + public String toString() { return value; } } @@ -237,50 +211,36 @@ public String toString() * Represents a version list item. This class is used both for the global item list and for sub-lists (which start * with '-(number)' in the version specification). */ - private static class ListItem - extends ArrayList - implements Item - { - public int getType() - { + private static class ListItem extends ArrayList implements Item { + public int getType() { return LIST_ITEM; } - public boolean isNull() - { - return ( size() == 0 ); + public boolean isNull() { + return (size() == 0); } - void normalize() - { - for ( ListIterator iterator = listIterator( size() ); iterator.hasPrevious(); ) - { + void normalize() { + for (ListIterator iterator = listIterator(size()); iterator.hasPrevious(); ) { Item item = iterator.previous(); - if ( item.isNull() ) - { + if (item.isNull()) { iterator.remove(); // remove null trailing items: 0, "", empty list - } - else - { + } else { break; } } } - public int compareTo( Item item ) - { - if ( item == null ) - { - if ( size() == 0 ) - { + public int compareTo(Item item) { + if (item == null) { + if (size() == 0) { return 0; // 1-0 = 1- (normalize) = 1 } - Item first = get( 0 ); - return first.compareTo( null ); + Item first = get(0); + return first.compareTo(null); } - switch ( item.getType() ) - { + switch (item.getType()) { case INTEGER_ITEM: return -1; // 1-1 < 1.0.x @@ -289,18 +249,16 @@ public int compareTo( Item item ) case LIST_ITEM: Iterator left = iterator(); - Iterator right = ( (ListItem) item ).iterator(); + Iterator right = ((ListItem) item).iterator(); - while ( left.hasNext() || right.hasNext() ) - { + while (left.hasNext() || right.hasNext()) { Item l = left.hasNext() ? left.next() : null; Item r = right.hasNext() ? right.next() : null; // if this is shorter, then invert the compare and mul with -1 - int result = l == null ? -1 * r.compareTo( l ) : l.compareTo( r ); + int result = l == null ? -1 * r.compareTo(l) : l.compareTo(r); - if ( result != 0 ) - { + if (result != 0) { return result; } } @@ -308,107 +266,84 @@ public int compareTo( Item item ) return 0; default: - throw new RuntimeException( "invalid item: " + item.getClass() ); + throw new RuntimeException("invalid item: " + item.getClass()); } } - public String toString() - { - StringBuilder buffer = new StringBuilder( "(" ); - for ( Iterator iter = iterator(); iter.hasNext(); ) - { - buffer.append( iter.next() ); - if ( iter.hasNext() ) - { - buffer.append( ',' ); + public String toString() { + StringBuilder buffer = new StringBuilder("("); + for (Iterator iter = iterator(); iter.hasNext(); ) { + buffer.append(iter.next()); + if (iter.hasNext()) { + buffer.append(','); } } - buffer.append( ')' ); + buffer.append(')'); return buffer.toString(); } } - public ComparableVersion( String version ) - { - parseVersion( version ); + public ComparableVersion(String version) { + parseVersion(version); } - public final void parseVersion( String version ) - { + public final void parseVersion(String version) { this.value = version; items = new ListItem(); - version = version.toLowerCase( Locale.ENGLISH ); + version = version.toLowerCase(Locale.ENGLISH); ListItem list = items; Stack stack = new Stack<>(); - stack.push( list ); + stack.push(list); boolean isDigit = false; int startIndex = 0; - for ( int i = 0; i < version.length(); i++ ) - { - char c = version.charAt( i ); + for (int i = 0; i < version.length(); i++) { + char c = version.charAt(i); - if ( c == '.' ) - { - if ( i == startIndex ) - { - list.add( IntegerItem.ZERO ); - } - else - { - list.add( parseItem( isDigit, version.substring( startIndex, i ) ) ); + if (c == '.') { + if (i == startIndex) { + list.add(IntegerItem.ZERO); + } else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); } startIndex = i + 1; - } - else if ( c == '-' ) - { - if ( i == startIndex ) - { - list.add( IntegerItem.ZERO ); - } - else - { - list.add( parseItem( isDigit, version.substring( startIndex, i ) ) ); + } else if (c == '-') { + if (i == startIndex) { + list.add(IntegerItem.ZERO); + } else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); } startIndex = i + 1; - if ( isDigit ) - { + if (isDigit) { list.normalize(); // 1.0-* = 1-* - if ( ( i + 1 < version.length() ) && Character.isDigit( version.charAt( i + 1 ) ) ) - { + if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) { // new ListItem only if previous were digits and new char is a digit, // ie need to differentiate only 1.1 from 1-1 // CHECKSTYLE_OFF: InnerAssignment - list.add( list = new ListItem() ); + list.add(list = new ListItem()); // CHECKSTYLE_ON: InnerAssignment - stack.push( list ); + stack.push(list); } } - } - else if ( Character.isDigit( c ) ) - { - if ( !isDigit && i > startIndex ) - { - list.add( new StringItem( version.substring( startIndex, i ), true ) ); + } else if (Character.isDigit(c)) { + if (!isDigit && i > startIndex) { + list.add(new StringItem(version.substring(startIndex, i), true)); startIndex = i; } isDigit = true; - } - else - { - if ( isDigit && i > startIndex ) - { - list.add( parseItem( true, version.substring( startIndex, i ) ) ); + } else { + if (isDigit && i > startIndex) { + list.add(parseItem(true, version.substring(startIndex, i))); startIndex = i; } @@ -416,13 +351,11 @@ else if ( Character.isDigit( c ) ) } } - if ( version.length() > startIndex ) - { - list.add( parseItem( isDigit, version.substring( startIndex ) ) ); + if (version.length() > startIndex) { + list.add(parseItem(isDigit, version.substring(startIndex))); } - while ( !stack.isEmpty() ) - { + while (!stack.isEmpty()) { list = stack.pop(); list.normalize(); } @@ -430,28 +363,23 @@ else if ( Character.isDigit( c ) ) canonical = items.toString(); } - private static Item parseItem( boolean isDigit, String buf ) - { - return isDigit ? new IntegerItem( buf ) : new StringItem( buf, false ); + private static Item parseItem(boolean isDigit, String buf) { + return isDigit ? new IntegerItem(buf) : new StringItem(buf, false); } - public int compareTo( ComparableVersion o ) - { - return items.compareTo( ( o ).items ); + public int compareTo(ComparableVersion o) { + return items.compareTo((o).items); } - public String toString() - { + public String toString() { return value; } - public boolean equals( Object o ) - { - return ( o instanceof ComparableVersion ) && canonical.equals( ( (ComparableVersion) o ).canonical ); + public boolean equals(Object o) { + return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical); } - public int hashCode() - { + public int hashCode() { return canonical.hashCode(); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/InvalidSegmentException.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/InvalidSegmentException.java index ad656cfe63..2be0171684 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/InvalidSegmentException.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/InvalidSegmentException.java @@ -25,8 +25,7 @@ /** * Represents an invalid segment being identified within a version. */ -public class InvalidSegmentException extends Exception -{ +public class InvalidSegmentException extends Exception { private final Segment segment; private final int segmentCount; @@ -40,10 +39,10 @@ public class InvalidSegmentException extends Exception * @param segmentCount the number of segments. * @param version the version object. */ - public InvalidSegmentException( Segment segment, int segmentCount, ArtifactVersion version ) - { - super( String.format( "Invalid segment %s for the %d segment version: '%s'", segment.toString(), segmentCount, - version.toString() ) ); + public InvalidSegmentException(Segment segment, int segmentCount, ArtifactVersion version) { + super(String.format( + "Invalid segment %s for the %d segment version: '%s'", + segment.toString(), segmentCount, version.toString())); this.segment = segment; this.segmentCount = segmentCount; this.version = version; @@ -52,24 +51,21 @@ public InvalidSegmentException( Segment segment, int segmentCount, ArtifactVersi /** * @return segment */ - public Segment getSegment() - { + public Segment getSegment() { return segment; } /** * @return segment count */ - public int getSegmentCount() - { + public int getSegmentCount() { return segmentCount; } /** * @return version object */ - public ArtifactVersion getVersion() - { + public ArtifactVersion getVersion() { return version; } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MavenVersionComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MavenVersionComparator.java index c4f5332ed9..2b6fde15f5 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MavenVersionComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MavenVersionComparator.java @@ -30,65 +30,53 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public class MavenVersionComparator extends AbstractVersionComparator -{ +public class MavenVersionComparator extends AbstractVersionComparator { /** * {@inheritDoc} */ - public int compare( ArtifactVersion o1, ArtifactVersion o2 ) - { - if ( o1 instanceof BoundArtifactVersion ) - { - return o1.compareTo( o2 ); + public int compare(ArtifactVersion o1, ArtifactVersion o2) { + if (o1 instanceof BoundArtifactVersion) { + return o1.compareTo(o2); } - return new ComparableVersion( o1.toString() ).compareTo( new ComparableVersion( o2.toString() ) ); + return new ComparableVersion(o1.toString()).compareTo(new ComparableVersion(o2.toString())); } /** * {@inheritDoc} */ - protected int innerGetSegmentCount( ArtifactVersion v ) - { + protected int innerGetSegmentCount(ArtifactVersion v) { // if the version does not match the maven rules, then we have only one segment // i.e. the qualifier - if ( v.getBuildNumber() != 0 ) - { + if (v.getBuildNumber() != 0) { // the version was successfully parsed, and we have a build number // have to have four segments return 4; } - if ( ( v.getMajorVersion() != 0 || v.getMinorVersion() != 0 || v.getIncrementalVersion() != 0 ) - && v.getQualifier() != null ) - { + if ((v.getMajorVersion() != 0 || v.getMinorVersion() != 0 || v.getIncrementalVersion() != 0) + && v.getQualifier() != null) { // the version was successfully parsed, and we have a qualifier // have to have four segments return 4; } final String version = v.toString(); - if ( version.indexOf( '-' ) != -1 ) - { + if (version.indexOf('-') != -1) { // the version has parts and was not parsed successfully // have to have one segment - return version.equals( v.getQualifier() ) ? 1 : 4; + return version.equals(v.getQualifier()) ? 1 : 4; } - if ( version.indexOf( '.' ) != -1 ) - { + if (version.indexOf('.') != -1) { // the version has parts and was not parsed successfully // have to have one segment - return version.equals( v.getQualifier() ) ? 1 : 3; + return version.equals(v.getQualifier()) ? 1 : 3; } - if ( StringUtils.isEmpty( version ) ) - { + if (StringUtils.isEmpty(version)) { return 3; } - try - { - Integer.parseInt( version ); + try { + Integer.parseInt(version); return 3; - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { return 1; } } @@ -96,33 +84,28 @@ protected int innerGetSegmentCount( ArtifactVersion v ) /** * {@inheritDoc} */ - protected ArtifactVersion innerIncrementSegment( ArtifactVersion v, Segment segment ) throws InvalidSegmentException - { + protected ArtifactVersion innerIncrementSegment(ArtifactVersion v, Segment segment) throws InvalidSegmentException { String version = v.toString(); - if ( innerGetSegmentCount( v ) == 1 ) - { + if (innerGetSegmentCount(v) == 1) { // only the qualifier - version = VersionComparators.alphaNumIncrement( version ); - return new DefaultArtifactVersion( version ); - } - else - { + version = VersionComparators.alphaNumIncrement(version); + return new DefaultArtifactVersion(version); + } else { int major = v.getMajorVersion(); int minor = v.getMinorVersion(); int incremental = v.getIncrementalVersion(); int build = v.getBuildNumber(); String qualifier = v.getQualifier(); - int minorIndex = version.indexOf( '.' ); + int minorIndex = version.indexOf('.'); boolean haveMinor = minorIndex != -1; - int incrementalIndex = haveMinor ? version.indexOf( '.', minorIndex + 1 ) : -1; + int incrementalIndex = haveMinor ? version.indexOf('.', minorIndex + 1) : -1; boolean haveIncremental = incrementalIndex != -1; - int buildIndex = version.indexOf( '-' ); + int buildIndex = version.indexOf('-'); boolean haveBuild = buildIndex != -1 && qualifier == null; boolean haveQualifier = buildIndex != -1 && qualifier != null; - switch ( segment ) - { + switch (segment) { case MAJOR: major++; minor = 0; @@ -134,8 +117,7 @@ protected ArtifactVersion innerIncrementSegment( ArtifactVersion v, Segment segm minor++; incremental = 0; build = 0; - if ( haveQualifier && qualifier.endsWith( "SNAPSHOT" ) ) - { + if (haveQualifier && qualifier.endsWith("SNAPSHOT")) { qualifier = "SNAPSHOT"; } break; @@ -145,12 +127,9 @@ protected ArtifactVersion innerIncrementSegment( ArtifactVersion v, Segment segm qualifier = null; break; case SUBINCREMENTAL: - if ( haveQualifier ) - { - qualifier = qualifierIncrement( qualifier ); - } - else - { + if (haveQualifier) { + qualifier = qualifierIncrement(qualifier); + } else { build++; } break; @@ -159,50 +138,41 @@ protected ArtifactVersion innerIncrementSegment( ArtifactVersion v, Segment segm break; } StringBuilder result = new StringBuilder(); - result.append( major ); - if ( haveMinor || minor > 0 || incremental > 0 ) - { - result.append( '.' ); - result.append( minor ); - } - if ( haveIncremental || incremental > 0 ) - { - result.append( '.' ); - result.append( incremental ); + result.append(major); + if (haveMinor || minor > 0 || incremental > 0) { + result.append('.'); + result.append(minor); } - if ( haveQualifier && qualifier != null ) - { - result.append( '-' ); - result.append( qualifier ); + if (haveIncremental || incremental > 0) { + result.append('.'); + result.append(incremental); } - else if ( haveBuild || build > 0 ) - { - result.append( '-' ); - result.append( build ); + if (haveQualifier && qualifier != null) { + result.append('-'); + result.append(qualifier); + } else if (haveBuild || build > 0) { + result.append('-'); + result.append(build); } - return new DefaultArtifactVersion( result.toString() ); + return new DefaultArtifactVersion(result.toString()); } } - private String qualifierIncrement( String qualifier ) - { - if ( qualifier.toLowerCase().startsWith( "alpha" ) ) - { - return qualifier.substring( 0, 5 ) + VersionComparators.alphaNumIncrement( qualifier.substring( 5 ) ); + private String qualifierIncrement(String qualifier) { + if (qualifier.toLowerCase().startsWith("alpha")) { + return qualifier.substring(0, 5) + VersionComparators.alphaNumIncrement(qualifier.substring(5)); } - if ( qualifier.toLowerCase().startsWith( "beta" ) ) - { - return qualifier.substring( 0, 4 ) + VersionComparators.alphaNumIncrement( qualifier.substring( 4 ) ); + if (qualifier.toLowerCase().startsWith("beta")) { + return qualifier.substring(0, 4) + VersionComparators.alphaNumIncrement(qualifier.substring(4)); } - if ( qualifier.toLowerCase().startsWith( "milestone" ) ) - { - return qualifier.substring( 0, 8 ) + VersionComparators.alphaNumIncrement( qualifier.substring( 8 ) ); + if (qualifier.toLowerCase().startsWith("milestone")) { + return qualifier.substring(0, 8) + VersionComparators.alphaNumIncrement(qualifier.substring(8)); } - if ( qualifier.toLowerCase().startsWith( "cr" ) || qualifier.toLowerCase().startsWith( "rc" ) - || qualifier.toLowerCase().startsWith( "sp" ) ) - { - return qualifier.substring( 0, 2 ) + VersionComparators.alphaNumIncrement( qualifier.substring( 2 ) ); + if (qualifier.toLowerCase().startsWith("cr") + || qualifier.toLowerCase().startsWith("rc") + || qualifier.toLowerCase().startsWith("sp")) { + return qualifier.substring(0, 2) + VersionComparators.alphaNumIncrement(qualifier.substring(2)); } - return VersionComparators.alphaNumIncrement( qualifier ); + return VersionComparators.alphaNumIncrement(qualifier); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparator.java index bccc150462..2f6e4a8bf0 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparator.java @@ -33,115 +33,87 @@ * @since 1.0-alpha-3 * @deprecated */ -public class MercuryVersionComparator - extends AbstractVersionComparator -{ - private static final BigInteger BIG_INTEGER_ONE = new BigInteger( "1" ); +public class MercuryVersionComparator extends AbstractVersionComparator { + private static final BigInteger BIG_INTEGER_ONE = new BigInteger("1"); /** * {@inheritDoc} */ - public int compare( ArtifactVersion o1, ArtifactVersion o2 ) - { - return new ComparableVersion( o1.toString() ).compareTo( new ComparableVersion( o2.toString() ) ); + public int compare(ArtifactVersion o1, ArtifactVersion o2) { + return new ComparableVersion(o1.toString()).compareTo(new ComparableVersion(o2.toString())); } - protected int innerGetSegmentCount( ArtifactVersion v ) - { + protected int innerGetSegmentCount(ArtifactVersion v) { final String version = v.toString(); - StringTokenizer tok = new StringTokenizer( version, ".-" ); + StringTokenizer tok = new StringTokenizer(version, ".-"); return tok.countTokens(); } - protected ArtifactVersion innerIncrementSegment( ArtifactVersion v, Segment segment ) throws InvalidSegmentException - { + protected ArtifactVersion innerIncrementSegment(ArtifactVersion v, Segment segment) throws InvalidSegmentException { final String version = v.toString(); - StringBuilder result = new StringBuilder( version.length() + 10 ); - StringTokenizer tok = new StringTokenizer( version, ".-" ); + StringBuilder result = new StringBuilder(version.length() + 10); + StringTokenizer tok = new StringTokenizer(version, ".-"); int index = 0; - while ( tok.hasMoreTokens() && segment.value() > 0 ) - { + while (tok.hasMoreTokens() && segment.value() > 0) { String token = tok.nextToken(); - result.append( token ); + result.append(token); index += token.length(); - if ( tok.hasMoreTokens() ) - { + if (tok.hasMoreTokens()) { // grab the token separator - result.append( version.charAt( index ) ); + result.append(version.charAt(index)); index++; } - segment = Segment.of( segment.value() - 1 ); + segment = Segment.of(segment.value() - 1); } - if ( segment.value() == 0 ) - { - if ( tok.hasMoreTokens() ) - { + if (segment.value() == 0) { + if (tok.hasMoreTokens()) { String token = tok.nextToken(); String newToken; - try - { - BigInteger n = new BigInteger( token ); - newToken = n.add( BIG_INTEGER_ONE ).toString(); - } - catch ( NumberFormatException e ) - { + try { + BigInteger n = new BigInteger(token); + newToken = n.add(BIG_INTEGER_ONE).toString(); + } catch (NumberFormatException e) { // ok, let's try some common tricks - if ( "alpha".equalsIgnoreCase( token ) ) - { + if ("alpha".equalsIgnoreCase(token)) { newToken = "beta"; - } - else if ( "beta".equalsIgnoreCase( token ) ) - { + } else if ("beta".equalsIgnoreCase(token)) { newToken = "milestone"; - } - else if ( "milestone".equalsIgnoreCase( token ) ) - { + } else if ("milestone".equalsIgnoreCase(token)) { newToken = "rc"; - } - else if ( "rc".equalsIgnoreCase( token ) || "cr".equalsIgnoreCase( token ) ) - { + } else if ("rc".equalsIgnoreCase(token) || "cr".equalsIgnoreCase(token)) { newToken = "ga"; - } - else if ( "final".equalsIgnoreCase( token ) || "ga".equalsIgnoreCase( token ) - || "".equalsIgnoreCase( token ) ) - { + } else if ("final".equalsIgnoreCase(token) + || "ga".equalsIgnoreCase(token) + || "".equalsIgnoreCase(token)) { newToken = "sp"; - } - else - { - newToken = VersionComparators.alphaNumIncrement( token ); + } else { + newToken = VersionComparators.alphaNumIncrement(token); } } - result.append( newToken ); + result.append(newToken); index += token.length(); - if ( tok.hasMoreTokens() ) - { + if (tok.hasMoreTokens()) { // grab the token separator - result.append( version.charAt( index ) ); + result.append(version.charAt(index)); index++; } - } - else - { + } else { // an empty part is equivalent to 0 for mercury version comparator - result.append( "1" ); + result.append("1"); } } - while ( tok.hasMoreTokens() ) - { + while (tok.hasMoreTokens()) { String token = tok.nextToken(); - result.append( "0" ); + result.append("0"); index += token.length(); - if ( tok.hasMoreTokens() ) - { + if (tok.hasMoreTokens()) { // grab the token separator - result.append( version.charAt( index ) ); + result.append(version.charAt(index)); index++; } } - return new DefaultArtifactVersion( result.toString() ); + return new DefaultArtifactVersion(result.toString()); } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/NumericVersionComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/NumericVersionComparator.java index 70a38f3011..71172f288b 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/NumericVersionComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/NumericVersionComparator.java @@ -34,113 +34,86 @@ * @since 1.0-alpha-3 * @deprecated */ -public class NumericVersionComparator - extends AbstractVersionComparator -{ - private static final BigInteger BIG_INTEGER_ZERO = new BigInteger( "0" ); +public class NumericVersionComparator extends AbstractVersionComparator { + private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); - private static final BigInteger BIG_INTEGER_ONE = new BigInteger( "1" ); + private static final BigInteger BIG_INTEGER_ONE = new BigInteger("1"); /** * {@inheritDoc} */ - public int compare( ArtifactVersion o1, ArtifactVersion o2 ) - { + public int compare(ArtifactVersion o1, ArtifactVersion o2) { String v1 = o1.toString(); String v2 = o2.toString(); - StringTokenizer tok1 = new StringTokenizer( v1, "." ); - StringTokenizer tok2 = new StringTokenizer( v2, "." ); - while ( tok1.hasMoreTokens() && tok2.hasMoreTokens() ) - { + StringTokenizer tok1 = new StringTokenizer(v1, "."); + StringTokenizer tok2 = new StringTokenizer(v2, "."); + while (tok1.hasMoreTokens() && tok2.hasMoreTokens()) { String p1 = tok1.nextToken(); String p2 = tok2.nextToken(); String q1 = null; String q2 = null; - if ( p1.indexOf( '-' ) >= 0 ) - { - int index = p1.indexOf( '-' ); - q1 = p1.substring( index ); - p1 = p1.substring( 0, index ); - } - if ( p2.indexOf( '-' ) >= 0 ) - { - int index = p2.indexOf( '-' ); - q2 = p2.substring( index ); - p2 = p2.substring( 0, index ); - } - try - { - BigInteger n1 = new BigInteger( p1 ); - BigInteger n2 = new BigInteger( p2 ); - int result = n1.compareTo( n2 ); - if ( result != 0 ) - { + if (p1.indexOf('-') >= 0) { + int index = p1.indexOf('-'); + q1 = p1.substring(index); + p1 = p1.substring(0, index); + } + if (p2.indexOf('-') >= 0) { + int index = p2.indexOf('-'); + q2 = p2.substring(index); + p2 = p2.substring(0, index); + } + try { + BigInteger n1 = new BigInteger(p1); + BigInteger n2 = new BigInteger(p2); + int result = n1.compareTo(n2); + if (result != 0) { return result; } - } - catch ( NumberFormatException e ) - { - int result = p1.compareTo( p2 ); - if ( result != 0 ) - { + } catch (NumberFormatException e) { + int result = p1.compareTo(p2); + if (result != 0) { return result; } } - if ( q1 != null && q2 != null ) - { - final int result = q1.compareTo( q2 ); - if ( result != 0 ) - { + if (q1 != null && q2 != null) { + final int result = q1.compareTo(q2); + if (result != 0) { return result; } } - if ( q1 != null ) - { + if (q1 != null) { return -1; } - if ( q2 != null ) - { + if (q2 != null) { return +1; } } - if ( tok1.hasMoreTokens() ) - { + if (tok1.hasMoreTokens()) { BigInteger n2 = BIG_INTEGER_ZERO; - while ( tok1.hasMoreTokens() ) - { - try - { - BigInteger n1 = new BigInteger( tok1.nextToken() ); - int result = n1.compareTo( n2 ); - if ( result != 0 ) - { + while (tok1.hasMoreTokens()) { + try { + BigInteger n1 = new BigInteger(tok1.nextToken()); + int result = n1.compareTo(n2); + if (result != 0) { return result; } - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { // any token is better than zero return +1; } } return -1; } - if ( tok2.hasMoreTokens() ) - { + if (tok2.hasMoreTokens()) { BigInteger n1 = BIG_INTEGER_ZERO; - while ( tok2.hasMoreTokens() ) - { - try - { - BigInteger n2 = new BigInteger( tok2.nextToken() ); - int result = n1.compareTo( n2 ); - if ( result != 0 ) - { + while (tok2.hasMoreTokens()) { + try { + BigInteger n2 = new BigInteger(tok2.nextToken()); + int result = n1.compareTo(n2); + if (result != 0) { return result; } - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { // any token is better than zero return -1; } @@ -153,180 +126,123 @@ public int compare( ArtifactVersion o1, ArtifactVersion o2 ) /** * {@inheritDoc} */ - protected int innerGetSegmentCount( ArtifactVersion v ) - { + protected int innerGetSegmentCount(ArtifactVersion v) { final String version = v.toString(); - StringTokenizer tok = new StringTokenizer( version, "." ); + StringTokenizer tok = new StringTokenizer(version, "."); return tok.countTokens(); } /** * {@inheritDoc} */ - @SuppressWarnings( "checkstyle:MethodLength" ) - protected ArtifactVersion innerIncrementSegment( ArtifactVersion v, Segment segment ) throws InvalidSegmentException - { + @SuppressWarnings("checkstyle:MethodLength") + protected ArtifactVersion innerIncrementSegment(ArtifactVersion v, Segment segment) throws InvalidSegmentException { final String version = v.toString(); StringBuilder buf = new StringBuilder(); - StringTokenizer tok = new StringTokenizer( version, "." ); + StringTokenizer tok = new StringTokenizer(version, "."); boolean first = true; - for ( int segmentIdx = segment.value(); segmentIdx >= 0 && tok.hasMoreTokens(); --segmentIdx ) - { - if ( first ) - { + for (int segmentIdx = segment.value(); segmentIdx >= 0 && tok.hasMoreTokens(); --segmentIdx) { + if (first) { first = false; - } - else - { - buf.append( '.' ); + } else { + buf.append('.'); } String p = tok.nextToken(); String q = null; - if ( p.indexOf( '-' ) >= 0 ) - { - int index = p.indexOf( '-' ); - q = p.substring( index + 1 ); - p = p.substring( 0, index ); + if (p.indexOf('-') >= 0) { + int index = p.indexOf('-'); + q = p.substring(index + 1); + p = p.substring(0, index); } - if ( segmentIdx == 0 ) - { - try - { - BigInteger n = new BigInteger( p ); - p = n.add( BIG_INTEGER_ONE ).toString(); + if (segmentIdx == 0) { + try { + BigInteger n = new BigInteger(p); + p = n.add(BIG_INTEGER_ONE).toString(); q = null; - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { // ok, let's try some common tricks - if ( "alpha".equalsIgnoreCase( p ) ) - { - if ( q == null ) - { + if ("alpha".equalsIgnoreCase(p)) { + if (q == null) { p = "beta"; - } - else - { - try - { - BigInteger n = new BigInteger( q ); - q = n.add( BIG_INTEGER_ONE ).toString(); - } - catch ( NumberFormatException e1 ) - { + } else { + try { + BigInteger n = new BigInteger(q); + q = n.add(BIG_INTEGER_ONE).toString(); + } catch (NumberFormatException e1) { p = "beta"; q = null; } } - } - else if ( "beta".equalsIgnoreCase( p ) ) - { - if ( q == null ) - { + } else if ("beta".equalsIgnoreCase(p)) { + if (q == null) { p = "milestone"; - } - else - { - try - { - BigInteger n = new BigInteger( q ); - q = n.add( BIG_INTEGER_ONE ).toString(); - } - catch ( NumberFormatException e1 ) - { + } else { + try { + BigInteger n = new BigInteger(q); + q = n.add(BIG_INTEGER_ONE).toString(); + } catch (NumberFormatException e1) { p = "milestone"; q = null; } } - } - else if ( "milestone".equalsIgnoreCase( p ) ) - { - if ( q == null ) - { + } else if ("milestone".equalsIgnoreCase(p)) { + if (q == null) { p = "rc"; - } - else - { - try - { - BigInteger n = new BigInteger( q ); - q = n.add( BIG_INTEGER_ONE ).toString(); - } - catch ( NumberFormatException e1 ) - { + } else { + try { + BigInteger n = new BigInteger(q); + q = n.add(BIG_INTEGER_ONE).toString(); + } catch (NumberFormatException e1) { p = "rc"; q = null; } } - } - else if ( "cr".equalsIgnoreCase( p ) || "rc".equalsIgnoreCase( p ) ) - { - if ( q == null ) - { + } else if ("cr".equalsIgnoreCase(p) || "rc".equalsIgnoreCase(p)) { + if (q == null) { p = "ga"; - } - else - { - try - { - BigInteger n = new BigInteger( q ); - q = n.add( BIG_INTEGER_ONE ).toString(); - } - catch ( NumberFormatException e1 ) - { + } else { + try { + BigInteger n = new BigInteger(q); + q = n.add(BIG_INTEGER_ONE).toString(); + } catch (NumberFormatException e1) { p = "ga"; q = null; } } - } - else if ( "ga".equalsIgnoreCase( p ) || "final".equalsIgnoreCase( p ) ) - { - if ( q == null ) - { + } else if ("ga".equalsIgnoreCase(p) || "final".equalsIgnoreCase(p)) { + if (q == null) { p = "sp"; q = "1"; - } - else - { - try - { - BigInteger n = new BigInteger( q ); - q = n.add( BIG_INTEGER_ONE ).toString(); - } - catch ( NumberFormatException e1 ) - { + } else { + try { + BigInteger n = new BigInteger(q); + q = n.add(BIG_INTEGER_ONE).toString(); + } catch (NumberFormatException e1) { p = "sp"; q = "1"; } } - } - else - { - p = VersionComparators.alphaNumIncrement( p ); + } else { + p = VersionComparators.alphaNumIncrement(p); } } } - buf.append( p ); - if ( q != null ) - { - buf.append( '-' ); - buf.append( q ); + buf.append(p); + if (q != null) { + buf.append('-'); + buf.append(q); } } - while ( tok.hasMoreTokens() ) - { - if ( first ) - { + while (tok.hasMoreTokens()) { + if (first) { first = false; - } - else - { - buf.append( '.' ); + } else { + buf.append('.'); } tok.nextToken(); - buf.append( "0" ); + buf.append("0"); } - return new DefaultArtifactVersion( buf.toString() ); + return new DefaultArtifactVersion(buf.toString()); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ReactorDepthComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ReactorDepthComparator.java index b9e0e7199b..25124511d5 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ReactorDepthComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/ReactorDepthComparator.java @@ -31,30 +31,23 @@ * @author Stephen Connolly * @since 15-Sep-2010 14:54:42 */ -public class ReactorDepthComparator - implements Comparator -{ +public class ReactorDepthComparator implements Comparator { private final Map reactor; - public ReactorDepthComparator( Map reactor ) - { + public ReactorDepthComparator(Map reactor) { this.reactor = reactor; } - public int compare( String o1, String o2 ) - { - final Model m1 = reactor.get( o1 ); - final Model m2 = reactor.get( o2 ); - final int d1 = PomHelper.getReactorParentCount( reactor, m1 ); - final int d2 = PomHelper.getReactorParentCount( reactor, m2 ); - if ( d1 < d2 ) - { + public int compare(String o1, String o2) { + final Model m1 = reactor.get(o1); + final Model m2 = reactor.get(o2); + final int d1 = PomHelper.getReactorParentCount(reactor, m1); + final int d2 = PomHelper.getReactorParentCount(reactor, m2); + if (d1 < d2) { return -1; - } - else if ( d1 > d2 ) - { + } else if (d1 > d2) { return 1; } - return PomHelper.getGAV( m1 ).compareTo( PomHelper.getGAV( m2 ) ); + return PomHelper.getGAV(m1).compareTo(PomHelper.getGAV(m2)); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparator.java index 1ca3e6b075..2b7fa449f7 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparator.java @@ -26,9 +26,7 @@ /** * A rule for comparing and manipulating versions. */ -public interface VersionComparator - extends Comparator -{ +public interface VersionComparator extends Comparator { /** * Returns the number of segments specified or specifiable in the supplied artifact version. * @@ -36,5 +34,5 @@ public interface VersionComparator * @return The number of segments. * @since 1.0-beta-1 */ - int getSegmentCount( ArtifactVersion artifactVersion ); + int getSegmentCount(ArtifactVersion artifactVersion); } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparators.java b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparators.java index 2693bb6a51..9e00ab02a7 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparators.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/ordering/VersionComparators.java @@ -33,13 +33,11 @@ * @deprecated * Note: This comparator should be replaced by using the one of Maven core instead. */ -public final class VersionComparators -{ - private static final Pattern SNAPSHOT_PATTERN = Pattern.compile( "(-((\\d{8}\\.\\d{6})-(\\d+))|(SNAPSHOT))$" ); +public final class VersionComparators { + private static final Pattern SNAPSHOT_PATTERN = Pattern.compile("(-((\\d{8}\\.\\d{6})-(\\d+))|(SNAPSHOT))$"); - private VersionComparators() - { - throw new IllegalAccessError( "Utility classes should never be instantiated" ); + private VersionComparators() { + throw new IllegalAccessError("Utility classes should never be instantiated"); } /** @@ -49,131 +47,93 @@ private VersionComparators() * @return the version comparator to use. * @since 1.0-alpha-1 */ - public static VersionComparator getVersionComparator( String comparisonMethod ) - { - if ( "numeric".equalsIgnoreCase( comparisonMethod ) ) - { + public static VersionComparator getVersionComparator(String comparisonMethod) { + if ("numeric".equalsIgnoreCase(comparisonMethod)) { return new NumericVersionComparator(); - } - else if ( "mercury".equalsIgnoreCase( comparisonMethod ) ) - { + } else if ("mercury".equalsIgnoreCase(comparisonMethod)) { return new MercuryVersionComparator(); } return new MavenVersionComparator(); } - public static String alphaNumIncrement( String token ) - { + public static String alphaNumIncrement(String token) { String newToken; int i = token.length(); boolean done = false; newToken = token; - while ( !done && i > 0 ) - { + while (!done && i > 0) { i--; - char c = token.charAt( i ); - if ( '0' <= c && c < '9' ) - { + char c = token.charAt(i); + if ('0' <= c && c < '9') { c++; - newToken = - newToken.substring( 0, i ) + c + ( i + 1 < newToken.length() ? newToken.substring( i + 1 ) : "" ); + newToken = newToken.substring(0, i) + c + (i + 1 < newToken.length() ? newToken.substring(i + 1) : ""); done = true; - } - else if ( c == '9' ) - { + } else if (c == '9') { c = '0'; - newToken = - newToken.substring( 0, i ) + c + ( i + 1 < newToken.length() ? newToken.substring( i + 1 ) : "" ); - } - else if ( 'A' <= c && c < 'Z' ) - { + newToken = newToken.substring(0, i) + c + (i + 1 < newToken.length() ? newToken.substring(i + 1) : ""); + } else if ('A' <= c && c < 'Z') { c++; - newToken = - newToken.substring( 0, i ) + c + ( i + 1 < newToken.length() ? newToken.substring( i + 1 ) : "" ); + newToken = newToken.substring(0, i) + c + (i + 1 < newToken.length() ? newToken.substring(i + 1) : ""); done = true; - } - else if ( c == 'Z' ) - { + } else if (c == 'Z') { c = 'A'; - newToken = - newToken.substring( 0, i ) + c + ( i + 1 < newToken.length() ? newToken.substring( i + 1 ) : "" ); - } - else if ( 'a' <= c && c < 'z' ) - { + newToken = newToken.substring(0, i) + c + (i + 1 < newToken.length() ? newToken.substring(i + 1) : ""); + } else if ('a' <= c && c < 'z') { c++; - newToken = - newToken.substring( 0, i ) + c + ( i + 1 < newToken.length() ? newToken.substring( i + 1 ) : "" ); + newToken = newToken.substring(0, i) + c + (i + 1 < newToken.length() ? newToken.substring(i + 1) : ""); done = true; - } - else if ( c == 'z' ) - { + } else if (c == 'z') { c = 'a'; - newToken = - newToken.substring( 0, i ) + c + ( i + 1 < newToken.length() ? newToken.substring( i + 1 ) : "" ); + newToken = newToken.substring(0, i) + c + (i + 1 < newToken.length() ? newToken.substring(i + 1) : ""); } } - if ( done ) - { + if (done) { return newToken; - } - else - { + } else { // ok this is roll-over time boolean lastNumeric = false; boolean lastAlpha = false; boolean lastUpper = false; i = token.length(); - while ( !lastAlpha && !lastNumeric && i > 0 ) - { + while (!lastAlpha && !lastNumeric && i > 0) { i--; - char c = token.charAt( i ); - lastAlpha = Character.isLetter( c ); - lastUpper = c == Character.toUpperCase( c ); - lastNumeric = Character.isDigit( c ); + char c = token.charAt(i); + lastAlpha = Character.isLetter(c); + lastUpper = c == Character.toUpperCase(c); + lastNumeric = Character.isDigit(c); } - if ( lastAlpha ) - { - if ( lastUpper ) - { + if (lastAlpha) { + if (lastUpper) { return token + 'A'; } return token + 'a'; } return token + '0'; - } } - static boolean isSnapshot( ArtifactVersion v ) - { - return v != null && SNAPSHOT_PATTERN.matcher( v.toString() ).find(); + static boolean isSnapshot(ArtifactVersion v) { + return v != null && SNAPSHOT_PATTERN.matcher(v.toString()).find(); } - static ArtifactVersion stripSnapshot( ArtifactVersion v ) - { + static ArtifactVersion stripSnapshot(ArtifactVersion v) { final String version = v.toString(); - final Matcher matcher = SNAPSHOT_PATTERN.matcher( version ); - if ( matcher.find() ) - { - return new DefaultArtifactVersion( version.substring( 0, matcher.start( 1 ) - 1 ) ); + final Matcher matcher = SNAPSHOT_PATTERN.matcher(version); + if (matcher.find()) { + return new DefaultArtifactVersion(version.substring(0, matcher.start(1) - 1)); } return v; } - static ArtifactVersion copySnapshot( ArtifactVersion source, ArtifactVersion destination ) - { - if ( isSnapshot( destination ) ) - { - destination = stripSnapshot( destination ); - } - final Matcher matcher = SNAPSHOT_PATTERN.matcher( source.toString() ); - if ( matcher.find() ) - { - return new DefaultArtifactVersion( destination.toString() + "-" + matcher.group( 0 ) ); + static ArtifactVersion copySnapshot(ArtifactVersion source, ArtifactVersion destination) { + if (isSnapshot(destination)) { + destination = stripSnapshot(destination); } - else - { - return new DefaultArtifactVersion( destination.toString() + "-SNAPSHOT" ); + final Matcher matcher = SNAPSHOT_PATTERN.matcher(source.toString()); + if (matcher.find()) { + return new DefaultArtifactVersion(destination.toString() + "-" + matcher.group(0)); + } else { + return new DefaultArtifactVersion(destination.toString() + "-SNAPSHOT"); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderNull.java b/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderNull.java index 46f1f798cb..d53025b4ef 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderNull.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderNull.java @@ -29,23 +29,16 @@ /** * A recorder that ignores updates. */ -@Named( "none" ) -public class ChangeRecorderNull implements ChangeRecorder -{ +@Named("none") +public class ChangeRecorderNull implements ChangeRecorder { /** * Creates a new instance */ - public ChangeRecorderNull() - { - } + public ChangeRecorderNull() {} @Override - public final void recordChange( ChangeRecord changeRecord ) - { - } + public final void recordChange(ChangeRecord changeRecord) {} @Override - public final void writeReport( final Path outputPath ) - { - } + public final void writeReport(final Path outputPath) {} } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderXML.java b/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderXML.java index 19051c5438..b924a5dcbc 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderXML.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/recording/ChangeRecorderXML.java @@ -49,14 +49,11 @@ /** * A recorder of version updates. */ - -@Named( "xml" ) -public class ChangeRecorderXML implements ChangeRecorder -{ +@Named("xml") +public class ChangeRecorderXML implements ChangeRecorder { /** * The XML namespace used for serialized changes. */ - public static final String CHANGES_NAMESPACE = "http://www.mojohaus.org/versions-maven-plugin/schema/updates/1.0"; private final Document document; @@ -65,63 +62,52 @@ public class ChangeRecorderXML implements ChangeRecorder /** * Creates a new instance */ - public ChangeRecorderXML() - { - try - { + public ChangeRecorderXML() { + try { final DocumentBuilderFactory documentBuilders = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder = documentBuilders.newDocumentBuilder(); document = documentBuilder.newDocument(); - root = document.createElementNS( CHANGES_NAMESPACE, "updates" ); - document.appendChild( root ); - } - catch ( final ParserConfigurationException | DOMException e ) - { - throw new IllegalStateException( e ); + root = document.createElementNS(CHANGES_NAMESPACE, "updates"); + document.appendChild(root); + } catch (final ParserConfigurationException | DOMException e) { + throw new IllegalStateException(e); } } @Override - public final void recordChange( ChangeRecord changeRecord ) - { - final Element update = this.document.createElementNS( CHANGES_NAMESPACE, "update" ); - update.setAttribute( "kind", changeRecord.getKind().getLabel() ); - update.setAttribute( "groupId", changeRecord.getVersionChange().getGroupId() ); - update.setAttribute( "artifactId", changeRecord.getVersionChange().getArtifactId() ); - update.setAttribute( "oldVersion", changeRecord.getVersionChange().getOldVersion() ); - update.setAttribute( "newVersion", changeRecord.getVersionChange().getNewVersion() ); - this.root.appendChild( update ); + public final void recordChange(ChangeRecord changeRecord) { + final Element update = this.document.createElementNS(CHANGES_NAMESPACE, "update"); + update.setAttribute("kind", changeRecord.getKind().getLabel()); + update.setAttribute("groupId", changeRecord.getVersionChange().getGroupId()); + update.setAttribute("artifactId", changeRecord.getVersionChange().getArtifactId()); + update.setAttribute("oldVersion", changeRecord.getVersionChange().getOldVersion()); + update.setAttribute("newVersion", changeRecord.getVersionChange().getNewVersion()); + this.root.appendChild(update); } @Override - public final void writeReport( final Path outputPath ) throws IOException - { - if ( outputPath == null ) - { - throw new IOException( "changeRecorderOutputFile not provided" ); + public final void writeReport(final Path outputPath) throws IOException { + if (outputPath == null) { + throw new IOException("changeRecorderOutputFile not provided"); } - if ( root.getChildNodes().getLength() == 0 ) - { + if (root.getChildNodes().getLength() == 0) { // don't generate empty file return; } - Files.createDirectories( outputPath.getParent() ); + Files.createDirectories(outputPath.getParent()); - try ( OutputStream outputStream = Files.newOutputStream( outputPath, CREATE, TRUNCATE_EXISTING, WRITE ) ) - { + try (OutputStream outputStream = Files.newOutputStream(outputPath, CREATE, TRUNCATE_EXISTING, WRITE)) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformerFactory.setAttribute( XMLConstants.ACCESS_EXTERNAL_DTD, "" ); - transformerFactory.setAttribute( XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "" ); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = transformerFactory.newTransformer(); - Source source = new DOMSource( this.document ); - transformer.transform( source, new StreamResult( outputStream ) ); + Source source = new DOMSource(this.document); + transformer.transform(source, new StreamResult(outputStream)); outputStream.flush(); - } - catch ( final TransformerException ex ) - { - throw new IOException( ex ); + } catch (final TransformerException ex) { + throw new IOException(ex); } } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/recording/DefaultChangeRecord.java b/versions-common/src/main/java/org/codehaus/mojo/versions/recording/DefaultChangeRecord.java index a3c8d82d7d..8334415fe7 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/recording/DefaultChangeRecord.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/recording/DefaultChangeRecord.java @@ -8,38 +8,30 @@ import org.codehaus.mojo.versions.api.recording.ChangeRecord; import org.codehaus.mojo.versions.change.DefaultVersionChange; -public class DefaultChangeRecord implements ChangeRecord -{ +public class DefaultChangeRecord implements ChangeRecord { private final ChangeKind kind; private final VersionChange versionChange; - private DefaultChangeRecord( ChangeKind kind, VersionChange versionChange ) - { - this.kind = Objects.requireNonNull( kind, "kind must not be null" ); - this.versionChange = Objects.requireNonNull( versionChange, "versionChange must not be null" ); - + private DefaultChangeRecord(ChangeKind kind, VersionChange versionChange) { + this.kind = Objects.requireNonNull(kind, "kind must not be null"); + this.versionChange = Objects.requireNonNull(versionChange, "versionChange must not be null"); } @Override - public ChangeKind getKind() - { + public ChangeKind getKind() { return kind; } @Override - public VersionChange getVersionChange() - { + public VersionChange getVersionChange() { return versionChange; } - - public static Builder builder() - { + public static Builder builder() { return new Builder(); } - public static class Builder - { + public static class Builder { private ChangeKind kind; private String groupId; @@ -47,58 +39,47 @@ public static class Builder private String oldVersion; private String newVersion; - public Builder withKind( ChangeKind kind ) - { + public Builder withKind(ChangeKind kind) { this.kind = kind; return this; } - public Builder withGroupId( String groupId ) - { + public Builder withGroupId(String groupId) { this.groupId = groupId; return this; } - public Builder withArtifactId( String artifactId ) - { + public Builder withArtifactId(String artifactId) { this.artifactId = artifactId; return this; } - public Builder withOldVersion( String oldVersion ) - { + public Builder withOldVersion(String oldVersion) { this.oldVersion = oldVersion; return this; } - public Builder withNewVersion( String newVersion ) - { + public Builder withNewVersion(String newVersion) { this.newVersion = newVersion; return this; } - public Builder withDependency( Dependency dependency ) - { + public Builder withDependency(Dependency dependency) { groupId = dependency.getGroupId(); artifactId = dependency.getArtifactId(); oldVersion = dependency.getVersion(); return this; } - public Builder withArtifact( Artifact artifact ) - { + public Builder withArtifact(Artifact artifact) { groupId = artifact.getGroupId(); artifactId = artifact.getArtifactId(); oldVersion = artifact.getVersion(); return this; } - public ChangeRecord build() - { - return new DefaultChangeRecord( kind, - new DefaultVersionChange( groupId, artifactId, oldVersion, newVersion ) ); + public ChangeRecord build() { + return new DefaultChangeRecord(kind, new DefaultVersionChange(groupId, artifactId, oldVersion, newVersion)); } } - - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReader.java b/versions-common/src/main/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReader.java index ea430c47d9..99d0cb224f 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReader.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReader.java @@ -39,9 +39,7 @@ * * @author Stephen Connolly */ -public class ModifiedPomXMLEventReader - implements XMLEventReader -{ +public class ModifiedPomXMLEventReader implements XMLEventReader { // ------------------------------ FIELDS ------------------------------ @@ -135,9 +133,8 @@ public class ModifiedPomXMLEventReader * @param path Path pointing to source of XML * @throws XMLStreamException when */ - public ModifiedPomXMLEventReader( StringBuilder pom, XMLInputFactory factory, String path ) - throws XMLStreamException - { + public ModifiedPomXMLEventReader(StringBuilder pom, XMLInputFactory factory, String path) + throws XMLStreamException { this.pom = pom; this.factory = factory; this.path = path; @@ -149,14 +146,11 @@ public ModifiedPomXMLEventReader( StringBuilder pom, XMLInputFactory factory, St * * @throws XMLStreamException when things go wrong. */ - public void rewind() - throws XMLStreamException - { - backing = factory.createXMLEventReader( new StringReader( pom.toString() ) ); + public void rewind() throws XMLStreamException { + backing = factory.createXMLEventReader(new StringReader(pom.toString())); nextEnd = 0; nextDelta = 0; - for ( int i = 0; i < MAX_MARKS; i++ ) - { + for (int i = 0; i < MAX_MARKS; i++) { markStart[i] = -1; markEnd[i] = -1; markDelta[i] = 0; @@ -174,8 +168,7 @@ public void rewind() * * @return Value for property 'modified'. */ - public boolean isModified() - { + public boolean isModified() { return modified; } @@ -186,14 +179,10 @@ public boolean isModified() /** * {@inheritDoc} */ - public Object next() - { - try - { + public Object next() { + try { return nextEvent(); - } - catch ( XMLStreamException e ) - { + } catch (XMLStreamException e) { return null; } } @@ -201,8 +190,7 @@ public Object next() /** * {@inheritDoc} */ - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } @@ -211,15 +199,10 @@ public void remove() /** * {@inheritDoc} */ - public XMLEvent nextEvent() - throws XMLStreamException - { - try - { + public XMLEvent nextEvent() throws XMLStreamException { + try { return next; - } - finally - { + } finally { next = null; lastStart = nextStart; lastEnd = nextEnd; @@ -230,56 +213,44 @@ public XMLEvent nextEvent() /** * {@inheritDoc} */ - public XMLEvent peek() - throws XMLStreamException - { + public XMLEvent peek() throws XMLStreamException { return backing.peek(); } /** * {@inheritDoc} */ - public String getElementText() - throws XMLStreamException - { + public String getElementText() throws XMLStreamException { return backing.getElementText(); } /** * {@inheritDoc} */ - public XMLEvent nextTag() - throws XMLStreamException - { - while ( hasNext() ) - { + public XMLEvent nextTag() throws XMLStreamException { + while (hasNext()) { XMLEvent e = nextEvent(); - if ( e.isCharacters() && !( (Characters) e ).isWhiteSpace() ) - { - throw new XMLStreamException( "Unexpected text" ); + if (e.isCharacters() && !((Characters) e).isWhiteSpace()) { + throw new XMLStreamException("Unexpected text"); } - if ( e.isStartElement() || e.isEndElement() ) - { + if (e.isStartElement() || e.isEndElement()) { return e; } } - throw new XMLStreamException( "Unexpected end of Document" ); + throw new XMLStreamException("Unexpected end of Document"); } /** * {@inheritDoc} */ - public Object getProperty( String name ) - { - return backing.getProperty( name ); + public Object getProperty(String name) { + return backing.getProperty(name); } /** * {@inheritDoc} */ - public void close() - throws XMLStreamException - { + public void close() throws XMLStreamException { backing.close(); next = null; backing = null; @@ -292,9 +263,8 @@ public void close() * * @return a copy of the backing string buffer. */ - public StringBuilder asStringBuilder() - { - return new StringBuilder( pom.toString() ); + public StringBuilder asStringBuilder() { + return new StringBuilder(pom.toString()); } /** @@ -302,8 +272,7 @@ public StringBuilder asStringBuilder() * * @param index the mark to clear. */ - public void clearMark( int index ) - { + public void clearMark(int index) { markStart[index] = -1; } @@ -313,11 +282,9 @@ public void clearMark( int index ) * @param index The mark index. * @return the current element when {@link #mark(int)} was called. */ - public String getMarkVerbatim( int index ) - { - if ( hasMark( index ) ) - { - return pom.substring( markDelta[index] + markStart[index], markDelta[index] + markEnd[index] ); + public String getMarkVerbatim(int index) { + if (hasMark(index)) { + return pom.substring(markDelta[index] + markStart[index], markDelta[index] + markEnd[index]); } return ""; } @@ -327,11 +294,9 @@ public String getMarkVerbatim( int index ) * * @return the verbatim text of the element returned by {@link #peek()}. */ - public String getPeekVerbatim() - { - if ( hasNext() ) - { - return pom.substring( nextDelta + nextStart, nextDelta + nextEnd ); + public String getPeekVerbatim() { + if (hasNext()) { + return pom.substring(nextDelta + nextStart, nextDelta + nextEnd); } return ""; } @@ -339,50 +304,38 @@ public String getPeekVerbatim() /** * {@inheritDoc} */ - public boolean hasNext() - { - if ( next != null ) - { + public boolean hasNext() { + if (next != null) { // fast path return true; } - if ( !backing.hasNext() ) - { + if (!backing.hasNext()) { // fast path return false; } - try - { + try { next = backing.nextEvent(); nextStart = nextEnd; - if ( backing.hasNext() ) - { + if (backing.hasNext()) { nextEnd = backing.peek().getLocation().getCharacterOffset(); } - if ( nextEnd != -1 ) - { - if ( !next.isCharacters() ) - { - while ( nextStart < nextEnd && nextStart < pom.length() - && ( c( nextStart ) == '\n' || c( nextStart ) == '\r' ) ) - { + if (nextEnd != -1) { + if (!next.isCharacters()) { + while (nextStart < nextEnd + && nextStart < pom.length() + && (c(nextStart) == '\n' || c(nextStart) == '\r')) { nextStart++; } - } - else - { - while ( nextEndIncludesNextEvent() || nextEndIncludesNextEndElement() ) - { + } else { + while (nextEndIncludesNextEvent() || nextEndIncludesNextEndElement()) { nextEnd--; } } } return nextStart < pom.length(); - } - catch ( XMLStreamException e ) - { - throw new RuntimeException( "Error parsing " + path + ": " + e.getMessage(), e ); + } catch (XMLStreamException e) { + throw new RuntimeException("Error parsing " + path + ": " + e.getMessage(), e); } } @@ -391,11 +344,9 @@ public boolean hasNext() * * @return Value for property 'verbatim'. */ - public String getVerbatim() - { - if ( lastStart >= 0 && lastEnd >= lastStart ) - { - return pom.substring( lastDelta + lastStart, lastDelta + lastEnd ); + public String getVerbatim() { + if (lastStart >= 0 && lastEnd >= lastStart) { + return pom.substring(lastDelta + lastStart, lastDelta + lastEnd); } return ""; } @@ -405,8 +356,7 @@ public String getVerbatim() * * @param index the mark to set. */ - public void mark( int index ) - { + public void mark(int index) { markStart[index] = lastStart; markEnd[index] = lastEnd; markDelta[index] = lastDelta; @@ -417,9 +367,8 @@ public void mark( int index ) * * @return true if nextEnd is including the start of and end element. */ - private boolean nextEndIncludesNextEndElement() - { - return ( nextEnd > nextStart + 2 && nextEnd - 2 < pom.length() && c( nextEnd - 2 ) == '<' ); + private boolean nextEndIncludesNextEndElement() { + return (nextEnd > nextStart + 2 && nextEnd - 2 < pom.length() && c(nextEnd - 2) == '<'); } /** @@ -427,10 +376,10 @@ private boolean nextEndIncludesNextEndElement() * * @return true if nextEnd is including the start of the next event. */ - private boolean nextEndIncludesNextEvent() - { - return nextEnd > nextStart + 1 && nextEnd - 2 < pom.length() - && ( c( nextEnd - 1 ) == '<' || c( nextEnd - 1 ) == '&' ); + private boolean nextEndIncludesNextEvent() { + return nextEnd > nextStart + 1 + && nextEnd - 2 < pom.length() + && (c(nextEnd - 1) == '<' || c(nextEnd - 1) == '&'); } /** @@ -439,9 +388,8 @@ private boolean nextEndIncludesNextEvent() * @param index the index. * @return char The character. */ - private char c( int index ) - { - return pom.charAt( nextDelta + index ); + private char c(int index) { + return pom.charAt(nextDelta + index); } /** @@ -449,25 +397,20 @@ private char c( int index ) * * @param replacement The replacement. */ - public void replace( String replacement ) - { - if ( lastStart < 0 || lastEnd < lastStart ) - { + public void replace(String replacement) { + if (lastStart < 0 || lastEnd < lastStart) { throw new IllegalStateException(); } int start = lastDelta + lastStart; int end = lastDelta + lastEnd; - if ( replacement.equals( pom.substring( start, end ) ) ) - { + if (replacement.equals(pom.substring(start, end))) { return; } - pom.replace( start, end, replacement ); - int delta = replacement.length() - ( lastEnd - lastStart ); + pom.replace(start, end, replacement); + int delta = replacement.length() - (lastEnd - lastStart); nextDelta += delta; - for ( int i = 0; i < MAX_MARKS; i++ ) - { - if ( hasMark( i ) && lastStart == markStart[i] && markEnd[i] == lastEnd ) - { + for (int i = 0; i < MAX_MARKS; i++) { + if (hasMark(i) && lastStart == markStart[i] && markEnd[i] == lastEnd) { markEnd[i] += delta; } } @@ -481,21 +424,17 @@ public void replace( String replacement ) * @param index The mark. * @return true if the specified mark is defined. */ - public boolean hasMark( int index ) - { + public boolean hasMark(int index) { return markStart[index] != -1; } - public String getBetween( int index1, int index2 ) - { - if ( !hasMark( index1 ) || !hasMark( index2 ) || markStart[index1] > markStart[index2] ) - { + public String getBetween(int index1, int index2) { + if (!hasMark(index1) || !hasMark(index2) || markStart[index1] > markStart[index2]) { throw new IllegalStateException(); } int start = markDelta[index1] + markEnd[index1]; int end = markDelta[index2] + markStart[index2]; - return pom.substring( start, end ); - + return pom.substring(start, end); } /** @@ -505,38 +444,28 @@ public String getBetween( int index1, int index2 ) * @param index2 The event mark to replace before. * @param replacement The replacement. */ - public void replaceBetween( int index1, int index2, String replacement ) - { - if ( !hasMark( index1 ) || !hasMark( index2 ) || markStart[index1] > markStart[index2] ) - { + public void replaceBetween(int index1, int index2, String replacement) { + if (!hasMark(index1) || !hasMark(index2) || markStart[index1] > markStart[index2]) { throw new IllegalStateException(); } int start = markDelta[index1] + markEnd[index1]; int end = markDelta[index2] + markStart[index2]; - if ( replacement.equals( pom.substring( start, end ) ) ) - { + if (replacement.equals(pom.substring(start, end))) { return; } - pom.replace( start, end, replacement ); - int delta = replacement.length() - ( end - start ); + pom.replace(start, end, replacement); + int delta = replacement.length() - (end - start); nextDelta += delta; - for ( int i = 0; i < MAX_MARKS; i++ ) - { - if ( i == index1 || i == index2 || markStart[i] == -1 ) - { + for (int i = 0; i < MAX_MARKS; i++) { + if (i == index1 || i == index2 || markStart[i] == -1) { continue; } - if ( markStart[i] > markStart[index2] ) - { + if (markStart[i] > markStart[index2]) { markDelta[i] += delta; - } - else if ( markStart[i] == markEnd[index1] && markEnd[i] == markStart[index1] ) - { + } else if (markStart[i] == markEnd[index1] && markEnd[i] == markStart[index1]) { markDelta[i] += delta; - } - else if ( markStart[i] > markEnd[index1] || markEnd[i] < markStart[index2] ) - { + } else if (markStart[i] > markEnd[index1] || markEnd[i] < markStart[index2]) { markStart[i] = -1; } } @@ -550,41 +479,30 @@ else if ( markStart[i] > markEnd[index1] || markEnd[i] < markStart[index2] ) * @param index The mark. * @param replacement The replacement. */ - public void replaceMark( int index, String replacement ) - { - if ( !hasMark( index ) ) - { + public void replaceMark(int index, String replacement) { + if (!hasMark(index)) { throw new IllegalStateException(); } int start = markDelta[index] + markStart[index]; int end = markDelta[index] + markEnd[index]; - if ( replacement.equals( pom.substring( start, end ) ) ) - { + if (replacement.equals(pom.substring(start, end))) { return; } - pom.replace( start, end, replacement ); - int delta = replacement.length() - ( markEnd[index] - markStart[index] ); + pom.replace(start, end, replacement); + int delta = replacement.length() - (markEnd[index] - markStart[index]); nextDelta += delta; - if ( lastStart == markStart[index] && lastEnd == markEnd[index] ) - { + if (lastStart == markStart[index] && lastEnd == markEnd[index]) { lastEnd += delta; - } - else if ( lastStart > markStart[index] ) - { + } else if (lastStart > markStart[index]) { lastDelta += delta; } - for ( int i = 0; i < MAX_MARKS; i++ ) - { - if ( i == index || markStart[i] == -1 ) - { + for (int i = 0; i < MAX_MARKS; i++) { + if (i == index || markStart[i] == -1) { continue; } - if ( markStart[i] > markStart[index] ) - { + if (markStart[i] > markStart[index]) { markDelta[i] += delta; - } - else if ( markStart[i] == markStart[index] && markEnd[i] == markEnd[index] ) - { + } else if (markStart[i] == markStart[index] && markEnd[i] == markEnd[index]) { markDelta[i] += delta; } } @@ -592,11 +510,8 @@ else if ( markStart[i] == markStart[index] && markEnd[i] == markEnd[index] ) modified = true; } - public Model parse() - throws IOException, XmlPullParserException - { + public Model parse() throws IOException, XmlPullParserException { MavenXpp3Reader reader = new MavenXpp3Reader(); - return reader.read( new StringReader( pom.toString() ) ); + return reader.read(new StringReader(pom.toString())); } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/ContextualLog.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/ContextualLog.java index f29d06964c..06d794ceac 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/ContextualLog.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/ContextualLog.java @@ -28,11 +28,9 @@ * @author Stephen Connolly * @since 15-Sep-2010 15:51:06 */ -public interface ContextualLog - extends Log -{ +public interface ContextualLog extends Log { - void setContext( String context ); + void setContext(String context); void clearContext(); } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DelegatingContextualLog.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DelegatingContextualLog.java index fa856d1dab..eb9b7e7d8b 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DelegatingContextualLog.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DelegatingContextualLog.java @@ -28,9 +28,7 @@ * @author Stephen Connolly * @since 15-Sep-2010 15:52:21 */ -public class DelegatingContextualLog - implements ContextualLog -{ +public class DelegatingContextualLog implements ContextualLog { private final Log delegate; private String currentContext = null; @@ -43,19 +41,15 @@ public class DelegatingContextualLog private boolean currentContextReportedError = false; - public DelegatingContextualLog( Log delegate ) - { + public DelegatingContextualLog(Log delegate) { this.delegate = delegate; } - public synchronized void setContext( String context ) - { - if ( StringUtils.equals( currentContext, context ) ) - { + public synchronized void setContext(String context) { + if (StringUtils.equals(currentContext, context)) { return; } - if ( currentContext != null ) - { + if (currentContext != null) { clearContext(); } currentContext = context; @@ -65,23 +59,15 @@ public synchronized void setContext( String context ) currentContextReportedError = false; } - public synchronized void clearContext() - { - if ( currentContextReportedError ) - { - delegate.error( "" ); - } - else if ( currentContextReportedWarn ) - { - delegate.warn( "" ); - } - else if ( currentContextReportedInfo ) - { - delegate.info( "" ); - } - else if ( currentContextReportedDebug ) - { - delegate.debug( "" ); + public synchronized void clearContext() { + if (currentContextReportedError) { + delegate.error(""); + } else if (currentContextReportedWarn) { + delegate.warn(""); + } else if (currentContextReportedInfo) { + delegate.info(""); + } else if (currentContextReportedDebug) { + delegate.debug(""); } currentContextReportedDebug = false; currentContextReportedInfo = false; @@ -89,132 +75,110 @@ else if ( currentContextReportedDebug ) currentContextReportedError = false; } - private void enterContextDebug() - { - if ( !currentContextReportedDebug && !currentContextReportedInfo && !currentContextReportedWarn - && !currentContextReportedError ) - { - delegate.debug( currentContext ); + private void enterContextDebug() { + if (!currentContextReportedDebug + && !currentContextReportedInfo + && !currentContextReportedWarn + && !currentContextReportedError) { + delegate.debug(currentContext); currentContextReportedDebug = true; } } - private void enterContextInfo() - { - if ( !currentContextReportedInfo && !currentContextReportedWarn && !currentContextReportedError ) - { - delegate.info( currentContext ); + private void enterContextInfo() { + if (!currentContextReportedInfo && !currentContextReportedWarn && !currentContextReportedError) { + delegate.info(currentContext); currentContextReportedInfo = true; } } - private void enterContextWarn() - { - if ( !currentContextReportedWarn && !currentContextReportedError ) - { - delegate.warn( currentContext ); + private void enterContextWarn() { + if (!currentContextReportedWarn && !currentContextReportedError) { + delegate.warn(currentContext); currentContextReportedWarn = true; } } - private void enterContextError() - { - if ( !currentContextReportedError ) - { - delegate.error( currentContext ); + private void enterContextError() { + if (!currentContextReportedError) { + delegate.error(currentContext); currentContextReportedError = true; } } - public void debug( CharSequence charSequence ) - { + public void debug(CharSequence charSequence) { enterContextDebug(); - delegate.debug( charSequence ); + delegate.debug(charSequence); } - public void debug( CharSequence charSequence, Throwable throwable ) - { + public void debug(CharSequence charSequence, Throwable throwable) { enterContextDebug(); - delegate.debug( charSequence, throwable ); + delegate.debug(charSequence, throwable); } - public void debug( Throwable throwable ) - { + public void debug(Throwable throwable) { enterContextDebug(); - delegate.debug( throwable ); + delegate.debug(throwable); } - public void info( CharSequence charSequence ) - { + public void info(CharSequence charSequence) { enterContextInfo(); - delegate.info( charSequence ); + delegate.info(charSequence); } - public void info( CharSequence charSequence, Throwable throwable ) - { + public void info(CharSequence charSequence, Throwable throwable) { enterContextInfo(); - delegate.info( charSequence, throwable ); + delegate.info(charSequence, throwable); } - public void info( Throwable throwable ) - { + public void info(Throwable throwable) { enterContextInfo(); - delegate.info( throwable ); + delegate.info(throwable); } - public void warn( CharSequence charSequence ) - { + public void warn(CharSequence charSequence) { enterContextWarn(); - delegate.warn( charSequence ); + delegate.warn(charSequence); } - public void warn( CharSequence charSequence, Throwable throwable ) - { + public void warn(CharSequence charSequence, Throwable throwable) { enterContextWarn(); - delegate.warn( charSequence, throwable ); + delegate.warn(charSequence, throwable); } - public void warn( Throwable throwable ) - { + public void warn(Throwable throwable) { enterContextWarn(); - delegate.warn( throwable ); + delegate.warn(throwable); } - public void error( CharSequence charSequence ) - { + public void error(CharSequence charSequence) { enterContextError(); - delegate.error( charSequence ); + delegate.error(charSequence); } - public void error( CharSequence charSequence, Throwable throwable ) - { + public void error(CharSequence charSequence, Throwable throwable) { enterContextError(); - delegate.error( charSequence, throwable ); + delegate.error(charSequence, throwable); } - public void error( Throwable throwable ) - { + public void error(Throwable throwable) { enterContextError(); - delegate.error( throwable ); + delegate.error(throwable); } - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return delegate.isDebugEnabled(); } - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return delegate.isInfoEnabled(); } - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return delegate.isWarnEnabled(); } - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return delegate.isErrorEnabled(); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyBuilder.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyBuilder.java index 24ad4df5a8..58ca87c2ff 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyBuilder.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyBuilder.java @@ -30,9 +30,8 @@ /** * Builder class for {@linkplain Dependency} */ -@SuppressWarnings( "OptionalUsedAsFieldOrParameterType" ) -public class DependencyBuilder -{ +@SuppressWarnings("OptionalUsedAsFieldOrParameterType") +public class DependencyBuilder { private Optional groupId = empty(); private Optional artifactId = empty(); private Optional version = empty(); @@ -41,18 +40,15 @@ public class DependencyBuilder private Optional scope = empty(); private Optional optional = empty(); - private DependencyBuilder() - { - } + private DependencyBuilder() {} /** * Passes groupId to the builder * @param groupId given groupId * @return builder instance */ - public DependencyBuilder withGroupId( String groupId ) - { - this.groupId = ofNullable( groupId ); + public DependencyBuilder withGroupId(String groupId) { + this.groupId = ofNullable(groupId); return this; } @@ -61,9 +57,8 @@ public DependencyBuilder withGroupId( String groupId ) * @param artifactId given artifactId * @return builder instance */ - public DependencyBuilder withArtifactId( String artifactId ) - { - this.artifactId = ofNullable( artifactId ); + public DependencyBuilder withArtifactId(String artifactId) { + this.artifactId = ofNullable(artifactId); return this; } @@ -72,9 +67,8 @@ public DependencyBuilder withArtifactId( String artifactId ) * @param version given version * @return builder instance */ - public DependencyBuilder withVersion( String version ) - { - this.version = ofNullable( version ); + public DependencyBuilder withVersion(String version) { + this.version = ofNullable(version); return this; } @@ -83,9 +77,8 @@ public DependencyBuilder withVersion( String version ) * @param type given type * @return builder instance */ - public DependencyBuilder withType( String type ) - { - this.type = ofNullable( type ); + public DependencyBuilder withType(String type) { + this.type = ofNullable(type); return this; } @@ -94,9 +87,8 @@ public DependencyBuilder withType( String type ) * @param classifier given classifier * @return builder instance */ - public DependencyBuilder withClassifier( String classifier ) - { - this.classifier = ofNullable( classifier ); + public DependencyBuilder withClassifier(String classifier) { + this.classifier = ofNullable(classifier); return this; } @@ -105,9 +97,8 @@ public DependencyBuilder withClassifier( String classifier ) * @param scope given scope * @return builder instance */ - public DependencyBuilder withScope( String scope ) - { - this.scope = ofNullable( scope ); + public DependencyBuilder withScope(String scope) { + this.scope = ofNullable(scope); return this; } @@ -116,9 +107,8 @@ public DependencyBuilder withScope( String scope ) * @param optional given optional as String * @return builder instance */ - public DependencyBuilder withOptional( String optional ) - { - this.optional = ofNullable( optional ); + public DependencyBuilder withOptional(String optional) { + this.optional = ofNullable(optional); return this; } @@ -127,9 +117,8 @@ public DependencyBuilder withOptional( String optional ) * @param optional given optional as boolean * @return builder instance */ - public DependencyBuilder withOptional( boolean optional ) - { - this.optional = of( String.valueOf( optional ) ); + public DependencyBuilder withOptional(boolean optional) { + this.optional = of(String.valueOf(optional)); return this; } @@ -137,8 +126,7 @@ public DependencyBuilder withOptional( boolean optional ) * Creates a new instance of the builder * @return new instance of the builder */ - public static DependencyBuilder newBuilder() - { + public static DependencyBuilder newBuilder() { return new DependencyBuilder(); } @@ -149,12 +137,11 @@ public static DependencyBuilder newBuilder() * @param version version of the dependency * @return new instance of {@linkplain Dependency} */ - public static Dependency dependencyWith( String groupId, String artifactId, String version ) - { + public static Dependency dependencyWith(String groupId, String artifactId, String version) { return newBuilder() - .withGroupId( groupId ) - .withArtifactId( artifactId ) - .withVersion( version ) + .withGroupId(groupId) + .withArtifactId(artifactId) + .withVersion(version) .build(); } @@ -168,16 +155,15 @@ public static Dependency dependencyWith( String groupId, String artifactId, Stri * @param scope scope of the dependency * @return new instance of {@linkplain Dependency} */ - public static Dependency dependencyWith( String groupId, String artifactId, String version, String type, - String classifier, String scope ) - { + public static Dependency dependencyWith( + String groupId, String artifactId, String version, String type, String classifier, String scope) { return newBuilder() - .withGroupId( groupId ) - .withArtifactId( artifactId ) - .withVersion( version ) - .withType( type ) - .withClassifier( classifier ) - .withScope( scope ) + .withGroupId(groupId) + .withArtifactId(artifactId) + .withVersion(version) + .withType(type) + .withClassifier(classifier) + .withScope(scope) .build(); } @@ -185,16 +171,15 @@ public static Dependency dependencyWith( String groupId, String artifactId, Stri * Builds the {@linkplain Dependency} instance * @return {@linkplain Dependency} instance */ - public Dependency build() - { + public Dependency build() { Dependency inst = new Dependency(); - groupId.ifPresent( inst::setGroupId ); - artifactId.ifPresent( inst::setArtifactId ); - version.ifPresent( inst::setVersion ); - type.ifPresent( inst::setType ); - classifier.ifPresent( inst::setClassifier ); - scope.ifPresent( inst::setScope ); - optional.ifPresent( inst::setOptional ); + groupId.ifPresent(inst::setGroupId); + artifactId.ifPresent(inst::setArtifactId); + version.ifPresent(inst::setVersion); + type.ifPresent(inst::setType); + classifier.ifPresent(inst::setClassifier); + scope.ifPresent(inst::setScope); + optional.ifPresent(inst::setOptional); return inst; } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyComparator.java index 8330fc4b28..641c27ef69 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/DependencyComparator.java @@ -29,8 +29,7 @@ * * @since 1.0-alpha-1 */ -public enum DependencyComparator implements Comparator -{ +public enum DependencyComparator implements Comparator { INSTANCE; /** @@ -40,21 +39,19 @@ public enum DependencyComparator implements Comparator * @see java.util.Comparator#compare(Object, Object) * @since 1.0-alpha-1 */ - @SuppressWarnings( "checkstyle:InnerAssignment" ) - public int compare( Dependency d1, Dependency d2 ) - { + @SuppressWarnings("checkstyle:InnerAssignment") + public int compare(Dependency d1, Dependency d2) { int r; return d1 == d2 ? 0 : d1 == null - ? 1 - : d2 == null - ? -1 - : ( r = StringUtils.compare( d1.getGroupId(), d2.getGroupId() ) ) != 0 - ? r - : ( r = StringUtils.compare( d1.getArtifactId(), d2.getArtifactId() ) ) != 0 - ? r - : StringUtils.compare( d1.getVersion(), d2.getVersion() ); + ? 1 + : d2 == null + ? -1 + : (r = StringUtils.compare(d1.getGroupId(), d2.getGroupId())) != 0 + ? r + : (r = StringUtils.compare(d1.getArtifactId(), d2.getArtifactId())) != 0 + ? r + : StringUtils.compare(d1.getVersion(), d2.getVersion()); } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java index fd51c9d37e..e1fd645070 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java @@ -36,24 +36,22 @@ /** * Utility methods for extracting dependencies from a {@link org.apache.maven.project.MavenProject} */ -public class MavenProjectUtils -{ +public class MavenProjectUtils { /** * Retrieves dependencies from the plugins section * @param project {@link MavenProject} instance * @return set of {@link Dependency} objects * or an empty set if none have been retrieveddependencies or an empty set if none have been retrieved */ - public static Set extractPluginDependenciesFromPluginsInPluginManagement( MavenProject project ) - { - return ofNullable( project.getBuild() ) - .map( Build::getPluginManagement ) - .map( PluginManagement::getPlugins ) - .orElse( emptyList() ) + public static Set extractPluginDependenciesFromPluginsInPluginManagement(MavenProject project) { + return ofNullable(project.getBuild()) + .map(Build::getPluginManagement) + .map(PluginManagement::getPlugins) + .orElse(emptyList()) .stream() - .filter( plugin -> plugin.getDependencies() != null ) - .flatMap( plugin -> plugin.getDependencies().stream() ) - .collect( () -> new TreeSet<>( DependencyComparator.INSTANCE ), Set::add, Set::addAll ); + .filter(plugin -> plugin.getDependencies() != null) + .flatMap(plugin -> plugin.getDependencies().stream()) + .collect(() -> new TreeSet<>(DependencyComparator.INSTANCE), Set::add, Set::addAll); } /** @@ -62,12 +60,11 @@ public static Set extractPluginDependenciesFromPluginsInPluginManage * @return set of {@link Dependency} objects * or an empty set if none have been retrieveddependencies or an empty set if none have been retrieved */ - public static Set extractDependenciesFromPlugins( MavenProject project ) - { + public static Set extractDependenciesFromPlugins(MavenProject project) { return project.getBuildPlugins().parallelStream() - .filter( plugin -> plugin.getDependencies() != null ) - .flatMap( plugin -> plugin.getDependencies().stream() ) - .collect( () -> new TreeSet<>( DependencyComparator.INSTANCE ), Set::add, Set::addAll ); + .filter(plugin -> plugin.getDependencies() != null) + .flatMap(plugin -> plugin.getDependencies().stream()) + .collect(() -> new TreeSet<>(DependencyComparator.INSTANCE), Set::add, Set::addAll); } /** @@ -81,60 +78,47 @@ public static Set extractDependenciesFromPlugins( MavenProject proje * @return set of {@link Dependency} objects * or an empty set if none have been retrieveddependencies or an empty set if none have been retrieved */ - public static Set extractDependenciesFromDependencyManagement( MavenProject project, - boolean processDependencyManagementTransitive, Log log ) - throws VersionRetrievalException - { - Set dependencyManagement = new TreeSet<>( DependencyComparator.INSTANCE ); + public static Set extractDependenciesFromDependencyManagement( + MavenProject project, boolean processDependencyManagementTransitive, Log log) + throws VersionRetrievalException { + Set dependencyManagement = new TreeSet<>(DependencyComparator.INSTANCE); DependencyManagement projectDependencyManagement = processDependencyManagementTransitive ? project.getDependencyManagement() : project.getOriginalModel().getDependencyManagement(); - if ( projectDependencyManagement != null ) - { + if (projectDependencyManagement != null) { List dependenciesFromPom = projectDependencyManagement.getDependencies(); - for ( Dependency dependency : dependenciesFromPom ) - { - log.debug( "dependency from pom: " + dependency.getGroupId() + ":" + dependency.getArtifactId() - + ":" + dependency.getVersion() + ":" + dependency.getScope() ); - if ( dependency.getVersion() == null ) - { + for (Dependency dependency : dependenciesFromPom) { + log.debug("dependency from pom: " + dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + + dependency.getVersion() + ":" + dependency.getScope()); + if (dependency.getVersion() == null) { // get parent and get the information from there. - if ( project.hasParent() ) - { - log.debug( "Reading parent dependencyManagement information" ); - DependencyManagement parentProjectDependencyManagement = - processDependencyManagementTransitive - ? project.getParent().getDependencyManagement() - : project.getParent().getOriginalModel().getDependencyManagement(); - if ( parentProjectDependencyManagement != null ) - { + if (project.hasParent()) { + log.debug("Reading parent dependencyManagement information"); + DependencyManagement parentProjectDependencyManagement = processDependencyManagementTransitive + ? project.getParent().getDependencyManagement() + : project.getParent().getOriginalModel().getDependencyManagement(); + if (parentProjectDependencyManagement != null) { List parentDeps = parentProjectDependencyManagement.getDependencies(); - for ( Dependency parentDep : parentDeps ) - { + for (Dependency parentDep : parentDeps) { // only groupId && artifactId needed cause version is null - if ( dependency.getGroupId().equals( parentDep.getGroupId() ) - && dependency.getArtifactId().equals( parentDep.getArtifactId() ) - && dependency.getType().equals( parentDep.getType() ) ) - { - dependencyManagement.add( parentDep ); + if (dependency.getGroupId().equals(parentDep.getGroupId()) + && dependency.getArtifactId().equals(parentDep.getArtifactId()) + && dependency.getType().equals(parentDep.getType())) { + dependencyManagement.add(parentDep); } } } - } - else - { + } else { String message = "We can't get the version for the dependency " + dependency.getGroupId() + ":" - + dependency.getArtifactId() + " because there does not exist a parent."; - log.error( message ); + + dependency.getArtifactId() + " because there does not exist a parent."; + log.error(message); // Throw error because we will not able to get a version for a dependency. - throw new VersionRetrievalException( message ); + throw new VersionRetrievalException(message); } - } - else - { - dependency = interpolateVersion( dependency, project ); - dependencyManagement.add( dependency ); + } else { + dependency = interpolateVersion(dependency, project); + dependencyManagement.add(dependency); } } } @@ -149,18 +133,17 @@ public static Set extractDependenciesFromDependencyManagement( Maven * @return the dependency with interpolated property (as far as possible) * @since 2.14.0 */ - public static Dependency interpolateVersion( final Dependency dependency, final MavenProject project ) - { + public static Dependency interpolateVersion(final Dependency dependency, final MavenProject project) { // resolve version from model properties if necessary (e.g. "${mycomponent.myversion}" - if ( dependency.getVersion().startsWith( "${" ) ) - { + if (dependency.getVersion().startsWith("${")) { final String resolvedVersion = project.getOriginalModel() - .getProperties().getProperty( - dependency.getVersion().substring( 2, dependency.getVersion().length() - 1 ) ); - if ( resolvedVersion != null && !resolvedVersion.isEmpty() ) - { - dependency.setVersion( resolvedVersion ); + .getProperties() + .getProperty(dependency + .getVersion() + .substring(2, dependency.getVersion().length() - 1)); + if (resolvedVersion != null && !resolvedVersion.isEmpty()) { + dependency.setVersion(resolvedVersion); } } return dependency; diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MiscUtils.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MiscUtils.java index 215ae598a9..fb50f51c67 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MiscUtils.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/MiscUtils.java @@ -7,8 +7,7 @@ /** * Miscellaneous utility class. */ -public class MiscUtils -{ +public class MiscUtils { /** * Filters a given map leaving only elements fulfilling a predicate. Does not change the input map, * the filtered map is returned as output. @@ -19,10 +18,9 @@ public class MiscUtils * @param value type * @return map such that every element comforms with the predicate */ - public static Map filter( Map map, - Function predicate ) - { - return map.entrySet().stream().filter( e -> predicate.apply( e.getValue() ) ) - .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue ) ); + public static Map filter(Map map, Function predicate) { + return map.entrySet().stream() + .filter(e -> predicate.apply(e.getValue())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PluginComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PluginComparator.java index d4efe84646..221ccaf2c7 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PluginComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PluginComparator.java @@ -29,8 +29,7 @@ * * @since 1.0-beta-1 */ -public enum PluginComparator implements Comparator -{ +public enum PluginComparator implements Comparator { INSTANCE; /** @@ -42,44 +41,36 @@ public enum PluginComparator implements Comparator * @see java.util.Comparator#compare(Object, Object) * @since 1.0-beta-1 */ - public int compare( Object o1, Object o2 ) - { - if ( !( o1 instanceof Plugin || o1 instanceof ReportPlugin ) ) - { + public int compare(Object o1, Object o2) { + if (!(o1 instanceof Plugin || o1 instanceof ReportPlugin)) { throw new IllegalArgumentException( - "This comparator can only be used to compare Plugin and ReportPlugin instances" ); + "This comparator can only be used to compare Plugin and ReportPlugin instances"); } - if ( !( o2 instanceof Plugin || o2 instanceof ReportPlugin ) ) - { + if (!(o2 instanceof Plugin || o2 instanceof ReportPlugin)) { throw new IllegalArgumentException( - "This comparator can only be used to compare Plugin and ReportPlugin instances" ); + "This comparator can only be used to compare Plugin and ReportPlugin instances"); } - String g1 = o1 instanceof Plugin ? ( (Plugin) o1 ).getGroupId() : ( (ReportPlugin) o1 ).getGroupId(); - String g2 = o2 instanceof Plugin ? ( (Plugin) o2 ).getGroupId() : ( (ReportPlugin) o2 ).getGroupId(); + String g1 = o1 instanceof Plugin ? ((Plugin) o1).getGroupId() : ((ReportPlugin) o1).getGroupId(); + String g2 = o2 instanceof Plugin ? ((Plugin) o2).getGroupId() : ((ReportPlugin) o2).getGroupId(); - int r = g1.compareTo( g2 ); - if ( r == 0 ) - { - String a1 = o1 instanceof Plugin ? ( (Plugin) o1 ).getArtifactId() : ( (ReportPlugin) o1 ).getArtifactId(); - String a2 = o2 instanceof Plugin ? ( (Plugin) o2 ).getArtifactId() : ( (ReportPlugin) o2 ).getArtifactId(); - r = a1.compareTo( a2 ); + int r = g1.compareTo(g2); + if (r == 0) { + String a1 = o1 instanceof Plugin ? ((Plugin) o1).getArtifactId() : ((ReportPlugin) o1).getArtifactId(); + String a2 = o2 instanceof Plugin ? ((Plugin) o2).getArtifactId() : ((ReportPlugin) o2).getArtifactId(); + r = a1.compareTo(a2); } - if ( r == 0 ) - { - String v1 = o1 instanceof Plugin ? ( (Plugin) o1 ).getVersion() : ( (ReportPlugin) o1 ).getVersion(); - String v2 = o2 instanceof Plugin ? ( (Plugin) o2 ).getVersion() : ( (ReportPlugin) o2 ).getVersion(); - if ( v1 == null ) - { + if (r == 0) { + String v1 = o1 instanceof Plugin ? ((Plugin) o1).getVersion() : ((ReportPlugin) o1).getVersion(); + String v2 = o2 instanceof Plugin ? ((Plugin) o2).getVersion() : ((ReportPlugin) o2).getVersion(); + if (v1 == null) { // hope I got the +1/-1 the right way around return v2 == null ? 0 : -1; } - if ( v2 == null ) - { + if (v2 == null) { return 1; } - r = v1.compareTo( v2 ); + r = v1.compareTo(v2); } return r; } - } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReader.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReader.java index 95dc0b654a..0754b981bd 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReader.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReader.java @@ -8,9 +8,9 @@ * 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 @@ -33,8 +33,7 @@ /** * Reader class for reading property files */ -public class PropertiesVersionsFileReader -{ +public class PropertiesVersionsFileReader { /** * Commas-separated list of properties @@ -49,8 +48,7 @@ public class PropertiesVersionsFileReader * Creates an instance of the object with the given path to the property file * @param filePath path to the property file */ - public PropertiesVersionsFileReader( String filePath ) - { + public PropertiesVersionsFileReader(String filePath) { propertyFilePath = filePath; } @@ -58,30 +56,26 @@ public PropertiesVersionsFileReader( String filePath ) * Reads the property file * @throws IOException thrown if an I/O exception occurs during the read operation */ - public void read() throws IOException - { - try ( InputStream input = Files.newInputStream( Paths.get( propertyFilePath ) ) ) - { + public void read() throws IOException { + try (InputStream input = Files.newInputStream(Paths.get(propertyFilePath))) { Properties prop = new Properties(); // load a properties file - prop.load( input ); + prop.load(input); prop.propertyNames(); - propertiesCsv = prop.keySet().stream().map( Object::toString ).collect( Collectors.joining( "," ) ); + propertiesCsv = prop.keySet().stream().map(Object::toString).collect(Collectors.joining(",")); List propertiesConfigList = new ArrayList<>(); - prop.forEach( - ( name, version ) -> - { - Property propertyConfig = new Property( (String) name ); - propertyConfig.setVersion( (String) version ); - propertiesConfigList.add( propertyConfig ); - } ); - - propertiesConfig = propertiesConfigList.toArray( new Property[0] ); + prop.forEach((name, version) -> { + Property propertyConfig = new Property((String) name); + propertyConfig.setVersion((String) version); + propertiesConfigList.add(propertyConfig); + }); + + propertiesConfig = propertiesConfigList.toArray(new Property[0]); } } @@ -89,8 +83,7 @@ public void read() throws IOException * Returns the string contents of the property file * @return contents of the property file */ - public String getProperties() - { + public String getProperties() { return propertiesCsv; } @@ -98,8 +91,7 @@ public String getProperties() * Returns the array of {@link Property} objects * @return array of properties */ - public Property[] getPropertiesConfig() - { + public Property[] getPropertiesConfig() { return propertiesConfig; } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertyComparator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertyComparator.java index 88112eec75..14833f7e57 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertyComparator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/PropertyComparator.java @@ -20,6 +20,7 @@ */ import java.util.Comparator; + import org.apache.commons.lang3.StringUtils; import org.codehaus.mojo.versions.api.Property; @@ -28,10 +29,9 @@ * * @since 1.0-beta-1 */ -public enum PropertyComparator implements Comparator -{ +public enum PropertyComparator implements Comparator { INSTANCE; - + /** * Compares to {@link Property} instances. * @@ -41,9 +41,8 @@ public enum PropertyComparator implements Comparator * @see java.util.Comparator#compare(Object, Object) * @since 1.0-beta-1 */ - @SuppressWarnings( "checkstyle:InnerAssignment" ) - public int compare( Property p1, Property p2 ) - { + @SuppressWarnings("checkstyle:InnerAssignment") + public int compare(Property p1, Property p2) { int r; return p1 == p2 ? 0 @@ -51,8 +50,8 @@ public int compare( Property p1, Property p2 ) ? 1 : p2 == null ? -1 - : ( r = StringUtils.compare( p1.getName(), p2.getName() ) ) == 0 - ? StringUtils.compare( p1.getValue(), p2.getValue() ) - : r ; + : (r = StringUtils.compare(p1.getName(), p2.getName())) == 0 + ? StringUtils.compare(p1.getValue(), p2.getValue()) + : r; } } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/RegexUtils.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/RegexUtils.java index a9da7cfb42..b6f5081ead 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/RegexUtils.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/RegexUtils.java @@ -25,8 +25,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public final class RegexUtils -{ +public final class RegexUtils { /** * The end of a regex literal sequence. * @@ -48,9 +47,8 @@ public final class RegexUtils */ public static final String REGEX_QUOTE_END_ESCAPED = REGEX_QUOTE_END + '\\' + REGEX_QUOTE_END + REGEX_QUOTE_START; - private RegexUtils() - { - throw new IllegalAccessError( "Utility classes should never be instantiated" ); + private RegexUtils() { + throw new IllegalAccessError("Utility classes should never be instantiated"); } /** @@ -60,53 +58,43 @@ private RegexUtils() * @return The regex that will match the string exactly. * @since 1.0-alpha-1 */ - public static String quote( String s ) - { - int i = s.indexOf( REGEX_QUOTE_END ); - if ( i == -1 ) - { + public static String quote(String s) { + int i = s.indexOf(REGEX_QUOTE_END); + if (i == -1) { // we're safe as nobody has a crazy \E in the string return REGEX_QUOTE_START + s + REGEX_QUOTE_END; } // damn there's at least one \E in the string - StringBuilder sb = new StringBuilder( s.length() + 32 ); + StringBuilder sb = new StringBuilder(s.length() + 32); // each escape-escape takes 10 chars... // hope there's less than 4 of them - sb.append( REGEX_QUOTE_START ); + sb.append(REGEX_QUOTE_START); int pos = 0; - do - { + do { // we are safe from pos to i - sb.append( s, pos, i ); + sb.append(s, pos, i); // now escape-escape - sb.append( REGEX_QUOTE_END_ESCAPED ); + sb.append(REGEX_QUOTE_END_ESCAPED); // move the working start pos = i + REGEX_QUOTE_END.length(); - i = s.indexOf( REGEX_QUOTE_END, pos ); - } - while ( i != -1 ); + i = s.indexOf(REGEX_QUOTE_END, pos); + } while (i != -1); - sb.append( s.substring( pos ) ); - sb.append( REGEX_QUOTE_END ); + sb.append(s.substring(pos)); + sb.append(REGEX_QUOTE_END); return sb.toString(); } - public static int getWildcardScore( String wildcardRule ) - { + public static int getWildcardScore(String wildcardRule) { int score = 0; - if ( wildcardRule != null ) - { - for ( char c : wildcardRule.toCharArray() ) - { - if ( c == '?' ) - { + if (wildcardRule != null) { + for (char c : wildcardRule.toCharArray()) { + if (c == '?') { score++; - } - else if ( c == '*' ) - { + } else if (c == '*') { score += 1000; } } @@ -122,52 +110,39 @@ else if ( c == '*' ) * false will match the start of the string. * @return The regex rule. */ - public static String convertWildcardsToRegex( String wildcardRule, boolean exactMatch ) - { + public static String convertWildcardsToRegex(String wildcardRule, boolean exactMatch) { StringBuilder regex = new StringBuilder(); int index = 0; final int len = wildcardRule.length(); - while ( index < len ) - { - final int nextQ = wildcardRule.indexOf( '?', index ); - final int nextS = wildcardRule.indexOf( '*', index ); - if ( nextQ == -1 && nextS == -1 ) - { - regex.append( quote( wildcardRule.substring( index ) ) ); + while (index < len) { + final int nextQ = wildcardRule.indexOf('?', index); + final int nextS = wildcardRule.indexOf('*', index); + if (nextQ == -1 && nextS == -1) { + regex.append(quote(wildcardRule.substring(index))); break; } int nextIndex; - if ( nextQ == -1 ) - { + if (nextQ == -1) { nextIndex = nextS; - } - else if ( nextS == -1 ) - { + } else if (nextS == -1) { nextIndex = nextQ; + } else { + nextIndex = Math.min(nextQ, nextS); } - else - { - nextIndex = Math.min( nextQ, nextS ); - } - if ( index < nextIndex ) - { + if (index < nextIndex) { // we have some characters to match - regex.append( quote( wildcardRule.substring( index, nextIndex ) ) ); - } - char c = wildcardRule.charAt( nextIndex ); - if ( c == '?' ) - { - regex.append( '.' ); + regex.append(quote(wildcardRule.substring(index, nextIndex))); } - else - { - regex.append( ".*" ); + char c = wildcardRule.charAt(nextIndex); + if (c == '?') { + regex.append('.'); + } else { + regex.append(".*"); } index = nextIndex + 1; } - if ( !exactMatch ) - { - regex.append( ".*" ); + if (!exactMatch) { + regex.append(".*"); } return regex.toString(); } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java index 1331890d8e..791d954a86 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java @@ -1,6 +1,5 @@ package org.codehaus.mojo.versions.utils; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -34,8 +33,7 @@ /** * Utility class for manipulating with {@link Segment} objects */ -public class SegmentUtils -{ +public class SegmentUtils { /** *

Based on the passed flags, determines which segment which is not to be changed.

* @@ -64,31 +62,25 @@ public class SegmentUtils * @param log If not null, the {@linkplain Log} object to log the selected scope * @return Returns the segment (0-based) that is unchangeable. If any segment can change, returns -1. */ - public static Optional determineUnchangedSegment( boolean allowMajorUpdates, boolean allowMinorUpdates, - boolean allowIncrementalUpdates, Log log ) - { - if ( log != null && !allowIncrementalUpdates ) - { - log.info( "Assuming allowMinorUpdates false because allowIncrementalUpdates is false." ); + public static Optional determineUnchangedSegment( + boolean allowMajorUpdates, boolean allowMinorUpdates, boolean allowIncrementalUpdates, Log log) { + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); } - if ( log != null && !allowMinorUpdates ) - { - log.info( "Assuming allowMajorUpdates false because allowMinorUpdates is false." ); + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); } Optional unchangedSegment = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates ? empty() : allowMinorUpdates && allowIncrementalUpdates - ? of( MAJOR ) - : allowIncrementalUpdates - ? of( MINOR ) - : of( INCREMENTAL ); - if ( log != null && log.isDebugEnabled() ) - { - log.debug( - unchangedSegment.map( s -> Segment.of( s.value() + 1 ).toString() ) - .orElse( "ALL" ) + " version changes allowed" ); + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment + .map(s -> Segment.of(s.value() + 1).toString()) + .orElse("ALL") + " version changes allowed"); } return unchangedSegment; } diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/VersionsExpressionEvaluator.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/VersionsExpressionEvaluator.java index 7ab86be342..22aa75d6cb 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/VersionsExpressionEvaluator.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/VersionsExpressionEvaluator.java @@ -30,12 +30,8 @@ * @author Stephen Connolly * @since 17-Mar-2009 08:51:42 */ -public class VersionsExpressionEvaluator - extends PluginParameterExpressionEvaluator - implements ExpressionEvaluator -{ - public VersionsExpressionEvaluator( MavenSession mavenSession, MojoExecution mojoExecution ) - { - super( mavenSession, mojoExecution ); +public class VersionsExpressionEvaluator extends PluginParameterExpressionEvaluator implements ExpressionEvaluator { + public VersionsExpressionEvaluator(MavenSession mavenSession, MojoExecution mojoExecution) { + super(mavenSession, mojoExecution); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java index 25913f0af8..9809bfb7bd 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java @@ -45,163 +45,169 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -public class ArtifactVersionsTest -{ +public class ArtifactVersionsTest { @Test - public void test4DigitVersions() throws Exception - { - ArtifactVersion[] versions = versions( "1.0.0.1", "1.0.0.2", "2.121.2.1", "2.100.0.1", "3.1.0.1", "1.1.1" ); - final DefaultArtifact artifact = - new DefaultArtifact( "group", "artifact", VersionRange.createFromVersionSpec( "[1.0,3.0]" ), "foo", "bar", - "jar", new DefaultArtifactHandler() ); + public void test4DigitVersions() throws Exception { + ArtifactVersion[] versions = versions("1.0.0.1", "1.0.0.2", "2.121.2.1", "2.100.0.1", "3.1.0.1", "1.1.1"); + final DefaultArtifact artifact = new DefaultArtifact( + "group", + "artifact", + VersionRange.createFromVersionSpec("[1.0,3.0]"), + "foo", + "bar", + "jar", + new DefaultArtifactHandler()); // TODO This should also work for the MavenVersionComparator when using maven 3.x libraries ArtifactVersions instance = - new ArtifactVersions( artifact, Arrays.asList( versions ), new MercuryVersionComparator() ); - assertEquals( "artifact", instance.getArtifactId() ); - assertEquals( "group", instance.getGroupId() ); - assertThat( instance.getVersions(), - arrayContaining( versions( "1.0.0.1", "1.0.0.2", "1.1.1", "2.100.0.1", "2.121.2.1", - "3.1.0.1" ) ) ); - assertThat( instance.getVersions( new DefaultArtifactVersion( "1.1" ), null ), - arrayContaining( versions( "1.1.1", "2.100.0.1", "2.121.2.1", "3.1.0.1" ) ) ); - - assertThat( instance.getVersions( new DefaultArtifactVersion( "1.0.0.2" ), null ), - //Matchers.arrayContaining(versions("1.1.1", "2.121.2.1", "2.100.0.1", "3.1.0.1"))); - arrayContaining( versions( "1.1.1", "2.100.0.1", "2.121.2.1", "3.1.0.1" ) ) ); - - assertEquals( new DefaultArtifactVersion( "2.121.2.1" ), - instance.getNewestVersion( new DefaultArtifactVersion( "1.0" ), - new DefaultArtifactVersion( "3.0" ) ) ); - assertNull( - instance.getNewestVersion( new DefaultArtifactVersion( "1.1.1" ), - new DefaultArtifactVersion( "2.0" ) ) ); + new ArtifactVersions(artifact, Arrays.asList(versions), new MercuryVersionComparator()); + assertEquals("artifact", instance.getArtifactId()); + assertEquals("group", instance.getGroupId()); + assertThat( + instance.getVersions(), + arrayContaining(versions("1.0.0.1", "1.0.0.2", "1.1.1", "2.100.0.1", "2.121.2.1", "3.1.0.1"))); + assertThat( + instance.getVersions(new DefaultArtifactVersion("1.1"), null), + arrayContaining(versions("1.1.1", "2.100.0.1", "2.121.2.1", "3.1.0.1"))); + + assertThat( + instance.getVersions(new DefaultArtifactVersion("1.0.0.2"), null), + // Matchers.arrayContaining(versions("1.1.1", "2.121.2.1", "2.100.0.1", "3.1.0.1"))); + arrayContaining(versions("1.1.1", "2.100.0.1", "2.121.2.1", "3.1.0.1"))); + + assertEquals( + new DefaultArtifactVersion("2.121.2.1"), + instance.getNewestVersion(new DefaultArtifactVersion("1.0"), new DefaultArtifactVersion("3.0"))); + assertNull(instance.getNewestVersion(new DefaultArtifactVersion("1.1.1"), new DefaultArtifactVersion("2.0"))); } @Test - public void testSmokes() - throws Exception - { - ArtifactVersion[] versions = versions( "1.0", "3.0", "1.1", "1.0", "1.0.1" ); - final DefaultArtifact artifact = - new DefaultArtifact( "group", "artifact", VersionRange.createFromVersionSpec( "[1.0,3.0]" ), "foo", "bar", - "jar", new DefaultArtifactHandler() ); + public void testSmokes() throws Exception { + ArtifactVersion[] versions = versions("1.0", "3.0", "1.1", "1.0", "1.0.1"); + final DefaultArtifact artifact = new DefaultArtifact( + "group", + "artifact", + VersionRange.createFromVersionSpec("[1.0,3.0]"), + "foo", + "bar", + "jar", + new DefaultArtifactHandler()); ArtifactVersions instance = - new ArtifactVersions( artifact, Arrays.asList( versions ), new MavenVersionComparator() ); - assertEquals( "artifact", instance.getArtifactId() ); - assertEquals( "group", instance.getGroupId() ); - assertArrayEquals( - versions( "1.0", "1.0.1", "1.1", "3.0" ), - instance.getVersions() ); - assertArrayEquals( versions( "3.0" ), - instance.getVersions( new DefaultArtifactVersion( "1.1" ), null ) ); - assertArrayEquals( - versions( "1.1", "3.0" ), - instance.getVersions( new DefaultArtifactVersion( "1.0.1" ), null ) ); - assertEquals( new DefaultArtifactVersion( "1.1" ), - instance.getNewestVersion( new DefaultArtifactVersion( "1.0" ), - new DefaultArtifactVersion( "3.0" ) ) ); - assertNull( - instance.getNewestVersion( new DefaultArtifactVersion( "1.1" ), new DefaultArtifactVersion( "3.0" ) ) ); + new ArtifactVersions(artifact, Arrays.asList(versions), new MavenVersionComparator()); + assertEquals("artifact", instance.getArtifactId()); + assertEquals("group", instance.getGroupId()); + assertArrayEquals(versions("1.0", "1.0.1", "1.1", "3.0"), instance.getVersions()); + assertArrayEquals(versions("3.0"), instance.getVersions(new DefaultArtifactVersion("1.1"), null)); + assertArrayEquals(versions("1.1", "3.0"), instance.getVersions(new DefaultArtifactVersion("1.0.1"), null)); + assertEquals( + new DefaultArtifactVersion("1.1"), + instance.getNewestVersion(new DefaultArtifactVersion("1.0"), new DefaultArtifactVersion("3.0"))); + assertNull(instance.getNewestVersion(new DefaultArtifactVersion("1.1"), new DefaultArtifactVersion("3.0"))); } - private ArtifactVersion[] versions( String... versions ) - { + private ArtifactVersion[] versions(String... versions) { ArtifactVersion[] artifactVersions = new ArtifactVersion[versions.length]; - for ( int i = 0; i < versions.length; i++ ) - { - artifactVersions[i] = new DefaultArtifactVersion( versions[i] ); + for (int i = 0; i < versions.length; i++) { + artifactVersions[i] = new DefaultArtifactVersion(versions[i]); } return artifactVersions; } @Test - public void testReportLabels() - { - ArtifactVersion[] versions = versions( "1.0.1", "1.0", "1.1.0-2", "1.1.1", "1.1.1-2", "1.1.2", - "1.1.2-SNAPSHOT", "1.1.3", "1.1", "1.1-SNAPSHOT", "1.2.1", "1.2.2", "1.2", "1.3", - "1.9.1-SNAPSHOT", "2.0", "2.1.1-SNAPSHOT", "2.1", "3.0", "3.1.1-SNAPSHOT", - "3.1.5-SNAPSHOT", "3.4.0-SNAPSHOT" ); - ArtifactVersions instance = - new ArtifactVersions( new DefaultArtifact( "default-group", "dummy-api", - "1.1", "foo", "bar", - "jar", null ), - Arrays.asList( versions ), new MavenVersionComparator() ); - - assertThat( instance.getNewestUpdate( of( SUBINCREMENTAL ) ).toString(), is( "1.1.0-2" ) ); - assertThat( instance.getNewestUpdate( of( INCREMENTAL ) ).toString(), is( "1.1.3" ) ); + public void testReportLabels() { + ArtifactVersion[] versions = versions( + "1.0.1", + "1.0", + "1.1.0-2", + "1.1.1", + "1.1.1-2", + "1.1.2", + "1.1.2-SNAPSHOT", + "1.1.3", + "1.1", + "1.1-SNAPSHOT", + "1.2.1", + "1.2.2", + "1.2", + "1.3", + "1.9.1-SNAPSHOT", + "2.0", + "2.1.1-SNAPSHOT", + "2.1", + "3.0", + "3.1.1-SNAPSHOT", + "3.1.5-SNAPSHOT", + "3.4.0-SNAPSHOT"); + ArtifactVersions instance = new ArtifactVersions( + new DefaultArtifact("default-group", "dummy-api", "1.1", "foo", "bar", "jar", null), + Arrays.asList(versions), + new MavenVersionComparator()); + + assertThat(instance.getNewestUpdate(of(SUBINCREMENTAL)).toString(), is("1.1.0-2")); + assertThat(instance.getNewestUpdate(of(INCREMENTAL)).toString(), is("1.1.3")); } @Test - public void testGetNewerVersionsWithSnapshot() throws InvalidSegmentException - { - ArtifactVersion[] versions = versions( "1.0.0-SNAPSHOT", "1.0.0" ); - ArtifactVersions instance = - new ArtifactVersions( new DefaultArtifact( "default-group", "dummy-api", - "1.0.0-SNAPSHOT", "foo", "bar", - "jar", null ), - Arrays.asList( versions ), new MavenVersionComparator() ); - - assertThat( instance.getNewerVersions( "1.0.0-SNAPSHOT", of( SUBINCREMENTAL ), false, false ), - arrayContaining( new DefaultArtifactVersion( "1.0.0" ) ) ); + public void testGetNewerVersionsWithSnapshot() throws InvalidSegmentException { + ArtifactVersion[] versions = versions("1.0.0-SNAPSHOT", "1.0.0"); + ArtifactVersions instance = new ArtifactVersions( + new DefaultArtifact("default-group", "dummy-api", "1.0.0-SNAPSHOT", "foo", "bar", "jar", null), + Arrays.asList(versions), + new MavenVersionComparator()); + + assertThat( + instance.getNewerVersions("1.0.0-SNAPSHOT", of(SUBINCREMENTAL), false, false), + arrayContaining(new DefaultArtifactVersion("1.0.0"))); } @Test - public void testAllVersionsForIgnoreScopeSubIncremental() - { - ArtifactVersion[] versions = versions( "1.0.0", "1.0.0-1", "1.0.1" ); - ArtifactVersions instance = - new ArtifactVersions( new DefaultArtifact( "default-group", "dummy-api", - "1.0.0", "foo", "bar", - "jar", null ), - Arrays.asList( versions ), new MavenVersionComparator() ); - Restriction restriction = instance.restrictionForIgnoreScope( of( SUBINCREMENTAL ) ); - ArtifactVersion[] filteredVersions = instance.getVersions( restriction, false ); - assertThat( filteredVersions, arrayWithSize( 1 ) ); - assertThat( filteredVersions, arrayContaining( new DefaultArtifactVersion( "1.0.1" ) ) ); + public void testAllVersionsForIgnoreScopeSubIncremental() { + ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1"); + ArtifactVersions instance = new ArtifactVersions( + new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), + Arrays.asList(versions), + new MavenVersionComparator()); + Restriction restriction = instance.restrictionForIgnoreScope(of(SUBINCREMENTAL)); + ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); + assertThat(filteredVersions, arrayWithSize(1)); + assertThat(filteredVersions, arrayContaining(new DefaultArtifactVersion("1.0.1"))); } @Test - public void testAllVersionsForIgnoreScopeIncremental() - { - ArtifactVersion[] versions = versions( "1.0.0", "1.0.0-1", "1.0.1", "1.1.0" ); - ArtifactVersions instance = - new ArtifactVersions( new DefaultArtifact( "default-group", "dummy-api", - "1.0.0", "foo", "bar", - "jar", null ), - Arrays.asList( versions ), new MavenVersionComparator() ); - Restriction restriction = instance.restrictionForIgnoreScope( of( INCREMENTAL ) ); - ArtifactVersion[] filteredVersions = instance.getVersions( restriction, false ); - assertThat( filteredVersions, arrayWithSize( 1 ) ); - assertThat( filteredVersions, arrayContaining( new DefaultArtifactVersion( "1.1.0" ) ) ); + public void testAllVersionsForIgnoreScopeIncremental() { + ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1", "1.1.0"); + ArtifactVersions instance = new ArtifactVersions( + new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), + Arrays.asList(versions), + new MavenVersionComparator()); + Restriction restriction = instance.restrictionForIgnoreScope(of(INCREMENTAL)); + ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); + assertThat(filteredVersions, arrayWithSize(1)); + assertThat(filteredVersions, arrayContaining(new DefaultArtifactVersion("1.1.0"))); } @Test - public void testAllVersionsForIgnoreScopeMinor() - { - ArtifactVersion[] versions = versions( "1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0" ); - ArtifactVersions instance = - new ArtifactVersions( new DefaultArtifact( "default-group", "dummy-api", - "1.0.0", "foo", "bar", - "jar", null ), - Arrays.asList( versions ), new MavenVersionComparator() ); - Restriction restriction = instance.restrictionForIgnoreScope( of( MINOR ) ); - ArtifactVersion[] filteredVersions = instance.getVersions( restriction, false ); - assertThat( filteredVersions, arrayWithSize( 1 ) ); - assertThat( filteredVersions, arrayContaining( new DefaultArtifactVersion( "2.0.0" ) ) ); + public void testAllVersionsForIgnoreScopeMinor() { + ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0"); + ArtifactVersions instance = new ArtifactVersions( + new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), + Arrays.asList(versions), + new MavenVersionComparator()); + Restriction restriction = instance.restrictionForIgnoreScope(of(MINOR)); + ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); + assertThat(filteredVersions, arrayWithSize(1)); + assertThat(filteredVersions, arrayContaining(new DefaultArtifactVersion("2.0.0"))); } @Test - public void testAllVersionsForIgnoreScopeMajor() - { - ArtifactVersion[] versions = versions( "1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0" ); - ArtifactVersions instance = - new ArtifactVersions( new DefaultArtifact( "default-group", "dummy-api", - "1.0.0", "foo", "bar", - "jar", null ), - Arrays.asList( versions ), new MavenVersionComparator() ); - Restriction restriction = instance.restrictionForIgnoreScope( of( MAJOR ) ); - ArtifactVersion[] filteredVersions = instance.getVersions( restriction, false ); - assertThat( filteredVersions, arrayWithSize( 0 ) ); + public void testAllVersionsForIgnoreScopeMajor() { + ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0"); + ArtifactVersions instance = new ArtifactVersions( + new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), + Arrays.asList(versions), + new MavenVersionComparator()); + Restriction restriction = instance.restrictionForIgnoreScope(of(MAJOR)); + ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); + assertThat(filteredVersions, arrayWithSize(0)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/api/DefaultVersionsHelperTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/api/DefaultVersionsHelperTest.java index 47ee52d3ac..5a0d4534e3 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/api/DefaultVersionsHelperTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/api/DefaultVersionsHelperTest.java @@ -80,253 +80,252 @@ /** * Test {@link DefaultVersionsHelper} */ -public class DefaultVersionsHelperTest extends AbstractMojoTestCase -{ +public class DefaultVersionsHelperTest extends AbstractMojoTestCase { @Test - public void testPerRuleVersionsIgnored() throws Exception - { - final org.eclipse.aether.RepositorySystem repositorySystem = mock( org.eclipse.aether.RepositorySystem.class ); - final Artifact artifact = mock( Artifact.class ); - when( artifact.getGroupId() ).thenReturn( "com.mycompany.maven" ); - when( artifact.getArtifactId() ).thenReturn( "artifact-one" ); - when( artifact.getType() ).thenReturn( "jar" ); - when( artifact.getArtifactHandler() ).thenReturn( new DefaultArtifactHandlerStub( "default" ) ); - when( repositorySystem.resolveVersionRange( any(), any( VersionRangeRequest.class ) ) ) - .then( i -> new VersionRangeResult( i.getArgument( 1 ) ) - .setVersions( Arrays.asList( - new VersionStub( "one" ), - new VersionStub( "two" ), - new VersionStub( "three" ), - new VersionStub( "1.200" ), - new VersionStub( "illegalVersion" ) ) ) ); - - VersionsHelper helper = createHelper( repositorySystem ); - - final ArtifactVersions versions = helper.lookupArtifactVersions( artifact, true ); - - final List actual = Arrays.stream( versions.getVersions( true ) ) - .map( ArtifactVersion::toString ) - .collect( Collectors.toList() ); - - assertEquals( 3, actual.size() ); - assertThat( actual, hasItems( "three", "1.200", "illegalVersion" ) ); + public void testPerRuleVersionsIgnored() throws Exception { + final org.eclipse.aether.RepositorySystem repositorySystem = mock(org.eclipse.aether.RepositorySystem.class); + final Artifact artifact = mock(Artifact.class); + when(artifact.getGroupId()).thenReturn("com.mycompany.maven"); + when(artifact.getArtifactId()).thenReturn("artifact-one"); + when(artifact.getType()).thenReturn("jar"); + when(artifact.getArtifactHandler()).thenReturn(new DefaultArtifactHandlerStub("default")); + when(repositorySystem.resolveVersionRange(any(), any(VersionRangeRequest.class))) + .then(i -> new VersionRangeResult(i.getArgument(1)) + .setVersions(Arrays.asList( + new VersionStub("one"), + new VersionStub("two"), + new VersionStub("three"), + new VersionStub("1.200"), + new VersionStub("illegalVersion")))); + + VersionsHelper helper = createHelper(repositorySystem); + + final ArtifactVersions versions = helper.lookupArtifactVersions(artifact, true); + + final List actual = Arrays.stream(versions.getVersions(true)) + .map(ArtifactVersion::toString) + .collect(Collectors.toList()); + + assertEquals(3, actual.size()); + assertThat(actual, hasItems("three", "1.200", "illegalVersion")); } @Test - public void testGlobalRuleVersionsIgnored() throws Exception - { - final org.eclipse.aether.RepositorySystem repositorySystem = mock( org.eclipse.aether.RepositorySystem.class ); - final Artifact artifact = mock( Artifact.class ); - when( artifact.getGroupId() ).thenReturn( "other.company" ); - when( artifact.getArtifactId() ).thenReturn( "artifact-two" ); - when( artifact.getType() ).thenReturn( "jar" ); - when( artifact.getArtifactHandler() ).thenReturn( new DefaultArtifactHandlerStub( "default" ) ); + public void testGlobalRuleVersionsIgnored() throws Exception { + final org.eclipse.aether.RepositorySystem repositorySystem = mock(org.eclipse.aether.RepositorySystem.class); + final Artifact artifact = mock(Artifact.class); + when(artifact.getGroupId()).thenReturn("other.company"); + when(artifact.getArtifactId()).thenReturn("artifact-two"); + when(artifact.getType()).thenReturn("jar"); + when(artifact.getArtifactHandler()).thenReturn(new DefaultArtifactHandlerStub("default")); final List artifactVersions = new ArrayList<>(); - final Version one = new VersionStub( "one" ); - final Version two = new VersionStub( "two" ); - final Version three = new VersionStub( "three" ); - artifactVersions.add( one ); - artifactVersions.add( two ); - artifactVersions.add( new VersionStub( "three-alpha" ) ); - artifactVersions.add( new VersionStub( "three-beta" ) ); - artifactVersions.add( three ); - final Version illegal = new VersionStub( "illegalVersion" ); - artifactVersions.add( illegal ); + final Version one = new VersionStub("one"); + final Version two = new VersionStub("two"); + final Version three = new VersionStub("three"); + artifactVersions.add(one); + artifactVersions.add(two); + artifactVersions.add(new VersionStub("three-alpha")); + artifactVersions.add(new VersionStub("three-beta")); + artifactVersions.add(three); + final Version illegal = new VersionStub("illegalVersion"); + artifactVersions.add(illegal); - when( repositorySystem.resolveVersionRange( any(), any( VersionRangeRequest.class ) ) ) - .then( i -> new VersionRangeResult( i.getArgument( 1 ) ) - .setVersions( artifactVersions ) ); + when(repositorySystem.resolveVersionRange(any(), any(VersionRangeRequest.class))) + .then(i -> new VersionRangeResult(i.getArgument(1)).setVersions(artifactVersions)); - VersionsHelper helper = createHelper( repositorySystem ); + VersionsHelper helper = createHelper(repositorySystem); - final ArtifactVersions versions = helper.lookupArtifactVersions( artifact, true ); + final ArtifactVersions versions = helper.lookupArtifactVersions(artifact, true); - final List actual = Arrays.stream( versions.getVersions( true ) ) - .map( ArtifactVersion::toString ) - .map( VersionStub::new ) - .collect( Collectors.toList() ); + final List actual = Arrays.stream(versions.getVersions(true)) + .map(ArtifactVersion::toString) + .map(VersionStub::new) + .collect(Collectors.toList()); - assertEquals( 4, actual.size() ); - assertThat( actual, hasItems( one, two, three, illegal ) ); + assertEquals(4, actual.size()); + assertThat(actual, hasItems(one, two, three, illegal)); } @Test - public void testWildcardMatching() - throws Exception - { - assertTrue( DefaultVersionsHelper.exactMatch( "*", "com.foo.bar" ) ); - assertFalse( DefaultVersionsHelper.exactMatch( "com.bar*", "com-bar" ) ); - assertTrue( DefaultVersionsHelper.exactMatch( "com?foo.bar", "com.foo.bar" ) ); - assertTrue( DefaultVersionsHelper.exactMatch( "co*.foo.b?r", "com.foo.bar" ) ); - assertTrue( DefaultVersionsHelper.exactMatch( "c*oo*r", "com.foo.bar" ) ); + public void testWildcardMatching() throws Exception { + assertTrue(DefaultVersionsHelper.exactMatch("*", "com.foo.bar")); + assertFalse(DefaultVersionsHelper.exactMatch("com.bar*", "com-bar")); + assertTrue(DefaultVersionsHelper.exactMatch("com?foo.bar", "com.foo.bar")); + assertTrue(DefaultVersionsHelper.exactMatch("co*.foo.b?r", "com.foo.bar")); + assertTrue(DefaultVersionsHelper.exactMatch("c*oo*r", "com.foo.bar")); } @Test - public void testRuleSets() - throws Exception - { + public void testRuleSets() throws Exception { VersionsHelper helper = createHelper(); - assertEquals( "no match gives default", VersionComparators.getVersionComparator( "maven" ), - helper.getVersionComparator( "net.foo", "bar" ) ); - assertEquals( "matches wildcard", VersionComparators.getVersionComparator( "mercury" ), - helper.getVersionComparator( "org.apache.maven", "plugins" ) ); - assertEquals( "exact match wins over initial match", VersionComparators.getVersionComparator( "mercury" ), - helper.getVersionComparator( "com.mycompany.custom.maven", "plugins" ) ); - assertEquals( "non-wildcard prefix wins over wildcard prefix match", - VersionComparators.getVersionComparator( "maven" ), - helper.getVersionComparator( "com.mycompany.maven.plugins", "plugins" ) ); - assertEquals( VersionComparators.getVersionComparator( "maven" ), - helper.getVersionComparator( "com.mycompany.maven", "new-maven-plugin" ) ); - assertEquals( VersionComparators.getVersionComparator( "mercury" ), - helper.getVersionComparator( "com.mycompany.maven", "old-maven-plugin" ) ); + assertEquals( + "no match gives default", + VersionComparators.getVersionComparator("maven"), + helper.getVersionComparator("net.foo", "bar")); + assertEquals( + "matches wildcard", + VersionComparators.getVersionComparator("mercury"), + helper.getVersionComparator("org.apache.maven", "plugins")); + assertEquals( + "exact match wins over initial match", + VersionComparators.getVersionComparator("mercury"), + helper.getVersionComparator("com.mycompany.custom.maven", "plugins")); + assertEquals( + "non-wildcard prefix wins over wildcard prefix match", + VersionComparators.getVersionComparator("maven"), + helper.getVersionComparator("com.mycompany.maven.plugins", "plugins")); + assertEquals( + VersionComparators.getVersionComparator("maven"), + helper.getVersionComparator("com.mycompany.maven", "new-maven-plugin")); + assertEquals( + VersionComparators.getVersionComparator("mercury"), + helper.getVersionComparator("com.mycompany.maven", "old-maven-plugin")); } - @Test - public void testMVERSIONS159ExcludedAndNotIncluded() - throws Exception - { + public void testMVERSIONS159ExcludedAndNotIncluded() throws Exception { VersionsHelper helper = createHelper(); MavenProject project = null; - Property[] propertyDefinitions = new Property[] { - new Property( "bar.version" ) - }; + Property[] propertyDefinitions = new Property[] {new Property("bar.version")}; // should not throw an IllegalStateException Map result = - helper.getVersionPropertiesMap( VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( project ) - .withPropertyDefinitions( propertyDefinitions ) - .withIncludeProperties( "foo.version" ) - .withExcludeProperties( "bar.version" ) - .withIncludeParent( false ) - .withAutoLinkItems( false ) - .build() ); - assertTrue( result.isEmpty() ); + helper.getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(project) + .withPropertyDefinitions(propertyDefinitions) + .withIncludeProperties("foo.version") + .withExcludeProperties("bar.version") + .withIncludeParent(false) + .withAutoLinkItems(false) + .build()); + assertTrue(result.isEmpty()); } @Test - public void testIsClasspathUriDetectsClassPathProtocol() throws Exception - { + public void testIsClasspathUriDetectsClassPathProtocol() throws Exception { DefaultVersionsHelper helper = createHelper(); String uri = "classpath:/p/a/c/k/a/g/e/resource.res"; - assertThat( DefaultVersionsHelper.isClasspathUri( uri ), CoreMatchers.is( true ) ); + assertThat(DefaultVersionsHelper.isClasspathUri(uri), CoreMatchers.is(true)); } @Test - public void testIsClasspathUriDetectsThatItIsDifferentProtocol() throws Exception - { + public void testIsClasspathUriDetectsThatItIsDifferentProtocol() throws Exception { DefaultVersionsHelper helper = createHelper(); String uri = "http://10.10.10.10/p/a/c/k/a/g/e/resource.res"; - assertThat( DefaultVersionsHelper.isClasspathUri( uri ), CoreMatchers.is( false ) ); + assertThat(DefaultVersionsHelper.isClasspathUri(uri), CoreMatchers.is(false)); } - - private DefaultVersionsHelper createHelper() - throws Exception - { - return createHelper( null ); + private DefaultVersionsHelper createHelper() throws Exception { + return createHelper(null); } - private static Wagon mockFileWagon( URI rulesUri ) + private static Wagon mockFileWagon(URI rulesUri) throws AuthenticationException, ConnectionException, AuthorizationException, TransferFailedException, - ResourceDoesNotExistException - { - Wagon fileWagon = mock( Wagon.class ); - doNothing().when( fileWagon ).connect( any( org.apache.maven.wagon.repository.Repository.class ), - any( AuthenticationInfo.class ), any( ProxyInfo.class ) ); - doAnswer( i -> - { - File tempFile = i.getArgument( 1 ); - Files.copy( Paths.get( rulesUri ), tempFile.toPath(), REPLACE_EXISTING ); - return null; - } ).when( fileWagon ).get( anyString(), any( File.class ) ); + ResourceDoesNotExistException { + Wagon fileWagon = mock(Wagon.class); + doNothing() + .when(fileWagon) + .connect( + any(org.apache.maven.wagon.repository.Repository.class), + any(AuthenticationInfo.class), + any(ProxyInfo.class)); + doAnswer(i -> { + File tempFile = i.getArgument(1); + Files.copy(Paths.get(rulesUri), tempFile.toPath(), REPLACE_EXISTING); + return null; + }) + .when(fileWagon) + .get(anyString(), any(File.class)); return fileWagon; } - private DefaultVersionsHelper createHelper( org.eclipse.aether.RepositorySystem aetherRepositorySystem ) - throws Exception - { - final String resourcePath = "/" + getClass().getPackage().getName().replace( '.', '/' ) + "/rules.xml"; - final String rulesUri = Objects.requireNonNull( getClass().getResource( resourcePath ) ).toExternalForm(); - MavenSession mavenSession = mock( MavenSession.class ); - when( mavenSession.getCurrentProject() ).thenReturn( mock( MavenProject.class ) ); - when( mavenSession.getCurrentProject().getRemotePluginRepositories() ) - .thenReturn( emptyList() ); - when( mavenSession.getCurrentProject().getRemotePluginRepositories() ) - .thenReturn( emptyList() ); - when( mavenSession.getRepositorySession() ).thenReturn( new DefaultRepositorySystemSession() ); + private DefaultVersionsHelper createHelper(org.eclipse.aether.RepositorySystem aetherRepositorySystem) + throws Exception { + final String resourcePath = "/" + getClass().getPackage().getName().replace('.', '/') + "/rules.xml"; + final String rulesUri = + Objects.requireNonNull(getClass().getResource(resourcePath)).toExternalForm(); + MavenSession mavenSession = mock(MavenSession.class); + when(mavenSession.getCurrentProject()).thenReturn(mock(MavenProject.class)); + when(mavenSession.getCurrentProject().getRemotePluginRepositories()).thenReturn(emptyList()); + when(mavenSession.getCurrentProject().getRemotePluginRepositories()).thenReturn(emptyList()); + when(mavenSession.getRepositorySession()).thenReturn(new DefaultRepositorySystemSession()); return new DefaultVersionsHelper.Builder() - .withRepositorySystem( lookup( RepositorySystem.class ) ) - .withAetherRepositorySystem( aetherRepositorySystem ) - .withWagonMap( singletonMap( "file", mockFileWagon( new URI( rulesUri ) ) ) ) - .withServerId( "" ) - .withRulesUri( rulesUri ) - .withLog( mock( Log.class ) ) - .withMavenSession( mavenSession ) - .withMojoExecution( mock( MojoExecution.class ) ).build(); + .withRepositorySystem(lookup(RepositorySystem.class)) + .withAetherRepositorySystem(aetherRepositorySystem) + .withWagonMap(singletonMap("file", mockFileWagon(new URI(rulesUri)))) + .withServerId("") + .withRulesUri(rulesUri) + .withLog(mock(Log.class)) + .withMavenSession(mavenSession) + .withMojoExecution(mock(MojoExecution.class)) + .build(); } @Test public void testIgnoredVersionsShouldBeTheOnlyPresentInAnEmptyRuleSet() - throws MojoExecutionException, IllegalAccessException - { + throws MojoExecutionException, IllegalAccessException { DefaultVersionsHelper versionsHelper = new DefaultVersionsHelper.Builder() - .withLog( new SystemStreamLog() ) - .withIgnoredVersions( Arrays.asList( ".*-M.", ".*-SNAPSHOT" ) ) + .withLog(new SystemStreamLog()) + .withIgnoredVersions(Arrays.asList(".*-M.", ".*-SNAPSHOT")) .build(); - RuleSet ruleSet = (RuleSet) getVariableValueFromObject( versionsHelper, "ruleSet" ); - assertThat( ruleSet.getIgnoreVersions(), hasSize( 2 ) ); - assertThat( ruleSet.getIgnoreVersions().stream().map( IgnoreVersion::getVersion ) - .collect( Collectors.toList() ), containsInAnyOrder( ".*-M.", ".*-SNAPSHOT" ) ); + RuleSet ruleSet = (RuleSet) getVariableValueFromObject(versionsHelper, "ruleSet"); + assertThat(ruleSet.getIgnoreVersions(), hasSize(2)); + assertThat( + ruleSet.getIgnoreVersions().stream() + .map(IgnoreVersion::getVersion) + .collect(Collectors.toList()), + containsInAnyOrder(".*-M.", ".*-SNAPSHOT")); } @Test - public void testDefaultsShouldBePresentInAnEmptyRuleSet() - throws MojoExecutionException, IllegalAccessException - { + public void testDefaultsShouldBePresentInAnEmptyRuleSet() throws MojoExecutionException, IllegalAccessException { DefaultVersionsHelper versionsHelper = new DefaultVersionsHelper.Builder() - .withLog( new SystemStreamLog() ) - .withIgnoredVersions( singletonList( ".*-M." ) ) + .withLog(new SystemStreamLog()) + .withIgnoredVersions(singletonList(".*-M.")) .build(); - RuleSet ruleSet = (RuleSet) getVariableValueFromObject( versionsHelper, "ruleSet" ); - assertThat( ruleSet.getComparisonMethod(), is( "maven" ) ); + RuleSet ruleSet = (RuleSet) getVariableValueFromObject(versionsHelper, "ruleSet"); + assertThat(ruleSet.getComparisonMethod(), is("maven")); } @Test - public void testIgnoredVersionsShouldExtendTheRuleSet() throws MojoExecutionException, IllegalAccessException - { + public void testIgnoredVersionsShouldExtendTheRuleSet() throws MojoExecutionException, IllegalAccessException { DefaultVersionsHelper versionsHelper = new DefaultVersionsHelper.Builder() - .withLog( new SystemStreamLog() ) - .withRuleSet( new RuleSet() - {{ - setIgnoreVersions( new ArrayList<>( singletonList( new IgnoreVersion() - {{ - setVersion( "1.0.0" ); - }} ) ) ); - setRules( singletonList( new Rule() - {{ - setGroupId( "org.slf4j" ); - setArtifactId( "slf4j-api" ); - setIgnoreVersions( singletonList( new IgnoreVersion() - {{ - setType( "regex" ); - setVersion( "^[^1]\\.*" ); - }} ) ); - }} ) ); - }} ) - .withIgnoredVersions( Arrays.asList( ".*-M.", ".*-SNAPSHOT" ) ) + .withLog(new SystemStreamLog()) + .withRuleSet(new RuleSet() { + { + setIgnoreVersions(new ArrayList<>(singletonList(new IgnoreVersion() { + { + setVersion("1.0.0"); + } + }))); + setRules(singletonList(new Rule() { + { + setGroupId("org.slf4j"); + setArtifactId("slf4j-api"); + setIgnoreVersions(singletonList(new IgnoreVersion() { + { + setType("regex"); + setVersion("^[^1]\\.*"); + } + })); + } + })); + } + }) + .withIgnoredVersions(Arrays.asList(".*-M.", ".*-SNAPSHOT")) .build(); - RuleSet ruleSet = (RuleSet) getVariableValueFromObject( versionsHelper, "ruleSet" ); - assertThat( ruleSet.getIgnoreVersions(), hasSize( 3 ) ); - assertThat( ruleSet.getIgnoreVersions().stream().map( IgnoreVersion::getVersion ) - .collect( Collectors.toList() ), containsInAnyOrder( ".*-M.", ".*-SNAPSHOT", "1.0.0" ) ); + RuleSet ruleSet = (RuleSet) getVariableValueFromObject(versionsHelper, "ruleSet"); + assertThat(ruleSet.getIgnoreVersions(), hasSize(3)); + assertThat( + ruleSet.getIgnoreVersions().stream() + .map(IgnoreVersion::getVersion) + .collect(Collectors.toList()), + containsInAnyOrder(".*-M.", ".*-SNAPSHOT", "1.0.0")); } - } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/api/PomHelperTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/api/PomHelperTest.java index 4e50637ec6..5b13ccbe2f 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/api/PomHelperTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/api/PomHelperTest.java @@ -49,17 +49,15 @@ /** * Tests the methods of {@link PomHelper}. */ -public class PomHelperTest extends AbstractMojoTestCase -{ +public class PomHelperTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); private static final XMLInputFactory INPUT_FACTORY = XMLInputFactory2.newInstance(); @BeforeClass - public static void setUpClass() - { - INPUT_FACTORY.setProperty( P_PRESERVE_LOCATION, Boolean.TRUE ); + public static void setUpClass() { + INPUT_FACTORY.setProperty(P_PRESERVE_LOCATION, Boolean.TRUE); } /** @@ -69,199 +67,158 @@ public static void setUpClass() * @throws Exception if the test fails. */ @Test - public void testLongProperties() - throws Exception - { - URL url = getClass().getResource( "PomHelperTest.testLongProperties.pom.xml" ); + public void testLongProperties() throws Exception { + URL url = getClass().getResource("PomHelperTest.testLongProperties.pom.xml"); assert url != null; - File file = new File( url.getPath() ); - StringBuilder input = PomHelper.readXmlFile( file ); + File file = new File(url.getPath()); + StringBuilder input = PomHelper.readXmlFile(file); XMLInputFactory inputFactory = XMLInputFactory2.newInstance(); - inputFactory.setProperty( P_PRESERVE_LOCATION, Boolean.TRUE ); + inputFactory.setProperty(P_PRESERVE_LOCATION, Boolean.TRUE); - ModifiedPomXMLEventReader pom = new ModifiedPomXMLEventReader( input, inputFactory, file.getAbsolutePath() ); + ModifiedPomXMLEventReader pom = new ModifiedPomXMLEventReader(input, inputFactory, file.getAbsolutePath()); - String oldVersion = PomHelper.getProjectVersion( pom ); + String oldVersion = PomHelper.getProjectVersion(pom); String newVersion = "1"; - assertTrue( "The pom has been modified", PomHelper.setProjectVersion( pom, newVersion ) ); + assertTrue("The pom has been modified", PomHelper.setProjectVersion(pom, newVersion)); - assertEquals( newVersion, PomHelper.getProjectVersion( pom ) ); + assertEquals(newVersion, PomHelper.getProjectVersion(pom)); - assertNotSame( oldVersion, newVersion ); + assertNotSame(oldVersion, newVersion); } @Test - public void testGroupIdNotOnChildPom() - throws Exception - { - URL url = getClass().getResource( "PomHelperTest.noGroupIdOnChild.pom.xml" ); + public void testGroupIdNotOnChildPom() throws Exception { + URL url = getClass().getResource("PomHelperTest.noGroupIdOnChild.pom.xml"); assert url != null; - StringBuilder input = PomHelper.readXmlFile( new File( url.getPath() ) ); + StringBuilder input = PomHelper.readXmlFile(new File(url.getPath())); MavenXpp3Reader reader = new MavenXpp3Reader(); - Model model = reader.read( new StringReader( input.toString() ) ); + Model model = reader.read(new StringReader(input.toString())); - assertEquals( "org.myorg", PomHelper.getGroupId( model ) ); + assertEquals("org.myorg", PomHelper.getGroupId(model)); } @Test - public void testVersionVersionEqual() - throws Exception - { - assertTrue( PomHelper.isVersionOverlap( "1.0.8", "1.0.8" ) ); + public void testVersionVersionEqual() throws Exception { + assertTrue(PomHelper.isVersionOverlap("1.0.8", "1.0.8")); } @Test - public void testVersionVersionDiffer() - throws Exception - { - assertFalse( PomHelper.isVersionOverlap( "1.0.8", "1.0.0" ) ); + public void testVersionVersionDiffer() throws Exception { + assertFalse(PomHelper.isVersionOverlap("1.0.8", "1.0.0")); } @Test - public void testVersionRangeIntersect() - throws Exception - { - assertTrue( PomHelper.isVersionOverlap( "1.0.8", "[1.0.3,1.1.0]" ) ); + public void testVersionRangeIntersect() throws Exception { + assertTrue(PomHelper.isVersionOverlap("1.0.8", "[1.0.3,1.1.0]")); } @Test - public void testVersionRangeDisjoint() - throws Exception - { - assertFalse( PomHelper.isVersionOverlap( "1.0.8", "[0.0.1,1.0.0]" ) ); + public void testVersionRangeDisjoint() throws Exception { + assertFalse(PomHelper.isVersionOverlap("1.0.8", "[0.0.1,1.0.0]")); } @Test - public void testVersionLeftOpenRangeDisjoint() - throws Exception - { - assertFalse( PomHelper.isVersionOverlap( "1.0.8", "[,1.0.0]" ) ); + public void testVersionLeftOpenRangeDisjoint() throws Exception { + assertFalse(PomHelper.isVersionOverlap("1.0.8", "[,1.0.0]")); } @Test - public void testVersionRightOpenRangeDisjoint() - throws Exception - { - assertFalse( PomHelper.isVersionOverlap( "1.0.8", "[1.1.0,)" ) ); + public void testVersionRightOpenRangeDisjoint() throws Exception { + assertFalse(PomHelper.isVersionOverlap("1.0.8", "[1.1.0,)")); } @Test - public void testEmptyRange() - throws Exception - { - assertTrue( PomHelper.isVersionOverlap( "1.0.8", "" ) ); + public void testEmptyRange() throws Exception { + assertTrue(PomHelper.isVersionOverlap("1.0.8", "")); } @Test - public void testRangeEmpty() - throws Exception - { - assertTrue( PomHelper.isVersionOverlap( "[1.0.5,1.0.8]", "" ) ); + public void testRangeEmpty() throws Exception { + assertTrue(PomHelper.isVersionOverlap("[1.0.5,1.0.8]", "")); } @Test - public void testRangeRangeIntersect() - throws Exception - { - assertTrue( PomHelper.isVersionOverlap( "[1.0.5,1.0.8]", "[1.0.7,1.1.0]" ) ); - + public void testRangeRangeIntersect() throws Exception { + assertTrue(PomHelper.isVersionOverlap("[1.0.5,1.0.8]", "[1.0.7,1.1.0]")); } @Test - public void testRangeRangeDisjoint() - throws Exception - { - assertFalse( PomHelper.isVersionOverlap( "[1.0.5,1.0.6]", "[1.0.7,1.1.0]" ) ); - + public void testRangeRangeDisjoint() throws Exception { + assertFalse(PomHelper.isVersionOverlap("[1.0.5,1.0.6]", "[1.0.7,1.1.0]")); } @Test - public void testRangeVersionDisjoint() - throws Exception - { - assertFalse( PomHelper.isVersionOverlap( "[1.0.5,1.0.6]", "1.0.8" ) ); - + public void testRangeVersionDisjoint() throws Exception { + assertFalse(PomHelper.isVersionOverlap("[1.0.5,1.0.6]", "1.0.8")); } @Test - public void testRangeVersionIntersect() - throws Exception - { - assertTrue( PomHelper.isVersionOverlap( "[1.0.0,2.0.0]", "1.0.8" ) ); - + public void testRangeVersionIntersect() throws Exception { + assertTrue(PomHelper.isVersionOverlap("[1.0.0,2.0.0]", "1.0.8")); } @Test - public void testSetElementValueExistingValue() throws XMLStreamException - { + public void testSetElementValueExistingValue() throws XMLStreamException { ModifiedPomXMLEventReader xmlEventReader = new ModifiedPomXMLEventReader( - new StringBuilder( "test" ), - INPUT_FACTORY, null ); + new StringBuilder("test"), + INPUT_FACTORY, + null); - assertThat( PomHelper.setElementValue( xmlEventReader, "/super-parent/parent", - "child", "value" ), is( true ) ); - MatcherAssert.assertThat( xmlEventReader, - matches( "value" ) ); + assertThat(PomHelper.setElementValue(xmlEventReader, "/super-parent/parent", "child", "value"), is(true)); + MatcherAssert.assertThat( + xmlEventReader, matches("value")); } @Test - public void testSetElementValueEmptyChild() throws XMLStreamException - { + public void testSetElementValueEmptyChild() throws XMLStreamException { ModifiedPomXMLEventReader xmlEventReader = new ModifiedPomXMLEventReader( - new StringBuilder( "" ), INPUT_FACTORY, null ); + new StringBuilder(""), INPUT_FACTORY, null); - assertThat( PomHelper.setElementValue( xmlEventReader, "/super-parent/parent", - "child", "value" ), is( true ) ); - MatcherAssert.assertThat( xmlEventReader, - matches( "value" ) ); + assertThat(PomHelper.setElementValue(xmlEventReader, "/super-parent/parent", "child", "value"), is(true)); + MatcherAssert.assertThat( + xmlEventReader, matches("value")); } @Test - public void testSetElementValueNewValueEmptyParent() throws XMLStreamException - { + public void testSetElementValueNewValueEmptyParent() throws XMLStreamException { ModifiedPomXMLEventReader xmlEventReader = new ModifiedPomXMLEventReader( - new StringBuilder( "" ), INPUT_FACTORY, null ); + new StringBuilder(""), INPUT_FACTORY, null); - assertThat( PomHelper.setElementValue( xmlEventReader, "/super-parent/parent", - "child", "value" ), is( true ) ); - MatcherAssert.assertThat( xmlEventReader, - matches( "value" ) ); + assertThat(PomHelper.setElementValue(xmlEventReader, "/super-parent/parent", "child", "value"), is(true)); + MatcherAssert.assertThat( + xmlEventReader, matches("value")); } @Test - public void testSetElementValueNewValueNoChild() throws XMLStreamException - { + public void testSetElementValueNewValueNoChild() throws XMLStreamException { ModifiedPomXMLEventReader xmlEventReader = new ModifiedPomXMLEventReader( - new StringBuilder( "" ), INPUT_FACTORY, null ); + new StringBuilder(""), INPUT_FACTORY, null); - assertThat( PomHelper.setElementValue( xmlEventReader, "/super-parent/parent", - "child", "value" ), is( true ) ); - MatcherAssert.assertThat( xmlEventReader, - matches( "value" ) ); + assertThat(PomHelper.setElementValue(xmlEventReader, "/super-parent/parent", "child", "value"), is(true)); + MatcherAssert.assertThat( + xmlEventReader, matches("value")); } @Test - public void testSetProjectValueNewValueNonEmptyParent() throws XMLStreamException - { + public void testSetProjectValueNewValueNonEmptyParent() throws XMLStreamException { ModifiedPomXMLEventReader xmlEventReader = new ModifiedPomXMLEventReader( - new StringBuilder( "test" ), INPUT_FACTORY, - null ); + new StringBuilder("test"), + INPUT_FACTORY, + null); - assertThat( PomHelper.setElementValue( xmlEventReader, "/super-parent/parent", - "child", "value" ), is( true ) ); - MatcherAssert.assertThat( xmlEventReader, - matches( "value" ) ); + assertThat(PomHelper.setElementValue(xmlEventReader, "/super-parent/parent", "child", "value"), is(true)); + MatcherAssert.assertThat( + xmlEventReader, matches("value")); } @Test - public void testIssue505ChildModules() throws Exception - { - MavenProject project = mojoRule.readMavenProject( - new File( "src/test/resources/org/codehaus/mojo/versions/api/issue-505" ) ); - Map reactorModels = PomHelper.getReactorModels( project, new SystemStreamLog() ); - assertThat( reactorModels.keySet(), hasSize( 3 ) ); + public void testIssue505ChildModules() throws Exception { + MavenProject project = + mojoRule.readMavenProject(new File("src/test/resources/org/codehaus/mojo/versions/api/issue-505")); + Map reactorModels = PomHelper.getReactorModels(project, new SystemStreamLog()); + assertThat(reactorModels.keySet(), hasSize(3)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/DependencyFilterTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/DependencyFilterTest.java index 422323bebd..67678c23d9 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/DependencyFilterTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/DependencyFilterTest.java @@ -34,193 +34,132 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; -class DependencyFilterTest -{ +class DependencyFilterTest { @Nested - class RemoveFromTest - { - private final Set input = new HashSet<>( asList( - DependencyBuilder.dependencyWith( "foo", "bar", "1" ), - DependencyBuilder.dependencyWith( "localhost", "my-api", "2" ), - DependencyBuilder.dependencyWith( "localhost", "my-impl", "3" ) - ) ); + class RemoveFromTest { + private final Set input = new HashSet<>(asList( + DependencyBuilder.dependencyWith("foo", "bar", "1"), + DependencyBuilder.dependencyWith("localhost", "my-api", "2"), + DependencyBuilder.dependencyWith("localhost", "my-impl", "3"))); @Test - void removesExcludedDepsWithExactMatch() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( - Collections.singletonList( "localhost:my-impl:3" ) ); + void removesExcludedDepsWithExactMatch() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("localhost:my-impl:3")); - Set actual = exclusions.removingFrom( input ); + Set actual = exclusions.removingFrom(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "foo", "bar", "1" ), - HasGAVMatcher.hasGAV( "localhost", "my-api", "2" ) - ) - ); + actual, + Matchers.containsInAnyOrder( + HasGAVMatcher.hasGAV("foo", "bar", "1"), HasGAVMatcher.hasGAV("localhost", "my-api", "2"))); } @Test - void removesExcludedDepsWithWildcardInVersion() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( - Collections.singletonList( "localhost:my-impl:*" ) ); + void removesExcludedDepsWithWildcardInVersion() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("localhost:my-impl:*")); - Set actual = exclusions.removingFrom( input ); + Set actual = exclusions.removingFrom(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "foo", "bar", "1" ), - HasGAVMatcher.hasGAV( "localhost", "my-api", "2" ) - ) - ); + actual, + Matchers.containsInAnyOrder( + HasGAVMatcher.hasGAV("foo", "bar", "1"), HasGAVMatcher.hasGAV("localhost", "my-api", "2"))); } @Test - void removesExcludedDepsWithWildcardInGroupId() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( Collections.singletonList( "localhost:*:*" ) ); + void removesExcludedDepsWithWildcardInGroupId() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("localhost:*:*")); - Set actual = exclusions.removingFrom( input ); + Set actual = exclusions.removingFrom(input); - MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "foo", "bar", "1" ) - ) - ); + MatcherAssert.assertThat(actual, Matchers.containsInAnyOrder(HasGAVMatcher.hasGAV("foo", "bar", "1"))); } @Test - void removesExcludedDepsWithAllWildcards() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( Collections.singletonList( "*:*:*" ) ); + void removesExcludedDepsWithAllWildcards() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("*:*:*")); - Set actual = exclusions.removingFrom( input ); + Set actual = exclusions.removingFrom(input); - assertThat( - actual, - empty() - ); + assertThat(actual, empty()); } @Test - void removesMultiplePatterns() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( asList( - "*:my-api", - "*:my-impl" - ) ); + void removesMultiplePatterns() { + DependencyFilter exclusions = DependencyFilter.parseFrom(asList("*:my-api", "*:my-impl")); - Set actual = exclusions.removingFrom( input ); + Set actual = exclusions.removingFrom(input); - MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "foo", "bar", "1" ) - ) - ); + MatcherAssert.assertThat(actual, Matchers.containsInAnyOrder(HasGAVMatcher.hasGAV("foo", "bar", "1"))); } - } @Nested - class RetainingInTest - { - private final Set input = new HashSet<>( asList( - DependencyBuilder.dependencyWith( "foo", "bar", "1" ), - DependencyBuilder.dependencyWith( "localhost", "my-api", "2" ), - DependencyBuilder.dependencyWith( "localhost", "my-impl", "3" ) - ) ); + class RetainingInTest { + private final Set input = new HashSet<>(asList( + DependencyBuilder.dependencyWith("foo", "bar", "1"), + DependencyBuilder.dependencyWith("localhost", "my-api", "2"), + DependencyBuilder.dependencyWith("localhost", "my-impl", "3"))); @Test - void retainsOnlyDepsWithExactMatch() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( - Collections.singletonList( "localhost:my-impl:3" ) ); + void retainsOnlyDepsWithExactMatch() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("localhost:my-impl:3")); - Set actual = exclusions.retainingIn( input ); + Set actual = exclusions.retainingIn(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "localhost", "my-impl", "3" ) - ) - ); + actual, Matchers.containsInAnyOrder(HasGAVMatcher.hasGAV("localhost", "my-impl", "3"))); } @Test - void retainsOnlyDepsMatchingWildcardInVersion() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( - Collections.singletonList( "localhost:my-api:*" ) ); + void retainsOnlyDepsMatchingWildcardInVersion() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("localhost:my-api:*")); - Set actual = exclusions.retainingIn( input ); + Set actual = exclusions.retainingIn(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "localhost", "my-api", "2" ) - ) - ); + actual, Matchers.containsInAnyOrder(HasGAVMatcher.hasGAV("localhost", "my-api", "2"))); } @Test - void retainsOnlyDepsWithMultipleWildcards() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( Collections.singletonList( "localhost:my-*:*" ) ); + void retainsOnlyDepsWithMultipleWildcards() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("localhost:my-*:*")); - Set actual = exclusions.retainingIn( input ); + Set actual = exclusions.retainingIn(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "localhost", "my-api", "2" ), - HasGAVMatcher.hasGAV( "localhost", "my-impl", "3" ) - ) - ); + actual, + Matchers.containsInAnyOrder( + HasGAVMatcher.hasGAV("localhost", "my-api", "2"), + HasGAVMatcher.hasGAV("localhost", "my-impl", "3"))); } @Test - void retainsAllOnAllWildcards() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( Collections.singletonList( "*:*:*" ) ); + void retainsAllOnAllWildcards() { + DependencyFilter exclusions = DependencyFilter.parseFrom(Collections.singletonList("*:*:*")); - Set actual = exclusions.retainingIn( input ); + Set actual = exclusions.retainingIn(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "foo", "bar", "1" ), - HasGAVMatcher.hasGAV( "localhost", "my-api", "2" ), - HasGAVMatcher.hasGAV( "localhost", "my-impl", "3" ) - ) - ); + actual, + Matchers.containsInAnyOrder( + HasGAVMatcher.hasGAV("foo", "bar", "1"), + HasGAVMatcher.hasGAV("localhost", "my-api", "2"), + HasGAVMatcher.hasGAV("localhost", "my-impl", "3"))); } - @Test - void retainsMultiplePatterns() - { - DependencyFilter exclusions = DependencyFilter.parseFrom( asList( - "*:my-api", - "*:my-impl" - ) ); + void retainsMultiplePatterns() { + DependencyFilter exclusions = DependencyFilter.parseFrom(asList("*:my-api", "*:my-impl")); - Set actual = exclusions.retainingIn( input ); + Set actual = exclusions.retainingIn(input); MatcherAssert.assertThat( - actual, - Matchers.containsInAnyOrder( - HasGAVMatcher.hasGAV( "localhost", "my-api", "2" ), - HasGAVMatcher.hasGAV( "localhost", "my-impl", "3" ) - ) - ); + actual, + Matchers.containsInAnyOrder( + HasGAVMatcher.hasGAV("localhost", "my-api", "2"), + HasGAVMatcher.hasGAV("localhost", "my-impl", "3"))); } } - } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/HasGAVMatcher.java b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/HasGAVMatcher.java index e9dd54321f..07abd297f6 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/HasGAVMatcher.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/HasGAVMatcher.java @@ -28,42 +28,36 @@ /** * Hamcrest-Matcher that matches a {@link Dependency} GAV */ -public class HasGAVMatcher extends TypeSafeMatcher -{ +public class HasGAVMatcher extends TypeSafeMatcher { private final String groupId; private final String artifactId; private final String version; - public HasGAVMatcher( String groupId, String artifactId, String version ) - { + public HasGAVMatcher(String groupId, String artifactId, String version) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; } - public static HasGAVMatcher hasGAVOf( Dependency dependency ) - { - return hasGAV( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion() ); + public static HasGAVMatcher hasGAVOf(Dependency dependency) { + return hasGAV(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); } - public static HasGAVMatcher hasGAV( String groupId, String artifactId, String version ) - { - return new HasGAVMatcher( groupId, artifactId, version ); + public static HasGAVMatcher hasGAV(String groupId, String artifactId, String version) { + return new HasGAVMatcher(groupId, artifactId, version); } @Override - protected boolean matchesSafely( Dependency item ) - { - boolean result = Objects.equals( groupId, item.getGroupId() ) - && Objects.equals( artifactId, item.getArtifactId() ) - && Objects.equals( version, item.getVersion() ); + protected boolean matchesSafely(Dependency item) { + boolean result = Objects.equals(groupId, item.getGroupId()) + && Objects.equals(artifactId, item.getArtifactId()) + && Objects.equals(version, item.getVersion()); return result; } @Override - public void describeTo( Description description ) - { - description.appendText( String.format( "has GAV %s:%s:%s", groupId, artifactId, version ) ); + public void describeTo(Description description) { + description.appendText(String.format("has GAV %s:%s:%s", groupId, artifactId, version)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/TokenizedMatcherTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/TokenizedMatcherTest.java index 62dd78791c..a662ecabe7 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/TokenizedMatcherTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/TokenizedMatcherTest.java @@ -10,155 +10,116 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -class TokenizedMatcherTest -{ +class TokenizedMatcherTest { @Nested - class ExactMatchPattern - { - - private final TokenizedMatcher matcher = TokenizedMatcher - .parse( "group:artifact:1.0:jar:tests:compile" ); + class ExactMatchPattern { + private final TokenizedMatcher matcher = TokenizedMatcher.parse("group:artifact:1.0:jar:tests:compile"); @Test - void acceptsExactMatch() - { - Dependency input = DependencyBuilder.dependencyWith( - "group", - "artifact", - "1.0", - "jar", - "tests", - "compile" ); - - boolean actual = matcher.test( input ); - - assertTrue( actual ); - } + void acceptsExactMatch() { + Dependency input = DependencyBuilder.dependencyWith("group", "artifact", "1.0", "jar", "tests", "compile"); + boolean actual = matcher.test(input); + + assertTrue(actual); + } @ParameterizedTest - @CsvSource( { + @CsvSource({ "xxxxx, artifact, 1.0, jar, tests, compile", "group, xxxxxxxx, 1.0, jar, tests, compile", "group, artifact, xxx, jar, tests, compile", "group, artifact, 1.0, xxx, tests, compile", "group, artifact, 1.0, jar, xxxxx, compile", "group, artifact, 1.0, jar, tests, xxxxxxx", - } ) + }) void rejectsDifferingFields( - String group, String artifact, String version, String type, String classifier, String scope - ) - { + String group, String artifact, String version, String type, String classifier, String scope) { - Dependency input = DependencyBuilder.dependencyWith( - group, - artifact, - version, - type, - classifier, - scope ); + Dependency input = DependencyBuilder.dependencyWith(group, artifact, version, type, classifier, scope); - boolean actual = matcher.test( input ); + boolean actual = matcher.test(input); - assertFalse( actual ); + assertFalse(actual); } } @Nested - class WildcardPattern - { + class WildcardPattern { @Test - void acceptsWildcards() - { - Dependency input = DependencyBuilder.dependencyWith( - "foo", - "my-api", - "foo", - "foo", - "foo", - "foo" ); - - TokenizedMatcher matcher = TokenizedMatcher - .parse( "*:my-api" ); - - boolean actual = matcher.test( input ); - - assertTrue( actual ); + void acceptsWildcards() { + Dependency input = DependencyBuilder.dependencyWith("foo", "my-api", "foo", "foo", "foo", "foo"); + + TokenizedMatcher matcher = TokenizedMatcher.parse("*:my-api"); + + boolean actual = matcher.test(input); + + assertTrue(actual); } @Nested - class NullClassifier - { + class NullClassifier { private final DependencyBuilder depBuilder = DependencyBuilder.newBuilder() - .withGroupId( "foo" ) - .withArtifactId( "foo" ) - .withVersion( "foo" ) - .withType( "foo" ) - .withClassifier( "foo" ) - .withScope( "foo" ); + .withGroupId("foo") + .withArtifactId("foo") + .withVersion("foo") + .withType("foo") + .withClassifier("foo") + .withScope("foo"); - private final TokenizedMatcher matcher = TokenizedMatcher - .parse( "*:*:*:*:null:*" ); + private final TokenizedMatcher matcher = TokenizedMatcher.parse("*:*:*:*:null:*"); @Test - void acceptsNullScope() - { - Dependency input = depBuilder.withClassifier( null ).build(); + void acceptsNullScope() { + Dependency input = depBuilder.withClassifier(null).build(); - boolean actual = matcher.test( input ); + boolean actual = matcher.test(input); - assertTrue( actual ); + assertTrue(actual); } @Test - void rejectsNonnullScope() - { - Dependency input = depBuilder.withClassifier( "tests" ).build(); + void rejectsNonnullScope() { + Dependency input = depBuilder.withClassifier("tests").build(); - boolean actual = matcher.test( input ); + boolean actual = matcher.test(input); - assertFalse( actual ); + assertFalse(actual); } } @Nested - class NullScope - { + class NullScope { private final DependencyBuilder depBuilder = DependencyBuilder.newBuilder() - .withGroupId( "foo" ) - .withArtifactId( "foo" ) - .withVersion( "foo" ) - .withType( "foo" ) - .withClassifier( "foo" ) - .withScope( "foo" ); + .withGroupId("foo") + .withArtifactId("foo") + .withVersion("foo") + .withType("foo") + .withClassifier("foo") + .withScope("foo"); - private final TokenizedMatcher matcher = TokenizedMatcher - .parse( "*:*:*:*:*:null" ); + private final TokenizedMatcher matcher = TokenizedMatcher.parse("*:*:*:*:*:null"); @Test - void acceptsNullScope() - { - Dependency input = depBuilder.withScope( null ).build(); + void acceptsNullScope() { + Dependency input = depBuilder.withScope(null).build(); - boolean actual = matcher.test( input ); + boolean actual = matcher.test(input); - assertTrue( actual ); + assertTrue(actual); } @Test - void rejectsNonnullScope() - { - Dependency input = depBuilder.withScope( "compile" ).build(); + void rejectsNonnullScope() { + Dependency input = depBuilder.withScope("compile").build(); - boolean actual = matcher.test( input ); + boolean actual = matcher.test(input); - assertFalse( actual ); + assertFalse(actual); } } - } - } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/WildcardMatcherTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/WildcardMatcherTest.java index c6b4717cba..1b072b11c1 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/WildcardMatcherTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/filtering/WildcardMatcherTest.java @@ -8,258 +8,219 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -class WildcardMatcherTest -{ +class WildcardMatcherTest { @Nested - class ExactValueTest - { - private final WildcardMatcher matcher = WildcardMatcher.parse( "asdf" ); + class ExactValueTest { + private final WildcardMatcher matcher = WildcardMatcher.parse("asdf"); @Test - void matchesTheExactInput() - { - boolean actual = matcher.test( "asdf" ); + void matchesTheExactInput() { + boolean actual = matcher.test("asdf"); - assertTrue( actual ); + assertTrue(actual); } @Test - void rejectsNull() - { - boolean actual = matcher.test( null ); + void rejectsNull() { + boolean actual = matcher.test(null); - assertFalse( actual ); + assertFalse(actual); } @ParameterizedTest - @ValueSource( strings = { - "", - " ", - "a", - "as", - "asf", - "asXf", - "asdfx", - } ) - void rejectsDifferentInput( String input ) - { - boolean actual = matcher.test( input ); - - assertFalse( actual ); + @ValueSource( + strings = { + "", " ", "a", "as", "asf", "asXf", "asdfx", + }) + void rejectsDifferentInput(String input) { + boolean actual = matcher.test(input); + + assertFalse(actual); } } @Nested - class WildcardOnlyPattern - { - private final WildcardMatcher matcher = WildcardMatcher.parse( "*" ); + class WildcardOnlyPattern { + private final WildcardMatcher matcher = WildcardMatcher.parse("*"); @Test - void acceptsNull() - { - boolean actual = matcher.test( null ); + void acceptsNull() { + boolean actual = matcher.test(null); - assertTrue( actual ); + assertTrue(actual); } - @ParameterizedTest - @ValueSource( strings = { - "", - " ", - "a", - "asdfx", - } ) - void accepts( String input ) - { - boolean actual = matcher.test( input ); - - assertTrue( actual ); - } + @ValueSource( + strings = { + "", " ", "a", "asdfx", + }) + void accepts(String input) { + boolean actual = matcher.test(input); + assertTrue(actual); + } } - @Nested - class PatternWithWildcardAtStartAndEnd - { - private final WildcardMatcher matcher = WildcardMatcher.parse( "*asdf*" ); + class PatternWithWildcardAtStartAndEnd { + private final WildcardMatcher matcher = WildcardMatcher.parse("*asdf*"); @Test - void rejectsNull() - { - boolean actual = matcher.test( null ); + void rejectsNull() { + boolean actual = matcher.test(null); - assertFalse( actual ); + assertFalse(actual); } - @ParameterizedTest - @ValueSource( strings = { - "asdf", - "fooasdf", - "asdfbar", - "fooasdfbar", - " asdf", - "asdf ", - " asdf ", - } ) - void accepts( String input ) - { - boolean actual = matcher.test( input ); - - assertTrue( actual ); + @ValueSource( + strings = { + "asdf", + "fooasdf", + "asdfbar", + "fooasdfbar", + " asdf", + "asdf ", + " asdf ", + }) + void accepts(String input) { + boolean actual = matcher.test(input); + + assertTrue(actual); } @ParameterizedTest - @ValueSource( strings = { - "", - " ", - "foo", - } ) - void rejects( String input ) - { - boolean actual = matcher.test( input ); - - assertFalse( actual ); - } + @ValueSource( + strings = { + "", " ", "foo", + }) + void rejects(String input) { + boolean actual = matcher.test(input); + assertFalse(actual); + } } @Nested - class PatternStartingWithWildcard - { - private final WildcardMatcher matcher = WildcardMatcher.parse( "*asdf" ); + class PatternStartingWithWildcard { + private final WildcardMatcher matcher = WildcardMatcher.parse("*asdf"); @Test - void rejectsNull() - { - boolean actual = matcher.test( null ); + void rejectsNull() { + boolean actual = matcher.test(null); - assertFalse( actual ); + assertFalse(actual); } - @ParameterizedTest - @ValueSource( strings = { - "asdf", - "asdfasdf", - " asdf", - "Xasdf", - "99999999asdf", - } ) - void accepts( String input ) - { - boolean actual = matcher.test( input ); - - assertTrue( actual ); + @ValueSource( + strings = { + "asdf", + "asdfasdf", + " asdf", + "Xasdf", + "99999999asdf", + }) + void accepts(String input) { + boolean actual = matcher.test(input); + + assertTrue(actual); } @ParameterizedTest - @ValueSource( strings = { - "", - " ", - "asdf ", - "asdfx", - "asdfbanana", - } ) - void rejects( String input ) - { - boolean actual = matcher.test( input ); - - assertFalse( actual ); + @ValueSource( + strings = { + "", + " ", + "asdf ", + "asdfx", + "asdfbanana", + }) + void rejects(String input) { + boolean actual = matcher.test(input); + + assertFalse(actual); } - } @Nested - class PatternEndingWithWildcard - { - private final WildcardMatcher matcher = WildcardMatcher.parse( "asdf*" ); + class PatternEndingWithWildcard { + private final WildcardMatcher matcher = WildcardMatcher.parse("asdf*"); @Test - void rejectsNull() - { - boolean actual = matcher.test( null ); + void rejectsNull() { + boolean actual = matcher.test(null); - assertFalse( actual ); + assertFalse(actual); } - @ParameterizedTest - @ValueSource( strings = { - "asdf", - "asdfasdf", - "asdf ", - "asdfx", - "asdfbanana", - } ) - void accepts( String input ) - { - boolean actual = matcher.test( input ); - - assertTrue( actual ); + @ValueSource( + strings = { + "asdf", + "asdfasdf", + "asdf ", + "asdfx", + "asdfbanana", + }) + void accepts(String input) { + boolean actual = matcher.test(input); + + assertTrue(actual); } @ParameterizedTest - @ValueSource( strings = { - "", - " ", - " asdf", - "Xasdf", - "99999999asdf", - } ) - void rejects( String input ) - { - boolean actual = matcher.test( input ); - - assertFalse( actual ); + @ValueSource( + strings = { + "", + " ", + " asdf", + "Xasdf", + "99999999asdf", + }) + void rejects(String input) { + boolean actual = matcher.test(input); + + assertFalse(actual); } - } @Nested - class PatternWithVersionRange - { - private final WildcardMatcher matcher = WildcardMatcher.parse( "[2.0,3.0]" ); + class PatternWithVersionRange { + private final WildcardMatcher matcher = WildcardMatcher.parse("[2.0,3.0]"); @Test - void rejectsNull() - { - boolean actual = matcher.test( null ); + void rejectsNull() { + boolean actual = matcher.test(null); - assertFalse( actual ); + assertFalse(actual); } - @ParameterizedTest - @ValueSource( strings = { - "2.0", - "2.1", - "3.0", - } ) - void accepts( String input ) - { - boolean actual = matcher.test( input ); - - assertTrue( actual ); + @ValueSource( + strings = { + "2.0", "2.1", "3.0", + }) + void accepts(String input) { + boolean actual = matcher.test(input); + + assertTrue(actual); } @ParameterizedTest - @ValueSource( strings = { - "", - " ", - "1.0", - "2.0-SNAPSHOT", - "4.0", - } ) - void rejects( String input ) - { - boolean actual = matcher.test( input ); - - assertFalse( actual ); + @ValueSource( + strings = { + "", + " ", + "1.0", + "2.0-SNAPSHOT", + "4.0", + }) + void rejects(String input) { + boolean actual = matcher.test(input); + + assertFalse(actual); } - } - } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersionTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersionTest.java index 32b4f3db14..a172eac1d7 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersionTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/BoundArtifactVersionTest.java @@ -33,77 +33,60 @@ /** * Unit tests for {@link BoundArtifactVersion} */ -public class BoundArtifactVersionTest -{ +public class BoundArtifactVersionTest { @Test - public void testMajorUpperBoundGreaterThanNextMajor() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.2.3" ), - MAJOR ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "2.0.0" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testMajorUpperBoundGreaterThanNextMajor() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.2.3"), MAJOR); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("2.0.0"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } @Test - public void testSubIncrementalUpperBoundGreaterThanNextSubIncremental() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.2.3-2" ), - SUBINCREMENTAL ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.2.3-3" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testSubIncrementalUpperBoundGreaterThanNextSubIncremental() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.2.3-2"), SUBINCREMENTAL); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.2.3-3"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } @Test - public void testVersionShorterThanSegment() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.1" ), - INCREMENTAL ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.1.3" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testVersionShorterThanSegment() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.1"), INCREMENTAL); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.1.3"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } @Test - public void testVersionBoundArtifactVersionShorterThanConcreteVersionAndSegment() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.1" ), - SUBINCREMENTAL ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.1.3" ); - assertThat( bound.compareTo( artifactVersion ), lessThan( 0 ) ); + public void testVersionBoundArtifactVersionShorterThanConcreteVersionAndSegment() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.1"), SUBINCREMENTAL); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.1.3"); + assertThat(bound.compareTo(artifactVersion), lessThan(0)); } @Test - public void testVersionSubIncrementalBoundGreaterThanSubIncremental() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.1" ), - SUBINCREMENTAL ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.1.0-2" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testVersionSubIncrementalBoundGreaterThanSubIncremental() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.1"), SUBINCREMENTAL); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.1.0-2"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } @Test - public void testVersionSubIncrementalBoundGreaterThanIncremental() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.1" ), - INCREMENTAL ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.1.3" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testVersionSubIncrementalBoundGreaterThanIncremental() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.1"), INCREMENTAL); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.1.3"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } @Test - public void testVersionSubIncrementalBoundGreaterThanMinor() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.1" ), - MINOR ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.3" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testVersionSubIncrementalBoundGreaterThanMinor() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.1"), MINOR); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.3"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } @Test - public void testSnapshotWithSubIncremental() - { - BoundArtifactVersion bound = new BoundArtifactVersion( new DefaultArtifactVersion( "1.0.0-SNAPSHOT" ), - MINOR ); - ArtifactVersion artifactVersion = new DefaultArtifactVersion( "1.0.0" ); - assertThat( bound.compareTo( artifactVersion ), greaterThan( 0 ) ); + public void testSnapshotWithSubIncremental() { + BoundArtifactVersion bound = new BoundArtifactVersion(new DefaultArtifactVersion("1.0.0-SNAPSHOT"), MINOR); + ArtifactVersion artifactVersion = new DefaultArtifactVersion("1.0.0"); + assertThat(bound.compareTo(artifactVersion), greaterThan(0)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MavenVersionComparatorTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MavenVersionComparatorTest.java index 452ef34786..1a072c2dc5 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MavenVersionComparatorTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MavenVersionComparatorTest.java @@ -29,54 +29,49 @@ import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.Is.is; -public class MavenVersionComparatorTest extends VersionComparatorTestBase -{ - public MavenVersionComparatorTest() - { - super( new MavenVersionComparator() ); +public class MavenVersionComparatorTest extends VersionComparatorTestBase { + public MavenVersionComparatorTest() { + super(new MavenVersionComparator()); } @Test - public void testSegmentCounting() - { - assertThat( 3, is( instance.getSegmentCount( version( "5" ) ) ) ); - assertThat( 3, is( instance.getSegmentCount( version( "5.0" ) ) ) ); - assertThat( 4, is( instance.getSegmentCount( version( "5-0" ) ) ) ); - assertThat( 1, is( instance.getSegmentCount( version( "5.3.a" ) ) ) ); - assertThat( 1, is( instance.getSegmentCount( version( "5.0.a.1.4.5" ) ) ) ); - assertThat( 3, is( instance.getSegmentCount( version( "" ) ) ) ); + public void testSegmentCounting() { + assertThat(3, is(instance.getSegmentCount(version("5")))); + assertThat(3, is(instance.getSegmentCount(version("5.0")))); + assertThat(4, is(instance.getSegmentCount(version("5-0")))); + assertThat(1, is(instance.getSegmentCount(version("5.3.a")))); + assertThat(1, is(instance.getSegmentCount(version("5.0.a.1.4.5")))); + assertThat(3, is(instance.getSegmentCount(version("")))); } @Test - public void testUpperBoundaryCustom() - { - assertThat( instance.compare( new BoundArtifactVersion( version( "1.2.3" ), - INCREMENTAL ), version( "1.2.3-ANDRZEJ" ) ), greaterThan( 0 ) ); + public void testUpperBoundaryCustom() { + assertThat( + instance.compare(new BoundArtifactVersion(version("1.2.3"), INCREMENTAL), version("1.2.3-ANDRZEJ")), + greaterThan(0)); } @Test - public void testUpperBoundaryRelease() - { - assertThat( instance.compare( new BoundArtifactVersion( version( "1.1.0" ), - INCREMENTAL ), version( "1.1.0" ) ), greaterThan( 0 ) ); + public void testUpperBoundaryRelease() { + assertThat( + instance.compare(new BoundArtifactVersion(version("1.1.0"), INCREMENTAL), version("1.1.0")), + greaterThan(0)); } @Test - public void testUpperBoundarySnapshot() - { - assertThat( instance.compare( new BoundArtifactVersion( version( "1.1.0" ), - INCREMENTAL ), version( "1.1.0-SNAPSHOT" ) ), greaterThan( 0 ) ); + public void testUpperBoundarySnapshot() { + assertThat( + instance.compare(new BoundArtifactVersion(version("1.1.0"), INCREMENTAL), version("1.1.0-SNAPSHOT")), + greaterThan(0)); } @Test - public void testScopeLessThanNumSegmentsUpper() - { - ArtifactVersion artifactVersion = new BoundArtifactVersion( version( "1.1" ), - SUBINCREMENTAL ); - assertThat( artifactVersion.compareTo( version( "1.0.1" ) ), greaterThan( 0 ) ); - assertThat( artifactVersion.compareTo( version( "1.1-SNAPSHOT" ) ), greaterThan( 0 ) ); - assertThat( artifactVersion.compareTo( version( "1.1" ) ), greaterThan( 0 ) ); - assertThat( artifactVersion.compareTo( version( "1.1.0-2" ) ), greaterThan( 0 ) ); - assertThat( artifactVersion.compareTo( version( "1.1.1-2" ) ), lessThan( 0 ) ); + public void testScopeLessThanNumSegmentsUpper() { + ArtifactVersion artifactVersion = new BoundArtifactVersion(version("1.1"), SUBINCREMENTAL); + assertThat(artifactVersion.compareTo(version("1.0.1")), greaterThan(0)); + assertThat(artifactVersion.compareTo(version("1.1-SNAPSHOT")), greaterThan(0)); + assertThat(artifactVersion.compareTo(version("1.1")), greaterThan(0)); + assertThat(artifactVersion.compareTo(version("1.1.0-2")), greaterThan(0)); + assertThat(artifactVersion.compareTo(version("1.1.1-2")), lessThan(0)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparatorTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparatorTest.java index 9af7bbc4c6..f5e8683cba 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparatorTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/MercuryVersionComparatorTest.java @@ -24,23 +24,18 @@ import static org.junit.Assert.assertEquals; -public class MercuryVersionComparatorTest extends VersionComparatorTestBase -{ - public MercuryVersionComparatorTest() - { - super( new MercuryVersionComparator() ); +public class MercuryVersionComparatorTest extends VersionComparatorTestBase { + public MercuryVersionComparatorTest() { + super(new MercuryVersionComparator()); } @Test - public void testSegmentCounting() - { - assertEquals( 1, instance.getSegmentCount( new DefaultArtifactVersion( "5" ) ) ); - assertEquals( 2, instance.getSegmentCount( new DefaultArtifactVersion( "5.0" ) ) ); - assertEquals( 2, instance.getSegmentCount( new DefaultArtifactVersion( "5-0" ) ) ); - assertEquals( 3, instance.getSegmentCount( new DefaultArtifactVersion( "5.3.a" ) ) ); - assertEquals( 6, instance.getSegmentCount( new DefaultArtifactVersion( "5.0.a.1.4.5" ) ) ); - assertEquals( 0, instance.getSegmentCount( new DefaultArtifactVersion( "" ) ) ); + public void testSegmentCounting() { + assertEquals(1, instance.getSegmentCount(new DefaultArtifactVersion("5"))); + assertEquals(2, instance.getSegmentCount(new DefaultArtifactVersion("5.0"))); + assertEquals(2, instance.getSegmentCount(new DefaultArtifactVersion("5-0"))); + assertEquals(3, instance.getSegmentCount(new DefaultArtifactVersion("5.3.a"))); + assertEquals(6, instance.getSegmentCount(new DefaultArtifactVersion("5.0.a.1.4.5"))); + assertEquals(0, instance.getSegmentCount(new DefaultArtifactVersion(""))); } - - } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/NumericVersionComparatorTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/NumericVersionComparatorTest.java index 3b858ee5d4..1200442d7c 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/NumericVersionComparatorTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/NumericVersionComparatorTest.java @@ -25,87 +25,77 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class NumericVersionComparatorTest extends VersionComparatorTestBase -{ - public NumericVersionComparatorTest() - { - super( new NumericVersionComparator() ); +public class NumericVersionComparatorTest extends VersionComparatorTestBase { + public NumericVersionComparatorTest() { + super(new NumericVersionComparator()); } - private int instanceCompare( String v1, String v2 ) - { - return instance.compare( new DefaultArtifactVersion( v1 ), new DefaultArtifactVersion( v2 ) ); + private int instanceCompare(String v1, String v2) { + return instance.compare(new DefaultArtifactVersion(v1), new DefaultArtifactVersion(v2)); } @Test - public void testSmokes() - { - assertTrue( instanceCompare( "1.0.0.0.0", "1.0.0.0.1" ) < 0 ); - assertTrue( instanceCompare( "1.0.0.0.0", "2.0.0.0.1" ) < 0 ); - assertTrue( instanceCompare( "1.0.0.0.0", "1.0.0.0" ) < 0 ); - assertTrue( instanceCompare( "1.0.0.0.0", "1.0.0.0.0" ) == 0 ); - assertTrue( instanceCompare( "1.0.0.0", "1.0.0.0.0" ) > 0 ); + public void testSmokes() { + assertTrue(instanceCompare("1.0.0.0.0", "1.0.0.0.1") < 0); + assertTrue(instanceCompare("1.0.0.0.0", "2.0.0.0.1") < 0); + assertTrue(instanceCompare("1.0.0.0.0", "1.0.0.0") < 0); + assertTrue(instanceCompare("1.0.0.0.0", "1.0.0.0.0") == 0); + assertTrue(instanceCompare("1.0.0.0", "1.0.0.0.0") > 0); } @Test - public void testBigValues() - { - assertTrue( instanceCompare( "1.92.0", "1.100000000000000000000000.0" ) < 0 ); - assertTrue( instanceCompare( "1.100000000000000000000000.0", "1.92.0" ) > 0 ); - assertTrue( instanceCompare( "1.100000000000000000000000.0", "1.100000000000000000000000.0" ) == 0 ); + public void testBigValues() { + assertTrue(instanceCompare("1.92.0", "1.100000000000000000000000.0") < 0); + assertTrue(instanceCompare("1.100000000000000000000000.0", "1.92.0") > 0); + assertTrue(instanceCompare("1.100000000000000000000000.0", "1.100000000000000000000000.0") == 0); } @Test - public void testStringValues() - { - assertTrue( instanceCompare( "1.a20.0", "1.a3.0" ) < 0 ); - assertTrue( instanceCompare( "1.a20.0", "1.b10.0" ) < 0 ); - assertTrue( instanceCompare( "1.a.0.b.0", "1.a.0.b.1" ) < 0 ); - assertTrue( instanceCompare( "1.162%a.0.b.0", "1.162%a.0.b.1" ) < 0 ); - assertTrue( instanceCompare( "1.162%a.0.b.0", "1.2.0.b.1" ) < 0 ); - assertTrue( instanceCompare( "1.0a.0.b.0", "1.162%.0.b.1" ) < 0 ); - assertTrue( instanceCompare( "1.a.0.b.0", "2.a.0.b.1" ) < 0 ); - assertTrue( instanceCompare( "1.a.0.b.0", "1.a.0.b" ) < 0 ); - assertTrue( instanceCompare( "1.a.0.b.0", "1.a.0.b.0" ) == 0 ); - assertTrue( instanceCompare( "1.a.0.b", "1.a.0.b.0" ) > 0 ); - assertTrue( instanceCompare( "1.a.0.0", "1.a.0" ) < 0 ); - assertTrue( instanceCompare( "1.a.0", "1.a.0.0" ) > 0 ); - assertTrue( instanceCompare( "1.a.0.1", "1.a.0" ) > 0 ); - assertTrue( instanceCompare( "1.a.0", "1.a.0.1" ) < 0 ); - assertTrue( instanceCompare( "1.a.0.b", "1.a.0" ) > 0 ); - assertTrue( instanceCompare( "1.a.0", "1.a.0.b" ) < 0 ); + public void testStringValues() { + assertTrue(instanceCompare("1.a20.0", "1.a3.0") < 0); + assertTrue(instanceCompare("1.a20.0", "1.b10.0") < 0); + assertTrue(instanceCompare("1.a.0.b.0", "1.a.0.b.1") < 0); + assertTrue(instanceCompare("1.162%a.0.b.0", "1.162%a.0.b.1") < 0); + assertTrue(instanceCompare("1.162%a.0.b.0", "1.2.0.b.1") < 0); + assertTrue(instanceCompare("1.0a.0.b.0", "1.162%.0.b.1") < 0); + assertTrue(instanceCompare("1.a.0.b.0", "2.a.0.b.1") < 0); + assertTrue(instanceCompare("1.a.0.b.0", "1.a.0.b") < 0); + assertTrue(instanceCompare("1.a.0.b.0", "1.a.0.b.0") == 0); + assertTrue(instanceCompare("1.a.0.b", "1.a.0.b.0") > 0); + assertTrue(instanceCompare("1.a.0.0", "1.a.0") < 0); + assertTrue(instanceCompare("1.a.0", "1.a.0.0") > 0); + assertTrue(instanceCompare("1.a.0.1", "1.a.0") > 0); + assertTrue(instanceCompare("1.a.0", "1.a.0.1") < 0); + assertTrue(instanceCompare("1.a.0.b", "1.a.0") > 0); + assertTrue(instanceCompare("1.a.0", "1.a.0.b") < 0); } @Test - public void testQualifiers() - { - assertTrue( instanceCompare( "1.0-alpha.10", "1.0-alpha.20" ) < 0 ); - assertTrue( instanceCompare( "1.0-alpha.10", "1.0-beta.1" ) < 0 ); - assertTrue( instanceCompare( "1.0", "1.0-alpha.2" ) > 0 ); - assertTrue( instanceCompare( "1.0-alpha.10", "1.0" ) < 0 ); - assertTrue( instanceCompare( "1.0.10", "1.0-alpha.10" ) > 0 ); + public void testQualifiers() { + assertTrue(instanceCompare("1.0-alpha.10", "1.0-alpha.20") < 0); + assertTrue(instanceCompare("1.0-alpha.10", "1.0-beta.1") < 0); + assertTrue(instanceCompare("1.0", "1.0-alpha.2") > 0); + assertTrue(instanceCompare("1.0-alpha.10", "1.0") < 0); + assertTrue(instanceCompare("1.0.10", "1.0-alpha.10") > 0); } @Test - public void testSegmentCounting() - { - assertEquals( 1, instance.getSegmentCount( new DefaultArtifactVersion( "5" ) ) ); - assertEquals( 2, instance.getSegmentCount( new DefaultArtifactVersion( "5.0" ) ) ); - assertEquals( 1, instance.getSegmentCount( new DefaultArtifactVersion( "5-0" ) ) ); - assertEquals( 3, instance.getSegmentCount( new DefaultArtifactVersion( "5.3.a" ) ) ); - assertEquals( 6, instance.getSegmentCount( new DefaultArtifactVersion( "5.0.a.1.4.5" ) ) ); - assertEquals( 0, instance.getSegmentCount( new DefaultArtifactVersion( "" ) ) ); + public void testSegmentCounting() { + assertEquals(1, instance.getSegmentCount(new DefaultArtifactVersion("5"))); + assertEquals(2, instance.getSegmentCount(new DefaultArtifactVersion("5.0"))); + assertEquals(1, instance.getSegmentCount(new DefaultArtifactVersion("5-0"))); + assertEquals(3, instance.getSegmentCount(new DefaultArtifactVersion("5.3.a"))); + assertEquals(6, instance.getSegmentCount(new DefaultArtifactVersion("5.0.a.1.4.5"))); + assertEquals(0, instance.getSegmentCount(new DefaultArtifactVersion(""))); } @Override - public void testVersionComparatorRow5() - { + public void testVersionComparatorRow5() { // non-numeric -- does not apply } @Override - public void testVersionComparatorRow6() - { + public void testVersionComparatorRow6() { // non-numeric -- does not apply } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/VersionComparatorTestBase.java b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/VersionComparatorTestBase.java index 28e326a2ec..69a71510f7 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/VersionComparatorTestBase.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/ordering/VersionComparatorTestBase.java @@ -29,72 +29,62 @@ * Abstract base class for {@link MavenVersionComparatorTest}, {@link MercuryVersionComparatorTest}, * and {@link NumericVersionComparatorTest} */ -public abstract class VersionComparatorTestBase -{ +public abstract class VersionComparatorTestBase { protected final VersionComparator instance; - public VersionComparatorTestBase( VersionComparator instance ) - { + public VersionComparatorTestBase(VersionComparator instance) { this.instance = instance; } - protected static ArtifactVersion version( String version ) - { - return new DefaultArtifactVersion( version ); + protected static ArtifactVersion version(String version) { + return new DefaultArtifactVersion(version); } @Test - public void testVersionComparatorRow1() - { - assertThat( instance.compare( version( "1" ), version( "2" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0" ), version( "2.0" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0" ), version( "1.1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0" ), version( "1.1" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow1() { + assertThat(instance.compare(version("1"), version("2")), lessThan(0)); + assertThat(instance.compare(version("1.0"), version("2.0")), lessThan(0)); + assertThat(instance.compare(version("1.0"), version("1.1")), lessThan(0)); + assertThat(instance.compare(version("1.0"), version("1.1")), lessThan(0)); } @Test - public void testVersionComparatorRow2() - { - assertThat( instance.compare( version( "1.0" ), version( "2.0" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0" ), version( "1.1" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow2() { + assertThat(instance.compare(version("1.0"), version("2.0")), lessThan(0)); + assertThat(instance.compare(version("1.0"), version("1.1")), lessThan(0)); } @Test - public void testVersionComparatorRow3() - { - assertThat( instance.compare( version( "1.0.0" ), version( "2.0.0" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0" ), version( "1.1.0" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0" ), version( "1.0.1" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow3() { + assertThat(instance.compare(version("1.0.0"), version("2.0.0")), lessThan(0)); + assertThat(instance.compare(version("1.0.0"), version("1.1.0")), lessThan(0)); + assertThat(instance.compare(version("1.0.0"), version("1.0.1")), lessThan(0)); } @Test - public void testVersionComparatorRow4() - { - assertThat( instance.compare( version( "1.0.0-1" ), version( "2.0.0-1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0-1" ), version( "1.1.0-1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0-1" ), version( "1.0.1-1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0-1" ), version( "1.0.0-2" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow4() { + assertThat(instance.compare(version("1.0.0-1"), version("2.0.0-1")), lessThan(0)); + assertThat(instance.compare(version("1.0.0-1"), version("1.1.0-1")), lessThan(0)); + assertThat(instance.compare(version("1.0.0-1"), version("1.0.1-1")), lessThan(0)); + assertThat(instance.compare(version("1.0.0-1"), version("1.0.0-2")), lessThan(0)); } @Test - public void testVersionComparatorRow5() - { - assertThat( instance.compare( version( "1.0.0-sp1" ), version( "2.0.0-sp1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0-sp1" ), version( "1.1.0-sp1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0-sp1" ), version( "1.0.1-sp1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1.0.0-sp1" ), version( "1.0.0-1-sp1" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow5() { + assertThat(instance.compare(version("1.0.0-sp1"), version("2.0.0-sp1")), lessThan(0)); + assertThat(instance.compare(version("1.0.0-sp1"), version("1.1.0-sp1")), lessThan(0)); + assertThat(instance.compare(version("1.0.0-sp1"), version("1.0.1-sp1")), lessThan(0)); + assertThat(instance.compare(version("1.0.0-sp1"), version("1.0.0-1-sp1")), lessThan(0)); } @Test - public void testVersionComparatorRow6() - { - assertThat( instance.compare( version( "foobar" ), version( "foobar-1" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow6() { + assertThat(instance.compare(version("foobar"), version("foobar-1")), lessThan(0)); } @Test - public void testVersionComparatorRow7() - { - assertThat( instance.compare( version( "1-alpha-1" ), version( "2-alpha-1" ) ), lessThan( 0 ) ); - assertThat( instance.compare( version( "1-alpha-1" ), version( "1-alpha-2" ) ), lessThan( 0 ) ); + public void testVersionComparatorRow7() { + assertThat(instance.compare(version("1-alpha-1"), version("2-alpha-1")), lessThan(0)); + assertThat(instance.compare(version("1-alpha-1"), version("1-alpha-2")), lessThan(0)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/recording/ChangeRecorderXMLTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/recording/ChangeRecorderXMLTest.java index b852179d1b..7d49e2bcd6 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/recording/ChangeRecorderXMLTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/recording/ChangeRecorderXMLTest.java @@ -38,89 +38,86 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -public final class ChangeRecorderXMLTest -{ - private static void copyResource( final String name, final Path output ) throws IOException - { - try ( InputStream inputStream = ChangeRecorderXMLTest.class.getResourceAsStream( name ) ) - { - Files.copy( inputStream, output, StandardCopyOption.REPLACE_EXISTING ); +public final class ChangeRecorderXMLTest { + private static void copyResource(final String name, final Path output) throws IOException { + try (InputStream inputStream = ChangeRecorderXMLTest.class.getResourceAsStream(name)) { + Files.copy(inputStream, output, StandardCopyOption.REPLACE_EXISTING); } } - private static Document parseXML( final Path path ) throws ParserConfigurationException, IOException, SAXException - { + private static Document parseXML(final Path path) throws ParserConfigurationException, IOException, SAXException { final DocumentBuilderFactory documentBuilders = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder = documentBuilders.newDocumentBuilder(); - return documentBuilder.parse( path.toFile() ); + return documentBuilder.parse(path.toFile()); } @Test - public void testChanges() throws Exception - { - final Path path0 = Files.createTempFile( "ChangeRecorderTest", ".xml" ); - final Path path1 = Files.createTempDirectory( "ChangeRecorderTest" ) - .resolve( "subDirectory" ) - .resolve( "ChangeRecorderTest.xml" ); + public void testChanges() throws Exception { + final Path path0 = Files.createTempFile("ChangeRecorderTest", ".xml"); + final Path path1 = Files.createTempDirectory("ChangeRecorderTest") + .resolve("subDirectory") + .resolve("ChangeRecorderTest.xml"); - copyResource( "expectedFile.xml", path0 ); + copyResource("expectedFile.xml", path0); final ChangeRecorder recorder = new ChangeRecorderXML(); - recorder.recordChange( DefaultChangeRecord.builder() - .withKind( ChangeRecord.ChangeKind.DEPENDENCY ) - .withGroupId( "org.codehaus" ) - .withArtifactId( "example0" ) - .withOldVersion( "0.0.1" ) - .withNewVersion( "0.0.2" ) - .build() ); - - recorder.recordChange( DefaultChangeRecord.builder() - .withKind( ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ) - .withGroupId( "org.codehaus" ) - .withArtifactId( "example1" ) - .withOldVersion( "1.0.0" ) - .withNewVersion( "2.0.0" ) - .build() ); - - recorder.writeReport( path1 ); - - final Document document0 = parseXML( path0 ); - final Document document1 = parseXML( path1 ); - - final NodeList elements0 = document0.getElementsByTagNameNS( ChangeRecorderXML.CHANGES_NAMESPACE, "updated" ); - final NodeList elements1 = document1.getElementsByTagNameNS( ChangeRecorderXML.CHANGES_NAMESPACE, "updated" ); - - Assert.assertEquals( "Correct number of updates", elements0.getLength(), elements1.getLength() ); - - for ( int index = 0; index < elements0.getLength(); ++index ) - { - final Element element0 = (Element) elements0.item( index ); - final Element element1 = (Element) elements1.item( index ); - - Assert.assertEquals( element0.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "artifactId" ), - element1.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "artifactId" ) ); - Assert.assertEquals( element0.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "groupId" ), - element1.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "groupId" ) ); - Assert.assertEquals( element0.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "oldVersion" ), - element1.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "oldVersion" ) ); - Assert.assertEquals( element0.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "newVersion" ), - element1.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "newVersion" ) ); + recorder.recordChange(DefaultChangeRecord.builder() + .withKind(ChangeRecord.ChangeKind.DEPENDENCY) + .withGroupId("org.codehaus") + .withArtifactId("example0") + .withOldVersion("0.0.1") + .withNewVersion("0.0.2") + .build()); + + recorder.recordChange(DefaultChangeRecord.builder() + .withKind(ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT) + .withGroupId("org.codehaus") + .withArtifactId("example1") + .withOldVersion("1.0.0") + .withNewVersion("2.0.0") + .build()); + + recorder.writeReport(path1); + + final Document document0 = parseXML(path0); + final Document document1 = parseXML(path1); + + final NodeList elements0 = document0.getElementsByTagNameNS(ChangeRecorderXML.CHANGES_NAMESPACE, "updated"); + final NodeList elements1 = document1.getElementsByTagNameNS(ChangeRecorderXML.CHANGES_NAMESPACE, "updated"); + + Assert.assertEquals("Correct number of updates", elements0.getLength(), elements1.getLength()); + + for (int index = 0; index < elements0.getLength(); ++index) { + final Element element0 = (Element) elements0.item(index); + final Element element1 = (Element) elements1.item(index); + + Assert.assertEquals( + element0.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "artifactId"), + element1.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "artifactId")); + Assert.assertEquals( + element0.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "groupId"), + element1.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "groupId")); + Assert.assertEquals( + element0.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "oldVersion"), + element1.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "oldVersion")); + Assert.assertEquals( + element0.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "newVersion"), + element1.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "newVersion")); // FIXME - looks like assertions not working - Assert.assertEquals( element0.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "kind" ), - element1.getAttributeNS( ChangeRecorderXML.CHANGES_NAMESPACE, "kind" ) ); + Assert.assertEquals( + element0.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "kind"), + element1.getAttributeNS(ChangeRecorderXML.CHANGES_NAMESPACE, "kind")); } } @Test - public void emptyResultShouldNotGenerateReports() throws Exception - { - Path path = Files.createTempDirectory( "ChangeRecorderTest" ).resolve( "ChangeRecorderTest.xml" ); + public void emptyResultShouldNotGenerateReports() throws Exception { + Path path = Files.createTempDirectory("ChangeRecorderTest").resolve("ChangeRecorderTest.xml"); ChangeRecorder recorder = new ChangeRecorderXML(); - recorder.writeReport( path ); - - Assert.assertFalse( "File should not be created", Files.isRegularFile( path ) ); + recorder.writeReport(path); + Assert.assertFalse("File should not be created", Files.isRegularFile(path)); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReaderTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReaderTest.java index 5ae699c20c..efe6787692 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReaderTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/rewriting/ModifiedPomXMLEventReaderTest.java @@ -44,10 +44,8 @@ * * @author Andrzej Jarmoniuk */ - -@RunWith( MockitoJUnitRunner.class ) -public class ModifiedPomXMLEventReaderTest extends AbstractMojoTestCase -{ +@RunWith(MockitoJUnitRunner.class) +public class ModifiedPomXMLEventReaderTest extends AbstractMojoTestCase { private static final String[] STR = {"xyz", "0123456789abcdef"}; private static final String REPLACEMENT = "abcdef"; @@ -66,73 +64,64 @@ public class ModifiedPomXMLEventReaderTest extends AbstractMojoTestCase private ModifiedPomXMLEventReader pomXMLEventReader; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - when( location.getCharacterOffset() ) - .thenReturn( STR[0].length() ) - .thenReturn( STR[0].length() + STR[1].length() ); + when(location.getCharacterOffset()).thenReturn(STR[0].length()).thenReturn(STR[0].length() + STR[1].length()); - when( xmlEvent.isCharacters() ).thenReturn( true ); - when( xmlEvent.getLocation() ).thenReturn( location ); + when(xmlEvent.isCharacters()).thenReturn(true); + when(xmlEvent.getLocation()).thenReturn(location); - when( xmlEventReader.hasNext() ) - .thenReturn( true ).thenReturn( true ) // str[0] - .thenReturn( true ).thenReturn( true ) // str[1] - .thenReturn( false ); // ∅ - when( xmlEventReader.nextEvent() ) - .thenReturn( xmlEvent ) - .thenReturn( xmlEvent ); - when( xmlEventReader.peek() ) - .thenReturn( xmlEvent ); + when(xmlEventReader.hasNext()) + .thenReturn(true) + .thenReturn(true) // str[0] + .thenReturn(true) + .thenReturn(true) // str[1] + .thenReturn(false); // ∅ + when(xmlEventReader.nextEvent()).thenReturn(xmlEvent).thenReturn(xmlEvent); + when(xmlEventReader.peek()).thenReturn(xmlEvent); - when( xmlInputFactory.createXMLEventReader( any( StringReader.class ) ) ) - .thenReturn( xmlEventReader ); + when(xmlInputFactory.createXMLEventReader(any(StringReader.class))).thenReturn(xmlEventReader); pomXMLEventReader = - new ModifiedPomXMLEventReader( new StringBuilder( STR[0] ).append( STR[1] ), xmlInputFactory, "" ); + new ModifiedPomXMLEventReader(new StringBuilder(STR[0]).append(STR[1]), xmlInputFactory, ""); } @Test - public void testReplace() throws XMLStreamException, IllegalAccessException - { - assertThat( pomXMLEventReader.hasNext(), is( true ) ); - assertThat( pomXMLEventReader.nextEvent(), is( xmlEvent ) ); + public void testReplace() throws XMLStreamException, IllegalAccessException { + assertThat(pomXMLEventReader.hasNext(), is(true)); + assertThat(pomXMLEventReader.nextEvent(), is(xmlEvent)); - assertThat( pomXMLEventReader.hasNext(), is( true ) ); - assertThat( pomXMLEventReader.nextEvent(), is( xmlEvent ) ); + assertThat(pomXMLEventReader.hasNext(), is(true)); + assertThat(pomXMLEventReader.nextEvent(), is(xmlEvent)); - pomXMLEventReader.replace( REPLACEMENT ); - assertThat( pomXMLEventReader.asStringBuilder().toString(), is( STR[0] + REPLACEMENT ) ); + pomXMLEventReader.replace(REPLACEMENT); + assertThat(pomXMLEventReader.asStringBuilder().toString(), is(STR[0] + REPLACEMENT)); - pomXMLEventReader.mark( 0 ); - assertThat( pomXMLEventReader.getMarkVerbatim( 0 ), is( REPLACEMENT ) ); + pomXMLEventReader.mark(0); + assertThat(pomXMLEventReader.getMarkVerbatim(0), is(REPLACEMENT)); // more dangerous test since this touches the implementation - assertThat( getVariableValueFromObject( pomXMLEventReader, "lastEnd" ), - is( ( STR[0] + REPLACEMENT ).length() ) ); + assertThat(getVariableValueFromObject(pomXMLEventReader, "lastEnd"), is((STR[0] + REPLACEMENT).length())); } @Test - public void testReplaceMark() throws XMLStreamException, IllegalAccessException - { - assertThat( pomXMLEventReader.hasNext(), is( true ) ); - assertThat( pomXMLEventReader.nextEvent(), is( xmlEvent ) ); + public void testReplaceMark() throws XMLStreamException, IllegalAccessException { + assertThat(pomXMLEventReader.hasNext(), is(true)); + assertThat(pomXMLEventReader.nextEvent(), is(xmlEvent)); - assertThat( pomXMLEventReader.hasNext(), is( true ) ); - assertThat( pomXMLEventReader.nextEvent(), is( xmlEvent ) ); + assertThat(pomXMLEventReader.hasNext(), is(true)); + assertThat(pomXMLEventReader.nextEvent(), is(xmlEvent)); - pomXMLEventReader.mark( 0 ); + pomXMLEventReader.mark(0); - pomXMLEventReader.replaceMark( 0, REPLACEMENT ); - assertThat( pomXMLEventReader.asStringBuilder().toString(), is( STR[0] + REPLACEMENT ) ); + pomXMLEventReader.replaceMark(0, REPLACEMENT); + assertThat(pomXMLEventReader.asStringBuilder().toString(), is(STR[0] + REPLACEMENT)); - pomXMLEventReader.mark( 0 ); - assertThat( pomXMLEventReader.getMarkVerbatim( 0 ), is( REPLACEMENT ) ); + pomXMLEventReader.mark(0); + assertThat(pomXMLEventReader.getMarkVerbatim(0), is(REPLACEMENT)); // more dangerous test since this touches the implementation - assertThat( getVariableValueFromObject( pomXMLEventReader, "lastEnd" ), - is( ( STR[0] + REPLACEMENT ).length() ) ); + assertThat(getVariableValueFromObject(pomXMLEventReader, "lastEnd"), is((STR[0] + REPLACEMENT).length())); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/ModifiedPomXMLEventReaderUtils.java b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/ModifiedPomXMLEventReaderUtils.java index fb8a37a3b3..01143daa4f 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/ModifiedPomXMLEventReaderUtils.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/ModifiedPomXMLEventReaderUtils.java @@ -29,33 +29,26 @@ * * @author Andrzej Jarmoniuk */ -public class ModifiedPomXMLEventReaderUtils -{ - public static

Matcher

matches( String pattern ) - { - return new TypeSafeMatcher

() - { +public class ModifiedPomXMLEventReaderUtils { + public static

Matcher

matches(String pattern) { + return new TypeSafeMatcher

() { @Override - public void describeTo( Description description ) - { - description.appendText( pattern ); + public void describeTo(Description description) { + description.appendText(pattern); } @Override - protected void describeMismatchSafely( P pom, Description description ) - { - description.appendText( asString( pom ) ); + protected void describeMismatchSafely(P pom, Description description) { + description.appendText(asString(pom)); } @Override - protected boolean matchesSafely( P pom ) - { - return pattern.matches( asString( pom ) ); + protected boolean matchesSafely(P pom) { + return pattern.matches(asString(pom)); } - private String asString( P pom ) - { - return pom.asStringBuilder().toString().replaceAll( "\\s", "" ); + private String asString(P pom) { + return pom.asStringBuilder().toString().replaceAll("\\s", ""); } }; } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReaderTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReaderTest.java index 4f68d71089..5fd8c98413 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReaderTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/PropertiesVersionsFileReaderTest.java @@ -28,32 +28,28 @@ import org.junit.Assert; import org.junit.Test; -public class PropertiesVersionsFileReaderTest -{ +public class PropertiesVersionsFileReaderTest { private static final String TEST_PROPERTIES_FILE = - "src/test/resources/org/codehaus/mojo/versions/utils/testPropertiesVersionsFile.properties"; + "src/test/resources/org/codehaus/mojo/versions/utils/testPropertiesVersionsFile.properties"; @Test - public void testRead() throws IOException - { - PropertiesVersionsFileReader reader = new PropertiesVersionsFileReader( TEST_PROPERTIES_FILE ); + public void testRead() throws IOException { + PropertiesVersionsFileReader reader = new PropertiesVersionsFileReader(TEST_PROPERTIES_FILE); reader.read(); int numberOfPropertiesConfig = 3; - Assert.assertTrue( equalsCvsUnordered( "booking-api.version,booking-lib.version,be-air-impl.version", - reader.getProperties() ) ); - Assert.assertEquals( numberOfPropertiesConfig, reader.getPropertiesConfig().length ); + Assert.assertTrue(equalsCvsUnordered( + "booking-api.version,booking-lib.version,be-air-impl.version", reader.getProperties())); + Assert.assertEquals(numberOfPropertiesConfig, reader.getPropertiesConfig().length); } - private boolean equalsCvsUnordered( String csvExpected, String csvActual ) - { - if ( StringUtils.isEmpty( csvExpected ) ) - { + private boolean equalsCvsUnordered(String csvExpected, String csvActual) { + if (StringUtils.isEmpty(csvExpected)) { return false; } - Set listExpected = new HashSet<>( Arrays.asList( csvExpected.split( "," ) ) ); - Set listActual = new HashSet<>( Arrays.asList( csvActual.split( "," ) ) ); - return listExpected.equals( listActual ); + Set listExpected = new HashSet<>(Arrays.asList(csvExpected.split(","))); + Set listActual = new HashSet<>(Arrays.asList(csvActual.split(","))); + return listExpected.equals(listActual); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java index 4170e2dc7e..7d22804b35 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java @@ -32,39 +32,27 @@ /** * Unit tests for {@link SegmentUtils} */ -public class SegmentUtilsTest -{ +public class SegmentUtilsTest { @Test - public void testIncremental() - { - assertThat( determineUnchangedSegment( false, false, false, null ), - is( of( INCREMENTAL ) ) ); - assertThat( determineUnchangedSegment( true, false, false, null ), - is( of( INCREMENTAL ) ) ); - assertThat( determineUnchangedSegment( true, true, false, null ), - is( of( INCREMENTAL ) ) ); + public void testIncremental() { + assertThat(determineUnchangedSegment(false, false, false, null), is(of(INCREMENTAL))); + assertThat(determineUnchangedSegment(true, false, false, null), is(of(INCREMENTAL))); + assertThat(determineUnchangedSegment(true, true, false, null), is(of(INCREMENTAL))); } @Test - public void testMinor() - { - assertThat( determineUnchangedSegment( false, false, true, null ), - is( of( MINOR ) ) ); - assertThat( determineUnchangedSegment( true, false, true, null ), - is( of( MINOR ) ) ); + public void testMinor() { + assertThat(determineUnchangedSegment(false, false, true, null), is(of(MINOR))); + assertThat(determineUnchangedSegment(true, false, true, null), is(of(MINOR))); } @Test - public void testMajor() - { - assertThat( determineUnchangedSegment( false, true, true, null ), - is( of( MAJOR ) ) ); + public void testMajor() { + assertThat(determineUnchangedSegment(false, true, true, null), is(of(MAJOR))); } @Test - public void testEmpty() - { - assertThat( determineUnchangedSegment( true, true, true, null ), - is( empty() ) ); + public void testEmpty() { + assertThat(determineUnchangedSegment(true, true, true, null), is(empty())); } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/VersionStub.java b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/VersionStub.java index 699644eeca..c23e057580 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/VersionStub.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/VersionStub.java @@ -24,53 +24,43 @@ /** * Stubs the {@link org.eclipse.aether.version.Version} */ -public class VersionStub implements Version -{ +public class VersionStub implements Version { private final String version; /** * Creates a new instance with the given version string * @param version version to be set */ - public VersionStub( String version ) - { + public VersionStub(String version) { assert version != null; this.version = version; } @Override - public String toString() - { + public String toString() { return version; } @Override - public int compareTo( Version o ) - { - return o != null - ? version.compareTo( o.toString() ) - : 1; + public int compareTo(Version o) { + return o != null ? version.compareTo(o.toString()) : 1; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof Version ) ) - { + if (!(o instanceof Version)) { return false; } - return version.equals( o.toString() ); + return version.equals(o.toString()); } @Override - public int hashCode() - { + public int hashCode() { return version.hashCode(); } } diff --git a/versions-enforcer/pom.xml b/versions-enforcer/pom.xml index 376f23b5f9..e90199247d 100644 --- a/versions-enforcer/pom.xml +++ b/versions-enforcer/pom.xml @@ -1,186 +1,184 @@ - - - versions - org.codehaus.mojo.versions - 2.14.0-SNAPSHOT - - 4.0.0 - - versions-enforcer - - Versions Enforcer - Enforcer rules using Versions Maven Plugin - - - ${maven-enforcer-plugin.version} - - - - - - org.codehaus.mojo.versions - versions-common - ${project.version} - - - - org.codehaus.mojo.versions - versions-test - ${project.version} - test - - - - org.apache.maven.enforcer - enforcer-api - provided - - - - org.apache.maven - maven-core - ${mavenVersion} - provided - - - - org.junit.jupiter - junit-jupiter - test - - - - org.junit.vintage - junit-vintage-engine - test - - - org.hamcrest - hamcrest-core - - - - - - org.apache.maven.plugin-testing - maven-plugin-testing-harness - test - - - - org.mockito - mockito-inline - test - - - - org.hamcrest - hamcrest - test - - - - org.slf4j - slf4j-simple - test - - - - - - - - org.eclipse.sisu - sisu-maven-plugin - - - org.apache.maven.plugins - maven-invoker-plugin - - src/it - ${project.build.directory}/it - ${project.build.directory}/local-repo - src/it/settings.xml - true - true - - 1 - - */pom.xml - - verify - - ${repository.proxy.url} - - -Xmx256m - - - - - - - - - run-its - - verify - - - - org.codehaus.mojo - mrm-maven-plugin - - - - start - stop - - - - - repository.proxy.url - - - src/it-repo - - - ${project.build.directory}/local-repo - - - - - - - org.apache.maven.plugins - maven-invoker-plugin - - - integration-test - - install - integration-test - verify - - - false - true - - - - - - - - - - \ No newline at end of file + run-its + + verify + + + + org.codehaus.mojo + mrm-maven-plugin + + repository.proxy.url + + + src/it-repo + + + ${project.build.directory}/local-repo + + + + + + + + start + stop + + + + + + org.apache.maven.plugins + maven-invoker-plugin + + + integration-test + + install + integration-test + verify + + + false + true + + + + + + + + + + diff --git a/versions-enforcer/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java b/versions-enforcer/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java index 2895596b70..4956a2fd50 100644 --- a/versions-enforcer/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java +++ b/versions-enforcer/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java @@ -62,8 +62,7 @@ import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromPlugins; import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractPluginDependenciesFromPluginsInPluginManagement; -public class MaxDependencyUpdates implements EnforcerRule2 -{ +public class MaxDependencyUpdates implements EnforcerRule2 { /** * Maximum allowed number of updates. * @@ -145,7 +144,7 @@ public class MaxDependencyUpdates implements EnforcerRule2 * * @since 2.14.0 */ - protected List dependencyIncludes = singletonList( WILDCARD ); + protected List dependencyIncludes = singletonList(WILDCARD); /** * List of dependency exclusion patterns. @@ -165,7 +164,7 @@ public class MaxDependencyUpdates implements EnforcerRule2 * * @since 2.14.0 */ - protected List dependencyManagementIncludes = singletonList( WILDCARD ); + protected List dependencyManagementIncludes = singletonList(WILDCARD); /** * List of dependency management exclusion patterns. @@ -185,7 +184,7 @@ public class MaxDependencyUpdates implements EnforcerRule2 * * @since 2.14.0 */ - protected List pluginDependencyIncludes = singletonList( WILDCARD ); + protected List pluginDependencyIncludes = singletonList(WILDCARD); /** * List of plugin dependency exclusion patterns. @@ -205,7 +204,7 @@ public class MaxDependencyUpdates implements EnforcerRule2 * * @since 2.14.0 */ - protected List pluginManagementDependencyIncludes = singletonList( WILDCARD ); + protected List pluginManagementDependencyIncludes = singletonList(WILDCARD); /** * List of plugin dependency management exclusion patterns. @@ -249,15 +248,11 @@ public class MaxDependencyUpdates implements EnforcerRule2 * @param ruleHelper EnforcerRuleHelper object * @return maven project */ - private static MavenProject getMavenProject( EnforcerRuleHelper ruleHelper ) - { - try - { - return (MavenProject) ruleHelper.evaluate( "${project}" ); - } - catch ( ExpressionEvaluationException e ) - { - throw new RuntimeException( "Cannot evaluate project metadata", e ); + private static MavenProject getMavenProject(EnforcerRuleHelper ruleHelper) { + try { + return (MavenProject) ruleHelper.evaluate("${project}"); + } catch (ExpressionEvaluationException e) { + throw new RuntimeException("Cannot evaluate project metadata", e); } } @@ -266,136 +261,114 @@ private static MavenProject getMavenProject( EnforcerRuleHelper ruleHelper ) * @param ruleHelper EnforcerRuleHelper object * @return VersionsHelper object */ - @SuppressWarnings( "unchecked" ) - private static VersionsHelper createVersionsHelper( EnforcerRuleHelper ruleHelper, - String serverId, - String rulesUri, - RuleSet ruleSet ) - { - try - { + @SuppressWarnings("unchecked") + private static VersionsHelper createVersionsHelper( + EnforcerRuleHelper ruleHelper, String serverId, String rulesUri, RuleSet ruleSet) { + try { return new DefaultVersionsHelper.Builder() - .withRepositorySystem( ruleHelper.getComponent( RepositorySystem.class ) ) - .withAetherRepositorySystem( ruleHelper.getComponent( org.eclipse.aether.RepositorySystem.class ) ) - .withWagonMap( ruleHelper.getComponentMap( Wagon.class.getName() ) - .entrySet() - .parallelStream() - .filter( e -> e.getValue() instanceof Wagon ) - .collect( HashMap::new, - ( m, e ) -> m.put( e.getKey(), (Wagon) e.getValue() ), - HashMap::putAll ) ) - .withServerId( serverId ) - .withRulesUri( rulesUri ) - .withRuleSet( ruleSet ) - .withIgnoredVersions( null ) - .withLog( ruleHelper.getLog() ) - .withMavenSession( (MavenSession) ruleHelper.evaluate( "${session}" ) ) - .withMojoExecution( (MojoExecution) ruleHelper.evaluate( "${mojoExecution}" ) ) + .withRepositorySystem(ruleHelper.getComponent(RepositorySystem.class)) + .withAetherRepositorySystem(ruleHelper.getComponent(org.eclipse.aether.RepositorySystem.class)) + .withWagonMap(ruleHelper.getComponentMap(Wagon.class.getName()).entrySet().parallelStream() + .filter(e -> e.getValue() instanceof Wagon) + .collect(HashMap::new, (m, e) -> m.put(e.getKey(), (Wagon) e.getValue()), HashMap::putAll)) + .withServerId(serverId) + .withRulesUri(rulesUri) + .withRuleSet(ruleSet) + .withIgnoredVersions(null) + .withLog(ruleHelper.getLog()) + .withMavenSession((MavenSession) ruleHelper.evaluate("${session}")) + .withMojoExecution((MojoExecution) ruleHelper.evaluate("${mojoExecution}")) .build(); - } - catch ( ExpressionEvaluationException e ) - { - throw new RuntimeException( "Cannot evaluate project metadata", e ); - } - catch ( ComponentLookupException | MojoExecutionException e ) - { - throw new RuntimeException( "Cannot resolve dependency", e ); + } catch (ExpressionEvaluationException e) { + throw new RuntimeException("Cannot evaluate project metadata", e); + } catch (ComponentLookupException | MojoExecutionException e) { + throw new RuntimeException("Cannot resolve dependency", e); } } + @Override - public boolean isCacheable() - { + public boolean isCacheable() { return false; } @Override - public boolean isResultValid( EnforcerRule enforcerRule ) - { + public boolean isResultValid(EnforcerRule enforcerRule) { return false; } @Override - public String getCacheId() - { + public String getCacheId() { return "Does not matter as not cacheable"; } @Override - public void execute( EnforcerRuleHelper ruleHelper ) throws EnforcerRuleException - { - VersionsHelper versionsHelper = createVersionsHelper( ruleHelper, serverId != null ? serverId : "serverId", - rulesUri, ruleSet ); - MavenProject project = getMavenProject( ruleHelper ); - Set dependencies = new TreeSet<>( DependencyComparator.INSTANCE ); - if ( processDependencyManagement ) - { - try - { - dependencies.addAll( filterDependencies( extractDependenciesFromDependencyManagement( project, - processDependencyManagementTransitive, ruleHelper.getLog() ), - dependencyManagementIncludes, dependencyManagementExcludes, "Dependency Management", - ruleHelper.getLog() ) ); - } - catch ( VersionRetrievalException e ) - { - throw new EnforcerRuleException( e.getMessage() ); + public void execute(EnforcerRuleHelper ruleHelper) throws EnforcerRuleException { + VersionsHelper versionsHelper = + createVersionsHelper(ruleHelper, serverId != null ? serverId : "serverId", rulesUri, ruleSet); + MavenProject project = getMavenProject(ruleHelper); + Set dependencies = new TreeSet<>(DependencyComparator.INSTANCE); + if (processDependencyManagement) { + try { + dependencies.addAll(filterDependencies( + extractDependenciesFromDependencyManagement( + project, processDependencyManagementTransitive, ruleHelper.getLog()), + dependencyManagementIncludes, + dependencyManagementExcludes, + "Dependency Management", + ruleHelper.getLog())); + } catch (VersionRetrievalException e) { + throw new EnforcerRuleException(e.getMessage()); } } - if ( processPluginDependencies ) - { - dependencies.addAll( filterDependencies( extractDependenciesFromPlugins( project ), - pluginDependencyIncludes, pluginDependencyExcludes, - "Plugin Dependencies", ruleHelper.getLog() ) ); + if (processPluginDependencies) { + dependencies.addAll(filterDependencies( + extractDependenciesFromPlugins(project), + pluginDependencyIncludes, + pluginDependencyExcludes, + "Plugin Dependencies", + ruleHelper.getLog())); } - if ( processPluginDependenciesInPluginManagement ) - { - dependencies.addAll( filterDependencies( - extractPluginDependenciesFromPluginsInPluginManagement( project ), - pluginManagementDependencyIncludes, pluginManagementDependencyExcludes, - "Plugin Management Dependencies", ruleHelper.getLog() ) ); + if (processPluginDependenciesInPluginManagement) { + dependencies.addAll(filterDependencies( + extractPluginDependenciesFromPluginsInPluginManagement(project), + pluginManagementDependencyIncludes, + pluginManagementDependencyExcludes, + "Plugin Management Dependencies", + ruleHelper.getLog())); } - if ( processDependencies ) - { - dependencies.addAll( filterDependencies( project.getDependencies(), - dependencyIncludes, dependencyExcludes, "Dependencies", ruleHelper.getLog() ) ); + if (processDependencies) { + dependencies.addAll(filterDependencies( + project.getDependencies(), + dependencyIncludes, + dependencyExcludes, + "Dependencies", + ruleHelper.getLog())); } - try - { + try { Optional ignoredSegment = ignoreSubIncrementalUpdates - ? of( SUBINCREMENTAL ) - : ignoreIncrementalUpdates - ? of( INCREMENTAL ) - : ignoreMinorUpdates - ? of( MINOR ) - : empty(); - List upgradable = versionsHelper - .lookupDependenciesUpdates( dependencies, false ) - .values() - .parallelStream() - .filter( v -> - v.getVersions( v.restrictionForIgnoreScope( ignoredSegment ), true ).length > 0 - ) - .collect( Collectors.toList() ); - if ( upgradable.size() > maxUpdates ) - { - throw new EnforcerRuleException( "More than " + maxUpdates + " upgradable artifacts detected: " - + upgradable.stream().map( av -> av.getArtifact() + " -> [" - + Arrays.stream( av.getVersions() ) - .map( ArtifactVersion::toString ) - .collect( Collectors.joining( ", " ) ) - + "]" ) - .collect( Collectors.joining( ", " ) ) ); + ? of(SUBINCREMENTAL) + : ignoreIncrementalUpdates ? of(INCREMENTAL) : ignoreMinorUpdates ? of(MINOR) : empty(); + List upgradable = + versionsHelper.lookupDependenciesUpdates(dependencies, false).values().parallelStream() + .filter(v -> v.getVersions(v.restrictionForIgnoreScope(ignoredSegment), true).length > 0) + .collect(Collectors.toList()); + if (upgradable.size() > maxUpdates) { + throw new EnforcerRuleException("More than " + maxUpdates + " upgradable artifacts detected: " + + upgradable.stream() + .map(av -> av.getArtifact() + " -> [" + + Arrays.stream(av.getVersions()) + .map(ArtifactVersion::toString) + .collect(Collectors.joining(", ")) + + "]") + .collect(Collectors.joining(", "))); } - } - catch ( VersionRetrievalException e ) - { - throw new RuntimeException( e.getMessage(), e ); + } catch (VersionRetrievalException e) { + throw new RuntimeException(e.getMessage(), e); } } @Override - public EnforcerLevel getLevel() - { + public EnforcerLevel getLevel() { // all reported items should be treated as errors return EnforcerLevel.ERROR; } diff --git a/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java b/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java index 62e029e813..09ad456716 100644 --- a/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java +++ b/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java @@ -44,237 +44,226 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class MaxDependencyUpdatesTest -{ - private static EnforcerRuleHelper mockRuleHelper( MavenProject mavenProject, - org.eclipse.aether.RepositorySystem aetherRepositorySystem ) - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mock( EnforcerRuleHelper.class ); - when( ruleHelper.evaluate( anyString() ) ) - .then( ( a ) -> "${project}".equals( a.getArgument( 0 ) ) +public class MaxDependencyUpdatesTest { + private static EnforcerRuleHelper mockRuleHelper( + MavenProject mavenProject, org.eclipse.aether.RepositorySystem aetherRepositorySystem) + throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mock(EnforcerRuleHelper.class); + when(ruleHelper.evaluate(anyString())) + .then((a) -> "${project}".equals(a.getArgument(0)) ? mavenProject - : "${session}".equals( a.getArgument( 0 ) ) - ? mockMavenSession() - : "${mojoExecution}".equals( a.getArgument( 0 ) ) - ? mock( MojoExecution.class ) - : null ); - when( ruleHelper.getComponent( ArgumentMatchers.>any() ) ) - .then( ( a ) -> a.getArgument( 0 ) == RepositorySystem.class + : "${session}".equals(a.getArgument(0)) + ? mockMavenSession() + : "${mojoExecution}".equals(a.getArgument(0)) ? mock(MojoExecution.class) : null); + when(ruleHelper.getComponent(ArgumentMatchers.>any())) + .then((a) -> a.getArgument(0) == RepositorySystem.class ? mockRepositorySystem() - : a.getArgument( 0 ) == org.eclipse.aether.RepositorySystem.class - ? aetherRepositorySystem - : null ); + : a.getArgument(0) == org.eclipse.aether.RepositorySystem.class + ? aetherRepositorySystem + : null); return ruleHelper; } @Test - public void testRuleFailsByMaxUpdatesExceeded() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( asList( - dependencyWith( "group", "artifactA", "1.0.0" ), - dependencyWith( "group", "artifactB", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0", "2.0.0" } ); - }} ) ); + public void testRuleFailsByMaxUpdatesExceeded() throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(asList( + dependencyWith("group", "artifactA", "1.0.0"), + dependencyWith("group", "artifactB", "1.0.0"))); + } + }, + mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0", "2.0.0"}); + } + })); - try - { - new MaxDependencyUpdates() - {{ - maxUpdates = 1; - }}.execute( ruleHelper ); + try { + new MaxDependencyUpdates() { + { + maxUpdates = 1; + } + }.execute(ruleHelper); - fail( "EnforcerRuleException should have been thrown" ); - } - catch ( EnforcerRuleException e ) - { - assertThat( e.getMessage(), containsString( "More than 1 upgradable artifacts detected" ) ); + fail("EnforcerRuleException should have been thrown"); + } catch (EnforcerRuleException e) { + assertThat(e.getMessage(), containsString("More than 1 upgradable artifacts detected")); } } @Test - public void testRulePassesByMaxUpdatesNotExceeded() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( singletonList( - dependencyWith( "group", "artifactA", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( singletonMap( "artifactA", new String[] { "1.0.0", "2.0.0" } ) ) ); + public void testRulePassesByMaxUpdatesNotExceeded() throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(singletonList(dependencyWith("group", "artifactA", "1.0.0"))); + } + }, + mockAetherRepositorySystem(singletonMap("artifactA", new String[] {"1.0.0", "2.0.0"}))); - try - { - new MaxDependencyUpdates() - {{ - maxUpdates = 1; - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + maxUpdates = 1; + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } @Test public void testRulePassesByMaxUpdatesNotExceededDependencyIncludes() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( asList( - dependencyWith( "group", "artifactA", "1.0.0" ), - dependencyWith( "group", "artifactB", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0" } ); - }} ) ); + throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(asList( + dependencyWith("group", "artifactA", "1.0.0"), + dependencyWith("group", "artifactB", "1.0.0"))); + } + }, + mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0"}); + } + })); - try - { - new MaxDependencyUpdates() - {{ - dependencyIncludes = singletonList( "group:artifactB" ); - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + dependencyIncludes = singletonList("group:artifactB"); + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } @Test public void testRulePassesByMaxUpdatesNotExceededDependencyExcludes() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( asList( - dependencyWith( "group", "artifactA", "1.0.0" ), - dependencyWith( "group", "artifactB", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0" } ); - }} ) ); + throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(asList( + dependencyWith("group", "artifactA", "1.0.0"), + dependencyWith("group", "artifactB", "1.0.0"))); + } + }, + mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0"}); + } + })); - try - { - new MaxDependencyUpdates() - {{ - dependencyExcludes = singletonList( "group:artifactA" ); - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + dependencyExcludes = singletonList("group:artifactA"); + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } @Test public void testRulePassesByMaxUpdatesNotExceededDependencyIncludesExcludes() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( asList( - dependencyWith( "group", "artifactA", "1.0.0" ), - dependencyWith( "group", "artifactB", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0" } ); - }} ) ); + throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(asList( + dependencyWith("group", "artifactA", "1.0.0"), + dependencyWith("group", "artifactB", "1.0.0"))); + } + }, + mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0"}); + } + })); - try - { - new MaxDependencyUpdates() - {{ - dependencyIncludes = singletonList( "group:*" ); - dependencyExcludes = singletonList( "group:artifactA" ); - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + dependencyIncludes = singletonList("group:*"); + dependencyExcludes = singletonList("group:artifactA"); + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } @Test - public void testIgnoreSubIncrementalUpdates() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( singletonList( - dependencyWith( "group", "artifactA", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( singletonMap( "artifactA", - new String[] { "1.0.0", "1.0.0-1" } ) ) ); + public void testIgnoreSubIncrementalUpdates() throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(singletonList(dependencyWith("group", "artifactA", "1.0.0"))); + } + }, + mockAetherRepositorySystem(singletonMap("artifactA", new String[] {"1.0.0", "1.0.0-1"}))); - try - { - new MaxDependencyUpdates() - {{ - ignoreSubIncrementalUpdates = true; - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + ignoreSubIncrementalUpdates = true; + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } @Test - public void testIgnoreIncrementalUpdates() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( singletonList( - dependencyWith( "group", "artifactA", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( singletonMap( "artifactA", - new String[] { "1.0.0", "1.0.0-1", "1.0.1" } ) ) ); + public void testIgnoreIncrementalUpdates() throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(singletonList(dependencyWith("group", "artifactA", "1.0.0"))); + } + }, + mockAetherRepositorySystem(singletonMap("artifactA", new String[] {"1.0.0", "1.0.0-1", "1.0.1"}))); - try - { - new MaxDependencyUpdates() - {{ - ignoreIncrementalUpdates = true; - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + ignoreIncrementalUpdates = true; + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } @Test - public void testIgnoreMinorUpdates() - throws ExpressionEvaluationException, ComponentLookupException - { - EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() - {{ - setDependencies( asList( - dependencyWith( "group", "artifactA", "1.0.0" ) ) ); - }}, mockAetherRepositorySystem( singletonMap( "artifactA", - new String[] { "1.0.0", "1.0.0-1", "1.0.1", "1.1.0" } ) ) ); + public void testIgnoreMinorUpdates() throws ExpressionEvaluationException, ComponentLookupException { + EnforcerRuleHelper ruleHelper = mockRuleHelper( + new MavenProject() { + { + setDependencies(asList(dependencyWith("group", "artifactA", "1.0.0"))); + } + }, + mockAetherRepositorySystem( + singletonMap("artifactA", new String[] {"1.0.0", "1.0.0-1", "1.0.1", "1.1.0"}))); - try - { - new MaxDependencyUpdates() - {{ - ignoreMinorUpdates = true; - }}.execute( ruleHelper ); - } - catch ( EnforcerRuleException e ) - { - fail( "No EnforcerRuleException should have been thrown" ); + try { + new MaxDependencyUpdates() { + { + ignoreMinorUpdates = true; + } + }.execute(ruleHelper); + } catch (EnforcerRuleException e) { + fail("No EnforcerRuleException should have been thrown"); } } } diff --git a/versions-maven-plugin/pom.xml b/versions-maven-plugin/pom.xml index 629e0eaa5a..b531444ddb 100644 --- a/versions-maven-plugin/pom.xml +++ b/versions-maven-plugin/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 @@ -85,7 +86,6 @@ maven-common-artifact-filters - org.apache.maven.doxia @@ -255,14 +255,6 @@ org.codehaus.mojo mrm-maven-plugin - - - - start - stop - - - repository.proxy.url @@ -275,6 +267,14 @@ + + + + start + stop + + + org.apache.maven.plugins diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractDependencyUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractDependencyUpdatesReportMojo.java index d183fbdb2d..ac9b15b083 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractDependencyUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractDependencyUpdatesReportMojo.java @@ -17,11 +17,6 @@ * */ - -import static java.util.Collections.emptyMap; -import static org.codehaus.mojo.versions.utils.MavenProjectUtils.interpolateVersion; -import static org.codehaus.mojo.versions.utils.MiscUtils.filter; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -33,6 +28,7 @@ import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; + import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.model.Dependency; @@ -49,11 +45,14 @@ import org.codehaus.mojo.versions.xml.DependencyUpdatesXmlReportRenderer; import org.codehaus.plexus.i18n.I18N; +import static java.util.Collections.emptyMap; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.interpolateVersion; +import static org.codehaus.mojo.versions.utils.MiscUtils.filter; + /** * Generates a report of available updates for the dependencies of a project. */ -public abstract class AbstractDependencyUpdatesReportMojo extends AbstractVersionsReport -{ +public abstract class AbstractDependencyUpdatesReportMojo extends AbstractVersionsReport { private static final DependencyComparator DEPENDENCY_COMPARATOR = DependencyComparator.INSTANCE; @@ -62,7 +61,7 @@ public abstract class AbstractDependencyUpdatesReportMojo extends AbstractVersio * * @since 2.5 */ - @Parameter( property = "processDependencyManagement", defaultValue = "true" ) + @Parameter(property = "processDependencyManagement", defaultValue = "true") protected boolean processDependencyManagement; /** @@ -75,13 +74,13 @@ public abstract class AbstractDependencyUpdatesReportMojo extends AbstractVersio * * @since 2.5 Note: Currently in experimental state. */ - @Parameter( property = "processDependencyManagementTransitive", defaultValue = "true" ) + @Parameter(property = "processDependencyManagementTransitive", defaultValue = "true") protected boolean processDependencyManagementTransitive; /** * Report formats (html and/or xml). HTML by default. */ - @Parameter( property = "dependencyUpdatesReportFormats", defaultValue = "html" ) + @Parameter(property = "dependencyUpdatesReportFormats", defaultValue = "html") protected String[] formats = new String[] {"html"}; /** @@ -90,7 +89,7 @@ public abstract class AbstractDependencyUpdatesReportMojo extends AbstractVersio * * @since 2.12 */ - @Parameter( property = "onlyProjectDependencies", defaultValue = "false" ) + @Parameter(property = "onlyProjectDependencies", defaultValue = "false") protected boolean onlyProjectDependencies; /** @@ -98,31 +97,29 @@ public abstract class AbstractDependencyUpdatesReportMojo extends AbstractVersio * * @since 2.12 */ - @Parameter( property = "onlyUpgradable", defaultValue = "false" ) + @Parameter(property = "onlyUpgradable", defaultValue = "false") protected boolean onlyUpgradable; - public AbstractDependencyUpdatesReportMojo( I18N i18n, - RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + public AbstractDependencyUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} */ - public boolean isExternalReport() - { + public boolean isExternalReport() { return false; } /** * {@inheritDoc} */ - public boolean canGenerateReport() - { + public boolean canGenerateReport() { return true; } @@ -132,115 +129,93 @@ public boolean canGenerateReport() * @param locale the locale to generate the report for. * @param sink the report formatting tool */ - @SuppressWarnings( "deprecation" ) - protected void doGenerateReport( Locale locale, Sink sink ) throws MavenReportException - { + @SuppressWarnings("deprecation") + protected void doGenerateReport(Locale locale, Sink sink) throws MavenReportException { Set dependencies = getDependencies(); Set dependencyManagement; - if ( processDependencyManagement ) - { - dependencyManagement = getDependencyManagement( dependencies ); - handleOnlyProjectDependencies( dependencyManagement, dependencies ); - } - else - { + if (processDependencyManagement) { + dependencyManagement = getDependencyManagement(dependencies); + handleOnlyProjectDependencies(dependencyManagement, dependencies); + } else { dependencyManagement = Collections.emptySet(); } - try - { + try { Map dependencyUpdates = - getHelper().lookupDependenciesUpdates( dependencies, false ); + getHelper().lookupDependenciesUpdates(dependencies, false); - Map dependencyManagementUpdates = - processDependencyManagement ? getHelper().lookupDependenciesUpdates( dependencyManagement, false ) - : emptyMap(); + Map dependencyManagementUpdates = processDependencyManagement + ? getHelper().lookupDependenciesUpdates(dependencyManagement, false) + : emptyMap(); - if ( onlyUpgradable ) - { - dependencyUpdates = filter( dependencyUpdates, e -> e.getVersions().length > 0 ); - dependencyManagementUpdates = filter( dependencyManagementUpdates, e -> e.getVersions().length > 0 ); + if (onlyUpgradable) { + dependencyUpdates = filter(dependencyUpdates, e -> e.getVersions().length > 0); + dependencyManagementUpdates = filter(dependencyManagementUpdates, e -> e.getVersions().length > 0); } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Dependency versions:" ); - dependencyUpdates.forEach( ( key, value ) -> getLog().debug( - key.toString() + ": " + Arrays.stream( value.getVersions() ) - .map( ArtifactVersion::toString ) - .collect( Collectors.joining( ", " ) ) ) ); - - getLog().debug( "Dependency management versions:" ); - dependencyManagementUpdates.forEach( ( key, value ) -> getLog().debug( - key.toString() + ": " + Arrays.stream( value.getVersions() ) - .map( ArtifactVersion::toString ) - .collect( Collectors.joining( ", " ) ) ) ); + if (getLog().isDebugEnabled()) { + getLog().debug("Dependency versions:"); + dependencyUpdates.forEach((key, value) -> getLog().debug(key.toString() + ": " + + Arrays.stream(value.getVersions()) + .map(ArtifactVersion::toString) + .collect(Collectors.joining(", ")))); + + getLog().debug("Dependency management versions:"); + dependencyManagementUpdates.forEach((key, value) -> getLog().debug(key.toString() + ": " + + Arrays.stream(value.getVersions()) + .map(ArtifactVersion::toString) + .collect(Collectors.joining(", ")))); } - DependencyUpdatesModel model = new DependencyUpdatesModel( dependencyUpdates, dependencyManagementUpdates ); + DependencyUpdatesModel model = new DependencyUpdatesModel(dependencyUpdates, dependencyManagementUpdates); - renderReport( locale, sink, model ); - } - catch ( VersionRetrievalException e ) - { - throw new RuntimeException( e ); + renderReport(locale, sink, model); + } catch (VersionRetrievalException e) { + throw new RuntimeException(e); } } - protected void handleDependencyManagementTransitive( MavenProject project, - Set dependencyManagementCollector ) - throws MavenReportException - { - if ( processDependencyManagementTransitive ) - { - if ( hasDependencyManagement( project ) ) - { - for ( Dependency dep : project.getDependencyManagement().getDependencies() ) - { - getLog().debug( - "Dpmg: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() + ":" - + dep.getType() + ":" + dep.getScope() ); + protected void handleDependencyManagementTransitive( + MavenProject project, Set dependencyManagementCollector) throws MavenReportException { + if (processDependencyManagementTransitive) { + if (hasDependencyManagement(project)) { + for (Dependency dep : project.getDependencyManagement().getDependencies()) { + getLog().debug("Dpmg: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() + + ":" + dep.getType() + ":" + dep.getScope()); } - dependencyManagementCollector.addAll( project.getDependencyManagement().getDependencies() ); + dependencyManagementCollector.addAll( + project.getDependencyManagement().getDependencies()); } - } - else - { - if ( project.getOriginalModel().getDependencyManagement() != null - && project.getOriginalModel().getDependencyManagement().getDependencies() != null ) - { + } else { + if (project.getOriginalModel().getDependencyManagement() != null + && project.getOriginalModel().getDependencyManagement().getDependencies() != null) { // Using the original model to get the original dependencyManagement entries and // not the interpolated model. // TODO: I'm not 100% sure if this will work correctly in all cases. - for ( Dependency dep : project.getOriginalModel().getDependencyManagement().getDependencies() ) - { - dep = interpolateVersion( dep, project ); + for (Dependency dep : + project.getOriginalModel().getDependencyManagement().getDependencies()) { + dep = interpolateVersion(dep, project); - getLog().debug( "Original Dpmg: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" - + dep.getVersion() + ":" + dep.getType() + ":" + dep.getScope() ); + getLog().debug("Original Dpmg: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + + dep.getVersion() + ":" + dep.getType() + ":" + dep.getScope()); } dependencyManagementCollector.addAll( - project.getOriginalModel().getDependencyManagement().getDependencies() ); + project.getOriginalModel().getDependencyManagement().getDependencies()); } } } - private void handleOnlyProjectDependencies( Set dependencyManagement, - Set dependencies ) - { - if ( !onlyProjectDependencies ) - { + private void handleOnlyProjectDependencies(Set dependencyManagement, Set dependencies) { + if (!onlyProjectDependencies) { // Retains only dependencies not present in dependencyManagement - dependencies.removeIf( dep -> dependencyManagement.stream().anyMatch( dmDep -> match( dep, dmDep ) ) ); - } - else - { + dependencies.removeIf(dep -> dependencyManagement.stream().anyMatch(dmDep -> match(dep, dmDep))); + } else { // Retain only dependencies in dependencyManagement that are also present in dependencies - dependencyManagement.removeIf( dep -> dependencies.stream().noneMatch( dmDep -> match( dep, dmDep ) ) ); + dependencyManagement.removeIf(dep -> dependencies.stream().noneMatch(dmDep -> match(dep, dmDep))); } } @@ -252,10 +227,9 @@ private void handleOnlyProjectDependencies( Set dependencyManagement * @return a {@link Set} that can be additionally populated by {@link #populateDependencies(Set)}. * If not, an empty set is returned * */ - private Set getDependencies() - { - final Set dependenciesCollector = new TreeSet<>( DEPENDENCY_COMPARATOR ); - populateDependencies( dependenciesCollector ); + private Set getDependencies() { + final Set dependenciesCollector = new TreeSet<>(DEPENDENCY_COMPARATOR); + populateDependencies(dependenciesCollector); return dependenciesCollector; } @@ -267,7 +241,7 @@ private Set getDependencies() * @param dependenciesCollector, a Set, initialized with a DependencyComparator * comparator. * */ - protected abstract void populateDependencies( Set dependenciesCollector ); + protected abstract void populateDependencies(Set dependenciesCollector); /** * Constructs a final instance of a {@link Set} with a {@link DependencyComparator} comparator. @@ -277,10 +251,9 @@ private Set getDependencies() * @return a {@link Set} that can be additionally populated by * {@link #populateDependencyManagement(Set, Set)}. If not, an empty set is returned * */ - private Set getDependencyManagement( Set dependencies ) throws MavenReportException - { - final Set dependencyManagementCollector = new TreeSet<>( DEPENDENCY_COMPARATOR ); - populateDependencyManagement ( dependencyManagementCollector, dependencies ); + private Set getDependencyManagement(Set dependencies) throws MavenReportException { + final Set dependencyManagementCollector = new TreeSet<>(DEPENDENCY_COMPARATOR); + populateDependencyManagement(dependencyManagementCollector, dependencies); return dependencyManagementCollector; } @@ -295,37 +268,26 @@ private Set getDependencyManagement( Set dependencies ) * * @throws MavenReportException when things go wrong. * */ - protected abstract void populateDependencyManagement( Set dependencyManagementCollector, - Set dependencies ) - throws MavenReportException; - - private void renderReport( Locale locale, - Sink sink, - DependencyUpdatesModel model ) - throws MavenReportException - { - for ( String format : formats ) - { - if ( "html".equals( format ) ) - { - rendererFactory.createReportRenderer( getOutputName(), sink, locale, model ).render(); - } - else if ( "xml".equals( format ) ) - { - Path outputDir = Paths.get( getProject().getBuild().getDirectory() ); - if ( !Files.exists( outputDir ) ) - { - try - { - Files.createDirectories( outputDir ); - } - catch ( IOException e ) - { - throw new MavenReportException( "Could not create the output directory" ); + protected abstract void populateDependencyManagement( + Set dependencyManagementCollector, Set dependencies) throws MavenReportException; + + private void renderReport(Locale locale, Sink sink, DependencyUpdatesModel model) throws MavenReportException { + for (String format : formats) { + if ("html".equals(format)) { + rendererFactory + .createReportRenderer(getOutputName(), sink, locale, model) + .render(); + } else if ("xml".equals(format)) { + Path outputDir = Paths.get(getProject().getBuild().getDirectory()); + if (!Files.exists(outputDir)) { + try { + Files.createDirectories(outputDir); + } catch (IOException e) { + throw new MavenReportException("Could not create the output directory"); } } - Path outputFile = outputDir.resolve( getOutputName() + ".xml" ); - new DependencyUpdatesXmlReportRenderer( model, outputFile ).render(); + Path outputFile = outputDir.resolve(getOutputName() + ".xml"); + new DependencyUpdatesXmlReportRenderer(model, outputFile).render(); } } } @@ -335,20 +297,18 @@ else if ( "xml".equals( format ) ) * * @return true if the two dependencies match */ - private boolean match( Dependency dep, Dependency dmDep ) - { - return dmDep.getGroupId().equals( dep.getGroupId() ) - && dmDep.getArtifactId().equals( dep.getArtifactId() ) - && ( dmDep.getScope() == null || dmDep.getScope().equals( dep.getScope() ) ) - && ( dmDep.getClassifier() == null || dmDep.getClassifier().equals( dep.getClassifier() ) ) - && ( dep.getVersion() == null || dmDep.getVersion() == null || dmDep.getVersion() - .equals( dep.getVersion() ) ); + private boolean match(Dependency dep, Dependency dmDep) { + return dmDep.getGroupId().equals(dep.getGroupId()) + && dmDep.getArtifactId().equals(dep.getArtifactId()) + && (dmDep.getScope() == null || dmDep.getScope().equals(dep.getScope())) + && (dmDep.getClassifier() == null || dmDep.getClassifier().equals(dep.getClassifier())) + && (dep.getVersion() == null + || dmDep.getVersion() == null + || dmDep.getVersion().equals(dep.getVersion())); } - protected boolean hasDependencyManagement( MavenProject project ) - { - if ( project == null ) - { + protected boolean hasDependencyManagement(MavenProject project) { + if (project == null) { return false; } return project.getDependencyManagement() != null @@ -358,8 +318,7 @@ protected boolean hasDependencyManagement( MavenProject project ) /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "dependency-updates-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPluginUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPluginUpdatesReportMojo.java index 36ed84d9f0..f96ec322cb 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPluginUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPluginUpdatesReportMojo.java @@ -17,8 +17,6 @@ * */ -import static org.codehaus.mojo.versions.utils.MiscUtils.filter; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -27,6 +25,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; + import org.apache.maven.doxia.sink.Sink; import org.apache.maven.model.Plugin; import org.apache.maven.plugins.annotations.Parameter; @@ -42,20 +41,20 @@ import org.codehaus.mojo.versions.xml.PluginUpdatesXmlReportRenderer; import org.codehaus.plexus.i18n.I18N; +import static org.codehaus.mojo.versions.utils.MiscUtils.filter; + /** * Generates a report of available updates for the plugins of a project. */ - -public abstract class AbstractPluginUpdatesReportMojo extends AbstractVersionsReport -{ +public abstract class AbstractPluginUpdatesReportMojo extends AbstractVersionsReport { private static final PluginComparator PLUGIN_COMPARATOR = PluginComparator.INSTANCE; /** * Report formats (html and/or xml). HTML by default. */ - @Parameter( property = "pluginUpdatesReportFormats", defaultValue = "html" ) - private String[] formats = new String[] { "html" }; + @Parameter(property = "pluginUpdatesReportFormats", defaultValue = "html") + private String[] formats = new String[] {"html"}; /** * If true, only shows the subsection of the pluginManagement artifacts that @@ -63,7 +62,7 @@ public abstract class AbstractPluginUpdatesReportMojo extends AbstractVersionsRe * * @since 2.12 */ - @Parameter( property = "onlyProjectPlugins", defaultValue = "false" ) + @Parameter(property = "onlyProjectPlugins", defaultValue = "false") protected boolean onlyProjectPlugins; /** @@ -71,44 +70,42 @@ public abstract class AbstractPluginUpdatesReportMojo extends AbstractVersionsRe * * @since 2.12 */ - @Parameter( property = "onlyUpgradable", defaultValue = "false" ) + @Parameter(property = "onlyUpgradable", defaultValue = "false") protected boolean onlyUpgradable; - public AbstractPluginUpdatesReportMojo( I18N i18n, - RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + public AbstractPluginUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} */ - public boolean isExternalReport() - { + public boolean isExternalReport() { return false; } /** * {@inheritDoc} */ - public boolean canGenerateReport() - { - return haveBuildPlugins( getProject() ) || haveBuildPluginManagementPlugins( getProject() ); + public boolean canGenerateReport() { + return haveBuildPlugins(getProject()) || haveBuildPluginManagementPlugins(getProject()); } - protected boolean haveBuildPluginManagementPlugins( MavenProject project ) - { - return project.getBuild() != null && project.getBuild().getPluginManagement() != null - && project.getBuild().getPluginManagement().getPlugins() != null && !project.getBuild() - .getPluginManagement().getPlugins().isEmpty(); + protected boolean haveBuildPluginManagementPlugins(MavenProject project) { + return project.getBuild() != null + && project.getBuild().getPluginManagement() != null + && project.getBuild().getPluginManagement().getPlugins() != null + && !project.getBuild().getPluginManagement().getPlugins().isEmpty(); } - protected boolean haveBuildPlugins( MavenProject project ) - { - return project.getBuild() != null && project.getBuild().getPlugins() != null + protected boolean haveBuildPlugins(MavenProject project) { + return project.getBuild() != null + && project.getBuild().getPlugins() != null && !project.getBuild().getPlugins().isEmpty(); } @@ -118,34 +115,29 @@ protected boolean haveBuildPlugins( MavenProject project ) * @param locale the locale to generate the report for. * @param sink the report formatting tool */ - protected void doGenerateReport( Locale locale, Sink sink ) throws MavenReportException - { + protected void doGenerateReport(Locale locale, Sink sink) throws MavenReportException { Set pluginManagement = getPluginManagement(); Set plugins = getPlugins(); - handleOnlyProjectPlugins( pluginManagement, plugins ); + handleOnlyProjectPlugins(pluginManagement, plugins); - try - { + try { Map pluginUpdates = - getHelper().lookupPluginsUpdates( plugins, getAllowSnapshots() ); + getHelper().lookupPluginsUpdates(plugins, getAllowSnapshots()); Map pluginManagementUpdates = - getHelper().lookupPluginsUpdates( pluginManagement, getAllowSnapshots() ); + getHelper().lookupPluginsUpdates(pluginManagement, getAllowSnapshots()); - if ( onlyUpgradable ) - { - pluginUpdates = filter( pluginUpdates, p -> p.getVersions().length > 0 ); - pluginManagementUpdates = filter( pluginManagementUpdates, p -> p.getVersions().length > 0 ); + if (onlyUpgradable) { + pluginUpdates = filter(pluginUpdates, p -> p.getVersions().length > 0); + pluginManagementUpdates = filter(pluginManagementUpdates, p -> p.getVersions().length > 0); } - renderReport( locale, sink, new PluginUpdatesModel( pluginUpdates, pluginManagementUpdates ) ); - } - catch ( VersionRetrievalException e ) - { - throw new MavenReportException( e.getMessage(), e ); + renderReport(locale, sink, new PluginUpdatesModel(pluginUpdates, pluginManagementUpdates)); + } catch (VersionRetrievalException e) { + throw new MavenReportException(e.getMessage(), e); } } @@ -157,10 +149,9 @@ protected void doGenerateReport( Locale locale, Sink sink ) throws MavenReportEx * @return a {@link Set} that can be additionally populated by {@link #populatePluginManagement(Set)}}. * If not, an empty set is returned * */ - private Set getPluginManagement() - { - final Set pluginManagementCollector = new TreeSet<>( PLUGIN_COMPARATOR ); - populatePluginManagement( pluginManagementCollector ); + private Set getPluginManagement() { + final Set pluginManagementCollector = new TreeSet<>(PLUGIN_COMPARATOR); + populatePluginManagement(pluginManagementCollector); return pluginManagementCollector; } @@ -170,8 +161,7 @@ private Set getPluginManagement() * * @param pluginManagementCollector, a set initialized with a {@link PluginComparator} comparator. * */ - protected abstract void populatePluginManagement( Set pluginManagementCollector ); - + protected abstract void populatePluginManagement(Set pluginManagementCollector); /** * Constructs a final instance of a {@link Set} with a {@link PluginComparator} comparator. This set can be @@ -180,10 +170,9 @@ private Set getPluginManagement() * @return a {@link Set} that can be additionally populated by {@link #populatePlugins(Set)}. * If not, an empty set is returned * */ - private Set getPlugins() - { - final Set pluginsCollector = new TreeSet<>( PLUGIN_COMPARATOR ); - populatePlugins( pluginsCollector ); + private Set getPlugins() { + final Set pluginsCollector = new TreeSet<>(PLUGIN_COMPARATOR); + populatePlugins(pluginsCollector); return pluginsCollector; } @@ -193,52 +182,39 @@ private Set getPlugins() * *@param pluginsCollector, a set initialized with a {@link PluginComparator} comparator. * */ - protected abstract void populatePlugins( Set pluginsCollector ); - - private void renderReport( Locale locale, Sink sink, PluginUpdatesModel model ) - throws MavenReportException - { - for ( String format : formats ) - { - if ( "html".equals( format ) ) - { - rendererFactory.createReportRenderer( getOutputName(), sink, locale, model ).render(); - } - else if ( "xml".equals( format ) ) - { - Path outputDir = Paths.get( getProject().getBuild().getDirectory() ); - if ( !Files.exists( outputDir ) ) - { - try - { - Files.createDirectories( outputDir ); - } - catch ( IOException e ) - { - throw new MavenReportException( "Could not create the output directory" ); + protected abstract void populatePlugins(Set pluginsCollector); + + private void renderReport(Locale locale, Sink sink, PluginUpdatesModel model) throws MavenReportException { + for (String format : formats) { + if ("html".equals(format)) { + rendererFactory + .createReportRenderer(getOutputName(), sink, locale, model) + .render(); + } else if ("xml".equals(format)) { + Path outputDir = Paths.get(getProject().getBuild().getDirectory()); + if (!Files.exists(outputDir)) { + try { + Files.createDirectories(outputDir); + } catch (IOException e) { + throw new MavenReportException("Could not create the output directory"); } } - Path outputFile = outputDir.resolve( getOutputName() + ".xml" ); - new PluginUpdatesXmlReportRenderer( model, outputFile ).render(); + Path outputFile = outputDir.resolve(getOutputName() + ".xml"); + new PluginUpdatesXmlReportRenderer(model, outputFile).render(); } } } - private void handleOnlyProjectPlugins( Set pluginManagement, Set plugins ) - { + private void handleOnlyProjectPlugins(Set pluginManagement, Set plugins) { - if ( !onlyProjectPlugins ) - { + if (!onlyProjectPlugins) { // Retains only plugins not present in pluginManagement - plugins.removeIf( plugin -> pluginManagement.stream() - .anyMatch( pmPlugin -> PLUGIN_COMPARATOR.compare( plugin, pmPlugin ) == 0 ) ); - } - else - { + plugins.removeIf(plugin -> + pluginManagement.stream().anyMatch(pmPlugin -> PLUGIN_COMPARATOR.compare(plugin, pmPlugin) == 0)); + } else { // Retain only plugins in pluginManagement that are also present in plugins pluginManagement.removeIf( - pmPlugin -> plugins.stream() - .noneMatch( plugin -> PLUGIN_COMPARATOR.compare( plugin, pmPlugin ) == 0 ) ); + pmPlugin -> plugins.stream().noneMatch(plugin -> PLUGIN_COMPARATOR.compare(plugin, pmPlugin) == 0)); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPropertyUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPropertyUpdatesReportMojo.java index 0380369d03..e2ab84276a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPropertyUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractPropertyUpdatesReportMojo.java @@ -24,6 +24,7 @@ import java.util.Locale; import java.util.Map; import java.util.TreeMap; + import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; @@ -44,9 +45,7 @@ * Generates a report of available updates for properties of a project which are linked to the dependencies and/or * plugins of a project. */ -public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersionsReport -{ - +public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersionsReport { private static final PropertyComparator PROPERTIES_COMPARATOR = PropertyComparator.INSTANCE; @@ -63,7 +62,7 @@ public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersions * * @since 1.0-beta-1 */ - @Parameter( property = "includeProperties" ) + @Parameter(property = "includeProperties") private String includeProperties = null; /** @@ -71,7 +70,7 @@ public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersions * * @since 1.0-beta-1 */ - @Parameter( property = "excludeProperties" ) + @Parameter(property = "excludeProperties") private String excludeProperties = null; /** @@ -79,7 +78,7 @@ public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersions * * @since 1.0-beta-1 */ - @Parameter( property = "autoLinkItems", defaultValue = "true" ) + @Parameter(property = "autoLinkItems", defaultValue = "true") private boolean autoLinkItems; /** @@ -87,7 +86,7 @@ public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersions * * @since 2.14.0 */ - @Parameter( property = "includeParent", defaultValue = "true" ) + @Parameter(property = "includeParent", defaultValue = "true") private boolean includeParent = true; /** @@ -95,56 +94,46 @@ public abstract class AbstractPropertyUpdatesReportMojo extends AbstractVersions * * @since 2.14.0 */ - @Parameter( property = "propertyUpdatesReportFormats", defaultValue = "html" ) + @Parameter(property = "propertyUpdatesReportFormats", defaultValue = "html") protected String[] formats = new String[] {"html"}; - public AbstractPropertyUpdatesReportMojo( I18N i18n, - RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + public AbstractPropertyUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} */ - public boolean isExternalReport() - { + public boolean isExternalReport() { return false; } /** * {@inheritDoc} */ - public boolean canGenerateReport() - { + public boolean canGenerateReport() { return haveBuildProperties(); } - protected boolean haveBuildProperties() - { - return getProject().getProperties() != null && !getProject().getProperties().isEmpty(); + protected boolean haveBuildProperties() { + return getProject().getProperties() != null + && !getProject().getProperties().isEmpty(); } - protected void doGenerateReport( Locale locale, Sink sink ) - throws MavenReportException - { - try - { - final Map updateSet = new TreeMap<>( PROPERTIES_COMPARATOR ); - populateUpdateSet( updateSet ); - - renderReport( locale, - sink, - getPropertyUpdatesModel( updateSet ) ); - } - catch ( MojoExecutionException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } + protected void doGenerateReport(Locale locale, Sink sink) throws MavenReportException { + try { + final Map updateSet = new TreeMap<>(PROPERTIES_COMPARATOR); + populateUpdateSet(updateSet); + renderReport(locale, sink, getPropertyUpdatesModel(updateSet)); + } catch (MojoExecutionException e) { + throw new MavenReportException(e.getMessage(), e); + } } /** @@ -155,64 +144,51 @@ protected void doGenerateReport( Locale locale, Sink sink ) * @throws MavenReportException when things go wrong. * @throws MojoExecutionException if something goes wrong. * */ - protected abstract void populateUpdateSet( - Map propertyCollector ) + protected abstract void populateUpdateSet(Map propertyCollector) throws MojoExecutionException, MavenReportException; + private void renderReport(Locale locale, Sink sink, PropertyUpdatesModel propertyUpdatesModel) + throws MavenReportException { - private void renderReport( Locale locale, Sink sink, PropertyUpdatesModel propertyUpdatesModel ) - throws MavenReportException - { - - for ( String format : this.formats ) - { - if ( "html".equals( format ) ) - { - this.rendererFactory.createReportRenderer( getOutputName(), sink, locale, propertyUpdatesModel ) + for (String format : this.formats) { + if ("html".equals(format)) { + this.rendererFactory + .createReportRenderer(getOutputName(), sink, locale, propertyUpdatesModel) .render(); - } - else if ( "xml".equals( format ) ) - { - Path outputDir = Paths.get( getProject().getBuild().getDirectory() ); - if ( !Files.exists( outputDir ) ) - { - try - { - Files.createDirectories( outputDir ); - } - catch ( IOException e ) - { - throw new MavenReportException( "Could not create the output directory" ); + } else if ("xml".equals(format)) { + Path outputDir = Paths.get(getProject().getBuild().getDirectory()); + if (!Files.exists(outputDir)) { + try { + Files.createDirectories(outputDir); + } catch (IOException e) { + throw new MavenReportException("Could not create the output directory"); } } - Path outputFile = outputDir.resolve( getOutputName() + ".xml" ); - new PropertyUpdatesXmlReportRenderer( propertyUpdatesModel, outputFile ).render(); + Path outputFile = outputDir.resolve(getOutputName() + ".xml"); + new PropertyUpdatesXmlReportRenderer(propertyUpdatesModel, outputFile).render(); } } } - private PropertyUpdatesModel getPropertyUpdatesModel( Map updateSet ) - { - return new PropertyUpdatesModel( PROPERTIES_COMPARATOR, updateSet ); + private PropertyUpdatesModel getPropertyUpdatesModel(Map updateSet) { + return new PropertyUpdatesModel(PROPERTIES_COMPARATOR, updateSet); } - protected VersionPropertiesMapRequest getRequest( MavenProject project ) - { + protected VersionPropertiesMapRequest getRequest(MavenProject project) { return VersionPropertiesMapRequest.builder() - .withMavenProject( project ) - .withPropertyDefinitions( this.properties ) - .withIncludeProperties( this.includeProperties ) - .withExcludeProperties( this.excludeProperties ) - .withIncludeParent( this.includeParent ) - .withAutoLinkItems( this.autoLinkItems ) + .withMavenProject(project) + .withPropertyDefinitions(this.properties) + .withIncludeProperties(this.includeProperties) + .withExcludeProperties(this.excludeProperties) + .withIncludeParent(this.includeParent) + .withAutoLinkItems(this.autoLinkItems) .build(); } /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "property-updates-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDependencyUpdaterMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDependencyUpdaterMojo.java index 2f442832aa..dd27032b9b 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDependencyUpdaterMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDependencyUpdaterMojo.java @@ -56,9 +56,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public abstract class AbstractVersionsDependencyUpdaterMojo - extends AbstractVersionsUpdaterMojo -{ +public abstract class AbstractVersionsDependencyUpdaterMojo extends AbstractVersionsUpdaterMojo { private static final String END_RANGE_CHARS = "])"; private static final String START_RANGE_CHARS = "[("; @@ -66,8 +64,7 @@ public abstract class AbstractVersionsDependencyUpdaterMojo /** * Pattern to match snapshot versions */ - protected static final Pattern SNAPSHOT_REGEX = Pattern.compile( "^(.+)-((SNAPSHOT)|(\\d{8}\\.\\d{6}-\\d+))$" ); - + protected static final Pattern SNAPSHOT_REGEX = Pattern.compile("^(.+)-((SNAPSHOT)|(\\d{8}\\.\\d{6}-\\d+))$"); /** * A comma separated list of artifact patterns to include. Follows the pattern @@ -77,7 +74,7 @@ public abstract class AbstractVersionsDependencyUpdaterMojo * * @since 1.0-beta-1 */ - @Parameter( property = "includes" ) + @Parameter(property = "includes") private String includesList = null; /** @@ -88,7 +85,7 @@ public abstract class AbstractVersionsDependencyUpdaterMojo * * @since 1.0-beta-1 */ - @Parameter( property = "excludes" ) + @Parameter(property = "excludes") private String excludesList = null; /** @@ -114,7 +111,7 @@ public abstract class AbstractVersionsDependencyUpdaterMojo * * @since 1.0-alpha-3 */ - @Parameter( property = "processDependencies", defaultValue = "true" ) + @Parameter(property = "processDependencies", defaultValue = "true") private boolean processDependencies = true; /** @@ -122,7 +119,7 @@ public abstract class AbstractVersionsDependencyUpdaterMojo * * @since 1.0-alpha-3 */ - @Parameter( property = "processDependencyManagement", defaultValue = "true" ) + @Parameter(property = "processDependencyManagement", defaultValue = "true") private boolean processDependencyManagement = true; /** @@ -130,7 +127,7 @@ public abstract class AbstractVersionsDependencyUpdaterMojo * * @since 2.3 */ - @Parameter( property = "processParent", defaultValue = "false" ) + @Parameter(property = "processParent", defaultValue = "false") private boolean processParent = false; /** @@ -152,16 +149,16 @@ public abstract class AbstractVersionsDependencyUpdaterMojo * * @since 1.0-alpha-3 */ - @Parameter( property = "excludeReactor", defaultValue = "true" ) + @Parameter(property = "excludeReactor", defaultValue = "true") private boolean excludeReactor = true; @Inject - protected AbstractVersionsDependencyUpdaterMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + protected AbstractVersionsDependencyUpdaterMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -170,8 +167,7 @@ protected AbstractVersionsDependencyUpdaterMojo( RepositorySystem repositorySyst * @return returns true if the project/dependencies section of the pom should be processed. * @since 1.0-alpha-3 */ - public boolean isProcessingDependencies() - { + public boolean isProcessingDependencies() { return processDependencies; } @@ -181,8 +177,7 @@ public boolean isProcessingDependencies() * @return returns true if the project/dependencyManagement section of the pom should be processed. * @since 1.0-alpha-3 */ - public boolean isProcessingDependencyManagement() - { + public boolean isProcessingDependencyManagement() { return processDependencyManagement; } @@ -192,8 +187,7 @@ public boolean isProcessingDependencyManagement() * @return returns true if the project/parent section of the pom should be processed. * @since 2.3 */ - public boolean isProcessingParent() - { + public boolean isProcessingParent() { return processParent; } @@ -204,8 +198,7 @@ public boolean isProcessingParent() * should be excluded from processing. * @since 1.0-alpha-3 */ - public boolean isExcludeReactor() - { + public boolean isExcludeReactor() { return excludeReactor; } @@ -216,10 +209,9 @@ public boolean isExcludeReactor() * @return true if the version starts with '${' * @since 2.8 */ - protected boolean isHandledByProperty( Dependency dependency ) - { + protected boolean isHandledByProperty(Dependency dependency) { String version = dependency.getVersion(); - return version != null && version.startsWith( "${" ); + return version != null && version.startsWith("${"); } /** @@ -229,16 +221,12 @@ protected boolean isHandledByProperty( Dependency dependency ) * @return Artifact * @since 1.0-alpha-3 */ - protected Artifact findArtifact( Dependency dependency ) - { - if ( getProject().getDependencyArtifacts() == null ) - { + protected Artifact findArtifact(Dependency dependency) { + if (getProject().getDependencyArtifacts() == null) { return null; } - for ( Artifact artifact : getProject().getDependencyArtifacts() ) - { - if ( compare( artifact, dependency ) ) - { + for (Artifact artifact : getProject().getDependencyArtifacts()) { + if (compare(artifact, dependency)) { return artifact; } } @@ -253,84 +241,70 @@ protected Artifact findArtifact( Dependency dependency ) * @throws MojoExecutionException Mojo execution exception * @since 1.0-alpha-3 */ - protected Artifact toArtifact( Dependency dependency ) - throws MojoExecutionException - { - Artifact artifact = findArtifact( dependency ); - if ( artifact == null ) - { - return getHelper().createDependencyArtifact( dependency ); + protected Artifact toArtifact(Dependency dependency) throws MojoExecutionException { + Artifact artifact = findArtifact(dependency); + if (artifact == null) { + return getHelper().createDependencyArtifact(dependency); } return artifact; } - protected Artifact toArtifact( Parent model ) - throws MojoExecutionException - { - return this.toArtifact( DependencyBuilder.newBuilder() - .withGroupId( model.getGroupId() ) - .withArtifactId( model.getArtifactId() ) - .withVersion( model.getVersion() ) - .withType( "pom" ) - .withScope( Artifact.SCOPE_COMPILE ) - .build() ); + protected Artifact toArtifact(Parent model) throws MojoExecutionException { + return this.toArtifact(DependencyBuilder.newBuilder() + .withGroupId(model.getGroupId()) + .withArtifactId(model.getArtifactId()) + .withVersion(model.getVersion()) + .withType("pom") + .withScope(Artifact.SCOPE_COMPILE) + .build()); } /** * Returns the {@link Dependency} instance for the parent project * @return {@link Dependency} object for the parent */ - protected Dependency getParentDependency() - { + protected Dependency getParentDependency() { return DependencyBuilder.newBuilder() - .withGroupId( getProject().getParent().getGroupId() ) - .withArtifactId( getProject().getParent().getArtifactId() ) - .withVersion( getProject().getParent().getVersion() ) - .withType( "pom" ) + .withGroupId(getProject().getParent().getGroupId()) + .withArtifactId(getProject().getParent().getArtifactId()) + .withVersion(getProject().getParent().getVersion()) + .withType("pom") .build(); } - protected String toString( MavenProject project ) - { + protected String toString(MavenProject project) { StringBuilder buf = new StringBuilder(); - buf.append( project.getGroupId() ); - buf.append( ':' ); - buf.append( project.getArtifactId() ); + buf.append(project.getGroupId()); + buf.append(':'); + buf.append(project.getArtifactId()); - if ( project.getVersion() != null && project.getVersion().length() > 0 ) - { - buf.append( ":" ); - buf.append( project.getVersion() ); + if (project.getVersion() != null && project.getVersion().length() > 0) { + buf.append(":"); + buf.append(project.getVersion()); } return buf.toString(); } - protected String toString( Dependency d ) - { + protected String toString(Dependency d) { StringBuilder buf = new StringBuilder(); - buf.append( d.getGroupId() ); - buf.append( ':' ); - buf.append( d.getArtifactId() ); - if ( d.getType() != null && d.getType().length() > 0 ) - { - buf.append( ':' ); - buf.append( d.getType() ); - } - else - { - buf.append( ":jar" ); + buf.append(d.getGroupId()); + buf.append(':'); + buf.append(d.getArtifactId()); + if (d.getType() != null && d.getType().length() > 0) { + buf.append(':'); + buf.append(d.getType()); + } else { + buf.append(":jar"); } - if ( d.getClassifier() != null && d.getClassifier().length() > 0 ) - { - buf.append( ':' ); - buf.append( d.getClassifier() ); + if (d.getClassifier() != null && d.getClassifier().length() > 0) { + buf.append(':'); + buf.append(d.getClassifier()); } - if ( d.getVersion() != null && d.getVersion().length() > 0 ) - { - buf.append( ":" ); - buf.append( d.getVersion() ); + if (d.getVersion() != null && d.getVersion().length() > 0) { + buf.append(":"); + buf.append(d.getVersion()); } return buf.toString(); } @@ -342,10 +316,8 @@ protected String toString( Dependency d ) * @return true if the dependency is produced by the current reactor. * @since 1.0-alpha-3 */ - protected boolean isProducedByReactor( Dependency dependency ) - { - return reactorProjects.stream() - .anyMatch( reactorProject -> compare( reactorProject, dependency ) ); + protected boolean isProducedByReactor(Dependency dependency) { + return reactorProjects.stream().anyMatch(reactorProject -> compare(reactorProject, dependency)); } /** @@ -355,13 +327,11 @@ protected boolean isProducedByReactor( Dependency dependency ) * @param dep the dependency * @return true if project and dep refer to the same artifact */ - private boolean compare( MavenProject project, Dependency dep ) - { - if ( !StringUtils.equals( project.getGroupId(), dep.getGroupId() ) ) - { + private boolean compare(MavenProject project, Dependency dep) { + if (!StringUtils.equals(project.getGroupId(), dep.getGroupId())) { return false; } - return project.getArtifactId().equals( dep.getArtifactId() ); + return project.getArtifactId().equals(dep.getArtifactId()); } /** @@ -372,21 +342,17 @@ private boolean compare( MavenProject project, Dependency dep ) * @param dep Dependency * @return true if artifact and dep refer to the same artifact */ - private boolean compare( Artifact artifact, Dependency dep ) - { - if ( !StringUtils.equals( artifact.getGroupId(), dep.getGroupId() ) ) - { + private boolean compare(Artifact artifact, Dependency dep) { + if (!StringUtils.equals(artifact.getGroupId(), dep.getGroupId())) { return false; } - if ( !StringUtils.equals( artifact.getArtifactId(), dep.getArtifactId() ) ) - { + if (!StringUtils.equals(artifact.getArtifactId(), dep.getArtifactId())) { return false; } - if ( !StringUtils.equals( artifact.getType(), dep.getType() ) ) - { + if (!StringUtils.equals(artifact.getType(), dep.getType())) { return false; } - return StringUtils.equals( artifact.getClassifier(), dep.getClassifier() ); + return StringUtils.equals(artifact.getClassifier(), dep.getClassifier()); } /** @@ -395,22 +361,19 @@ private boolean compare( Artifact artifact, Dependency dep ) * @param artifact The artifact we want to check. * @return true if the artifact should be processed, false otherwise. */ - protected boolean isIncluded( Artifact artifact ) - { + protected boolean isIncluded(Artifact artifact) { boolean result = true; ArtifactFilter includesFilter = this.getIncludesArtifactFilter(); - if ( includesFilter != null ) - { - result = includesFilter.include( artifact ); + if (includesFilter != null) { + result = includesFilter.include(artifact); } ArtifactFilter excludesFilter = this.getExcludesArtifactFilter(); - if ( excludesFilter != null ) - { - result = result && excludesFilter.include( artifact ); + if (excludesFilter != null) { + result = result && excludesFilter.include(artifact); } return result; @@ -421,43 +384,32 @@ protected boolean isIncluded( Artifact artifact ) * * @return true if includes were specified, false otherwise. */ - protected boolean hasIncludes() - { + protected boolean hasIncludes() { return includes != null || includesList != null; } - private ArtifactFilter getIncludesArtifactFilter() - { - if ( includesFilter == null && ( includes != null || includesList != null ) ) - { + private ArtifactFilter getIncludesArtifactFilter() { + if (includesFilter == null && (includes != null || includesList != null)) { List patterns = new ArrayList<>(); - if ( this.includesList != null ) - { - patterns.addAll( separatePatterns( includesList ) ); - } - else if ( includes != null ) - { - patterns.addAll( Arrays.asList( includes ) ); + if (this.includesList != null) { + patterns.addAll(separatePatterns(includesList)); + } else if (includes != null) { + patterns.addAll(Arrays.asList(includes)); } - includesFilter = new PatternIncludesArtifactFilter( patterns ); + includesFilter = new PatternIncludesArtifactFilter(patterns); } return includesFilter; } - private ArtifactFilter getExcludesArtifactFilter() - { - if ( excludesFilter == null && ( excludes != null || excludesList != null ) ) - { + private ArtifactFilter getExcludesArtifactFilter() { + if (excludesFilter == null && (excludes != null || excludesList != null)) { List patterns = new ArrayList<>(); - if ( excludesList != null ) - { - patterns.addAll( separatePatterns( excludesList ) ); + if (excludesList != null) { + patterns.addAll(separatePatterns(excludesList)); + } else if (excludes != null) { + patterns.addAll(Arrays.asList(excludes)); } - else if ( excludes != null ) - { - patterns.addAll( Arrays.asList( excludes ) ); - } - excludesFilter = new PatternExcludesArtifactFilter( patterns ); + excludesFilter = new PatternExcludesArtifactFilter(patterns); } return excludesFilter; } @@ -469,62 +421,49 @@ else if ( excludes != null ) * @param includeString the string to parse * @return list of patterns */ - protected List separatePatterns( String includeString ) - { - if ( includeString == null ) - { + protected List separatePatterns(String includeString) { + if (includeString == null) { return Collections.emptyList(); } List patterns = new ArrayList<>(); - int indexOf = nextCommaIndex( includeString ); - while ( indexOf >= 0 ) - { - patterns.add( includeString.substring( 0, indexOf ) ); - includeString = includeString.substring( indexOf + 1 ); - indexOf = nextCommaIndex( includeString ); + int indexOf = nextCommaIndex(includeString); + while (indexOf >= 0) { + patterns.add(includeString.substring(0, indexOf)); + includeString = includeString.substring(indexOf + 1); + indexOf = nextCommaIndex(includeString); } - patterns.add( includeString ); + patterns.add(includeString); return patterns; } - private int nextCommaIndex( final String includeString ) - { + private int nextCommaIndex(final String includeString) { - int indexOfComma = includeString.indexOf( ',' ); - int nextRangeStartDelimiterIndex = findFirstChar( includeString, START_RANGE_CHARS ); - if ( nextRangeStartDelimiterIndex >= 0 ) - { - if ( !( indexOfComma >= 0 && indexOfComma < nextRangeStartDelimiterIndex ) ) - { - int nextStopDelimiterIndex = findFirstChar( includeString, END_RANGE_CHARS ); + int indexOfComma = includeString.indexOf(','); + int nextRangeStartDelimiterIndex = findFirstChar(includeString, START_RANGE_CHARS); + if (nextRangeStartDelimiterIndex >= 0) { + if (!(indexOfComma >= 0 && indexOfComma < nextRangeStartDelimiterIndex)) { + int nextStopDelimiterIndex = findFirstChar(includeString, END_RANGE_CHARS); // recursive call - int tmp = nextCommaIndex( includeString.substring( nextStopDelimiterIndex + 1 ) ); - indexOfComma = ( tmp >= 0 ) ? nextStopDelimiterIndex + 1 + tmp : -1; + int tmp = nextCommaIndex(includeString.substring(nextStopDelimiterIndex + 1)); + indexOfComma = (tmp >= 0) ? nextStopDelimiterIndex + 1 + tmp : -1; } } return indexOfComma; - } - private int findFirstChar( final String includeString, final String chars ) - { + private int findFirstChar(final String includeString, final String chars) { int nextRangeStartDelimiterIndex = -1; char[] delimiters = chars.toCharArray(); - for ( char delimiter : delimiters ) - { - int index = includeString.indexOf( delimiter ); - if ( index >= 0 && nextRangeStartDelimiterIndex >= 0 ) - { - nextRangeStartDelimiterIndex = Math.min( index, nextRangeStartDelimiterIndex ); - } - else - { - if ( index >= 0 ) - { + for (char delimiter : delimiters) { + int index = includeString.indexOf(delimiter); + if (index >= 0 && nextRangeStartDelimiterIndex >= 0) { + nextRangeStartDelimiterIndex = Math.min(index, nextRangeStartDelimiterIndex); + } else { + if (index >= 0) { nextRangeStartDelimiterIndex = index; } } @@ -543,45 +482,52 @@ private int findFirstChar( final String includeString, final String chars ) * @return {@code true} if an update has been made, {@code false} otherwise * @throws XMLStreamException thrown if updating the XML doesn't succeed */ - protected boolean updateDependencyVersion( ModifiedPomXMLEventReader pom, Dependency dep, - String newVersion, ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException - { + protected boolean updateDependencyVersion( + ModifiedPomXMLEventReader pom, Dependency dep, String newVersion, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException { boolean updated = false; - if ( isProcessingParent() + if (isProcessingParent() && getProject().getParent() != null - && DependencyComparator.INSTANCE.compare( dep, DependencyBuilder.newBuilder() - .withGroupId( getProject().getParentArtifact().getGroupId() ) - .withArtifactId( getProject().getParentArtifact().getArtifactId() ) - .withVersion( getProject().getParentArtifact().getVersion() ) - .build() ) == 0 - && PomHelper.setProjectParentVersion( pom, newVersion ) ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Made parent update from " + dep.getVersion() + " to " + newVersion ); + && DependencyComparator.INSTANCE.compare( + dep, + DependencyBuilder.newBuilder() + .withGroupId( + getProject().getParentArtifact().getGroupId()) + .withArtifactId( + getProject().getParentArtifact().getArtifactId()) + .withVersion( + getProject().getParentArtifact().getVersion()) + .build()) + == 0 + && PomHelper.setProjectParentVersion(pom, newVersion)) { + if (getLog().isDebugEnabled()) { + getLog().debug("Made parent update from " + dep.getVersion() + " to " + newVersion); } - getChangeRecorder().recordChange( DefaultChangeRecord.builder() - .withKind( changeKind ) - .withDependency( dep ) - .withNewVersion( newVersion ) - .build() ); + getChangeRecorder() + .recordChange(DefaultChangeRecord.builder() + .withKind(changeKind) + .withDependency(dep) + .withNewVersion(newVersion) + .build()); updated = true; } - if ( PomHelper.setDependencyVersion( pom, - dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), - newVersion, getProject().getModel() ) ) - { - if ( getLog().isInfoEnabled() ) - { - getLog().info( "Updated " + toString( dep ) + " to version " + newVersion ); + if (PomHelper.setDependencyVersion( + pom, + dep.getGroupId(), + dep.getArtifactId(), + dep.getVersion(), + newVersion, + getProject().getModel())) { + if (getLog().isInfoEnabled()) { + getLog().info("Updated " + toString(dep) + " to version " + newVersion); } - getChangeRecorder().recordChange( DefaultChangeRecord.builder() - .withKind( changeKind ) - .withDependency( dep ) - .withNewVersion( newVersion ) - .build() ); + getChangeRecorder() + .recordChange(DefaultChangeRecord.builder() + .withKind(changeKind) + .withDependency(dep) + .withNewVersion(newVersion) + .build()); updated = true; } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDisplayMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDisplayMojo.java index 635732cb83..e59587f3e9 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDisplayMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsDisplayMojo.java @@ -40,10 +40,8 @@ * * @author Stephen Connolly */ -public abstract class AbstractVersionsDisplayMojo - extends AbstractVersionsUpdaterMojo -{ - static final String NL = System.getProperty( "line.separator" ); +public abstract class AbstractVersionsDisplayMojo extends AbstractVersionsUpdaterMojo { + static final String NL = System.getProperty("line.separator"); private static final int DEFAULT_OUTPUT_LINE_WIDTH = 80; @@ -52,7 +50,7 @@ public abstract class AbstractVersionsDisplayMojo * * @since 2.2 */ - @Parameter( property = "versions.outputFile" ) + @Parameter(property = "versions.outputFile") protected File outputFile; /** @@ -60,7 +58,7 @@ public abstract class AbstractVersionsDisplayMojo * * @since 2.2 */ - @Parameter( property = "versions.logOutput", defaultValue = "true" ) + @Parameter(property = "versions.logOutput", defaultValue = "true") protected boolean logOutput; /** @@ -68,7 +66,7 @@ public abstract class AbstractVersionsDisplayMojo * * @since 2.2 */ - @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") protected String outputEncoding; /** @@ -76,105 +74,81 @@ public abstract class AbstractVersionsDisplayMojo * * @since 2.10.0 */ - @Parameter( property = "versions.outputLineWidth", - defaultValue = AbstractVersionsDisplayMojo.DEFAULT_OUTPUT_LINE_WIDTH + "" ) + @Parameter( + property = "versions.outputLineWidth", + defaultValue = AbstractVersionsDisplayMojo.DEFAULT_OUTPUT_LINE_WIDTH + "") protected int outputLineWidth; private boolean outputFileError = false; @Inject - protected AbstractVersionsDisplayMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + protected AbstractVersionsDisplayMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } - @SuppressWarnings( "unchecked" ) - protected void logInit() - { - if ( outputFile != null && !outputFileError ) - { - if ( outputFile.isFile() ) - { + @SuppressWarnings("unchecked") + protected void logInit() { + if (outputFile != null && !outputFileError) { + if (outputFile.isFile()) { final String key = AbstractVersionsDisplayMojo.class.getName() + ".outputFile"; String outputFileName; - try - { + try { outputFileName = outputFile.getCanonicalPath(); - } - catch ( IOException e ) - { + } catch (IOException e) { outputFileName = outputFile.getAbsolutePath(); } - Set files = (Set) getPluginContext().get( key ); - if ( files == null ) - { + Set files = (Set) getPluginContext().get(key); + if (files == null) { files = new LinkedHashSet<>(); + } else { + files = new LinkedHashSet<>(files); } - else - { - files = new LinkedHashSet<>( files ); - } - if ( !files.contains( outputFileName ) ) - { - if ( !outputFile.delete() ) - { - getLog().error( "Cannot delete " + outputFile + " will append instead" ); + if (!files.contains(outputFileName)) { + if (!outputFile.delete()) { + getLog().error("Cannot delete " + outputFile + " will append instead"); } } - files.add( outputFileName ); - getPluginContext().put( key, files ); - } - else - { - if ( outputFile.exists() ) - { - getLog().error( "Cannot send output to " + outputFile + " as it exists but is not a file" ); + files.add(outputFileName); + getPluginContext().put(key, files); + } else { + if (outputFile.exists()) { + getLog().error("Cannot send output to " + outputFile + " as it exists but is not a file"); outputFileError = true; - } - else if ( !outputFile.getParentFile().isDirectory() ) - { - if ( !outputFile.getParentFile().mkdirs() ) - { + } else if (!outputFile.getParentFile().isDirectory()) { + if (!outputFile.getParentFile().mkdirs()) { outputFileError = true; } } } - if ( !outputFileError && StringUtils.isBlank( outputEncoding ) ) - { - outputEncoding = System.getProperty( "file.encoding" ); - getLog().warn( "File encoding has not been set, using platform encoding " + outputEncoding - + ", i.e. build is platform dependent!" ); + if (!outputFileError && StringUtils.isBlank(outputEncoding)) { + outputEncoding = System.getProperty("file.encoding"); + getLog().warn("File encoding has not been set, using platform encoding " + outputEncoding + + ", i.e. build is platform dependent!"); } } } - protected void logLine( boolean error, String line ) - { - if ( logOutput ) - { - if ( error ) - { - getLog().error( line ); - } - else - { - getLog().info( line ); + protected void logLine(boolean error, String line) { + if (logOutput) { + if (error) { + getLog().error(line); + } else { + getLog().info(line); } } - if ( outputFile != null && !outputFileError ) - { - try - { - Files.write( outputFile.toPath(), - ( error ? "> " + line + NL : line + NL ).getBytes( outputEncoding ), - StandardOpenOption.APPEND, StandardOpenOption.CREATE ); - } - catch ( IOException e ) - { - getLog().error( "Cannot send output to " + outputFile, e ); + if (outputFile != null && !outputFileError) { + try { + Files.write( + outputFile.toPath(), + (error ? "> " + line + NL : line + NL).getBytes(outputEncoding), + StandardOpenOption.APPEND, + StandardOpenOption.CREATE); + } catch (IOException e) { + getLog().error("Cannot send output to " + outputFile, e); outputFileError = true; } } @@ -183,9 +157,7 @@ protected void logLine( boolean error, String line ) /** * @return Offset of the configured output line width compared to the default with of 80. */ - protected int getOutputLineWidthOffset() - { + protected int getOutputLineWidthOffset() { return this.outputLineWidth - DEFAULT_OUTPUT_LINE_WIDTH; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java index bf7d697965..18f815eca6 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java @@ -48,9 +48,7 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -public abstract class AbstractVersionsReport - extends AbstractMavenReport -{ +public abstract class AbstractVersionsReport extends AbstractMavenReport { /** * Internationalization component. * @@ -65,7 +63,7 @@ public abstract class AbstractVersionsReport * * @since 1.0-alpha-3 */ - @Parameter( property = "versions.skip" ) + @Parameter(property = "versions.skip") private boolean skip; /** @@ -78,7 +76,7 @@ public abstract class AbstractVersionsReport * * @since 1.0-alpha-3 */ - @Parameter( property = "maven.version.rules.serverId", defaultValue = "serverId" ) + @Parameter(property = "maven.version.rules.serverId", defaultValue = "serverId") private String serverId; /** @@ -88,7 +86,7 @@ public abstract class AbstractVersionsReport * * @since 1.0-alpha-3 */ - @Parameter( property = "maven.version.rules" ) + @Parameter(property = "maven.version.rules") private String rulesUri; /** @@ -98,7 +96,7 @@ public abstract class AbstractVersionsReport * * @since 1.0-alpha-1 */ - @Parameter( property = "comparisonMethod" ) + @Parameter(property = "comparisonMethod") protected String comparisonMethod; /** @@ -106,7 +104,7 @@ public abstract class AbstractVersionsReport * * @since 1.0-alpha-3 */ - @Parameter( property = "allowSnapshots", defaultValue = "false" ) + @Parameter(property = "allowSnapshots", defaultValue = "false") protected boolean allowSnapshots; /** @@ -119,10 +117,10 @@ public abstract class AbstractVersionsReport * * @since 1.0-beta-1 */ - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) protected MavenSession session; - @Parameter( defaultValue = "${mojoExecution}", required = true, readonly = true ) + @Parameter(defaultValue = "${mojoExecution}", required = true, readonly = true) private MojoExecution mojoExecution; /** @@ -149,7 +147,7 @@ public abstract class AbstractVersionsReport *

Currently, this parameter will override the defined {@link #ruleSet}

* @since 2.13.0 */ - @Parameter( property = "maven.version.ignore" ) + @Parameter(property = "maven.version.ignore") protected Set ignoredVersions; /** @@ -168,11 +166,12 @@ public abstract class AbstractVersionsReport // --------------------- GETTER / SETTER METHODS --------------------- - protected AbstractVersionsReport( I18N i18n, RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { + protected AbstractVersionsReport( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { this.i18n = i18n; this.repositorySystem = repositorySystem; this.aetherRepositorySystem = aetherRepositorySystem; @@ -180,29 +179,23 @@ protected AbstractVersionsReport( I18N i18n, RepositorySystem repositorySystem, this.rendererFactory = rendererFactory; } - public VersionsHelper getHelper() - throws MavenReportException - { - if ( helper == null ) - { - try - { + public VersionsHelper getHelper() throws MavenReportException { + if (helper == null) { + try { helper = new DefaultVersionsHelper.Builder() - .withRepositorySystem( repositorySystem ) - .withAetherRepositorySystem( aetherRepositorySystem ) - .withWagonMap( wagonMap ) - .withServerId( serverId ) - .withRulesUri( rulesUri ) - .withRuleSet( ruleSet ) - .withIgnoredVersions( ignoredVersions ) - .withLog( getLog() ) - .withMavenSession( session ) - .withMojoExecution( mojoExecution ) + .withRepositorySystem(repositorySystem) + .withAetherRepositorySystem(aetherRepositorySystem) + .withWagonMap(wagonMap) + .withServerId(serverId) + .withRulesUri(rulesUri) + .withRuleSet(ruleSet) + .withIgnoredVersions(ignoredVersions) + .withLog(getLog()) + .withMavenSession(session) + .withMojoExecution(mojoExecution) .build(); - } - catch ( MojoExecutionException e ) - { - throw new MavenReportException( e.getMessage(), e ); + } catch (MojoExecutionException e) { + throw new MavenReportException(e.getMessage(), e); } } return helper; @@ -211,18 +204,12 @@ public VersionsHelper getHelper() /** * {@inheritDoc} */ - protected void executeReport( Locale locale ) - throws MavenReportException - { - if ( !skip ) - { - try - { - doGenerateReport( locale, getSink() ); - } - catch ( MojoExecutionException e ) - { - throw new MavenReportException( e.getMessage(), e ); + protected void executeReport(Locale locale) throws MavenReportException { + if (!skip) { + try { + doGenerateReport(locale, getSink()); + } catch (MojoExecutionException e) { + throw new MavenReportException(e.getMessage(), e); } } } @@ -235,42 +222,36 @@ protected void executeReport( Locale locale ) * @throws MavenReportException when things go wrong. * @throws MojoExecutionException if something goes wrong. */ - protected abstract void doGenerateReport( Locale locale, Sink sink ) - throws MavenReportException, MojoExecutionException; + protected abstract void doGenerateReport(Locale locale, Sink sink) + throws MavenReportException, MojoExecutionException; @Override - protected MavenProject getProject() - { + protected MavenProject getProject() { return project; } @Override - protected String getOutputDirectory() - { - if ( !outputDirectory.isAbsolute() ) - { - outputDirectory = new File( project.getBasedir(), outputDirectory.getPath() ); + protected String getOutputDirectory() { + if (!outputDirectory.isAbsolute()) { + outputDirectory = new File(project.getBasedir(), outputDirectory.getPath()); } return outputDirectory.getAbsolutePath(); } @Override - protected Renderer getSiteRenderer() - { + protected Renderer getSiteRenderer() { return siteRenderer; } @Override - public String getDescription( Locale locale ) - { - return getText( locale, "report.description" ); + public String getDescription(Locale locale) { + return getText(locale, "report.description"); } @Override - public String getName( Locale locale ) - { - return getText( locale, "report.title" ); + public String getName(Locale locale) { + return getText(locale, "report.title"); } /** @@ -280,24 +261,19 @@ public String getName( Locale locale ) * @param key the message key. * @return the message. */ - public String getText( Locale locale, String key ) - { - return i18n.getString( getOutputName(), locale, key ); + public String getText(Locale locale, String key) { + return i18n.getString(getOutputName(), locale, key); } - public Boolean getAllowSnapshots() - { + public Boolean getAllowSnapshots() { return this.allowSnapshots; } - public String getComparisonMethod() - { + public String getComparisonMethod() { return comparisonMethod; } - public I18N getI18n() - { + public I18N getI18n() { return i18n; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java index b9b15b5cf6..caee51d729 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java @@ -67,9 +67,7 @@ * * @author Stephen Connolly */ -public abstract class AbstractVersionsUpdaterMojo - extends AbstractMojo -{ +public abstract class AbstractVersionsUpdaterMojo extends AbstractMojo { // ------------------------------ FIELDS ------------------------------ @@ -78,7 +76,7 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 1.0-alpha-1 */ - @Parameter( defaultValue = "${project}", required = true, readonly = true ) + @Parameter(defaultValue = "${project}", required = true, readonly = true) protected MavenProject project; /** @@ -94,7 +92,7 @@ public abstract class AbstractVersionsUpdaterMojo /** * @since 1.0-alpha-1 */ - @Parameter( defaultValue = "${reactorProjects}", required = true, readonly = true ) + @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true) protected List reactorProjects; /** @@ -102,7 +100,7 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 1.0-alpha-3 */ - @Parameter( property = "maven.version.rules.serverId", defaultValue = "serverId" ) + @Parameter(property = "maven.version.rules.serverId", defaultValue = "serverId") private String serverId; /** @@ -112,7 +110,7 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 1.0-alpha-3 */ - @Parameter( property = "maven.version.rules" ) + @Parameter(property = "maven.version.rules") private String rulesUri; /** @@ -120,7 +118,7 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 1.0-alpha-3 */ - @Parameter( property = "generateBackupPoms", defaultValue = "true" ) + @Parameter(property = "generateBackupPoms", defaultValue = "true") private boolean generateBackupPoms; /** @@ -128,7 +126,7 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 1.0-alpha-1 */ - @Parameter( property = "allowSnapshots", defaultValue = "false" ) + @Parameter(property = "allowSnapshots", defaultValue = "false") protected boolean allowSnapshots; /** @@ -141,10 +139,10 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 1.0-alpha-1 */ - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) protected MavenSession session; - @Parameter( defaultValue = "${mojoExecution}", required = true, readonly = true ) + @Parameter(defaultValue = "${mojoExecution}", required = true, readonly = true) private MojoExecution mojoExecution; /** @@ -152,15 +150,14 @@ public abstract class AbstractVersionsUpdaterMojo * * @since 2.11 */ - @Parameter( property = "changeRecorderFormat", defaultValue = "none" ) + @Parameter(property = "changeRecorderFormat", defaultValue = "none") private String changeRecorderFormat = "none"; /** * The output file used to record changes. * * @since 2.11 */ - @Parameter( property = "changeRecorderOutputFile", - defaultValue = "${project.build.directory}/versions-changes.xml" ) + @Parameter(property = "changeRecorderOutputFile", defaultValue = "${project.build.directory}/versions-changes.xml") private File changeRecorderOutputFile; /** @@ -192,7 +189,7 @@ public abstract class AbstractVersionsUpdaterMojo *

Currently, this parameter will override the defined {@link #ruleSet}

* @since 2.13.0 */ - @Parameter( property = "maven.version.ignore" ) + @Parameter(property = "maven.version.ignore") protected Set ignoredVersions; /** @@ -205,32 +202,30 @@ public abstract class AbstractVersionsUpdaterMojo // --------------------- GETTER / SETTER METHODS --------------------- @Inject - protected AbstractVersionsUpdaterMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { + protected AbstractVersionsUpdaterMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { this.repositorySystem = repositorySystem; this.aetherRepositorySystem = aetherRepositorySystem; this.wagonMap = wagonMap; this.changeRecorders = changeRecorders; } - public VersionsHelper getHelper() throws MojoExecutionException - { - if ( helper == null ) - { + public VersionsHelper getHelper() throws MojoExecutionException { + if (helper == null) { helper = new DefaultVersionsHelper.Builder() - .withRepositorySystem( repositorySystem ) - .withAetherRepositorySystem( aetherRepositorySystem ) - .withWagonMap( wagonMap ) - .withServerId( serverId ) - .withRulesUri( rulesUri ) - .withRuleSet( ruleSet ) - .withIgnoredVersions( ignoredVersions ) - .withLog( getLog() ) - .withMavenSession( session ) - .withMojoExecution( mojoExecution ) + .withRepositorySystem(repositorySystem) + .withAetherRepositorySystem(aetherRepositorySystem) + .withWagonMap(wagonMap) + .withServerId(serverId) + .withRulesUri(rulesUri) + .withRuleSet(ruleSet) + .withIgnoredVersions(ignoredVersions) + .withLog(getLog()) + .withMavenSession(session) + .withMojoExecution(mojoExecution) .build(); } return helper; @@ -242,8 +237,7 @@ public VersionsHelper getHelper() throws MojoExecutionException * @return Value for property 'project'. * @since 1.0-alpha-1 */ - public MavenProject getProject() - { + public MavenProject getProject() { return project; } @@ -253,13 +247,11 @@ public MavenProject getProject() * @param project Value to set for property 'project'. * @since 1.0-alpha-1 */ - public void setProject( MavenProject project ) - { + public void setProject(MavenProject project) { this.project = project; } - public String getVersion() - { + public String getVersion() { return getProject() == null ? null : getProject().getVersion(); } @@ -272,12 +264,10 @@ public String getVersion() * * @since 1.0-alpha-1 */ - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { validateInput(); File outFile = project.getFile(); - process( outFile ); + process(outFile); } // -------------------------- OTHER METHODS -------------------------- @@ -287,9 +277,7 @@ public void execute() * * @throws MojoExecutionException thrown if any of input parameters is invalid */ - protected void validateInput() throws MojoExecutionException - { - } + protected void validateInput() throws MojoExecutionException {} /** * Finds the latest version of the specified artifact that matches the version range. * @@ -303,14 +291,13 @@ protected void validateInput() throws MojoExecutionException * @throws MojoExecutionException if something goes wrong. * @since 1.0-alpha-1 */ - protected ArtifactVersion findLatestVersion( Artifact artifact, VersionRange versionRange, - Boolean allowingSnapshots, boolean usePluginRepositories ) - throws MojoExecutionException, VersionRetrievalException - { + protected ArtifactVersion findLatestVersion( + Artifact artifact, VersionRange versionRange, Boolean allowingSnapshots, boolean usePluginRepositories) + throws MojoExecutionException, VersionRetrievalException { boolean includeSnapshots = allowingSnapshots != null ? allowingSnapshots : this.allowSnapshots; - final ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifact, versionRange, - usePluginRepositories ); - return artifactVersions.getNewestVersion( versionRange, null, includeSnapshots, false ); + final ArtifactVersions artifactVersions = + getHelper().lookupArtifactVersions(artifact, versionRange, usePluginRepositories); + return artifactVersions.getNewestVersion(versionRange, null, includeSnapshots, false); } /** @@ -322,9 +309,8 @@ protected ArtifactVersion findLatestVersion( Artifact artifact, VersionRange ver * @return The value as defined in the pom or null if not defined. * @since 1.0-alpha-1 */ - protected String getPropertyValue( StringBuilder pom, String property ) - { - return project.getProperties().getProperty( property ); + protected String getPropertyValue(StringBuilder pom, String property) { + return project.getProperties().getProperty(property); } /** @@ -335,49 +321,34 @@ protected String getPropertyValue( StringBuilder pom, String property ) * @throws MojoFailureException If things go wrong. * @since 1.0-alpha-1 */ - protected void process( File outFile ) - throws MojoExecutionException, MojoFailureException - { - try - { - StringBuilder input = PomHelper.readXmlFile( outFile ); - ModifiedPomXMLEventReader newPom = newModifiedPomXER( input, outFile.getAbsolutePath() ); - - update( newPom ); - - if ( newPom.isModified() ) - { - if ( generateBackupPoms ) - { - File backupFile = new File( outFile.getParentFile(), outFile.getName() + ".versionsBackup" ); - if ( !backupFile.exists() ) - { - getLog().debug( "Backing up " + outFile + " to " + backupFile ); - FileUtils.copyFile( outFile, backupFile ); - } - else - { - getLog().debug( "Leaving existing backup " + backupFile + " unmodified" ); + protected void process(File outFile) throws MojoExecutionException, MojoFailureException { + try { + StringBuilder input = PomHelper.readXmlFile(outFile); + ModifiedPomXMLEventReader newPom = newModifiedPomXER(input, outFile.getAbsolutePath()); + + update(newPom); + + if (newPom.isModified()) { + if (generateBackupPoms) { + File backupFile = new File(outFile.getParentFile(), outFile.getName() + ".versionsBackup"); + if (!backupFile.exists()) { + getLog().debug("Backing up " + outFile + " to " + backupFile); + FileUtils.copyFile(outFile, backupFile); + } else { + getLog().debug("Leaving existing backup " + backupFile + " unmodified"); } + } else { + getLog().debug("Skipping generation of backup file"); } - else - { - getLog().debug( "Skipping generation of backup file" ); - } - writeFile( outFile, input ); + writeFile(outFile, input); } saveChangeRecorderResults(); + } catch (IOException | XMLStreamException e) { + getLog().error(e); + } catch (VersionRetrievalException e) { + throw new MojoExecutionException(e.getMessage(), e); } - catch ( IOException | XMLStreamException e ) - { - getLog().error( e ); - } - catch ( VersionRetrievalException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); - } - } /** @@ -387,18 +358,14 @@ protected void process( File outFile ) * @param path Path pointing to the source of the XML * @return The {@link org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader}. */ - protected final ModifiedPomXMLEventReader newModifiedPomXER( StringBuilder input, String path ) - { + protected final ModifiedPomXMLEventReader newModifiedPomXER(StringBuilder input, String path) { ModifiedPomXMLEventReader newPom = null; - try - { + try { XMLInputFactory inputFactory = XMLInputFactory2.newInstance(); - inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE ); - newPom = new ModifiedPomXMLEventReader( input, inputFactory, path ); - } - catch ( XMLStreamException e ) - { - getLog().error( e ); + inputFactory.setProperty(XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE); + newPom = new ModifiedPomXMLEventReader(input, inputFactory, path); + } catch (XMLStreamException e) { + getLog().error(e); } return newPom; } @@ -410,12 +377,9 @@ protected final ModifiedPomXMLEventReader newModifiedPomXER( StringBuilder input * @param input The contents of the file. * @throws IOException when things go wrong. */ - protected final void writeFile( File outFile, StringBuilder input ) - throws IOException - { - try ( Writer writer = WriterFactory.newXmlWriter( outFile ) ) - { - IOUtil.copy( input.toString(), writer ); + protected final void writeFile(File outFile, StringBuilder input) throws IOException { + try (Writer writer = WriterFactory.newXmlWriter(outFile)) { + IOUtil.copy(input.toString(), writer); } } @@ -429,8 +393,8 @@ protected final void writeFile( File outFile, StringBuilder input ) * @throws VersionRetrievalException if version retrieval goes wrong * @since 1.0-alpha-1 */ - protected abstract void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException; + protected abstract void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException; /** * @param artifact The artifact. @@ -445,9 +409,8 @@ protected abstract void update( ModifiedPomXMLEventReader pom ) * Returns true if the update should be applied. */ @Deprecated - protected boolean shouldApplyUpdate( Artifact artifact, String currentVersion, ArtifactVersion updateVersion ) - { - return shouldApplyUpdate( artifact, currentVersion, updateVersion, false ); + protected boolean shouldApplyUpdate(Artifact artifact, String currentVersion, ArtifactVersion updateVersion) { + return shouldApplyUpdate(artifact, currentVersion, updateVersion, false); } /** @@ -460,37 +423,30 @@ protected boolean shouldApplyUpdate( Artifact artifact, String currentVersion, A * @return true if the update should be applied to the pom. * @since 2.9 */ - protected boolean shouldApplyUpdate( Artifact artifact, String currentVersion, ArtifactVersion updateVersion, - boolean forceUpdate ) - { - getLog().debug( "Proposal is to update from " + currentVersion + " to " + updateVersion ); - - if ( updateVersion == null ) - { - getLog().warn( "Not updating version: could not resolve any versions" ); + protected boolean shouldApplyUpdate( + Artifact artifact, String currentVersion, ArtifactVersion updateVersion, boolean forceUpdate) { + getLog().debug("Proposal is to update from " + currentVersion + " to " + updateVersion); + + if (updateVersion == null) { + getLog().warn("Not updating version: could not resolve any versions"); return false; } - if ( forceUpdate ) - { - getLog().info( "Force update enabled. LATEST or RELEASE versions will be overwritten with real version" ); + if (forceUpdate) { + getLog().info("Force update enabled. LATEST or RELEASE versions will be overwritten with real version"); return true; } - artifact.setVersion( updateVersion.toString() ); - try - { - getHelper().resolveArtifact( artifact, false ); - } - catch ( ArtifactResolutionException | MojoExecutionException e ) - { - getLog().warn( "Not updating version: could not resolve " + artifact, e ); + artifact.setVersion(updateVersion.toString()); + try { + getHelper().resolveArtifact(artifact, false); + } catch (ArtifactResolutionException | MojoExecutionException e) { + getLog().warn("Not updating version: could not resolve " + artifact, e); return false; } - if ( currentVersion.equals( updateVersion.toString() ) ) - { - getLog().info( "Current version of " + artifact + " is the latest." ); + if (currentVersion.equals(updateVersion.toString())) { + getLog().info("Current version of " + artifact + " is the latest."); return false; } return true; @@ -510,24 +466,28 @@ protected boolean shouldApplyUpdate( Artifact artifact, String currentVersion, A * @throws InvalidSegmentException thrown if {@code unchangedSegment} is invalid * @throws MojoExecutionException thrown if any other error occurs */ - protected ArtifactVersion updatePropertyToNewestVersion( ModifiedPomXMLEventReader pom, Property property, - PropertyVersions version, String currentVersion, - boolean allowDowngrade, - Optional unchangedSegment ) - throws XMLStreamException, InvalidVersionSpecificationException, - InvalidSegmentException, MojoExecutionException - { - ArtifactVersion winner = - version.getNewestVersion( currentVersion, property, this.allowSnapshots, this.reactorProjects, - this.getHelper(), allowDowngrade, unchangedSegment ); - - if ( winner == null || currentVersion.equals( winner.toString() ) ) - { - getLog().info( "Property ${" + property.getName() + "}: Leaving unchanged as " + currentVersion ); - } - else if ( PomHelper.setPropertyVersion( pom, version.getProfileId(), property.getName(), winner.toString() ) ) - { - getLog().info( "Updated ${" + property.getName() + "} from " + currentVersion + " to " + winner ); + protected ArtifactVersion updatePropertyToNewestVersion( + ModifiedPomXMLEventReader pom, + Property property, + PropertyVersions version, + String currentVersion, + boolean allowDowngrade, + Optional unchangedSegment) + throws XMLStreamException, InvalidVersionSpecificationException, InvalidSegmentException, + MojoExecutionException { + ArtifactVersion winner = version.getNewestVersion( + currentVersion, + property, + this.allowSnapshots, + this.reactorProjects, + this.getHelper(), + allowDowngrade, + unchangedSegment); + + if (winner == null || currentVersion.equals(winner.toString())) { + getLog().info("Property ${" + property.getName() + "}: Leaving unchanged as " + currentVersion); + } else if (PomHelper.setPropertyVersion(pom, version.getProfileId(), property.getName(), winner.toString())) { + getLog().info("Updated ${" + property.getName() + "} from " + currentVersion + " to " + winner); return winner; } @@ -540,13 +500,11 @@ else if ( PomHelper.setPropertyVersion( pom, version.getProfileId(), property.ge * @return The change recorder * @throws MojoExecutionException if something goes wrong. */ - protected ChangeRecorder getChangeRecorder() throws MojoExecutionException - { - ChangeRecorder changeRecorder = changeRecorders.get( changeRecorderFormat ); - if ( changeRecorder == null ) - { - throw new MojoExecutionException( "Only " + changeRecorders.keySet() - + " formats are supported for change recordings" ); + protected ChangeRecorder getChangeRecorder() throws MojoExecutionException { + ChangeRecorder changeRecorder = changeRecorders.get(changeRecorderFormat); + if (changeRecorder == null) { + throw new MojoExecutionException( + "Only " + changeRecorders.keySet() + " formats are supported for change recordings"); } return changeRecorder; } @@ -557,13 +515,12 @@ protected ChangeRecorder getChangeRecorder() throws MojoExecutionException * @throws IOException On I/O errors * @throws MojoExecutionException if something goes wrong. */ + protected void saveChangeRecorderResults() throws IOException, MojoExecutionException { - protected void saveChangeRecorderResults() throws IOException, MojoExecutionException - { - - this.getLog().debug( "writing change record to " + this.changeRecorderOutputFile ); - getChangeRecorder().writeReport( Optional.ofNullable( changeRecorderOutputFile ) - .map( File::toPath ) - .orElse( null ) ); + this.getLog().debug("writing change record to " + this.changeRecorderOutputFile); + getChangeRecorder() + .writeReport(Optional.ofNullable(changeRecorderOutputFile) + .map(File::toPath) + .orElse(null)); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CommitMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CommitMojo.java index b1bf396613..4e160c7d2d 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CommitMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CommitMojo.java @@ -36,34 +36,26 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "commit", threadSafe = true ) -public class CommitMojo - extends AbstractMojo -{ +@Mojo(name = "commit", threadSafe = true) +public class CommitMojo extends AbstractMojo { /** * The Maven Project. * * @since 1.0-alpha-1 */ - @Parameter( defaultValue = "${project}", required = true, readonly = true ) + @Parameter(defaultValue = "${project}", required = true, readonly = true) private MavenProject project; - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { File outFile = project.getFile(); - File backupFile = new File( outFile.getParentFile(), outFile.getName() + ".versionsBackup" ); + File backupFile = new File(outFile.getParentFile(), outFile.getName() + ".versionsBackup"); - if ( backupFile.exists() ) - { - getLog().info( "Accepting all changes to " + outFile ); - try - { - FileUtils.forceDelete( backupFile ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + if (backupFile.exists()) { + getLog().info("Accepting all changes to " + outFile); + try { + FileUtils.forceDelete(backupFile); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CompareDependenciesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CompareDependenciesMojo.java index a531a5c131..13fb201ee2 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CompareDependenciesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/CompareDependenciesMojo.java @@ -63,10 +63,8 @@ * @author Paul Gier * @since 1.3 */ -@Mojo( name = "compare-dependencies", threadSafe = true ) -public class CompareDependenciesMojo - extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "compare-dependencies", threadSafe = true) +public class CompareDependenciesMojo extends AbstractVersionsDependencyUpdaterMojo { /** * The width to pad info messages. @@ -79,44 +77,44 @@ public class CompareDependenciesMojo * The groupId, artifactId, and version of the remote project (POM) to which we are comparing. This should be in the * form "groupId:artifactId:version" */ - @Parameter( property = "remotePom", required = true ) + @Parameter(property = "remotePom", required = true) protected String remotePom; /** * Ignore the list of remote dependencies and only compare the remote dependencyManagement */ - @Parameter( property = "ignoreRemoteDependencies", defaultValue = "false" ) + @Parameter(property = "ignoreRemoteDependencies", defaultValue = "false") protected boolean ignoreRemoteDependencies; /** * Ignore the remote dependency management and only check against the actual dependencies of the remote project */ - @Parameter( property = "ignoreRemoteDependencyManagement", defaultValue = "false" ) + @Parameter(property = "ignoreRemoteDependencyManagement", defaultValue = "false") protected boolean ignoreRemoteDependencyManagement; /** * Update dependency versions in the current POM. */ - @Parameter( property = "updateDependencies", defaultValue = "false" ) + @Parameter(property = "updateDependencies", defaultValue = "false") protected boolean updateDependencies; /** * Update dependency versions stored in properties */ - @Parameter( property = "updatePropertyVersions", defaultValue = "false" ) + @Parameter(property = "updatePropertyVersions", defaultValue = "false") protected boolean updatePropertyVersions; /** * Display the dependency version differences on the command line, but do not update the versions in the current * pom. If updateDependencies is set to "true" this will automatically be set to false. */ - @Parameter( property = "reportMode", defaultValue = "true" ) + @Parameter(property = "reportMode", defaultValue = "true") protected boolean reportMode; /** * If the output file is set, the diff report will be written to this file. */ - @Parameter( property = "reportOutputFile" ) + @Parameter(property = "reportOutputFile") protected File reportOutputFile; /** @@ -129,13 +127,13 @@ public class CompareDependenciesMojo // ------------------------------ METHODS -------------------------- @Inject - public CompareDependenciesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ProjectBuilder projectBuilder, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public CompareDependenciesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ProjectBuilder projectBuilder, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); this.projectBuilder = projectBuilder; } @@ -146,128 +144,101 @@ public CompareDependenciesMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - if ( this.ignoreRemoteDependencies && this.ignoreRemoteDependencyManagement ) - { - throw new MojoFailureException( " ignoreRemoteDependencies and ignoreRemoteDependencyManagement " - + "are both set to true. At least one of these needs to be false " ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + if (this.ignoreRemoteDependencies && this.ignoreRemoteDependencyManagement) { + throw new MojoFailureException(" ignoreRemoteDependencies and ignoreRemoteDependencyManagement " + + "are both set to true. At least one of these needs to be false "); } - if ( updateDependencies ) - { + if (updateDependencies) { reportMode = false; } - String[] remoteGAV = this.remotePom.split( ":" ); - if ( remoteGAV.length != 3 ) - { - throw new MojoFailureException( " Invalid format for remotePom: " + remotePom ); + String[] remoteGAV = this.remotePom.split(":"); + if (remoteGAV.length != 3) { + throw new MojoFailureException(" Invalid format for remotePom: " + remotePom); } MavenProject remoteMavenProject = null; - try - { - remoteMavenProject = getRemoteMavenProject( remoteGAV[0], remoteGAV[1], - remoteGAV[2] ); - } - catch ( ArtifactResolutionException | ProjectBuildingException e ) - { - throw new MojoFailureException( e.getMessage() ); + try { + remoteMavenProject = getRemoteMavenProject(remoteGAV[0], remoteGAV[1], remoteGAV[2]); + } catch (ArtifactResolutionException | ProjectBuildingException e) { + throw new MojoFailureException(e.getMessage()); } Map remoteDepsMap = new HashMap<>(); - if ( !ignoreRemoteDependencyManagement ) - { + if (!ignoreRemoteDependencyManagement) { List remoteProjectDepMgmtDeps = remoteMavenProject.getDependencyManagement() == null ? null : remoteMavenProject.getDependencyManagement().getDependencies(); - if ( remoteProjectDepMgmtDeps != null ) - { - remoteProjectDepMgmtDeps.forEach( dep -> remoteDepsMap.putIfAbsent( dep.getManagementKey(), dep ) ); + if (remoteProjectDepMgmtDeps != null) { + remoteProjectDepMgmtDeps.forEach(dep -> remoteDepsMap.putIfAbsent(dep.getManagementKey(), dep)); } } - if ( !ignoreRemoteDependencies && remoteMavenProject.getDependencies() != null ) - { - remoteMavenProject.getDependencies().forEach( dep -> - remoteDepsMap.putIfAbsent( dep.getManagementKey(), dep ) ); + if (!ignoreRemoteDependencies && remoteMavenProject.getDependencies() != null) { + remoteMavenProject.getDependencies().forEach(dep -> remoteDepsMap.putIfAbsent(dep.getManagementKey(), dep)); } List totalDiffs = new ArrayList<>(); List propertyDiffs = new ArrayList<>(); - if ( getProject().getDependencyManagement() != null && isProcessingDependencyManagement() ) - { - totalDiffs.addAll( - compareVersions( pom, getProject().getDependencyManagement().getDependencies(), remoteDepsMap, - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ) ); + if (getProject().getDependencyManagement() != null && isProcessingDependencyManagement()) { + totalDiffs.addAll(compareVersions( + pom, + getProject().getDependencyManagement().getDependencies(), + remoteDepsMap, + ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT)); } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - totalDiffs.addAll( compareVersions( pom, getProject().getDependencies(), remoteDepsMap, - ChangeRecord.ChangeKind.DEPENDENCY ) ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + totalDiffs.addAll(compareVersions( + pom, getProject().getDependencies(), remoteDepsMap, ChangeRecord.ChangeKind.DEPENDENCY)); } - if ( updatePropertyVersions ) - { - Map versionProperties = - this.getHelper().getVersionPropertiesMap( VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( getProject() ).build() ); - propertyDiffs.addAll( updatePropertyVersions( pom, versionProperties, remoteDepsMap ) ); + if (updatePropertyVersions) { + Map versionProperties = this.getHelper() + .getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(getProject()) + .build()); + propertyDiffs.addAll(updatePropertyVersions(pom, versionProperties, remoteDepsMap)); } - if ( getProject().getParent() != null - && remoteMavenProject.getParent() != null - && isProcessingParent() ) - { + if (getProject().getParent() != null && remoteMavenProject.getParent() != null && isProcessingParent()) { Dependency parent = DependencyBuilder.newBuilder() - .withGroupId( remoteMavenProject.getParentArtifact().getGroupId() ) - .withArtifactId( remoteMavenProject.getParentArtifact().getArtifactId() ) - .withVersion( remoteMavenProject.getParentArtifact().getVersion() ) - .withType( remoteMavenProject.getParentArtifact().getType() ) - .withScope( remoteMavenProject.getParentArtifact().getScope() ) - .withClassifier( remoteMavenProject.getParentArtifact().getClassifier() ) + .withGroupId(remoteMavenProject.getParentArtifact().getGroupId()) + .withArtifactId(remoteMavenProject.getParentArtifact().getArtifactId()) + .withVersion(remoteMavenProject.getParentArtifact().getVersion()) + .withType(remoteMavenProject.getParentArtifact().getType()) + .withScope(remoteMavenProject.getParentArtifact().getScope()) + .withClassifier(remoteMavenProject.getParentArtifact().getClassifier()) .build(); - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Processing parent dependency: " + parent ); + if (getLog().isDebugEnabled()) { + getLog().debug("Processing parent dependency: " + parent); } - remoteDepsMap.putIfAbsent( parent.getManagementKey(), parent ); - totalDiffs.addAll( compareVersions( pom, singletonList( getParentDependency() ), remoteDepsMap, - ChangeRecord.ChangeKind.PARENT ) ); + remoteDepsMap.putIfAbsent(parent.getManagementKey(), parent); + totalDiffs.addAll(compareVersions( + pom, singletonList(getParentDependency()), remoteDepsMap, ChangeRecord.ChangeKind.PARENT)); } - if ( reportMode ) - { - getLog().info( "The following differences were found:" ); - if ( totalDiffs.size() == 0 ) - { - getLog().info( " none" ); - } - else - { - for ( String totalDiff : totalDiffs ) - { - getLog().info( " " + totalDiff ); + if (reportMode) { + getLog().info("The following differences were found:"); + if (totalDiffs.size() == 0) { + getLog().info(" none"); + } else { + for (String totalDiff : totalDiffs) { + getLog().info(" " + totalDiff); } } - getLog().info( "The following property differences were found:" ); - if ( propertyDiffs.size() == 0 ) - { - getLog().info( " none" ); - } - else - { - for ( String propertyDiff : propertyDiffs ) - { - getLog().info( " " + propertyDiff ); + getLog().info("The following property differences were found:"); + if (propertyDiffs.size() == 0) { + getLog().info(" none"); + } else { + for (String propertyDiff : propertyDiffs) { + getLog().info(" " + propertyDiff); } } } - if ( reportOutputFile != null ) - { - writeReportFile( totalDiffs, propertyDiffs ); + if (reportOutputFile != null) { + writeReportFile(totalDiffs, propertyDiffs); } - } /** @@ -280,26 +251,23 @@ && isProcessingParent() ) * @throws MojoExecutionException thrown if the artifact for the dependency could not be constructed * @throws ProjectBuildingException thrown if the {@link MavenProject} instance could not be constructed */ - private MavenProject getRemoteMavenProject( String groupId, String artifactId, String version ) - throws MojoExecutionException, ArtifactResolutionException, ProjectBuildingException - { - Artifact remoteArtifact = toArtifact( DependencyBuilder.newBuilder() - .withGroupId( groupId ) - .withArtifactId( artifactId ) - .withVersion( version ) - .build() ); - ProjectBuildingResult result = - projectBuilder.build( remoteArtifact, true, - PomHelper.createProjectBuilderRequest( session, - r -> r.setProcessPlugins( false ), - r -> r.setRemoteRepositories( session.getCurrentProject() - .getPluginArtifactRepositories() ) ) ); - if ( !result.getProblems().isEmpty() ) - { - getLog().warn( "Problems encountered during construction of the POM for " - + remoteArtifact.toString() ); - result.getProblems().forEach( p -> - getLog().warn( "\t" + p.getMessage() ) ); + private MavenProject getRemoteMavenProject(String groupId, String artifactId, String version) + throws MojoExecutionException, ArtifactResolutionException, ProjectBuildingException { + Artifact remoteArtifact = toArtifact(DependencyBuilder.newBuilder() + .withGroupId(groupId) + .withArtifactId(artifactId) + .withVersion(version) + .build()); + ProjectBuildingResult result = projectBuilder.build( + remoteArtifact, + true, + PomHelper.createProjectBuilderRequest( + session, + r -> r.setProcessPlugins(false), + r -> r.setRemoteRepositories(session.getCurrentProject().getPluginArtifactRepositories()))); + if (!result.getProblems().isEmpty()) { + getLog().warn("Problems encountered during construction of the POM for " + remoteArtifact.toString()); + result.getProblems().forEach(p -> getLog().warn("\t" + p.getMessage())); } return result.getProject(); } @@ -310,68 +278,59 @@ private MavenProject getRemoteMavenProject( String groupId, String artifactId, S * @throws XMLStreamException * @throws MojoExecutionException */ - private List compareVersions( ModifiedPomXMLEventReader pom, List dependencies, - Map remoteDependencies, - ChangeRecord.ChangeKind changeKind ) - throws MojoExecutionException, XMLStreamException - { + private List compareVersions( + ModifiedPomXMLEventReader pom, + List dependencies, + Map remoteDependencies, + ChangeRecord.ChangeKind changeKind) + throws MojoExecutionException, XMLStreamException { List updates = new ArrayList<>(); - for ( Dependency dep : dependencies ) - { - Artifact artifact = this.toArtifact( dep ); - if ( !isIncluded( artifact ) ) - { + for (Dependency dep : dependencies) { + Artifact artifact = this.toArtifact(dep); + if (!isIncluded(artifact)) { continue; } - Dependency remoteDep = remoteDependencies.get( dep.getManagementKey() ); - if ( remoteDep != null ) - { + Dependency remoteDep = remoteDependencies.get(dep.getManagementKey()); + if (remoteDep != null) { String remoteVersion = remoteDep.getVersion(); - if ( !dep.getVersion().equals( remoteVersion ) ) - { - StringBuilder buf = writeDependencyDiffMessage( dep, remoteVersion ); - updates.add( buf.toString() ); - if ( !reportMode ) - { - updateDependencyVersion( pom, dep, remoteVersion, changeKind ); + if (!dep.getVersion().equals(remoteVersion)) { + StringBuilder buf = writeDependencyDiffMessage(dep, remoteVersion); + updates.add(buf.toString()); + if (!reportMode) { + updateDependencyVersion(pom, dep, remoteVersion, changeKind); } - } - } } return updates; - } /** * Updates the properties holding a version if necessary. */ - private List updatePropertyVersions( ModifiedPomXMLEventReader pom, - Map versionProperties, - Map remoteDependencies ) - throws XMLStreamException - { + private List updatePropertyVersions( + ModifiedPomXMLEventReader pom, + Map versionProperties, + Map remoteDependencies) + throws XMLStreamException { List result = new ArrayList<>(); - for ( Map.Entry entry : versionProperties.entrySet() ) - { + for (Map.Entry entry : versionProperties.entrySet()) { Property property = entry.getKey(); PropertyVersions version = entry.getValue(); - String candidateVersion = computeCandidateVersion( remoteDependencies, property, version ); - if ( candidateVersion != null ) - { - String originalVersion = version.getAssociations()[0].getArtifact().getVersion(); // Yekes - if ( !candidateVersion.equals( originalVersion ) ) // Update needed + String candidateVersion = computeCandidateVersion(remoteDependencies, property, version); + if (candidateVersion != null) { + String originalVersion = + version.getAssociations()[0].getArtifact().getVersion(); // Yekes + if (!candidateVersion.equals(originalVersion)) // Update needed { - result.add( writeDiffMessage( property.getName(), originalVersion, candidateVersion ).toString() ); - if ( !reportMode - && PomHelper.setPropertyVersion( pom, null, property.getName(), candidateVersion ) ) - { - getLog().info( "Updated ${" + property.getName() + "} from " + originalVersion + " to " - + candidateVersion ); + result.add(writeDiffMessage(property.getName(), originalVersion, candidateVersion) + .toString()); + if (!reportMode && PomHelper.setPropertyVersion(pom, null, property.getName(), candidateVersion)) { + getLog().info("Updated ${" + property.getName() + "} from " + originalVersion + " to " + + candidateVersion); } } } @@ -391,28 +350,20 @@ private List updatePropertyVersions( ModifiedPomXMLEventReader pom, * @param propertyVersions the association * @return the candidate version or null if there isn't any */ - private String computeCandidateVersion( Map remoteDependencies, Property property, - PropertyVersions propertyVersions ) - { + private String computeCandidateVersion( + Map remoteDependencies, Property property, PropertyVersions propertyVersions) { String candidateVersion = null; - for ( ArtifactAssociation artifactAssociation : propertyVersions.getAssociations() ) - { - String id = generateId( artifactAssociation.getArtifact() ); - Dependency dependency = remoteDependencies.get( id ); - if ( dependency == null ) - { - getLog().info( "Not updating ${" + property.getName() + "}: no info for " + id ); + for (ArtifactAssociation artifactAssociation : propertyVersions.getAssociations()) { + String id = generateId(artifactAssociation.getArtifact()); + Dependency dependency = remoteDependencies.get(id); + if (dependency == null) { + getLog().info("Not updating ${" + property.getName() + "}: no info for " + id); return null; - } - else - { - if ( candidateVersion == null ) - { + } else { + if (candidateVersion == null) { candidateVersion = dependency.getVersion(); - } - else if ( !candidateVersion.equals( dependency.getVersion() ) ) - { - getLog().warn( "Could not update ${" + property.getName() + "}: version mismatch" ); + } else if (!candidateVersion.equals(dependency.getVersion())) { + getLog().warn("Could not update ${" + property.getName() + "}: version mismatch"); return null; } } @@ -420,48 +371,35 @@ else if ( !candidateVersion.equals( dependency.getVersion() ) ) return candidateVersion; } - private void writeReportFile( List dependenciesUpdate, List propertiesUpdate ) - throws MojoExecutionException - { - if ( !reportOutputFile.getParentFile().exists() ) - { + private void writeReportFile(List dependenciesUpdate, List propertiesUpdate) + throws MojoExecutionException { + if (!reportOutputFile.getParentFile().exists()) { reportOutputFile.getParentFile().mkdirs(); } - try ( FileWriter fw = new FileWriter( reportOutputFile ); // - PrintWriter pw = new PrintWriter( fw ) ) - { - pw.println( "The following differences were found:" ); + try (FileWriter fw = new FileWriter(reportOutputFile); // + PrintWriter pw = new PrintWriter(fw)) { + pw.println("The following differences were found:"); pw.println(); - if ( dependenciesUpdate.size() == 0 ) - { - pw.println( " none" ); - } - else - { - for ( String dependencyUpdate : dependenciesUpdate ) - { - pw.println( " " + dependencyUpdate ); + if (dependenciesUpdate.size() == 0) { + pw.println(" none"); + } else { + for (String dependencyUpdate : dependenciesUpdate) { + pw.println(" " + dependencyUpdate); } } pw.println(); - pw.println( "The following property differences were found:" ); + pw.println("The following property differences were found:"); pw.println(); - if ( propertiesUpdate.size() == 0 ) - { - pw.println( " none" ); - } - else - { - for ( String propertyUpdate : propertiesUpdate ) - { - pw.println( " " + propertyUpdate ); + if (propertiesUpdate.size() == 0) { + pw.println(" none"); + } else { + for (String propertyUpdate : propertiesUpdate) { + pw.println(" " + propertyUpdate); } } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to write report file. ", e ); + } catch (IOException e) { + throw new MojoExecutionException("Unable to write report file. ", e); } } @@ -472,42 +410,39 @@ private void writeReportFile( List dependenciesUpdate, List prop * @param remoteVersion * @return The message */ - private StringBuilder writeDependencyDiffMessage( Dependency dep, String remoteVersion ) - { + private StringBuilder writeDependencyDiffMessage(Dependency dep, String remoteVersion) { String id = dep.getGroupId() + ":" + dep.getArtifactId(); - return writeDiffMessage( id, dep.getVersion(), remoteVersion ); + return writeDiffMessage(id, dep.getVersion(), remoteVersion); } - private StringBuilder writeDiffMessage( String id, String originalVersion, String targetVersion ) - { + private StringBuilder writeDiffMessage(String id, String originalVersion, String targetVersion) { StringBuilder buf = new StringBuilder(); - buf.append( id ); - buf.append( ' ' ); + buf.append(id); + buf.append(' '); int padding = INFO_PAD_SIZE - originalVersion.length() - targetVersion.length() - 4; - while ( buf.length() < padding ) - { - buf.append( '.' ); + while (buf.length() < padding) { + buf.append('.'); } - buf.append( ' ' ); - buf.append( originalVersion ); - buf.append( " -> " ); - buf.append( targetVersion ); + buf.append(' '); + buf.append(originalVersion); + buf.append(" -> "); + buf.append(targetVersion); return buf; } /** * Creates a key that is similar to what {@link Dependency#getManagementKey()} generates for a dependency. */ - private static String generateId( Artifact artifact ) - { + private static String generateId(Artifact artifact) { StringBuilder sb = new StringBuilder(); - sb.append( artifact.getGroupId() ).append( ":" ).append( artifact.getArtifactId() ).append( ":" ) - .append( artifact.getType() ); - if ( artifact.getClassifier() != null ) - { - sb.append( ":" ).append( artifact.getClassifier() ); + sb.append(artifact.getGroupId()) + .append(":") + .append(artifact.getArtifactId()) + .append(":") + .append(artifact.getType()); + if (artifact.getClassifier() != null) { + sb.append(":").append(artifact.getClassifier()); } return sb.toString(); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesAggregateReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesAggregateReportMojo.java index 63b07f8513..d7736aa59d 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesAggregateReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesAggregateReportMojo.java @@ -17,10 +17,11 @@ * */ +import javax.inject.Inject; import java.util.Map; import java.util.Set; -import javax.inject.Inject; + import org.apache.maven.model.Dependency; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -37,31 +38,31 @@ * * @since 2.14.0 */ -@Mojo( name = "dependency-updates-aggregate-report", - requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true, aggregator = true ) -public class DependencyUpdatesAggregateReportMojo extends AbstractDependencyUpdatesReportMojo -{ +@Mojo( + name = "dependency-updates-aggregate-report", + requiresDependencyResolution = ResolutionScope.RUNTIME, + threadSafe = true, + aggregator = true) +public class DependencyUpdatesAggregateReportMojo extends AbstractDependencyUpdatesReportMojo { @Inject - protected DependencyUpdatesAggregateReportMojo( I18N i18n, RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected DependencyUpdatesAggregateReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} * */ @Override - protected void populateDependencies( Set dependenciesCollector ) - { - getLog().debug( String.format( "Collecting dependencies for project %s", - project.getName() ) ); - for ( MavenProject project : AggregateReportUtils.getProjectsToProcess( getProject() ) ) - { - dependenciesCollector.addAll( project.getDependencies() ); + protected void populateDependencies(Set dependenciesCollector) { + getLog().debug(String.format("Collecting dependencies for project %s", project.getName())); + for (MavenProject project : AggregateReportUtils.getProjectsToProcess(getProject())) { + dependenciesCollector.addAll(project.getDependencies()); } } @@ -69,14 +70,11 @@ protected void populateDependencies( Set dependenciesCollector ) * {@inheritDoc} * */ @Override - protected void populateDependencyManagement( Set dependencyManagementCollector, - Set dependencies ) throws MavenReportException - { - for ( MavenProject project : AggregateReportUtils.getProjectsToProcess( getProject() ) ) - { - getLog().debug( String.format( "Collecting managed dependencies for project %s", - project.getName() ) ); - handleDependencyManagementTransitive( project, dependencyManagementCollector ); + protected void populateDependencyManagement( + Set dependencyManagementCollector, Set dependencies) throws MavenReportException { + for (MavenProject project : AggregateReportUtils.getProjectsToProcess(getProject())) { + getLog().debug(String.format("Collecting managed dependencies for project %s", project.getName())); + handleDependencyManagementTransitive(project, dependencyManagementCollector); } } @@ -84,9 +82,7 @@ protected void populateDependencyManagement( Set dependencyManagemen * {@inheritDoc} */ @Override - public String getOutputName() - { + public String getOutputName() { return "dependency-updates-aggregate-report"; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojo.java index 711086ccb8..76e49a3669 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojo.java @@ -19,9 +19,11 @@ * under the License. */ +import javax.inject.Inject; + import java.util.Map; import java.util.Set; -import javax.inject.Inject; + import org.apache.maven.model.Dependency; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -37,51 +39,47 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "dependency-updates-report", - requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true ) -public class DependencyUpdatesReportMojo extends AbstractDependencyUpdatesReportMojo -{ +@Mojo(name = "dependency-updates-report", requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) +public class DependencyUpdatesReportMojo extends AbstractDependencyUpdatesReportMojo { @Inject - protected DependencyUpdatesReportMojo( I18N i18n, RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected DependencyUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} * */ @Override - protected void populateDependencies( Set dependenciesCollector ) - { - getLog().debug( String.format( "Collecting dependencies for project %s", - getProject().getName() ) ); - dependenciesCollector.addAll( getProject().getDependencies() ); + protected void populateDependencies(Set dependenciesCollector) { + getLog().debug(String.format( + "Collecting dependencies for project %s", getProject().getName())); + dependenciesCollector.addAll(getProject().getDependencies()); } /** * {@inheritDoc} * */ @Override - protected void populateDependencyManagement( Set dependencyManagementCollector, - Set dependencies ) throws MavenReportException - { - if ( hasDependencyManagement( getProject() ) ) - { - getLog().debug( String.format( "Collecting managed dependencies for project %s", - getProject().getName() ) ); - handleDependencyManagementTransitive( getProject(), dependencyManagementCollector ); + protected void populateDependencyManagement( + Set dependencyManagementCollector, Set dependencies) throws MavenReportException { + if (hasDependencyManagement(getProject())) { + getLog().debug(String.format( + "Collecting managed dependencies for project %s", + getProject().getName())); + handleDependencyManagementTransitive(getProject(), dependencyManagementCollector); } } /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "dependency-updates-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java index 9f978b18aa..de698b1743 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java @@ -66,10 +66,8 @@ * @author Stephen Connolly * @since 1.0-alpha-1 */ -@Mojo( name = "display-dependency-updates", threadSafe = true ) -public class DisplayDependencyUpdatesMojo - extends AbstractVersionsDisplayMojo -{ +@Mojo(name = "display-dependency-updates", threadSafe = true) +public class DisplayDependencyUpdatesMojo extends AbstractVersionsDisplayMojo { // ------------------------------ FIELDS ------------------------------ @@ -85,7 +83,7 @@ public class DisplayDependencyUpdatesMojo * * @since 1.2 */ - @Parameter( property = "processDependencyManagement", defaultValue = "true" ) + @Parameter(property = "processDependencyManagement", defaultValue = "true") private boolean processDependencyManagement; /** @@ -98,7 +96,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.11 */ - @Parameter( property = "processDependencyManagementTransitive", defaultValue = "true" ) + @Parameter(property = "processDependencyManagementTransitive", defaultValue = "true") private boolean processDependencyManagementTransitive; /** @@ -120,7 +118,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "dependencyManagementIncludes", defaultValue = WildcardMatcher.WILDCARD ) + @Parameter(property = "dependencyManagementIncludes", defaultValue = WildcardMatcher.WILDCARD) private List dependencyManagementIncludes; /** @@ -142,7 +140,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "dependencyManagementExcludes" ) + @Parameter(property = "dependencyManagementExcludes") private List dependencyManagementExcludes; /** @@ -150,7 +148,7 @@ public class DisplayDependencyUpdatesMojo * * @since 1.2 */ - @Parameter( property = "processDependencies", defaultValue = "true" ) + @Parameter(property = "processDependencies", defaultValue = "true") private boolean processDependencies; /** @@ -172,7 +170,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "dependencyIncludes", defaultValue = WildcardMatcher.WILDCARD ) + @Parameter(property = "dependencyIncludes", defaultValue = WildcardMatcher.WILDCARD) private List dependencyIncludes; /** @@ -194,7 +192,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "dependencyExcludes" ) + @Parameter(property = "dependencyExcludes") private List dependencyExcludes; /** @@ -202,7 +200,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "processPluginDependencies", defaultValue = "true" ) + @Parameter(property = "processPluginDependencies", defaultValue = "true") private boolean processPluginDependencies; /** @@ -210,7 +208,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "processPluginDependenciesInPluginManagement", defaultValue = "true" ) + @Parameter(property = "processPluginDependenciesInPluginManagement", defaultValue = "true") private boolean processPluginDependenciesInPluginManagement; /** @@ -221,7 +219,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") private boolean allowMajorUpdates = true; /** @@ -232,7 +230,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") private boolean allowMinorUpdates = true; /** @@ -244,7 +242,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") private boolean allowIncrementalUpdates = true; /** @@ -258,7 +256,7 @@ public class DisplayDependencyUpdatesMojo * @deprecated This will be removed with version 3.0.0 */ @Deprecated - @Parameter( property = "allowAnyUpdates", defaultValue = "true" ) + @Parameter(property = "allowAnyUpdates", defaultValue = "true") private boolean allowAnyUpdates = true; /** @@ -266,7 +264,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.1 */ - @Parameter( property = "verbose", defaultValue = "false" ) + @Parameter(property = "verbose", defaultValue = "false") private boolean verbose; /** @@ -284,7 +282,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "pluginDependencyIncludes", defaultValue = WildcardMatcher.WILDCARD ) + @Parameter(property = "pluginDependencyIncludes", defaultValue = WildcardMatcher.WILDCARD) private List pluginDependencyIncludes; /** @@ -302,13 +300,13 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "pluginDependencyExcludes" ) + @Parameter(property = "pluginDependencyExcludes") private List pluginDependencyExcludes; /** *

Only take these artifacts into consideration:
* Comma-separated list of {@code groupId:[artifactId[:version]]} patterns

- + * * The wildcard "*" can be used as the only, first, last or both characters in each token. * The version token does support version ranges. *

@@ -319,7 +317,7 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "pluginManagementDependencyIncludes", defaultValue = WildcardMatcher.WILDCARD ) + @Parameter(property = "pluginManagementDependencyIncludes", defaultValue = WildcardMatcher.WILDCARD) private List pluginManagementDependencyIncludes; /** @@ -337,72 +335,62 @@ public class DisplayDependencyUpdatesMojo * * @since 2.12.0 */ - @Parameter( property = "pluginManagementDependencyExcludes" ) + @Parameter(property = "pluginManagementDependencyExcludes") private List pluginManagementDependencyExcludes; // --------------------- GETTER / SETTER METHODS --------------------- @Inject - public DisplayDependencyUpdatesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public DisplayDependencyUpdatesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } // open for tests - protected static boolean dependenciesMatch( Dependency dependency, Dependency managedDependency ) - { - if ( !managedDependency.getGroupId().equals( dependency.getGroupId() ) ) - { + protected static boolean dependenciesMatch(Dependency dependency, Dependency managedDependency) { + if (!managedDependency.getGroupId().equals(dependency.getGroupId())) { return false; } - if ( !managedDependency.getArtifactId().equals( dependency.getArtifactId() ) ) - { + if (!managedDependency.getArtifactId().equals(dependency.getArtifactId())) { return false; } - if ( managedDependency.getScope() == null - || Objects.equals( managedDependency.getScope(), dependency.getScope() ) ) - { + if (managedDependency.getScope() == null + || Objects.equals(managedDependency.getScope(), dependency.getScope())) { return false; } - if ( managedDependency.getClassifier() == null - || Objects.equals( managedDependency.getClassifier(), dependency.getClassifier() ) ) - { + if (managedDependency.getClassifier() == null + || Objects.equals(managedDependency.getClassifier(), dependency.getClassifier())) { return false; } return dependency.getVersion() == null - || managedDependency.getVersion() == null - || Objects.equals( managedDependency.getVersion(), dependency.getVersion() ); + || managedDependency.getVersion() == null + || Objects.equals(managedDependency.getVersion(), dependency.getVersion()); } - public boolean isProcessingDependencyManagement() - { + public boolean isProcessingDependencyManagement() { return processDependencyManagement; } - public boolean isProcessingDependencies() - { + public boolean isProcessingDependencies() { return processDependencies; } - public boolean isProcessingPluginDependencies() - { + public boolean isProcessingPluginDependencies() { return processPluginDependencies; } - public boolean isProcessPluginDependenciesInDependencyManagement() - { + public boolean isProcessPluginDependenciesInDependencyManagement() { return processPluginDependenciesInPluginManagement; } - public boolean isVerbose() - { + public boolean isVerbose() { return verbose; } @@ -417,73 +405,85 @@ public boolean isVerbose() * @since 1.0-alpha-1 */ @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { logInit(); validateInput(); Set dependencyManagement = emptySet(); - try - { - if ( isProcessingDependencyManagement() ) - { - dependencyManagement = filterDependencies( extractDependenciesFromDependencyManagement( getProject(), - processDependencyManagementTransitive, getLog() ), - dependencyManagementIncludes, dependencyManagementExcludes, "Dependecy Management", - getLog() ); - - logUpdates( getHelper().lookupDependenciesUpdates( dependencyManagement, - false ), "Dependency Management" ); + try { + if (isProcessingDependencyManagement()) { + dependencyManagement = filterDependencies( + extractDependenciesFromDependencyManagement( + getProject(), processDependencyManagementTransitive, getLog()), + dependencyManagementIncludes, + dependencyManagementExcludes, + "Dependecy Management", + getLog()); + + logUpdates(getHelper().lookupDependenciesUpdates(dependencyManagement, false), "Dependency Management"); } - if ( isProcessingDependencies() ) - { + if (isProcessingDependencies()) { Set finalDependencyManagement = dependencyManagement; - logUpdates( getHelper().lookupDependenciesUpdates( - filterDependencies( getProject().getDependencies() - .parallelStream() - .filter( dep -> finalDependencyManagement.parallelStream() - .noneMatch( depMan -> dependenciesMatch( dep, depMan ) ) ) - .collect( () -> new TreeSet<>( DependencyComparator.INSTANCE ), Set::add, Set::addAll ), - dependencyIncludes, dependencyExcludes, "Dependencies", getLog() ), - false ), - "Dependencies" ); + logUpdates( + getHelper() + .lookupDependenciesUpdates( + filterDependencies( + getProject().getDependencies().parallelStream() + .filter(dep -> finalDependencyManagement.parallelStream() + .noneMatch(depMan -> dependenciesMatch(dep, depMan))) + .collect( + () -> new TreeSet<>(DependencyComparator.INSTANCE), + Set::add, + Set::addAll), + dependencyIncludes, + dependencyExcludes, + "Dependencies", + getLog()), + false), + "Dependencies"); } - if ( isProcessPluginDependenciesInDependencyManagement() ) - { - logUpdates( getHelper().lookupDependenciesUpdates( filterDependencies( - extractPluginDependenciesFromPluginsInPluginManagement( getProject() ), - pluginManagementDependencyIncludes, pluginManagementDependencyExcludes, - "Plugin Management Dependencies", getLog() ), false ), - "pluginManagement of plugins" ); + if (isProcessPluginDependenciesInDependencyManagement()) { + logUpdates( + getHelper() + .lookupDependenciesUpdates( + filterDependencies( + extractPluginDependenciesFromPluginsInPluginManagement(getProject()), + pluginManagementDependencyIncludes, + pluginManagementDependencyExcludes, + "Plugin Management Dependencies", + getLog()), + false), + "pluginManagement of plugins"); } - if ( isProcessingPluginDependencies() ) - { - logUpdates( getHelper().lookupDependenciesUpdates( filterDependencies( - extractDependenciesFromPlugins( getProject() ), - pluginDependencyIncludes, pluginDependencyExcludes, "Plugin Dependencies", - getLog() ), false ), - "Plugin Dependencies" ); + if (isProcessingPluginDependencies()) { + logUpdates( + getHelper() + .lookupDependenciesUpdates( + filterDependencies( + extractDependenciesFromPlugins(getProject()), + pluginDependencyIncludes, + pluginDependencyExcludes, + "Plugin Dependencies", + getLog()), + false), + "Plugin Dependencies"); } - } - catch ( VersionRetrievalException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (VersionRetrievalException e) { + throw new MojoExecutionException(e.getMessage(), e); } } @Override - protected void validateInput() throws MojoExecutionException - { - validateGAVList( dependencyIncludes, 6, "dependencyIncludes" ); - validateGAVList( dependencyExcludes, 6, "dependencyExcludes" ); - validateGAVList( dependencyManagementIncludes, 6, "dependencyManagementIncludes" ); - validateGAVList( dependencyManagementIncludes, 6, "dependencyManagementExcludes" ); - validateGAVList( pluginDependencyIncludes, 3, "pluginDependencyIncludes" ); - validateGAVList( pluginDependencyExcludes, 3, "pluginDependencyExcludes" ); - validateGAVList( pluginManagementDependencyIncludes, 3, "pluginManagementDependencyIncludes" ); - validateGAVList( pluginManagementDependencyExcludes, 3, "pluginManagementDependencyExcludes" ); + protected void validateInput() throws MojoExecutionException { + validateGAVList(dependencyIncludes, 6, "dependencyIncludes"); + validateGAVList(dependencyExcludes, 6, "dependencyExcludes"); + validateGAVList(dependencyManagementIncludes, 6, "dependencyManagementIncludes"); + validateGAVList(dependencyManagementIncludes, 6, "dependencyManagementExcludes"); + validateGAVList(pluginDependencyIncludes, 3, "pluginDependencyIncludes"); + validateGAVList(pluginDependencyExcludes, 3, "pluginDependencyExcludes"); + validateGAVList(pluginManagementDependencyIncludes, 3, "pluginManagementDependencyIncludes"); + validateGAVList(pluginManagementDependencyExcludes, 3, "pluginManagementDependencyExcludes"); } /** @@ -493,105 +493,83 @@ protected void validateInput() throws MojoExecutionException * @param argumentName argument name to indicate in the exception * @throws MojoExecutionException if the argument is invalid */ - static void validateGAVList( List gavList, int numSections, String argumentName ) - throws MojoExecutionException - { - if ( gavList != null && gavList.stream().anyMatch( gav -> countMatches( gav, ":" ) >= numSections ) ) - { - throw new MojoExecutionException( argumentName + " should not contain more than 6 segments" ); + static void validateGAVList(List gavList, int numSections, String argumentName) + throws MojoExecutionException { + if (gavList != null && gavList.stream().anyMatch(gav -> countMatches(gav, ":") >= numSections)) { + throw new MojoExecutionException(argumentName + " should not contain more than 6 segments"); } } - private Optional calculateUpdateScope() - { + private Optional calculateUpdateScope() { return allowAnyUpdates - ? empty() - : of( SegmentUtils.determineUnchangedSegment( allowMajorUpdates, allowMinorUpdates, - allowIncrementalUpdates, getLog() ) - .map( s -> Segment.of( s.value() + 1 ) ) - .orElse( MAJOR ) ); + ? empty() + : of(SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()) + .map(s -> Segment.of(s.value() + 1)) + .orElse(MAJOR)); } - private void logUpdates( Map updates, String section ) - { + private void logUpdates(Map updates, String section) { List withUpdates = new ArrayList<>(); List usingCurrent = new ArrayList<>(); - for ( ArtifactVersions versions : updates.values() ) - { - String left = " " + ArtifactUtils.versionlessKey( versions.getArtifact() ) + " "; + for (ArtifactVersions versions : updates.values()) { + String left = " " + ArtifactUtils.versionlessKey(versions.getArtifact()) + " "; final String current; ArtifactVersion latest; - if ( versions.isCurrentVersionDefined() ) - { + if (versions.isCurrentVersionDefined()) { current = versions.getCurrentVersion().toString(); - latest = versions.getNewestUpdate( calculateUpdateScope(), allowSnapshots ); - } - else - { + latest = versions.getNewestUpdate(calculateUpdateScope(), allowSnapshots); + } else { ArtifactVersion newestVersion = - versions.getNewestVersion( versions.getArtifact().getVersionRange(), allowSnapshots ); + versions.getNewestVersion(versions.getArtifact().getVersionRange(), allowSnapshots); current = versions.getArtifact().getVersionRange().toString(); - latest = newestVersion == null ? null - : versions.getNewestUpdate( newestVersion, calculateUpdateScope(), allowSnapshots ); - if ( latest != null - && ArtifactVersions.isVersionInRange( latest, versions.getArtifact().getVersionRange() ) ) - { + latest = newestVersion == null + ? null + : versions.getNewestUpdate(newestVersion, calculateUpdateScope(), allowSnapshots); + if (latest != null + && ArtifactVersions.isVersionInRange( + latest, versions.getArtifact().getVersionRange())) { latest = null; } } - String right = " " + ( latest == null ? current : current + " -> " + latest ); + String right = " " + (latest == null ? current : current + " -> " + latest); List t = latest == null ? usingCurrent : withUpdates; - if ( right.length() + left.length() + 3 > INFO_PAD_SIZE + getOutputLineWidthOffset() ) - { - t.add( left + "..." ); - t.add( StringUtils.leftPad( right, INFO_PAD_SIZE + getOutputLineWidthOffset() ) ); + if (right.length() + left.length() + 3 > INFO_PAD_SIZE + getOutputLineWidthOffset()) { + t.add(left + "..."); + t.add(StringUtils.leftPad(right, INFO_PAD_SIZE + getOutputLineWidthOffset())); - } - else - { - t.add( StringUtils.rightPad( left, INFO_PAD_SIZE + getOutputLineWidthOffset() - right.length(), "." ) - + right ); + } else { + t.add(StringUtils.rightPad(left, INFO_PAD_SIZE + getOutputLineWidthOffset() - right.length(), ".") + + right); } } - if ( isVerbose() ) - { - if ( usingCurrent.isEmpty() ) - { - if ( !withUpdates.isEmpty() ) - { - logLine( false, "No dependencies in " + section + " are using the newest version." ); - logLine( false, "" ); + if (isVerbose()) { + if (usingCurrent.isEmpty()) { + if (!withUpdates.isEmpty()) { + logLine(false, "No dependencies in " + section + " are using the newest version."); + logLine(false, ""); } - } - else - { - logLine( false, "The following dependencies in " + section + " are using the newest version:" ); - for ( String s : usingCurrent ) - { - logLine( false, s ); + } else { + logLine(false, "The following dependencies in " + section + " are using the newest version:"); + for (String s : usingCurrent) { + logLine(false, s); } - logLine( false, "" ); + logLine(false, ""); } } - - if ( withUpdates.isEmpty() ) - { - if ( !usingCurrent.isEmpty() ) - { - logLine( false, "No dependencies in " + section + " have newer versions." ); - logLine( false, "" ); + if (withUpdates.isEmpty()) { + if (!usingCurrent.isEmpty()) { + logLine(false, "No dependencies in " + section + " have newer versions."); + logLine(false, ""); } - } - else - { - logLine( false, "The following dependencies in " + section + " have newer versions:" ); - for ( String withUpdate : withUpdates ) - { - logLine( false, withUpdate ); + } else { + logLine(false, "The following dependencies in " + section + " have newer versions:"); + for (String withUpdate : withUpdates) { + logLine(false, withUpdate); } - logLine( false, "" ); + logLine(false, ""); } } @@ -601,9 +579,7 @@ private void logUpdates( Map updates, String secti * @since 1.0-alpha-1 */ @Override - protected void update( ModifiedPomXMLEventReader pom ) - { + protected void update(ModifiedPomXMLEventReader pom) { // do nothing } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojo.java index a65d58faa2..af8ee80e31 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojo.java @@ -43,36 +43,30 @@ * @author Stephen Connolly * @since 2.2 */ -@Mojo( name = "display-parent-updates", threadSafe = true ) -public class DisplayParentUpdatesMojo - extends AbstractVersionsDisplayMojo -{ +@Mojo(name = "display-parent-updates", threadSafe = true) +public class DisplayParentUpdatesMojo extends AbstractVersionsDisplayMojo { public static final int MESSAGE_LENGTH = 68; @Inject - public DisplayParentUpdatesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public DisplayParentUpdatesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { logInit(); - if ( getProject().getParent() == null ) - { - logLine( false, "Project does not have a parent." ); + if (getProject().getParent() == null) { + logLine(false, "Project does not have a parent."); return; } - if ( reactorProjects.contains( getProject().getParent() ) ) - { - logLine( false, "Parent project is part of the reactor." ); + if (reactorProjects.contains(getProject().getParent())) { + logLine(false, "Parent project is part of the reactor."); return; } @@ -80,75 +74,65 @@ public void execute() String version = currentVersion; VersionRange versionRange; - try - { - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new MojoExecutionException( "Invalid version range specification: " + version, e ); + try { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { + throw new MojoExecutionException("Invalid version range specification: " + version, e); } - Artifact artifact = getHelper().createDependencyArtifact( DependencyBuilder.newBuilder() - .withGroupId( getProject().getParent().getGroupId() ) - .withArtifactId( getProject().getParent().getArtifactId() ) - .withVersion( version ) - .withType( "pom" ) - .build() ); + Artifact artifact = getHelper() + .createDependencyArtifact(DependencyBuilder.newBuilder() + .withGroupId(getProject().getParent().getGroupId()) + .withArtifactId(getProject().getParent().getArtifactId()) + .withVersion(version) + .withType("pom") + .build()); ArtifactVersion artifactVersion; - try - { - artifactVersion = findLatestVersion( artifact, versionRange, null, false ); - } - catch ( VersionRetrievalException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + artifactVersion = findLatestVersion(artifact, versionRange, null, false); + } catch (VersionRetrievalException e) { + throw new MojoExecutionException(e.getMessage(), e); } - if ( artifactVersion == null || currentVersion.equals( artifactVersion.toString() ) ) - { - logLine( false, "The parent project is the latest version:" ); - StringBuilder buf = new StringBuilder( MESSAGE_LENGTH ); - buf.append( " " ); - buf.append( getProject().getParent().getGroupId() ); - buf.append( ':' ); - buf.append( getProject().getParent().getArtifactId() ); - buf.append( ' ' ); + if (artifactVersion == null || currentVersion.equals(artifactVersion.toString())) { + logLine(false, "The parent project is the latest version:"); + StringBuilder buf = new StringBuilder(MESSAGE_LENGTH); + buf.append(" "); + buf.append(getProject().getParent().getGroupId()); + buf.append(':'); + buf.append(getProject().getParent().getArtifactId()); + buf.append(' '); int padding = MESSAGE_LENGTH - currentVersion.length(); - while ( buf.length() < padding ) - { - buf.append( '.' ); + while (buf.length() < padding) { + buf.append('.'); } - buf.append( ' ' ); - buf.append( currentVersion ); - logLine( false, buf.toString() ); - } - else - { - logLine( false, "The parent project has a newer version:" ); - StringBuilder buf = new StringBuilder( MESSAGE_LENGTH ); - buf.append( " " ); - buf.append( getProject().getParent().getGroupId() ); - buf.append( ':' ); - buf.append( getProject().getParent().getArtifactId() ); - buf.append( ' ' ); - int padding = MESSAGE_LENGTH - currentVersion.length() - - artifactVersion.toString().length() - " -> ".length(); - while ( buf.length() < padding ) - { - buf.append( '.' ); + buf.append(' '); + buf.append(currentVersion); + logLine(false, buf.toString()); + } else { + logLine(false, "The parent project has a newer version:"); + StringBuilder buf = new StringBuilder(MESSAGE_LENGTH); + buf.append(" "); + buf.append(getProject().getParent().getGroupId()); + buf.append(':'); + buf.append(getProject().getParent().getArtifactId()); + buf.append(' '); + int padding = MESSAGE_LENGTH + - currentVersion.length() + - artifactVersion.toString().length() + - " -> ".length(); + while (buf.length() < padding) { + buf.append('.'); } - buf.append( ' ' ); - buf.append( currentVersion ); - buf.append( " -> " ); - buf.append( artifactVersion ); - logLine( false, buf.toString() ); + buf.append(' '); + buf.append(currentVersion); + buf.append(" -> "); + buf.append(artifactVersion); + logLine(false, buf.toString()); } } @Override - protected void update( ModifiedPomXMLEventReader pom ) - { - } + protected void update(ModifiedPomXMLEventReader pom) {} } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java index 0b9c84508b..8f7724d7b6 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java @@ -93,10 +93,8 @@ * @author Stephen Connolly * @since 1.0-alpha-1 */ -@Mojo( name = "display-plugin-updates", threadSafe = true ) -public class DisplayPluginUpdatesMojo - extends AbstractVersionsDisplayMojo -{ +@Mojo(name = "display-plugin-updates", threadSafe = true) +public class DisplayPluginUpdatesMojo extends AbstractVersionsDisplayMojo { // ------------------------------ FIELDS ------------------------------ @@ -120,6 +118,7 @@ public class DisplayPluginUpdatesMojo * @since 1.0-alpha-1 */ private static final String FROM_SUPER_POM = "(from super-pom) "; + public static final String DEFAULT_MVN_VERSION = "3.2.5"; /** @@ -149,17 +148,17 @@ public class DisplayPluginUpdatesMojo // --------------------- GETTER / SETTER METHODS --------------------- @Inject - @SuppressWarnings( "checkstyle:ParameterNumber" ) - public DisplayPluginUpdatesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - ProjectBuilder projectBuilder, - Map wagonMap, - LifecycleExecutor lifecycleExecutor, - ModelInterpolator modelInterpolator, - RuntimeInformation runtimeInformation, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + @SuppressWarnings("checkstyle:ParameterNumber") + public DisplayPluginUpdatesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + ProjectBuilder projectBuilder, + Map wagonMap, + LifecycleExecutor lifecycleExecutor, + ModelInterpolator modelInterpolator, + RuntimeInformation runtimeInformation, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); this.projectBuilder = projectBuilder; this.lifecycleExecutor = lifecycleExecutor; this.modelInterpolator = modelInterpolator; @@ -172,82 +171,65 @@ public DisplayPluginUpdatesMojo( RepositorySystem repositorySystem, * @return Returns the pluginManagement section of the super-pom. * @throws MojoExecutionException when things go wrong. */ - private Map getSuperPomPluginManagement() - throws MojoExecutionException - { + private Map getSuperPomPluginManagement() throws MojoExecutionException { // we need to provide a copy with the version blanked out so that inferring from super-pom // works as for 2.x as 3.x fills in the version on us! - Map result = lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles( getProject() - .getPackaging() ) - .stream() - .collect( LinkedHashMap::new, - ( m, p ) -> m.put( p.getKey(), p.getVersion() ), - Map::putAll ); - - URL superPom = getClass().getClassLoader().getResource( "org/apache/maven/model/pom-4.0.0.xml" ); - if ( superPom != null ) - { - try - { - try ( Reader reader = ReaderFactory.newXmlReader( superPom ) ) - { - StringBuilder buf = new StringBuilder( IOUtil.toString( reader ) ); - ModifiedPomXMLEventReader pom = newModifiedPomXER( buf, superPom.toString() ); - - Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" + Map result = + lifecycleExecutor + .getPluginsBoundByDefaultToAllLifecycles(getProject().getPackaging()) + .stream() + .collect(LinkedHashMap::new, (m, p) -> m.put(p.getKey(), p.getVersion()), Map::putAll); + + URL superPom = getClass().getClassLoader().getResource("org/apache/maven/model/pom-4.0.0.xml"); + if (superPom != null) { + try { + try (Reader reader = ReaderFactory.newXmlReader(superPom)) { + StringBuilder buf = new StringBuilder(IOUtil.toString(reader)); + ModifiedPomXMLEventReader pom = newModifiedPomXER(buf, superPom.toString()); + + Pattern pathRegex = Pattern.compile("/project(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))" - + "/plugins/plugin" ); + + "/plugins/plugin"); Stack pathStack = new Stack<>(); StackState curState = null; - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartDocument() ) - { - curState = new StackState( "" ); + if (event.isStartDocument()) { + curState = new StackState(""); pathStack.clear(); - } - else if ( event.isStartElement() ) - { - String elementName = event.asStartElement().getName().getLocalPart(); - if ( curState != null && pathRegex.matcher( curState.path ).matches() ) - { - if ( "groupId".equals( elementName ) ) - { + } else if (event.isStartElement()) { + String elementName = + event.asStartElement().getName().getLocalPart(); + if (curState != null + && pathRegex.matcher(curState.path).matches()) { + if ("groupId".equals(elementName)) { curState.groupId = pom.getElementText().trim(); continue; - } - else if ( "artifactId".equals( elementName ) ) - { + } else if ("artifactId".equals(elementName)) { curState.artifactId = pom.getElementText().trim(); continue; - } - else if ( "version".equals( elementName ) ) - { + } else if ("version".equals(elementName)) { curState.version = pom.getElementText().trim(); continue; } } - pathStack.push( curState ); - curState = new StackState( curState.path + "/" + elementName ); - } - else if ( event.isEndElement() ) - { - if ( curState != null && pathRegex.matcher( curState.path ).matches() ) - { - if ( curState.artifactId != null ) - { + pathStack.push(curState); + curState = new StackState(curState.path + "/" + elementName); + } else if (event.isEndElement()) { + if (curState != null + && pathRegex.matcher(curState.path).matches()) { + if (curState.artifactId != null) { Plugin plugin = new Plugin(); - plugin.setArtifactId( curState.artifactId ); - plugin.setGroupId( curState.groupId == null - ? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID - : curState.groupId ); - plugin.setVersion( curState.version ); - if ( !result.containsKey( plugin.getKey() ) ) - { - result.put( plugin.getKey(), plugin.getVersion() ); + plugin.setArtifactId(curState.artifactId); + plugin.setGroupId( + curState.groupId == null + ? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID + : curState.groupId); + plugin.setVersion(curState.version); + if (!result.containsKey(plugin.getKey())) { + result.put(plugin.getKey(), plugin.getVersion()); } } } @@ -255,9 +237,7 @@ else if ( event.isEndElement() ) } } } - } - catch ( IOException | XMLStreamException e ) - { + } catch (IOException | XMLStreamException e) { // ignore } } @@ -272,50 +252,36 @@ else if ( event.isEndElement() ) * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ - private Map getPluginManagement( Model model ) - { + private Map getPluginManagement(Model model) { // we want only those parts of pluginManagement that are defined in this project Map pluginManagement = new HashMap<>(); - try - { - for ( Plugin plugin : model.getBuild().getPluginManagement().getPlugins() ) - { + try { + for (Plugin plugin : model.getBuild().getPluginManagement().getPlugins()) { String coord = plugin.getKey(); String version = plugin.getVersion(); - if ( version != null ) - { - pluginManagement.put( coord, version ); + if (version != null) { + pluginManagement.put(coord, version); } } - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // guess there are no plugins here } - try - { - for ( Profile profile : model.getProfiles() ) - { - try - { - for ( Plugin plugin : profile.getBuild().getPluginManagement().getPlugins() ) - { + try { + for (Profile profile : model.getProfiles()) { + try { + for (Plugin plugin : + profile.getBuild().getPluginManagement().getPlugins()) { String coord = plugin.getKey(); String version = plugin.getVersion(); - if ( version != null ) - { - pluginManagement.put( coord, version ); + if (version != null) { + pluginManagement.put(coord, version); } } - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // guess there are no plugins here } } - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // guess there are no profiles here } @@ -332,29 +298,23 @@ private Map getPluginManagement( Model model ) * @see AbstractVersionsUpdaterMojo#execute() * @since 1.0-alpha-1 */ - @SuppressWarnings( "checkstyle:MethodLength" ) - public void execute() - throws MojoExecutionException, MojoFailureException - { + @SuppressWarnings("checkstyle:MethodLength") + public void execute() throws MojoExecutionException, MojoFailureException { logInit(); Set pluginsWithVersionsSpecified; - try - { + try { MavenProject project1 = getProject(); - pluginsWithVersionsSpecified = - findPluginsWithVersionsSpecified( PomHelper.readXmlFile( project1.getFile() ), - getSafeProjectPathInfo( project1 ) ); - } - catch ( XMLStreamException | IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + pluginsWithVersionsSpecified = findPluginsWithVersionsSpecified( + PomHelper.readXmlFile(project1.getFile()), getSafeProjectPathInfo(project1)); + } catch (XMLStreamException | IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } Map superPomPluginManagement = getSuperPomPluginManagement(); - getLog().debug( "superPom plugins = " + superPomPluginManagement ); + getLog().debug("superPom plugins = " + superPomPluginManagement); - List parents = getParentProjects( getProject() ); - Map parentPlugins = getParentsPlugins( parents ); + List parents = getParentProjects(getProject()); + Map parentPlugins = getParentsPlugins(parents); // TODO remove, not used any more (found while extracting getParentsPlugins method and // renaming parentPluginManagement to parentPlugins) // NOTICE: getProjectPlugins() takes profiles while getParentPlugins does not @@ -362,132 +322,117 @@ public void execute() Map parentBuildPlugins = new HashMap<>(); Map parentReportPlugins = new HashMap<>(); - Set plugins = getProjectPlugins( superPomPluginManagement, parentPlugins, parentBuildPlugins, - parentReportPlugins, pluginsWithVersionsSpecified ); + Set plugins = getProjectPlugins( + superPomPluginManagement, + parentPlugins, + parentBuildPlugins, + parentReportPlugins, + pluginsWithVersionsSpecified); List pluginUpdates = new ArrayList<>(); List pluginLockdowns = new ArrayList<>(); - ArtifactVersion curMavenVersion = new DefaultArtifactVersion( runtimeInformation.getMavenVersion() ); - ArtifactVersion specMavenVersion = MinimalMavenBuildVersionFinder.find( getProject(), DEFAULT_MVN_VERSION, - getLog() ); + ArtifactVersion curMavenVersion = new DefaultArtifactVersion(runtimeInformation.getMavenVersion()); + ArtifactVersion specMavenVersion = + MinimalMavenBuildVersionFinder.find(getProject(), DEFAULT_MVN_VERSION, getLog()); ArtifactVersion minMavenVersion = null; boolean superPomDrivingMinVersion = false; // if Maven prerequisite upgraded to a version, Map - Map> mavenUpgrades = new TreeMap<>( new MavenVersionComparator() ); + Map> mavenUpgrades = new TreeMap<>(new MavenVersionComparator()); - for ( Plugin plugin : plugins ) - { + for (Plugin plugin : plugins) { String groupId = plugin.getGroupId(); String artifactId = plugin.getArtifactId(); String version = plugin.getVersion(); - String coords = ArtifactUtils.versionlessKey( groupId, artifactId ); + String coords = ArtifactUtils.versionlessKey(groupId, artifactId); - if ( version == null ) - { - version = parentPlugins.get( coords ); + if (version == null) { + version = parentPlugins.get(coords); } - boolean versionSpecifiedInCurrentPom = pluginsWithVersionsSpecified.contains( coords ); - if ( !versionSpecifiedInCurrentPom && parentPlugins.containsKey( coords ) ) - { - getLog().debug( "Skip " + coords + ", version " + version + " is defined in parent POM." ); + boolean versionSpecifiedInCurrentPom = pluginsWithVersionsSpecified.contains(coords); + if (!versionSpecifiedInCurrentPom && parentPlugins.containsKey(coords)) { + getLog().debug("Skip " + coords + ", version " + version + " is defined in parent POM."); continue; } - getLog().debug( "Checking " + coords + " for updates newer than " + version ); + getLog().debug("Checking " + coords + " for updates newer than " + version); String effectiveVersion = version; - Artifact artifactRange = getHelper().createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), - version ); + Artifact artifactRange = + getHelper().createPluginArtifact(plugin.getGroupId(), plugin.getArtifactId(), version); ArtifactVersion artifactVersion = null; - try - { + try { // now we want to find the newest versions and check their Maven version prerequisite - ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifactRange, true ); - ArtifactVersion[] newerVersions = artifactVersions.getVersions( this.allowSnapshots ); + ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions(artifactRange, true); + ArtifactVersion[] newerVersions = artifactVersions.getVersions(this.allowSnapshots); ArtifactVersion minRequires = null; - for ( int j = newerVersions.length - 1; j >= 0; j-- ) - { - try - { + for (int j = newerVersions.length - 1; j >= 0; j--) { + try { ArtifactVersion pluginRequires = getPrerequisitesMavenVersion( - getPluginProject( groupId, artifactId, newerVersions[j].toString() ) ); - if ( artifactVersion == null && compare( specMavenVersion, pluginRequires ) >= 0 ) - { + getPluginProject(groupId, artifactId, newerVersions[j].toString())); + if (artifactVersion == null && compare(specMavenVersion, pluginRequires) >= 0) { // ok, newer version compatible with current specMavenVersion artifactVersion = newerVersions[j]; } - if ( effectiveVersion == null && compare( curMavenVersion, pluginRequires ) >= 0 ) - { + if (effectiveVersion == null && compare(curMavenVersion, pluginRequires) >= 0) { // version was unspecified, current version of maven thinks it should use this effectiveVersion = newerVersions[j].toString(); } - if ( artifactVersion != null && effectiveVersion != null ) - { + if (artifactVersion != null && effectiveVersion != null) { // no need to look at any older versions: latest compatible found break; } // newer version not compatible with current specMavenVersion: track opportunity if Maven spec // upgrade - if ( minRequires == null || compare( minRequires, pluginRequires ) > 0 ) - { + if (minRequires == null || compare(minRequires, pluginRequires) > 0) { Map upgradePlugins = - mavenUpgrades.computeIfAbsent( pluginRequires, k -> new LinkedHashMap<>() ); + mavenUpgrades.computeIfAbsent(pluginRequires, k -> new LinkedHashMap<>()); - String upgradePluginKey = compactKey( groupId, artifactId ); - if ( !upgradePlugins.containsKey( upgradePluginKey ) ) - { + String upgradePluginKey = compactKey(groupId, artifactId); + if (!upgradePlugins.containsKey(upgradePluginKey)) { String newer = newerVersions[j].toString(); - if ( newer.equals( effectiveVersion ) ) - { + if (newer.equals(effectiveVersion)) { // plugin version configured that require a Maven version higher than spec - upgradePlugins.put( upgradePluginKey, - pad( upgradePluginKey, - INFO_PAD_SIZE + getOutputLineWidthOffset(), newer ) ); - } - else - { + upgradePlugins.put( + upgradePluginKey, + pad(upgradePluginKey, INFO_PAD_SIZE + getOutputLineWidthOffset(), newer)); + } else { // plugin that can be upgraded - upgradePlugins.put( upgradePluginKey, pad( upgradePluginKey, INFO_PAD_SIZE - + getOutputLineWidthOffset(), - effectiveVersion, " -> ", newer ) ); + upgradePlugins.put( + upgradePluginKey, + pad( + upgradePluginKey, + INFO_PAD_SIZE + getOutputLineWidthOffset(), + effectiveVersion, + " -> ", + newer)); } } minRequires = pluginRequires; } - } - catch ( ArtifactResolutionException | ProjectBuildingException e ) - { + } catch (ArtifactResolutionException | ProjectBuildingException e) { // ignore bad version } } - if ( effectiveVersion != null ) - { - try - { - ArtifactVersion requires = getPrerequisitesMavenVersion( - getPluginProject( groupId, artifactId, effectiveVersion ) ); - if ( minMavenVersion == null || compare( minMavenVersion, requires ) < 0 ) - { + if (effectiveVersion != null) { + try { + ArtifactVersion requires = + getPrerequisitesMavenVersion(getPluginProject(groupId, artifactId, effectiveVersion)); + if (minMavenVersion == null || compare(minMavenVersion, requires) < 0) { minMavenVersion = requires; } - } - catch ( ArtifactResolutionException | ProjectBuildingException e ) - { + } catch (ArtifactResolutionException | ProjectBuildingException e) { // ignore bad version } } - } - catch ( VersionRetrievalException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (VersionRetrievalException e) { + throw new MojoExecutionException(e.getMessage(), e); } String newVersion; - if ( version == null && versionSpecifiedInCurrentPom ) - { + if (version == null && versionSpecifiedInCurrentPom) { // Hack ALERT! // // All this should be re-written in a less "pom is xml" way... but it'll @@ -498,165 +443,139 @@ public void execute() version = artifactVersion != null ? artifactVersion.toString() : null; } - getLog().debug( "[" + coords + "].version=" + version ); - getLog().debug( "[" + coords + "].artifactVersion=" + artifactVersion ); - getLog().debug( "[" + coords + "].effectiveVersion=" + effectiveVersion ); - getLog().debug( "[" + coords + "].specified=" + versionSpecifiedInCurrentPom ); - if ( version == null || !versionSpecifiedInCurrentPom ) - { - version = superPomPluginManagement.get( coords ); - getLog().debug( "[" + coords + "].superPom.version=" + version ); - - newVersion = artifactVersion != null ? artifactVersion.toString() - : ( version != null ? version - : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); - if ( version != null ) - { + getLog().debug("[" + coords + "].version=" + version); + getLog().debug("[" + coords + "].artifactVersion=" + artifactVersion); + getLog().debug("[" + coords + "].effectiveVersion=" + effectiveVersion); + getLog().debug("[" + coords + "].specified=" + versionSpecifiedInCurrentPom); + if (version == null || !versionSpecifiedInCurrentPom) { + version = superPomPluginManagement.get(coords); + getLog().debug("[" + coords + "].superPom.version=" + version); + + newVersion = artifactVersion != null + ? artifactVersion.toString() + : (version != null ? version : (effectiveVersion != null ? effectiveVersion : "(unknown)")); + if (version != null) { superPomDrivingMinVersion = true; } - pluginLockdowns.add( pad( compactKey( groupId, artifactId ), WARN_PAD_SIZE + getOutputLineWidthOffset(), - superPomDrivingMinVersion ? FROM_SUPER_POM : "", newVersion ) ); - } - else if ( artifactVersion != null ) - { + pluginLockdowns.add(pad( + compactKey(groupId, artifactId), + WARN_PAD_SIZE + getOutputLineWidthOffset(), + superPomDrivingMinVersion ? FROM_SUPER_POM : "", + newVersion)); + } else if (artifactVersion != null) { newVersion = artifactVersion.toString(); - } - else - { + } else { newVersion = null; } - if ( version != null && artifactVersion != null && newVersion != null && effectiveVersion != null - && - new DefaultArtifactVersion( effectiveVersion ).compareTo( new DefaultArtifactVersion( newVersion ) ) - < 0 ) - { - pluginUpdates.add( pad( compactKey( groupId, artifactId ), INFO_PAD_SIZE + getOutputLineWidthOffset(), - effectiveVersion, " -> ", newVersion ) ); + if (version != null + && artifactVersion != null + && newVersion != null + && effectiveVersion != null + && new DefaultArtifactVersion(effectiveVersion).compareTo(new DefaultArtifactVersion(newVersion)) + < 0) { + pluginUpdates.add(pad( + compactKey(groupId, artifactId), + INFO_PAD_SIZE + getOutputLineWidthOffset(), + effectiveVersion, + " -> ", + newVersion)); } } // info on each plugin gathered: now it's time to display the result! // - logLine( false, "" ); + logLine(false, ""); // updates keeping currently defined Maven version minimum - if ( pluginUpdates.isEmpty() ) - { - logLine( false, "All plugins with a version specified are using the latest versions." ); - } - else - { - logLine( false, "The following plugin updates are available:" ); - for ( String update : new TreeSet<>( pluginUpdates ) ) - { - logLine( false, update ); + if (pluginUpdates.isEmpty()) { + logLine(false, "All plugins with a version specified are using the latest versions."); + } else { + logLine(false, "The following plugin updates are available:"); + for (String update : new TreeSet<>(pluginUpdates)) { + logLine(false, update); } } - logLine( false, "" ); + logLine(false, ""); // has every plugin a specified version? - if ( pluginLockdowns.isEmpty() ) - { - logLine( false, "All plugins have a version specified." ); - } - else - { - getLog().warn( "The following plugins do not have their version specified:" ); - for ( String lockdown : new TreeSet<>( pluginLockdowns ) ) - { - getLog().warn( lockdown ); + if (pluginLockdowns.isEmpty()) { + logLine(false, "All plugins have a version specified."); + } else { + getLog().warn("The following plugins do not have their version specified:"); + for (String lockdown : new TreeSet<>(pluginLockdowns)) { + getLog().warn(lockdown); } } - logLine( false, "" ); + logLine(false, ""); // information on minimum Maven version - boolean noMavenMinVersion = MinimalMavenBuildVersionFinder.find( getProject(), null, getLog() ) == null; - if ( noMavenMinVersion ) - { - getLog().warn( "Project does not define minimum Maven version required for build, default is: " - + DEFAULT_MVN_VERSION ); + boolean noMavenMinVersion = MinimalMavenBuildVersionFinder.find(getProject(), null, getLog()) == null; + if (noMavenMinVersion) { + getLog().warn("Project does not define minimum Maven version required for build, default is: " + + DEFAULT_MVN_VERSION); + } else { + logLine(false, "Project requires minimum Maven version for build of: " + specMavenVersion); } - else - { - logLine( false, "Project requires minimum Maven version for build of: " + specMavenVersion ); + logLine(false, "Plugins require minimum Maven version of: " + minMavenVersion); + if (superPomDrivingMinVersion) { + logLine(false, "Note: the super-pom from Maven " + curMavenVersion + " defines some of the plugin"); + logLine(false, " versions and may be influencing the plugins required minimum Maven"); + logLine(false, " version."); } - logLine( false, "Plugins require minimum Maven version of: " + minMavenVersion ); - if ( superPomDrivingMinVersion ) - { - logLine( false, "Note: the super-pom from Maven " + curMavenVersion + " defines some of the plugin" ); - logLine( false, " versions and may be influencing the plugins required minimum Maven" ); - logLine( false, " version." ); - } - logLine( false, "" ); - - if ( isMavenPluginProject() ) - { - if ( noMavenMinVersion ) - { - getLog().warn( "Project (which is a Maven plugin) does not define required minimum version of Maven." ); - getLog().warn( "Update the pom.xml to contain" ); - getLog().warn( " " ); - getLog().warn( " " ); - getLog().warn( " " ); - getLog().warn( "To build this plugin you need at least Maven " + minMavenVersion ); - getLog().warn( "A Maven Enforcer rule can be used to enforce this if you have not already set one up" ); - getLog().warn( "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" ); - } - else if ( minMavenVersion != null && compare( specMavenVersion, minMavenVersion ) < 0 ) - { - getLog().warn( "Project (which is a Maven plugin) targets Maven " + specMavenVersion + " or newer" ); - getLog().warn( "but requires Maven " + minMavenVersion + " or newer to build." ); - getLog().warn( "This may or may not be a problem. A Maven Enforcer rule can help " ); - getLog().warn( "enforce that the correct version of Maven is used to build this plugin." ); - getLog().warn( "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" ); - } - else - { - logLine( false, "No plugins require a newer version of Maven than specified by the pom." ); - } - } - else - { - if ( noMavenMinVersion ) - { - logLine( true, "Project does not define required minimum version of Maven." ); - logLine( true, "Update the pom.xml to contain maven-enforcer-plugin to" ); - logLine( true, "force the Maven version which is needed to build this project." ); - logLine( true, "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" ); - logLine( true, "Using the minimum version of Maven: " + minMavenVersion ); - } - else if ( minMavenVersion != null && compare( specMavenVersion, minMavenVersion ) < 0 ) - { - logLine( true, "Project requires an incorrect minimum version of Maven." ); - logLine( true, "Update the pom.xml to contain maven-enforcer-plugin to" ); - logLine( true, "force the Maven version which is needed to build this project." ); - logLine( true, "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" ); - logLine( true, "Using the minimum version of Maven: " + specMavenVersion ); + logLine(false, ""); + + if (isMavenPluginProject()) { + if (noMavenMinVersion) { + getLog().warn("Project (which is a Maven plugin) does not define required minimum version of Maven."); + getLog().warn("Update the pom.xml to contain"); + getLog().warn(" "); + getLog().warn(" "); + getLog().warn(" "); + getLog().warn("To build this plugin you need at least Maven " + minMavenVersion); + getLog().warn("A Maven Enforcer rule can be used to enforce this if you have not already set one up"); + getLog().warn("See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html"); + } else if (minMavenVersion != null && compare(specMavenVersion, minMavenVersion) < 0) { + getLog().warn("Project (which is a Maven plugin) targets Maven " + specMavenVersion + " or newer"); + getLog().warn("but requires Maven " + minMavenVersion + " or newer to build."); + getLog().warn("This may or may not be a problem. A Maven Enforcer rule can help "); + getLog().warn("enforce that the correct version of Maven is used to build this plugin."); + getLog().warn("See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html"); + } else { + logLine(false, "No plugins require a newer version of Maven than specified by the pom."); } - else - { - logLine( false, "No plugins require a newer version of Maven than specified by the pom." ); + } else { + if (noMavenMinVersion) { + logLine(true, "Project does not define required minimum version of Maven."); + logLine(true, "Update the pom.xml to contain maven-enforcer-plugin to"); + logLine(true, "force the Maven version which is needed to build this project."); + logLine(true, "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html"); + logLine(true, "Using the minimum version of Maven: " + minMavenVersion); + } else if (minMavenVersion != null && compare(specMavenVersion, minMavenVersion) < 0) { + logLine(true, "Project requires an incorrect minimum version of Maven."); + logLine(true, "Update the pom.xml to contain maven-enforcer-plugin to"); + logLine(true, "force the Maven version which is needed to build this project."); + logLine(true, "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html"); + logLine(true, "Using the minimum version of Maven: " + specMavenVersion); + } else { + logLine(false, "No plugins require a newer version of Maven than specified by the pom."); } } // updates if minimum Maven version is changed - for ( Map.Entry> mavenUpgrade : mavenUpgrades.entrySet() ) - { + for (Map.Entry> mavenUpgrade : mavenUpgrades.entrySet()) { ArtifactVersion mavenUpgradeVersion = mavenUpgrade.getKey(); Map upgradePlugins = mavenUpgrade.getValue(); - if ( upgradePlugins.isEmpty() || compare( specMavenVersion, mavenUpgradeVersion ) >= 0 ) - { + if (upgradePlugins.isEmpty() || compare(specMavenVersion, mavenUpgradeVersion) >= 0) { continue; } - logLine( false, "" ); - logLine( false, "Require Maven " + mavenUpgradeVersion + " to use the following plugin updates:" ); - for ( Map.Entry entry : upgradePlugins.entrySet() ) - { - logLine( false, entry.getValue() ); + logLine(false, ""); + logLine(false, "Require Maven " + mavenUpgradeVersion + " to use the following plugin updates:"); + for (Map.Entry entry : upgradePlugins.entrySet()) { + logLine(false, entry.getValue()); } } - logLine( false, "" ); + logLine(false, ""); } /** @@ -670,151 +589,126 @@ else if ( minMavenVersion != null && compare( specMavenVersion, minMavenVersion * @throws MojoExecutionException thrown if the artifact for the plugin could not be constructed * @throws ProjectBuildingException thrown if the {@link MavenProject} instance could not be constructed */ - private MavenProject getPluginProject( String groupId, String artifactId, String version ) - throws MojoExecutionException, ProjectBuildingException, ArtifactResolutionException - { - Artifact probe = getHelper().createDependencyArtifact( DependencyBuilder.newBuilder() - .withGroupId( groupId ) - .withArtifactId( artifactId ) - .withVersion( version ) - .withType( "pom" ) - .withScope( Artifact.SCOPE_RUNTIME ) - .build() ); - getHelper().resolveArtifact( probe, true ); - ProjectBuildingResult result = - projectBuilder.build( probe, true, - PomHelper.createProjectBuilderRequest( session, - r -> r.setProcessPlugins( false ), - r -> r.setRemoteRepositories( session.getCurrentProject() - .getPluginArtifactRepositories() ) ) ); - if ( !result.getProblems().isEmpty() ) - { - getLog().warn( "Problems encountered during construction of the plugin POM for " - + probe.toString() ); - result.getProblems().forEach( p -> - getLog().warn( "\t" + p.getMessage() ) ); + private MavenProject getPluginProject(String groupId, String artifactId, String version) + throws MojoExecutionException, ProjectBuildingException, ArtifactResolutionException { + Artifact probe = getHelper() + .createDependencyArtifact(DependencyBuilder.newBuilder() + .withGroupId(groupId) + .withArtifactId(artifactId) + .withVersion(version) + .withType("pom") + .withScope(Artifact.SCOPE_RUNTIME) + .build()); + getHelper().resolveArtifact(probe, true); + ProjectBuildingResult result = projectBuilder.build( + probe, + true, + PomHelper.createProjectBuilderRequest( + session, + r -> r.setProcessPlugins(false), + r -> r.setRemoteRepositories(session.getCurrentProject().getPluginArtifactRepositories()))); + if (!result.getProblems().isEmpty()) { + getLog().warn("Problems encountered during construction of the plugin POM for " + probe.toString()); + result.getProblems().forEach(p -> getLog().warn("\t" + p.getMessage())); } return result.getProject(); } - private static String pad( String start, int len, String... ends ) - { - StringBuilder buf = new StringBuilder( len ); - buf.append( " " ); - buf.append( start ); + private static String pad(String start, int len, String... ends) { + StringBuilder buf = new StringBuilder(len); + buf.append(" "); + buf.append(start); int padding = len; - for ( String end : ends ) - { + for (String end : ends) { padding -= end.length(); } - buf.append( ' ' ); - while ( buf.length() < padding ) - { - buf.append( '.' ); + buf.append(' '); + while (buf.length() < padding) { + buf.append('.'); } - buf.append( ' ' ); - for ( String end : ends ) - { - buf.append( end ); + buf.append(' '); + for (String end : ends) { + buf.append(end); } return buf.toString(); } - private Map getParentsPlugins( List parents ) - throws MojoExecutionException - { + private Map getParentsPlugins(List parents) throws MojoExecutionException { Map parentPlugins = new HashMap<>(); - for ( MavenProject parentProject : parents ) - { - getLog().debug( "Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() - + ":" + parentProject.getVersion() + " -> " + parentProject.getFile() ); + for (MavenProject parentProject : parents) { + getLog().debug("Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + + ":" + parentProject.getVersion() + " -> " + parentProject.getFile()); StringWriter writer = new StringWriter(); boolean havePom = false; Model interpolatedModel; Model originalModel = parentProject.getOriginalModel(); - if ( originalModel == null ) - { - getLog().warn( "project.getOriginalModel()==null for " + parentProject.getGroupId() + ":" + if (originalModel == null) { + getLog().warn("project.getOriginalModel()==null for " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() - + " is null, substituting project.getModel()" ); + + " is null, substituting project.getModel()"); originalModel = parentProject.getModel(); } - try - { - new MavenXpp3Writer().write( writer, originalModel ); + try { + new MavenXpp3Writer().write(writer, originalModel); writer.close(); havePom = true; - } - catch ( IOException e ) - { + } catch (IOException e) { // ignore } ModelBuildingRequest modelBuildingRequest = new DefaultModelBuildingRequest(); - modelBuildingRequest.setUserProperties( getProject().getProperties() ); - interpolatedModel = modelInterpolator.interpolateModel( originalModel, null, - modelBuildingRequest, - new IgnoringModelProblemCollector() ); - if ( havePom ) - { - try - { - Set withVersionSpecified = - findPluginsWithVersionsSpecified( new StringBuilder( writer.toString() ), - getSafeProjectPathInfo( parentProject ) ); - - Map map = getPluginManagement( interpolatedModel ); - map.keySet().retainAll( withVersionSpecified ); - parentPlugins.putAll( map ); - - map = getBuildPlugins( interpolatedModel, true ); - map.keySet().retainAll( withVersionSpecified ); - parentPlugins.putAll( map ); - - map = getReportPlugins( interpolatedModel, true ); - map.keySet().retainAll( withVersionSpecified ); - parentPlugins.putAll( map ); - } - catch ( XMLStreamException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + modelBuildingRequest.setUserProperties(getProject().getProperties()); + interpolatedModel = modelInterpolator.interpolateModel( + originalModel, null, modelBuildingRequest, new IgnoringModelProblemCollector()); + if (havePom) { + try { + Set withVersionSpecified = findPluginsWithVersionsSpecified( + new StringBuilder(writer.toString()), getSafeProjectPathInfo(parentProject)); + + Map map = getPluginManagement(interpolatedModel); + map.keySet().retainAll(withVersionSpecified); + parentPlugins.putAll(map); + + map = getBuildPlugins(interpolatedModel, true); + map.keySet().retainAll(withVersionSpecified); + parentPlugins.putAll(map); + + map = getReportPlugins(interpolatedModel, true); + map.keySet().retainAll(withVersionSpecified); + parentPlugins.putAll(map); + } catch (XMLStreamException e) { + throw new MojoExecutionException(e.getMessage(), e); } - } - else - { - parentPlugins.putAll( getPluginManagement( interpolatedModel ) ); - parentPlugins.putAll( getBuildPlugins( interpolatedModel, true ) ); - parentPlugins.putAll( getReportPlugins( interpolatedModel, true ) ); + } else { + parentPlugins.putAll(getPluginManagement(interpolatedModel)); + parentPlugins.putAll(getBuildPlugins(interpolatedModel, true)); + parentPlugins.putAll(getReportPlugins(interpolatedModel, true)); } } return parentPlugins; } - private String getSafeProjectPathInfo( MavenProject project ) - { - return ofNullable( project.getFile() ) - .map( File::getAbsolutePath ) + private String getSafeProjectPathInfo(MavenProject project) { + return ofNullable(project.getFile()) + .map(File::getAbsolutePath) // path is used only as information in error message, // we can fallback to project artifact info here - .orElse( project.toString() ); + .orElse(project.toString()); } - private boolean isMavenPluginProject() - { - return "maven-plugin".equals( getProject().getPackaging() ); + private boolean isMavenPluginProject() { + return "maven-plugin".equals(getProject().getPackaging()); } - private String compactKey( String groupId, String artifactId ) - { - return PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ) + private String compactKey(String groupId, String artifactId) { + return PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals(groupId) // a core plugin... group id is not needed ? artifactId : groupId + ":" + artifactId; } - private static final class StackState - { + private static final class StackState { private final String path; private String groupId; @@ -823,13 +717,11 @@ private static final class StackState private String version; - StackState( String path ) - { + StackState(String path) { this.path = path; } - public String toString() - { + public String toString() { return path + "[groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + "]"; } } @@ -841,61 +733,45 @@ public String toString() * @param path Path that points to the source of the XML * @return a set of Strings which correspond to the plugin coordinates where there is a version specified. */ - private Set findPluginsWithVersionsSpecified( StringBuilder pomContents, String path ) - throws XMLStreamException - { + private Set findPluginsWithVersionsSpecified(StringBuilder pomContents, String path) + throws XMLStreamException { Set result = new HashSet<>(); - ModifiedPomXMLEventReader pom = newModifiedPomXER( pomContents, path ); + ModifiedPomXMLEventReader pom = newModifiedPomXER(pomContents, path); - Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" - + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); + Pattern pathRegex = Pattern.compile( + "/project(/profiles/profile)?" + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin"); Stack pathStack = new Stack<>(); StackState curState = null; - while ( pom.hasNext() ) - { + while (pom.hasNext()) { XMLEvent event = pom.nextEvent(); - if ( event.isStartDocument() ) - { - curState = new StackState( "" ); + if (event.isStartDocument()) { + curState = new StackState(""); pathStack.clear(); - } - else if ( event.isStartElement() ) - { + } else if (event.isStartElement()) { String elementName = event.asStartElement().getName().getLocalPart(); - if ( curState != null && pathRegex.matcher( curState.path ).matches() ) - { - if ( "groupId".equals( elementName ) ) - { + if (curState != null && pathRegex.matcher(curState.path).matches()) { + if ("groupId".equals(elementName)) { curState.groupId = pom.getElementText().trim(); continue; - } - else if ( "artifactId".equals( elementName ) ) - { + } else if ("artifactId".equals(elementName)) { curState.artifactId = pom.getElementText().trim(); continue; - } - else if ( "version".equals( elementName ) ) - { + } else if ("version".equals(elementName)) { curState.version = pom.getElementText().trim(); continue; } } - pathStack.push( curState ); - curState = new StackState( curState.path + "/" + elementName ); - } - else if ( event.isEndElement() ) - { - if ( curState != null && pathRegex.matcher( curState.path ).matches() ) - { - if ( curState.artifactId != null && curState.version != null ) - { - if ( curState.groupId == null ) - { + pathStack.push(curState); + curState = new StackState(curState.path + "/" + elementName); + } else if (event.isEndElement()) { + if (curState != null && pathRegex.matcher(curState.path).matches()) { + if (curState.artifactId != null && curState.version != null) { + if (curState.groupId == null) { curState.groupId = PomHelper.APACHE_MAVEN_PLUGINS_GROUPID; } - result.add( curState.groupId + ":" + curState.artifactId ); + result.add(curState.groupId + ":" + curState.artifactId); } } curState = pathStack.pop(); @@ -903,7 +779,6 @@ else if ( event.isEndElement() ) } return result; - } // -------------------------- OTHER METHODS -------------------------- @@ -916,12 +791,11 @@ else if ( event.isEndElement() ) * @param pluginProject the plugin for which to retrieve the minimum Maven version which is required * @return The minimally required Maven version (never {@code null}) */ - private ArtifactVersion getPrerequisitesMavenVersion( MavenProject pluginProject ) - { - return ofNullable( pluginProject.getPrerequisites() ) - .map( Prerequisites::getMaven ) - .map( DefaultArtifactVersion::new ) - .orElse( new DefaultArtifactVersion( DEFAULT_MVN_VERSION ) ); + private ArtifactVersion getPrerequisitesMavenVersion(MavenProject pluginProject) { + return ofNullable(pluginProject.getPrerequisites()) + .map(Prerequisites::getMaven) + .map(DefaultArtifactVersion::new) + .orElse(new DefaultArtifactVersion(DEFAULT_MVN_VERSION)); } /** @@ -932,15 +806,13 @@ private ArtifactVersion getPrerequisitesMavenVersion( MavenProject pluginProject * child projects. * @return map of plugin name x version */ - private Map getPluginsFromBuild( BuildBase build, boolean onlyIncludeInherited ) - { - return ofNullable( build ) - .flatMap( b -> ofNullable( b.getPlugins() ) - .map( plugins -> plugins.stream() - .filter( plugin -> plugin.getVersion() != null ) - .filter( plugin -> !onlyIncludeInherited || getPluginInherited( plugin ) ) - .collect( toMap( Plugin::getKey, Plugin::getVersion ) ) ) ) - .orElse( emptyMap() ); + private Map getPluginsFromBuild(BuildBase build, boolean onlyIncludeInherited) { + return ofNullable(build) + .flatMap(b -> ofNullable(b.getPlugins()).map(plugins -> plugins.stream() + .filter(plugin -> plugin.getVersion() != null) + .filter(plugin -> !onlyIncludeInherited || getPluginInherited(plugin)) + .collect(toMap(Plugin::getKey, Plugin::getVersion)))) + .orElse(emptyMap()); } /** @@ -952,14 +824,11 @@ private Map getPluginsFromBuild( BuildBase build, boolean onlyIn * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ - private Map getBuildPlugins( Model model, boolean onlyIncludeInherited ) - { - Map buildPlugins = - new HashMap<>( getPluginsFromBuild( model.getBuild(), onlyIncludeInherited ) ); - ofNullable( model.getProfiles() ) - .ifPresent( profiles -> profiles.stream() - .map( profile -> getPluginsFromBuild( profile.getBuild(), onlyIncludeInherited ) ) - .forEach( buildPlugins::putAll ) ); + private Map getBuildPlugins(Model model, boolean onlyIncludeInherited) { + Map buildPlugins = new HashMap<>(getPluginsFromBuild(model.getBuild(), onlyIncludeInherited)); + ofNullable(model.getProfiles()).ifPresent(profiles -> profiles.stream() + .map(profile -> getPluginsFromBuild(profile.getBuild(), onlyIncludeInherited)) + .forEach(buildPlugins::putAll)); return buildPlugins; } @@ -970,10 +839,12 @@ private Map getBuildPlugins( Model model, boolean onlyIncludeInh * @return the Inherited of the {@link Plugin} or {@link ReportPlugin} * @since 1.0-alpha-1 */ - private static boolean getPluginInherited( Object plugin ) - { - return "true".equalsIgnoreCase( plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getInherited() - : ( (Plugin) plugin ).getInherited() ); + private static boolean getPluginInherited(Object plugin) { + return "true" + .equalsIgnoreCase( + plugin instanceof ReportPlugin + ? ((ReportPlugin) plugin).getInherited() + : ((Plugin) plugin).getInherited()); } /** @@ -984,16 +855,11 @@ private static boolean getPluginInherited( Object plugin ) * @throws org.apache.maven.plugin.MojoExecutionException if things go wrong. * @since 1.0-alpha-1 */ - private Map getLifecyclePlugins( MavenProject project ) - throws MojoExecutionException - { - return getBoundPlugins( project ) - .parallelStream() - .filter( Objects::nonNull ) - .filter( p -> p.getKey() != null ) - .collect( HashMap::new, - ( m, p ) -> m.put( p.getKey(), p ), - Map::putAll ); + private Map getLifecyclePlugins(MavenProject project) throws MojoExecutionException { + return getBoundPlugins(project).parallelStream() + .filter(Objects::nonNull) + .filter(p -> p.getKey() != null) + .collect(HashMap::new, (m, p) -> m.put(p.getKey(), p), Map::putAll); } /** @@ -1005,18 +871,17 @@ private Map getLifecyclePlugins( MavenProject project ) */ // pilfered this from enforcer-rules // TODO coordinate with Brian Fox to remove the duplicate code - private Set getBoundPlugins( MavenProject project ) - { + private Set getBoundPlugins(MavenProject project) { // we need to provide a copy with the version blanked out so that inferring from super-pom // works as for 2.x as 3.x fills in the version on us! - return lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles( project.getPackaging() ) - .parallelStream() - .map( p -> new Plugin() - {{ - setGroupId( p.getGroupId() ); - setArtifactId( p.getArtifactId() ); - }} ) - .collect( toSet() ); + return lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles(project.getPackaging()).parallelStream() + .map(p -> new Plugin() { + { + setGroupId(p.getGroupId()); + setArtifactId(p.getArtifactId()); + } + }) + .collect(toSet()); } /** @@ -1027,19 +892,16 @@ private Set getBoundPlugins( MavenProject project ) * @throws org.apache.maven.plugin.MojoExecutionException if the super-pom could not be created. * @since 1.0-alpha-1 */ - private List getParentProjects( MavenProject project ) - throws MojoExecutionException - { + private List getParentProjects(MavenProject project) throws MojoExecutionException { List parents = new ArrayList<>(); - while ( project.getParent() != null ) - { + while (project.getParent() != null) { project = project.getParent(); - parents.add( 0, project ); + parents.add(0, project); } return parents; } - /** + /** * Returns the set of all plugins used by the project. * * @param superPomPluginManagement the super pom's pluginManagement plugins. @@ -1050,177 +912,144 @@ private List getParentProjects( MavenProject project ) * @return the set of plugins used by the project. * @throws org.apache.maven.plugin.MojoExecutionException if things go wrong. */ - @SuppressWarnings( "checkstyle:MethodLength" ) - private Set getProjectPlugins( Map superPomPluginManagement, - Map parentPluginManagement, - Map parentBuildPlugins, - Map parentReportPlugins, - Set pluginsWithVersionsSpecified ) - throws MojoExecutionException - { + @SuppressWarnings("checkstyle:MethodLength") + private Set getProjectPlugins( + Map superPomPluginManagement, + Map parentPluginManagement, + Map parentBuildPlugins, + Map parentReportPlugins, + Set pluginsWithVersionsSpecified) + throws MojoExecutionException { Map plugins = new HashMap<>(); - getLog().debug( "Building list of project plugins..." ); + getLog().debug("Building list of project plugins..."); - if ( getLog().isDebugEnabled() ) - { + if (getLog().isDebugEnabled()) { StringWriter origModel = new StringWriter(); - try - { - origModel.write( "Original model:\n" ); - getProject().writeOriginalModel( origModel ); - getLog().debug( origModel.toString() ); - } - catch ( IOException e ) - { + try { + origModel.write("Original model:\n"); + getProject().writeOriginalModel(origModel); + getLog().debug(origModel.toString()); + } catch (IOException e) { // ignore } } - debugVersionMap( "super-pom version map", superPomPluginManagement ); - debugVersionMap( "parent version map", parentPluginManagement ); + debugVersionMap("super-pom version map", superPomPluginManagement); + debugVersionMap("parent version map", parentPluginManagement); - Map excludePluginManagement = new HashMap<>( superPomPluginManagement ); - excludePluginManagement.putAll( parentPluginManagement ); + Map excludePluginManagement = new HashMap<>(superPomPluginManagement); + excludePluginManagement.putAll(parentPluginManagement); - debugVersionMap( "aggregate version map", excludePluginManagement ); + debugVersionMap("aggregate version map", excludePluginManagement); - excludePluginManagement.keySet().removeAll( pluginsWithVersionsSpecified ); + excludePluginManagement.keySet().removeAll(pluginsWithVersionsSpecified); - debugVersionMap( "final aggregate version map", excludePluginManagement ); + debugVersionMap("final aggregate version map", excludePluginManagement); ModelBuildingRequest modelBuildingRequest = new DefaultModelBuildingRequest(); - modelBuildingRequest.setUserProperties( getProject().getProperties() ); - Model originalModel = - modelInterpolator.interpolateModel( getProject().getOriginalModel(), getProject().getBasedir(), - modelBuildingRequest, new IgnoringModelProblemCollector() ); - - try - { - addProjectPlugins( plugins, originalModel.getBuild().getPluginManagement().getPlugins(), - excludePluginManagement ); - } - catch ( NullPointerException e ) - { + modelBuildingRequest.setUserProperties(getProject().getProperties()); + Model originalModel = modelInterpolator.interpolateModel( + getProject().getOriginalModel(), + getProject().getBasedir(), + modelBuildingRequest, + new IgnoringModelProblemCollector()); + + try { + addProjectPlugins( + plugins, originalModel.getBuild().getPluginManagement().getPlugins(), excludePluginManagement); + } catch (NullPointerException e) { // guess there are no plugins here } - debugPluginMap( "after adding local pluginManagement", plugins ); + debugPluginMap("after adding local pluginManagement", plugins); - try - { - List lifecyclePlugins = new ArrayList<>( getLifecyclePlugins( getProject() ).values() ); - for ( Iterator i = lifecyclePlugins.iterator(); i.hasNext(); ) - { + try { + List lifecyclePlugins = + new ArrayList<>(getLifecyclePlugins(getProject()).values()); + for (Iterator i = lifecyclePlugins.iterator(); i.hasNext(); ) { Plugin lifecyclePlugin = i.next(); - if ( lifecyclePlugin.getVersion() != null ) - { + if (lifecyclePlugin.getVersion() != null) { // version comes from lifecycle, therefore cannot modify i.remove(); - } - else - { + } else { // lifecycle leaves version open - String parentVersion = parentPluginManagement.get( lifecyclePlugin.getKey() ); - if ( parentVersion != null ) - { + String parentVersion = parentPluginManagement.get(lifecyclePlugin.getKey()); + if (parentVersion != null) { // parent controls version i.remove(); } } } - addProjectPlugins( plugins, lifecyclePlugins, parentPluginManagement ); + addProjectPlugins(plugins, lifecyclePlugins, parentPluginManagement); - debugPluginMap( "after adding lifecycle plugins", plugins ); - } - catch ( NullPointerException e ) - { + debugPluginMap("after adding lifecycle plugins", plugins); + } catch (NullPointerException e) { // using maven 3.x or newer } - try - { - List buildPlugins = new ArrayList<>( originalModel.getBuild().getPlugins() ); - for ( Iterator i = buildPlugins.iterator(); i.hasNext(); ) - { + try { + List buildPlugins = new ArrayList<>(originalModel.getBuild().getPlugins()); + for (Iterator i = buildPlugins.iterator(); i.hasNext(); ) { Plugin buildPlugin = i.next(); - if ( buildPlugin.getVersion() == null ) - { - String parentVersion = parentPluginManagement.get( buildPlugin.getKey() ); - if ( parentVersion != null ) - { + if (buildPlugin.getVersion() == null) { + String parentVersion = parentPluginManagement.get(buildPlugin.getKey()); + if (parentVersion != null) { // parent controls version i.remove(); } } } - addProjectPlugins( plugins, buildPlugins, parentBuildPlugins ); - } - catch ( NullPointerException e ) - { + addProjectPlugins(plugins, buildPlugins, parentBuildPlugins); + } catch (NullPointerException e) { // guess there are no plugins here } - debugPluginMap( "after adding build plugins", plugins ); + debugPluginMap("after adding build plugins", plugins); - try - { - List reportPlugins = new ArrayList<>( originalModel.getReporting().getPlugins() ); - for ( Iterator i = reportPlugins.iterator(); i.hasNext(); ) - { + try { + List reportPlugins = + new ArrayList<>(originalModel.getReporting().getPlugins()); + for (Iterator i = reportPlugins.iterator(); i.hasNext(); ) { ReportPlugin reportPlugin = i.next(); - if ( reportPlugin.getVersion() == null ) - { - String parentVersion = parentPluginManagement.get( reportPlugin.getKey() ); - if ( parentVersion != null ) - { + if (reportPlugin.getVersion() == null) { + String parentVersion = parentPluginManagement.get(reportPlugin.getKey()); + if (parentVersion != null) { // parent controls version i.remove(); } } } - addProjectPlugins( plugins, toPlugins( reportPlugins ), parentReportPlugins ); - } - catch ( NullPointerException e ) - { + addProjectPlugins(plugins, toPlugins(reportPlugins), parentReportPlugins); + } catch (NullPointerException e) { // guess there are no plugins here } - debugPluginMap( "after adding reporting plugins", plugins ); - - for ( Profile profile : originalModel.getProfiles() ) - { - try - { - addProjectPlugins( plugins, profile.getBuild().getPluginManagement().getPlugins(), - excludePluginManagement ); - } - catch ( NullPointerException e ) - { + debugPluginMap("after adding reporting plugins", plugins); + + for (Profile profile : originalModel.getProfiles()) { + try { + addProjectPlugins( + plugins, profile.getBuild().getPluginManagement().getPlugins(), excludePluginManagement); + } catch (NullPointerException e) { // guess there are no plugins here } - debugPluginMap( "after adding build pluginManagement for profile " + profile.getId(), plugins ); + debugPluginMap("after adding build pluginManagement for profile " + profile.getId(), plugins); - try - { - addProjectPlugins( plugins, profile.getBuild().getPlugins(), parentBuildPlugins ); - } - catch ( NullPointerException e ) - { + try { + addProjectPlugins(plugins, profile.getBuild().getPlugins(), parentBuildPlugins); + } catch (NullPointerException e) { // guess there are no plugins here } - debugPluginMap( "after adding build plugins for profile " + profile.getId(), plugins ); + debugPluginMap("after adding build plugins for profile " + profile.getId(), plugins); - try - { - addProjectPlugins( plugins, toPlugins( profile.getReporting().getPlugins() ), parentReportPlugins ); - } - catch ( NullPointerException e ) - { + try { + addProjectPlugins(plugins, toPlugins(profile.getReporting().getPlugins()), parentReportPlugins); + } catch (NullPointerException e) { // guess there are no plugins here } - debugPluginMap( "after adding reporting plugins for profile " + profile.getId(), plugins ); + debugPluginMap("after adding reporting plugins for profile " + profile.getId(), plugins); } - Set result = new TreeSet<>( PluginComparator.INSTANCE ); - result.addAll( plugins.values() ); + Set result = new TreeSet<>(PluginComparator.INSTANCE); + result.addAll(plugins.values()); return result; } @@ -1232,34 +1061,27 @@ private Set getProjectPlugins( Map superPomPluginManagem * @param parentDefinitions The parent plugin definitions. * @since 1.0-alpha-1 */ - private void addProjectPlugins( Map plugins, Collection projectPlugins, - Map parentDefinitions ) - { - for ( Plugin plugin : projectPlugins ) - { + private void addProjectPlugins( + Map plugins, Collection projectPlugins, Map parentDefinitions) { + for (Plugin plugin : projectPlugins) { String coord = plugin.getKey(); String version = plugin.getVersion(); - String parentVersion = parentDefinitions.get( coord ); - if ( version == null - && ( !plugins.containsKey( coord ) || plugins.get( coord ).getVersion() == null ) - && parentVersion != null ) - { + String parentVersion = parentDefinitions.get(coord); + if (version == null + && (!plugins.containsKey(coord) || plugins.get(coord).getVersion() == null) + && parentVersion != null) { Plugin parentPlugin = new Plugin(); - parentPlugin.setGroupId( plugin.getGroupId() ); - parentPlugin.setArtifactId( plugin.getArtifactId() ); - parentPlugin.setVersion( parentVersion ); - plugins.put( coord, parentPlugin ); - } - else if ( parentVersion == null || !parentVersion.equals( version ) ) - { - if ( !plugins.containsKey( coord ) || plugins.get( coord ).getVersion() == null ) - { - plugins.put( coord, plugin ); + parentPlugin.setGroupId(plugin.getGroupId()); + parentPlugin.setArtifactId(plugin.getArtifactId()); + parentPlugin.setVersion(parentVersion); + plugins.put(coord, parentPlugin); + } else if (parentVersion == null || !parentVersion.equals(version)) { + if (!plugins.containsKey(coord) || plugins.get(coord).getVersion() == null) { + plugins.put(coord, plugin); } } - if ( !plugins.containsKey( coord ) ) - { - plugins.put( coord, plugin ); + if (!plugins.containsKey(coord)) { + plugins.put(coord, plugin); } } } @@ -1272,21 +1094,18 @@ else if ( parentVersion == null || !parentVersion.equals( version ) ) * values * being {@link Plugin} or {@link ReportPlugin}. */ - private void debugPluginMap( String description, Map plugins ) - { - if ( getLog().isDebugEnabled() ) - { - Set sorted = new TreeSet<>( PluginComparator.INSTANCE ); - sorted.addAll( plugins.values() ); - StringBuilder buf = new StringBuilder( description ); - for ( Plugin plugin : sorted ) - { - buf.append( "\n " ); - buf.append( plugin.getKey() ); - buf.append( ":" ); - buf.append( plugin.getVersion() ); + private void debugPluginMap(String description, Map plugins) { + if (getLog().isDebugEnabled()) { + Set sorted = new TreeSet<>(PluginComparator.INSTANCE); + sorted.addAll(plugins.values()); + StringBuilder buf = new StringBuilder(description); + for (Plugin plugin : sorted) { + buf.append("\n "); + buf.append(plugin.getKey()); + buf.append(":"); + buf.append(plugin.getVersion()); } - getLog().debug( buf.toString() ); + getLog().debug(buf.toString()); } } @@ -1298,37 +1117,31 @@ private void debugPluginMap( String description, Map plugins ) * values * being {@link String} plugin version. */ - private void debugVersionMap( String description, Map pluginVersions ) - { - if ( getLog().isDebugEnabled() ) - { - StringBuilder buf = new StringBuilder( description ); - for ( Map.Entry pluginVersion : pluginVersions.entrySet() ) - { - buf.append( "\n " ); - buf.append( pluginVersion.getKey() ); - buf.append( ":" ); - buf.append( pluginVersion.getValue() ); + private void debugVersionMap(String description, Map pluginVersions) { + if (getLog().isDebugEnabled()) { + StringBuilder buf = new StringBuilder(description); + for (Map.Entry pluginVersion : pluginVersions.entrySet()) { + buf.append("\n "); + buf.append(pluginVersion.getKey()); + buf.append(":"); + buf.append(pluginVersion.getValue()); } - getLog().debug( buf.toString() ); + getLog().debug(buf.toString()); } } - private static Plugin toPlugin( ReportPlugin reportPlugin ) - { + private static Plugin toPlugin(ReportPlugin reportPlugin) { Plugin plugin = new Plugin(); - plugin.setGroupId( reportPlugin.getGroupId() ); - plugin.setArtifactId( reportPlugin.getArtifactId() ); - plugin.setVersion( reportPlugin.getVersion() ); + plugin.setGroupId(reportPlugin.getGroupId()); + plugin.setArtifactId(reportPlugin.getArtifactId()); + plugin.setVersion(reportPlugin.getVersion()); return plugin; } - private static List toPlugins( List reportPlugins ) - { - List result = new ArrayList<>( reportPlugins.size() ); - for ( ReportPlugin reportPlugin : reportPlugins ) - { - result.add( toPlugin( reportPlugin ) ); + private static List toPlugins(List reportPlugins) { + List result = new ArrayList<>(reportPlugins.size()); + for (ReportPlugin reportPlugin : reportPlugins) { + result.add(toPlugin(reportPlugin)); } return result; } @@ -1342,49 +1155,34 @@ private static List toPlugins( List reportPlugins ) * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ - private Map getReportPlugins( Model model, boolean onlyIncludeInherited ) - { + private Map getReportPlugins(Model model, boolean onlyIncludeInherited) { Map reportPlugins = new HashMap<>(); - try - { - for ( ReportPlugin plugin : model.getReporting().getPlugins() ) - { + try { + for (ReportPlugin plugin : model.getReporting().getPlugins()) { String coord = plugin.getKey(); String version = plugin.getVersion(); - if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) - { - reportPlugins.put( coord, version ); + if (version != null && (!onlyIncludeInherited || getPluginInherited(plugin))) { + reportPlugins.put(coord, version); } } - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // guess there are no plugins here } - try - { - for ( Profile profile : model.getProfiles() ) - { - try - { - for ( ReportPlugin plugin : profile.getReporting().getPlugins() ) - { + try { + for (Profile profile : model.getProfiles()) { + try { + for (ReportPlugin plugin : profile.getReporting().getPlugins()) { String coord = plugin.getKey(); String version = plugin.getVersion(); - if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) - { - reportPlugins.put( coord, version ); + if (version != null && (!onlyIncludeInherited || getPluginInherited(plugin))) { + reportPlugins.put(coord, version); } } - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // guess there are no plugins here } } - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { // guess there are no profiles here } return reportPlugins; @@ -1395,24 +1193,19 @@ private Map getReportPlugins( Model model, boolean onlyIncludeIn * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ - protected void update( ModifiedPomXMLEventReader pom ) - { + protected void update(ModifiedPomXMLEventReader pom) { // do nothing } - private static int compare( ArtifactVersion a, ArtifactVersion b ) - { - return a.compareTo( b ); + private static int compare(ArtifactVersion a, ArtifactVersion b) { + return a.compareTo(b); } - private static class IgnoringModelProblemCollector implements ModelProblemCollector - { + private static class IgnoringModelProblemCollector implements ModelProblemCollector { @Override - public void add( ModelProblemCollectorRequest req ) - { + public void add(ModelProblemCollectorRequest req) { // ignore } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java index dcf7be6ff9..ba5a0061e8 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java @@ -50,10 +50,8 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "display-property-updates", threadSafe = true ) -public class DisplayPropertyUpdatesMojo - extends AbstractVersionsDisplayMojo -{ +@Mojo(name = "display-property-updates", threadSafe = true) +public class DisplayPropertyUpdatesMojo extends AbstractVersionsDisplayMojo { /** * The width to pad info messages. @@ -77,7 +75,7 @@ public class DisplayPropertyUpdatesMojo * * @since 1.0-alpha-1 */ - @Parameter( property = "includeProperties" ) + @Parameter(property = "includeProperties") private String includeProperties = null; /** @@ -86,7 +84,7 @@ public class DisplayPropertyUpdatesMojo * @parameter property="excludeProperties" * @since 1.0-alpha-1 */ - @Parameter( property = "excludeProperties" ) + @Parameter(property = "excludeProperties") private String excludeProperties = null; /** @@ -94,7 +92,7 @@ public class DisplayPropertyUpdatesMojo * * @since 1.0-alpha-2 */ - @Parameter( property = "autoLinkItems", defaultValue = "true" ) + @Parameter(property = "autoLinkItems", defaultValue = "true") private boolean autoLinkItems; /** @@ -102,7 +100,7 @@ public class DisplayPropertyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") private boolean allowMajorUpdates; /** @@ -112,7 +110,7 @@ public class DisplayPropertyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") private boolean allowMinorUpdates; /** @@ -123,7 +121,7 @@ public class DisplayPropertyUpdatesMojo * * @since 2.5 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") private boolean allowIncrementalUpdates; /** @@ -131,7 +129,7 @@ public class DisplayPropertyUpdatesMojo * * @since 2.14.0 */ - @Parameter( property = "includeParent", defaultValue = "false" ) + @Parameter(property = "includeParent", defaultValue = "false") protected boolean includeParent = true; // -------------------------- STATIC METHODS -------------------------- @@ -139,122 +137,109 @@ public class DisplayPropertyUpdatesMojo // -------------------------- OTHER METHODS -------------------------- @Inject - public DisplayPropertyUpdatesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public DisplayPropertyUpdatesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { logInit(); List current = new ArrayList<>(); List updates = new ArrayList<>(); - Map propertyVersions = - this.getHelper().getVersionPropertiesMap( VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( getProject() ) - .withPropertyDefinitions( properties ) - .withIncludeProperties( includeProperties ) - .withExcludeProperties( excludeProperties ) - .withIncludeParent( includeParent ) - .withAutoLinkItems( autoLinkItems ) - .build() ); - for ( Map.Entry entry : propertyVersions.entrySet() ) - { + Map propertyVersions = this.getHelper() + .getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(getProject()) + .withPropertyDefinitions(properties) + .withIncludeProperties(includeProperties) + .withExcludeProperties(excludeProperties) + .withIncludeParent(includeParent) + .withAutoLinkItems(autoLinkItems) + .build()); + for (Map.Entry entry : propertyVersions.entrySet()) { Property property = entry.getKey(); PropertyVersions version = entry.getValue(); - final String currentVersion = getProject().getProperties().getProperty( property.getName() ); - if ( currentVersion == null ) - { + final String currentVersion = getProject().getProperties().getProperty(property.getName()); + if (currentVersion == null) { continue; } - Optional unchangedSegment = - SegmentUtils.determineUnchangedSegment( allowMajorUpdates, allowMinorUpdates, - allowIncrementalUpdates, getLog() ); - try - { - ArtifactVersion winner = version.getNewestVersion( currentVersion, property, this.allowSnapshots, - this.reactorProjects, this.getHelper(), false, unchangedSegment ); - if ( winner != null && !currentVersion.equals( winner.toString() ) ) - { + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + try { + ArtifactVersion winner = version.getNewestVersion( + currentVersion, + property, + this.allowSnapshots, + this.reactorProjects, + this.getHelper(), + false, + unchangedSegment); + if (winner != null && !currentVersion.equals(winner.toString())) { StringBuilder buf = new StringBuilder(); - buf.append( "${" ); - buf.append( property.getName() ); - buf.append( "} " ); + buf.append("${"); + buf.append(property.getName()); + buf.append("} "); final String newVersion = winner.toString(); - int padding = - INFO_PAD_SIZE - currentVersion.length() - newVersion.length() - 4 - + getOutputLineWidthOffset(); - while ( buf.length() < padding ) - { - buf.append( '.' ); + int padding = INFO_PAD_SIZE + - currentVersion.length() + - newVersion.length() + - 4 + + getOutputLineWidthOffset(); + while (buf.length() < padding) { + buf.append('.'); } - buf.append( ' ' ); - buf.append( currentVersion ); - buf.append( " -> " ); - buf.append( newVersion ); - updates.add( buf.toString() ); - } - else - { + buf.append(' '); + buf.append(currentVersion); + buf.append(" -> "); + buf.append(newVersion); + updates.add(buf.toString()); + } else { StringBuilder buf = new StringBuilder(); - buf.append( "${" ); - buf.append( property.getName() ); - buf.append( "} " ); + buf.append("${"); + buf.append(property.getName()); + buf.append("} "); int padding = INFO_PAD_SIZE - currentVersion.length() + getOutputLineWidthOffset(); - while ( buf.length() < padding ) - { - buf.append( '.' ); + while (buf.length() < padding) { + buf.append('.'); } - buf.append( ' ' ); - buf.append( currentVersion ); - current.add( buf.toString() ); + buf.append(' '); + buf.append(currentVersion); + current.add(buf.toString()); } - } - catch ( InvalidSegmentException | InvalidVersionSpecificationException e ) - { - getLog().warn( String.format( "Skipping the processing of %s:%s due to: %s", property.getName(), - property.getVersion(), e.getMessage() ) ); + } catch (InvalidSegmentException | InvalidVersionSpecificationException e) { + getLog().warn(String.format( + "Skipping the processing of %s:%s due to: %s", + property.getName(), property.getVersion(), e.getMessage())); } } - logLine( false, "" ); - if ( !current.isEmpty() ) - { - logLine( false, "The following version properties are referencing the newest available version:" ); - for ( String s : new TreeSet<>( current ) ) - { - logLine( false, " " + s ); + logLine(false, ""); + if (!current.isEmpty()) { + logLine(false, "The following version properties are referencing the newest available version:"); + for (String s : new TreeSet<>(current)) { + logLine(false, " " + s); } } - if ( updates.isEmpty() && current.isEmpty() ) - { - logLine( false, "This project does not have any properties associated with versions." ); - } - else if ( updates.isEmpty() ) - { - logLine( false, "All version properties are referencing the newest version available." ); + if (updates.isEmpty() && current.isEmpty()) { + logLine(false, "This project does not have any properties associated with versions."); + } else if (updates.isEmpty()) { + logLine(false, "All version properties are referencing the newest version available."); } - if ( !updates.isEmpty() ) - { - logLine( false, "The following version property updates are available:" ); - for ( String update : new TreeSet<>( updates ) ) - { - logLine( false, " " + update ); + if (!updates.isEmpty()) { + logLine(false, "The following version property updates are available:"); + for (String update : new TreeSet<>(updates)) { + logLine(false, " " + update); } } - logLine( false, "" ); + logLine(false, ""); } @Override - protected void update( ModifiedPomXMLEventReader pom ) - { - } + protected void update(ModifiedPomXMLEventReader pom) {} } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ForceReleasesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ForceReleasesMojo.java index 28de4ba3f5..2bdb0f298d 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ForceReleasesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ForceReleasesMojo.java @@ -53,27 +53,25 @@ * @author Stephen Connolly * @since 2.2 */ -@Mojo( name = "force-releases", threadSafe = true ) -public class ForceReleasesMojo - extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "force-releases", threadSafe = true) +public class ForceReleasesMojo extends AbstractVersionsDependencyUpdaterMojo { /** * Whether to fail if a SNAPSHOT could not be replaced * * @since 2.14.0 */ - @Parameter( property = "failIfNotReplaced", defaultValue = "false" ) + @Parameter(property = "failIfNotReplaced", defaultValue = "false") protected boolean failIfNotReplaced; // ------------------------------ METHODS -------------------------- @Inject - public ForceReleasesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public ForceReleasesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -83,91 +81,67 @@ public ForceReleasesMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useReleases( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useReleases( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useReleases( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useReleases(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useReleases( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useReleases(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useReleases( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - for ( Dependency dep : dependencies ) - { - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { - getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + private void useReleases( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + for (Dependency dep : dependencies) { + if (isExcludeReactor() && isProducedByReactor(dep)) { + getLog().info("Ignoring reactor dependency: " + toString(dep)); continue; } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } - Matcher versionMatcher = SNAPSHOT_REGEX.matcher( dep.getVersion() ); - if ( versionMatcher.matches() ) - { - String releaseVersion = versionMatcher.group( 1 ); - Artifact artifact = this.toArtifact( dep ); - if ( !isIncluded( artifact ) ) - { + Matcher versionMatcher = SNAPSHOT_REGEX.matcher(dep.getVersion()); + if (versionMatcher.matches()) { + String releaseVersion = versionMatcher.group(1); + Artifact artifact = this.toArtifact(dep); + if (!isIncluded(artifact)) { continue; } - getLog().debug( "Looking for a release of " + toString( dep ) ); - ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false ); - if ( versions.containsVersion( releaseVersion ) ) - { - updateDependencyVersion( pom, dep, releaseVersion, changeKind ); - } - else - { - ArtifactVersion newestRelease = versions.getNewestVersion( (VersionRange) null, null, - false, true ); - if ( newestRelease == null ) - { - getLog().info( "No release of " + toString( dep ) + " to force." ); - if ( failIfNotReplaced ) - { - throw new MojoExecutionException( "No matching release of " + toString( dep ) - + " found for update." ); + getLog().debug("Looking for a release of " + toString(dep)); + ArtifactVersions versions = getHelper().lookupArtifactVersions(artifact, false); + if (versions.containsVersion(releaseVersion)) { + updateDependencyVersion(pom, dep, releaseVersion, changeKind); + } else { + ArtifactVersion newestRelease = versions.getNewestVersion((VersionRange) null, null, false, true); + if (newestRelease == null) { + getLog().info("No release of " + toString(dep) + " to force."); + if (failIfNotReplaced) { + throw new MojoExecutionException( + "No matching release of " + toString(dep) + " found for update."); } - } - else - { - updateDependencyVersion( pom, dep, newestRelease.toString(), changeKind ); + } else { + updateDependencyVersion(pom, dep, newestRelease.toString(), changeKind); } } } } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/LockSnapshotsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/LockSnapshotsMojo.java index 9b57fc8914..4cb287f3ab 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/LockSnapshotsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/LockSnapshotsMojo.java @@ -52,27 +52,25 @@ * @author Paul Gier * @since 1.0-alpha-3 */ -@Mojo( name = "lock-snapshots", threadSafe = true ) -public class LockSnapshotsMojo - extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "lock-snapshots", threadSafe = true) +public class LockSnapshotsMojo extends AbstractVersionsDependencyUpdaterMojo { // ------------------------------ FIELDS ------------------------------ /** * Pattern to match a timestamped snapshot version. For example 1.0-20090128.202731-1 */ - private static final Pattern TIMESTAMPED_SNAPSHOT_REGEX = Pattern.compile( "-" + Artifact.SNAPSHOT_VERSION ); + private static final Pattern TIMESTAMPED_SNAPSHOT_REGEX = Pattern.compile("-" + Artifact.SNAPSHOT_VERSION); // ------------------------------ METHODS -------------------------- @Inject - public LockSnapshotsMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public LockSnapshotsMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -82,102 +80,84 @@ public LockSnapshotsMojo( RepositorySystem repositorySystem, * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - lockSnapshots( pom, dependencyManagement.getDependencies() ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + lockSnapshots(pom, dependencyManagement.getDependencies()); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - lockSnapshots( pom, getProject().getDependencies() ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + lockSnapshots(pom, getProject().getDependencies()); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - lockParentSnapshot( pom, getProject().getParent() ); + if (getProject().getParent() != null && isProcessingParent()) { + lockParentSnapshot(pom, getProject().getParent()); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void lockSnapshots( ModifiedPomXMLEventReader pom, Collection dependencies ) - throws XMLStreamException, MojoExecutionException - { - for ( Dependency dep : dependencies ) - { - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { - getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + private void lockSnapshots(ModifiedPomXMLEventReader pom, Collection dependencies) + throws XMLStreamException, MojoExecutionException { + for (Dependency dep : dependencies) { + if (isExcludeReactor() && isProducedByReactor(dep)) { + getLog().info("Ignoring reactor dependency: " + toString(dep)); continue; } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } - if ( !isIncluded( this.toArtifact( dep ) ) ) - { + if (!isIncluded(this.toArtifact(dep))) { continue; } String version = dep.getVersion(); - Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher( version ); - if ( versionMatcher.find() && versionMatcher.end() == version.length() ) - { - String lockedVersion = resolveSnapshotVersion( dep ); - if ( !version.equals( lockedVersion ) ) - { - if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), version, - lockedVersion, getProject().getModel() ) ) - { - getLog().info( "Locked " + toString( dep ) + " to version " + lockedVersion ); + Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher(version); + if (versionMatcher.find() && versionMatcher.end() == version.length()) { + String lockedVersion = resolveSnapshotVersion(dep); + if (!version.equals(lockedVersion)) { + if (PomHelper.setDependencyVersion( + pom, + dep.getGroupId(), + dep.getArtifactId(), + version, + lockedVersion, + getProject().getModel())) { + getLog().info("Locked " + toString(dep) + " to version " + lockedVersion); } } } } } - private void lockParentSnapshot( ModifiedPomXMLEventReader pom, MavenProject parent ) - throws XMLStreamException, MojoExecutionException - { - if ( parent == null ) - { - getLog().info( "Project does not have a parent" ); + private void lockParentSnapshot(ModifiedPomXMLEventReader pom, MavenProject parent) + throws XMLStreamException, MojoExecutionException { + if (parent == null) { + getLog().info("Project does not have a parent"); return; } - if ( reactorProjects.contains( parent ) ) - { - getLog().info( "Project's parent is part of the reactor" ); + if (reactorProjects.contains(parent)) { + getLog().info("Project's parent is part of the reactor"); return; } Artifact parentArtifact = parent.getArtifact(); String parentVersion = parentArtifact.getVersion(); - Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher( parentVersion ); - if ( versionMatcher.find() && versionMatcher.end() == parentVersion.length() ) - { - String lockedParentVersion = resolveSnapshotVersion( parentArtifact ); - if ( !parentVersion.equals( lockedParentVersion ) ) - { - if ( PomHelper.setProjectParentVersion( pom, lockedParentVersion ) ) - { - getLog().info( "Locked parent " + parentArtifact + " to version " - + lockedParentVersion ); + Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher(parentVersion); + if (versionMatcher.find() && versionMatcher.end() == parentVersion.length()) { + String lockedParentVersion = resolveSnapshotVersion(parentArtifact); + if (!parentVersion.equals(lockedParentVersion)) { + if (PomHelper.setProjectParentVersion(pom, lockedParentVersion)) { + getLog().info("Locked parent " + parentArtifact + " to version " + lockedParentVersion); } } } @@ -189,23 +169,22 @@ private void lockParentSnapshot( ModifiedPomXMLEventReader pom, MavenProject par * @param artifact * @return The timestamp version if exists, otherwise the original snapshot artifact version is returned. */ - private String resolveSnapshotVersion( Artifact artifact ) - { - getLog().debug( "Resolving snapshot version for artifact: " + artifact ); + private String resolveSnapshotVersion(Artifact artifact) { + getLog().debug("Resolving snapshot version for artifact: " + artifact); String lockedVersion = artifact.getVersion(); - try - { - aetherRepositorySystem.resolveArtifact( session.getRepositorySession(), - new ArtifactRequest( RepositoryUtils.toArtifact( artifact ), - getProject().getRemoteProjectRepositories(), getClass().getName() ) ); + try { + aetherRepositorySystem.resolveArtifact( + session.getRepositorySession(), + new ArtifactRequest( + RepositoryUtils.toArtifact(artifact), + getProject().getRemoteProjectRepositories(), + getClass().getName())); lockedVersion = artifact.getVersion(); - } - catch ( Exception e ) - { - getLog().error( e ); + } catch (Exception e) { + getLog().error(e); } return lockedVersion; } @@ -216,27 +195,24 @@ private String resolveSnapshotVersion( Artifact artifact ) * @param dep * @return The timestamp version if exists, otherwise the original snapshot dependency version is returned. */ - private String resolveSnapshotVersion( Dependency dep ) - { - getLog().debug( "Resolving snapshot version for dependency: " + dep ); + private String resolveSnapshotVersion(Dependency dep) { + getLog().debug("Resolving snapshot version for dependency: " + dep); String lockedVersion = dep.getVersion(); - try - { - Artifact depArtifact = getHelper().createDependencyArtifact( dep ); - aetherRepositorySystem.resolveArtifact( session.getRepositorySession(), - new ArtifactRequest( RepositoryUtils.toArtifact( depArtifact ), + try { + Artifact depArtifact = getHelper().createDependencyArtifact(dep); + aetherRepositorySystem.resolveArtifact( + session.getRepositorySession(), + new ArtifactRequest( + RepositoryUtils.toArtifact(depArtifact), getProject().getRemoteProjectRepositories(), - getClass().getName() ) ); + getClass().getName())); lockedVersion = depArtifact.getVersion(); - } - catch ( Exception e ) - { - getLog().error( e ); + } catch (Exception e) { + getLog().error(e); } return lockedVersion; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinder.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinder.java index 4f606ab0a7..818ad30d71 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinder.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinder.java @@ -18,129 +18,106 @@ * * @see Require Maven Version Rule */ -class MinimalMavenBuildVersionFinder -{ +class MinimalMavenBuildVersionFinder { - private MinimalMavenBuildVersionFinder() - { + private MinimalMavenBuildVersionFinder() { // not supposed to be created, static methods only } - static ArtifactVersion find( MavenProject mavenProject, String defaultVersion, Log log ) - { - ArtifactVersion version = getEnforcerMavenVersion( mavenProject, log ); - if ( version == null && defaultVersion != null ) - { - version = new DefaultArtifactVersion( defaultVersion ); + static ArtifactVersion find(MavenProject mavenProject, String defaultVersion, Log log) { + ArtifactVersion version = getEnforcerMavenVersion(mavenProject, log); + if (version == null && defaultVersion != null) { + version = new DefaultArtifactVersion(defaultVersion); } return version; } - private static ArtifactVersion getEnforcerMavenVersion( MavenProject mavenProject, Log log ) - { + private static ArtifactVersion getEnforcerMavenVersion(MavenProject mavenProject, Log log) { List buildPlugins = mavenProject.getBuildPlugins(); - if ( null == buildPlugins ) - { - log.debug( "MinimalMavenBuildVersionFinder: No build plugins found" ); + if (null == buildPlugins) { + log.debug("MinimalMavenBuildVersionFinder: No build plugins found"); return null; } - Plugin mavenEnforcerPlugin = getMavenEnforcerPlugin( buildPlugins ); - if ( null == mavenEnforcerPlugin ) - { - log.debug( "MinimalMavenBuildVersionFinder: No maven-enforcer-plugin used" ); + Plugin mavenEnforcerPlugin = getMavenEnforcerPlugin(buildPlugins); + if (null == mavenEnforcerPlugin) { + log.debug("MinimalMavenBuildVersionFinder: No maven-enforcer-plugin used"); return null; } List pluginExecutions = mavenEnforcerPlugin.getExecutions(); - if ( null == pluginExecutions ) - { - log.debug( "MinimalMavenBuildVersionFinder: No executions of maven-enforcer-plugin found" ); + if (null == pluginExecutions) { + log.debug("MinimalMavenBuildVersionFinder: No executions of maven-enforcer-plugin found"); return null; } - List pluginExecutionsWithEnforceGoal = getPluginExecutionsWithEnforceGoal( pluginExecutions ); - if ( pluginExecutionsWithEnforceGoal.isEmpty() ) - { - log.debug( "MinimalMavenBuildVersionFinder: No 'enforce' execution of maven-enforcer-plugin found" ); + List pluginExecutionsWithEnforceGoal = getPluginExecutionsWithEnforceGoal(pluginExecutions); + if (pluginExecutionsWithEnforceGoal.isEmpty()) { + log.debug("MinimalMavenBuildVersionFinder: No 'enforce' execution of maven-enforcer-plugin found"); return null; } - Xpp3Dom requireMavenVersionTag = getRequireMavenVersionTag( pluginExecutionsWithEnforceGoal ); - if ( null == requireMavenVersionTag ) - { - log.debug( "MinimalMavenBuildVersionFinder: " - + "No 'requireMavenVersion' rule of maven-enforcer-plugin found" ); + Xpp3Dom requireMavenVersionTag = getRequireMavenVersionTag(pluginExecutionsWithEnforceGoal); + if (null == requireMavenVersionTag) { + log.debug("MinimalMavenBuildVersionFinder: " + + "No 'requireMavenVersion' rule of maven-enforcer-plugin found"); return null; } - Xpp3Dom versionTag = requireMavenVersionTag.getChild( "version" ); - if ( null == versionTag ) - { - log.debug( "MinimalMavenBuildVersionFinder: " - + "No version specified in 'requireMavenVersion' rule of maven-enforcer-plugin" ); + Xpp3Dom versionTag = requireMavenVersionTag.getChild("version"); + if (null == versionTag) { + log.debug("MinimalMavenBuildVersionFinder: " + + "No version specified in 'requireMavenVersion' rule of maven-enforcer-plugin"); return null; } String versionTagValue = versionTag.getValue(); - if ( null == versionTagValue || "".equals( versionTagValue ) ) - { - log.debug( "MinimalMavenBuildVersionFinder: " - + "Empty version specified in 'requireMavenVersion' rule of maven-enforcer-plugin" ); + if (null == versionTagValue || "".equals(versionTagValue)) { + log.debug("MinimalMavenBuildVersionFinder: " + + "Empty version specified in 'requireMavenVersion' rule of maven-enforcer-plugin"); return null; } - ArtifactVersion minimumVersion = getMinimumVersionFromRange( versionTagValue ); - log.debug( "Calculated minimum version " + minimumVersion + " from version parameter value '" + versionTagValue - + "'" ); + ArtifactVersion minimumVersion = getMinimumVersionFromRange(versionTagValue); + log.debug("Calculated minimum version " + minimumVersion + " from version parameter value '" + versionTagValue + + "'"); return minimumVersion; } - private static Plugin getMavenEnforcerPlugin( List buildPlugins ) - { - for ( Plugin plugin : buildPlugins ) - { - if ( "maven-enforcer-plugin".equals( plugin.getArtifactId() ) && "org.apache.maven.plugins".equals( - plugin.getGroupId() ) ) - { + private static Plugin getMavenEnforcerPlugin(List buildPlugins) { + for (Plugin plugin : buildPlugins) { + if ("maven-enforcer-plugin".equals(plugin.getArtifactId()) + && "org.apache.maven.plugins".equals(plugin.getGroupId())) { return plugin; } } return null; } - private static List getPluginExecutionsWithEnforceGoal( List executions ) - { + private static List getPluginExecutionsWithEnforceGoal(List executions) { List pluginExecutions = new ArrayList<>(); - for ( PluginExecution pluginExecution : executions ) - { + for (PluginExecution pluginExecution : executions) { List goals = pluginExecution.getGoals(); - if ( goals != null && goals.contains( "enforce" ) ) - { - pluginExecutions.add( pluginExecution ); + if (goals != null && goals.contains("enforce")) { + pluginExecutions.add(pluginExecution); } } return pluginExecutions; } - private static Xpp3Dom getRequireMavenVersionTag( List executions ) - { - for ( PluginExecution pluginExecution : executions ) - { + private static Xpp3Dom getRequireMavenVersionTag(List executions) { + for (PluginExecution pluginExecution : executions) { Xpp3Dom configurationTag = (Xpp3Dom) pluginExecution.getConfiguration(); - if ( null == configurationTag ) - { + if (null == configurationTag) { continue; } - Xpp3Dom rulesTag = configurationTag.getChild( "rules" ); - if ( null == rulesTag ) - { + Xpp3Dom rulesTag = configurationTag.getChild("rules"); + if (null == rulesTag) { continue; } - Xpp3Dom requireMavenVersionTag = rulesTag.getChild( "requireMavenVersion" ); - if ( null == requireMavenVersionTag ) - { + Xpp3Dom requireMavenVersionTag = rulesTag.getChild("requireMavenVersion"); + if (null == requireMavenVersionTag) { continue; } @@ -153,100 +130,81 @@ private static Xpp3Dom getRequireMavenVersionTag( List executio * The below method implements the specification found at * https://maven.apache.org/enforcer/enforcer-rules/versionRanges.html */ - static ArtifactVersion getMinimumVersionFromRange( String versionRange ) - { + static ArtifactVersion getMinimumVersionFromRange(String versionRange) { int openIndicesCount = 0; int closeIndicesCount = 0; - for ( int i = 0; i < versionRange.length(); i++ ) - { - char character = versionRange.charAt( i ); + for (int i = 0; i < versionRange.length(); i++) { + char character = versionRange.charAt(i); - if ( '(' == character || '[' == character ) - { + if ('(' == character || '[' == character) { openIndicesCount++; - } - else if ( ')' == character || ']' == character ) - { + } else if (')' == character || ']' == character) { closeIndicesCount++; } } - if ( openIndicesCount != closeIndicesCount ) - { + if (openIndicesCount != closeIndicesCount) { return null; } - if ( openIndicesCount == 0 ) - { - return new DefaultArtifactVersion( versionRange ); + if (openIndicesCount == 0) { + return new DefaultArtifactVersion(versionRange); } - if ( !( ( versionRange.charAt( 0 ) == '[' || versionRange.charAt( 0 ) == '(' ) && ( - versionRange.charAt( versionRange.length() - 1 ) == ']' - || versionRange.charAt( versionRange.length() - 1 ) == ')' ) ) ) - { + if (!((versionRange.charAt(0) == '[' || versionRange.charAt(0) == '(') + && (versionRange.charAt(versionRange.length() - 1) == ']' + || versionRange.charAt(versionRange.length() - 1) == ')'))) { return null; } - if ( openIndicesCount != 1 ) - { + if (openIndicesCount != 1) { return null; } - String innerString = versionRange.substring( 1, versionRange.length() - 1 ); + String innerString = versionRange.substring(1, versionRange.length() - 1); - int commaIndex = innerString.indexOf( ',' ); + int commaIndex = innerString.indexOf(','); - if ( commaIndex == -1 ) - { - if ( versionRange.charAt( 0 ) == '[' && versionRange.charAt( versionRange.length() - 1 ) == ']' ) - { - return new DefaultArtifactVersion( innerString ); - } - else - { + if (commaIndex == -1) { + if (versionRange.charAt(0) == '[' && versionRange.charAt(versionRange.length() - 1) == ']') { + return new DefaultArtifactVersion(innerString); + } else { return null; } } - if ( commaIndex == 0 ) - { + if (commaIndex == 0) { return null; } - if ( commaIndex == innerString.length() - 1 ) - { - String minimumVersion = innerString.substring( 0, innerString.length() - 1 ); + if (commaIndex == innerString.length() - 1) { + String minimumVersion = innerString.substring(0, innerString.length() - 1); - if ( versionRange.charAt( 0 ) == '[' && versionRange.charAt( versionRange.length() - 1 ) == ')' ) - { - return new DefaultArtifactVersion( minimumVersion ); + if (versionRange.charAt(0) == '[' && versionRange.charAt(versionRange.length() - 1) == ')') { + return new DefaultArtifactVersion(minimumVersion); } - if ( versionRange.charAt( 0 ) == '(' && versionRange.charAt( versionRange.length() - 1 ) == ')' ) - { + if (versionRange.charAt(0) == '(' && versionRange.charAt(versionRange.length() - 1) == ')') { // this is actually wrong - the Maven version should be higher than this, // the Maven version cannot be equal to this, but the Maven Enforcer plugin should capture this - return new DefaultArtifactVersion( minimumVersion ); + return new DefaultArtifactVersion(minimumVersion); } return null; } - String minimumVersion = innerString.substring( 0, commaIndex ); + String minimumVersion = innerString.substring(0, commaIndex); - if ( versionRange.charAt( 0 ) == '[' ) - { - return new DefaultArtifactVersion( minimumVersion ); + if (versionRange.charAt(0) == '[') { + return new DefaultArtifactVersion(minimumVersion); } - if ( versionRange.charAt( 0 ) == '(' ) - { + if (versionRange.charAt(0) == '(') { // this is actually wrong - the Maven version should be higher than this, // the Maven version cannot be equal to this, but the Maven Enforcer plugin should capture this - return new DefaultArtifactVersion( minimumVersion ); + return new DefaultArtifactVersion(minimumVersion); } return null; diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ParentUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ParentUpdatesReportMojo.java index 61097221ee..fcef804c21 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ParentUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ParentUpdatesReportMojo.java @@ -46,45 +46,39 @@ * @author Andrzej Jarmoniuk * @since 2.13.0 */ -@Mojo( name = "parent-updates-report", - requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true ) -public class ParentUpdatesReportMojo extends AbstractVersionsReport -{ - @Parameter( defaultValue = "${reactorProjects}", required = true, readonly = true ) +@Mojo(name = "parent-updates-report", requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) +public class ParentUpdatesReportMojo extends AbstractVersionsReport { + @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true) protected List reactorProjects; @Inject - protected ParentUpdatesReportMojo( I18N i18n, - RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected ParentUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} */ - public boolean isExternalReport() - { + public boolean isExternalReport() { return false; } /** * {@inheritDoc} */ - public boolean canGenerateReport() - { - if ( getProject().getParent() == null ) - { - getLog().warn( "Project does not have a parent." ); + public boolean canGenerateReport() { + if (getProject().getParent() == null) { + getLog().warn("Project does not have a parent."); return false; } - if ( reactorProjects.contains( getProject().getParent() ) ) - { - getLog().warn( "Parent project is part of the reactor." ); + if (reactorProjects.contains(getProject().getParent())) { + getLog().warn("Parent project is part of the reactor."); return false; } @@ -97,36 +91,44 @@ public boolean canGenerateReport() * @param locale the locale to generate the report for. * @param sink the report formatting tool */ - @SuppressWarnings( "deprecation" ) - protected void doGenerateReport( Locale locale, Sink sink ) throws MavenReportException - { - try - { - ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( project.getParentArtifact(), - false ); - artifactVersions.setIncludeSnapshots( allowSnapshots ); - rendererFactory.createReportRenderer( getOutputName(), sink, locale, - new ParentUpdatesModel( DependencyBuilder.newBuilder() - .withGroupId( artifactVersions.getGroupId() ) - .withArtifactId( artifactVersions.getArtifactId() ) - .withVersion( artifactVersions.getArtifact().getVersion() ) - .withScope( artifactVersions.getArtifact().getScope() ) - .withType( artifactVersions.getArtifact().getType() ) - .withClassifier( artifactVersions.getArtifact().getClassifier() ) - .build(), artifactVersions ) ) + @SuppressWarnings("deprecation") + protected void doGenerateReport(Locale locale, Sink sink) throws MavenReportException { + try { + ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions(project.getParentArtifact(), false); + artifactVersions.setIncludeSnapshots(allowSnapshots); + rendererFactory + .createReportRenderer( + getOutputName(), + sink, + locale, + new ParentUpdatesModel( + DependencyBuilder.newBuilder() + .withGroupId(artifactVersions.getGroupId()) + .withArtifactId(artifactVersions.getArtifactId()) + .withVersion(artifactVersions + .getArtifact() + .getVersion()) + .withScope(artifactVersions + .getArtifact() + .getScope()) + .withType(artifactVersions + .getArtifact() + .getType()) + .withClassifier(artifactVersions + .getArtifact() + .getClassifier()) + .build(), + artifactVersions)) .render(); - } - catch ( VersionRetrievalException e ) - { - throw new MavenReportException( e.getMessage(), e ); + } catch (VersionRetrievalException e) { + throw new MavenReportException(e.getMessage(), e); } } /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "parent-updates-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesAggregateReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesAggregateReportMojo.java index f9305383b5..f11468c4b8 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesAggregateReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesAggregateReportMojo.java @@ -17,10 +17,11 @@ * */ +import javax.inject.Inject; import java.util.Map; import java.util.Set; -import javax.inject.Inject; + import org.apache.maven.model.Plugin; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -36,28 +37,29 @@ * * @since 2.14.0 */ -@Mojo( name = "plugin-updates-aggregate-report", requiresDependencyResolution = ResolutionScope.RUNTIME, - threadSafe = true, aggregator = true ) -public class PluginUpdatesAggregateReportMojo extends AbstractPluginUpdatesReportMojo -{ +@Mojo( + name = "plugin-updates-aggregate-report", + requiresDependencyResolution = ResolutionScope.RUNTIME, + threadSafe = true, + aggregator = true) +public class PluginUpdatesAggregateReportMojo extends AbstractPluginUpdatesReportMojo { @Inject - protected PluginUpdatesAggregateReportMojo( I18N i18n, RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected PluginUpdatesAggregateReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } @Override - protected void populatePluginManagement( Set pluginManagementCollector ) - { - for ( MavenProject project : AggregateReportUtils.getProjectsToProcess( getProject() ) ) - { - if ( haveBuildPluginManagementPlugins( project ) ) - { - pluginManagementCollector.addAll( project.getBuild().getPluginManagement().getPlugins() ); + protected void populatePluginManagement(Set pluginManagementCollector) { + for (MavenProject project : AggregateReportUtils.getProjectsToProcess(getProject())) { + if (haveBuildPluginManagementPlugins(project)) { + pluginManagementCollector.addAll( + project.getBuild().getPluginManagement().getPlugins()); } } } @@ -66,13 +68,10 @@ protected void populatePluginManagement( Set pluginManagementCollector ) * {@inheritDoc} * */ @Override - protected void populatePlugins( Set pluginsCollector ) - { - for ( MavenProject project : AggregateReportUtils.getProjectsToProcess( getProject() ) ) - { - if ( haveBuildPluginManagementPlugins( project ) ) - { - pluginsCollector.addAll( project.getBuild().getPlugins() ); + protected void populatePlugins(Set pluginsCollector) { + for (MavenProject project : AggregateReportUtils.getProjectsToProcess(getProject())) { + if (haveBuildPluginManagementPlugins(project)) { + pluginsCollector.addAll(project.getBuild().getPlugins()); } } } @@ -80,9 +79,7 @@ protected void populatePlugins( Set pluginsCollector ) /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "plugin-updates-aggregate-report"; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReportMojo.java index 8eec073c5b..f1cf564aa0 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReportMojo.java @@ -19,9 +19,11 @@ * under the License. */ +import javax.inject.Inject; + import java.util.Map; import java.util.Set; -import javax.inject.Inject; + import org.apache.maven.model.Plugin; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -36,30 +38,27 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "plugin-updates-report", requiresDependencyResolution = ResolutionScope.RUNTIME, - threadSafe = true ) -public class PluginUpdatesReportMojo extends AbstractPluginUpdatesReportMojo -{ +@Mojo(name = "plugin-updates-report", requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) +public class PluginUpdatesReportMojo extends AbstractPluginUpdatesReportMojo { @Inject - protected PluginUpdatesReportMojo( I18N i18n, - RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected PluginUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} * */ @Override - protected void populatePluginManagement( Set pluginManagementCollector ) - { - if ( haveBuildPluginManagementPlugins( getProject() ) ) - { - pluginManagementCollector.addAll( getProject().getBuild().getPluginManagement().getPlugins() ); + protected void populatePluginManagement(Set pluginManagementCollector) { + if (haveBuildPluginManagementPlugins(getProject())) { + pluginManagementCollector.addAll( + getProject().getBuild().getPluginManagement().getPlugins()); } } @@ -67,19 +66,16 @@ protected void populatePluginManagement( Set pluginManagementCollector ) * {@inheritDoc} * */ @Override - protected void populatePlugins( Set pluginsCollector ) - { - if ( haveBuildPlugins( getProject() ) ) - { - pluginsCollector.addAll( getProject().getBuild().getPlugins() ); + protected void populatePlugins(Set pluginsCollector) { + if (haveBuildPlugins(getProject())) { + pluginsCollector.addAll(getProject().getBuild().getPlugins()); } } /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "plugin-updates-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesAggregateReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesAggregateReportMojo.java index fdb022f74e..7230ecf9bc 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesAggregateReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesAggregateReportMojo.java @@ -17,9 +17,10 @@ * */ +import javax.inject.Inject; import java.util.Map; -import javax.inject.Inject; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -40,31 +41,32 @@ * * @since 2.14.0 */ -@Mojo( name = "property-updates-aggregate-report", requiresDependencyResolution = ResolutionScope.RUNTIME, - threadSafe = true, aggregator = true ) -public class PropertyUpdatesAggregateReportMojo extends AbstractPropertyUpdatesReportMojo -{ +@Mojo( + name = "property-updates-aggregate-report", + requiresDependencyResolution = ResolutionScope.RUNTIME, + threadSafe = true, + aggregator = true) +public class PropertyUpdatesAggregateReportMojo extends AbstractPropertyUpdatesReportMojo { @Inject - protected PropertyUpdatesAggregateReportMojo( I18N i18n, RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected PropertyUpdatesAggregateReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} * */ @Override - protected void populateUpdateSet( Map propertyCollector ) - throws MojoExecutionException, MavenReportException - { + protected void populateUpdateSet(Map propertyCollector) + throws MojoExecutionException, MavenReportException { VersionsHelper helper = getHelper(); - for ( MavenProject project : AggregateReportUtils.getProjectsToProcess( getProject() ) ) - { - propertyCollector.putAll( helper.getVersionPropertiesMap( getRequest( project ) ) ); + for (MavenProject project : AggregateReportUtils.getProjectsToProcess(getProject())) { + propertyCollector.putAll(helper.getVersionPropertiesMap(getRequest(project))); } } @@ -72,12 +74,9 @@ protected void populateUpdateSet( Map propertyCollec * {@inheritDoc} * */ @Override - protected boolean haveBuildProperties() - { - for ( MavenProject project : AggregateReportUtils.getProjectsToProcess( getProject() ) ) - { - if ( project.getProperties() != null && !project.getProperties().isEmpty() ) - { + protected boolean haveBuildProperties() { + for (MavenProject project : AggregateReportUtils.getProjectsToProcess(getProject())) { + if (project.getProperties() != null && !project.getProperties().isEmpty()) { return true; } } @@ -88,8 +87,7 @@ protected boolean haveBuildProperties() /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "property-updates-aggregate-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojo.java index 8b6abe85be..715616d4fe 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojo.java @@ -19,8 +19,10 @@ * under the License. */ -import java.util.Map; import javax.inject.Inject; + +import java.util.Map; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; @@ -39,35 +41,31 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "property-updates-report", requiresDependencyResolution = ResolutionScope.RUNTIME, - threadSafe = true ) -public class PropertyUpdatesReportMojo extends AbstractPropertyUpdatesReportMojo -{ +@Mojo(name = "property-updates-report", requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) +public class PropertyUpdatesReportMojo extends AbstractPropertyUpdatesReportMojo { @Inject - protected PropertyUpdatesReportMojo( I18N i18n, - RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - ReportRendererFactory rendererFactory ) - { - super( i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory ); + protected PropertyUpdatesReportMojo( + I18N i18n, + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + ReportRendererFactory rendererFactory) { + super(i18n, repositorySystem, aetherRepositorySystem, wagonMap, rendererFactory); } /** * {@inheritDoc} */ @Override - protected void populateUpdateSet( Map propertyCollector ) - throws MojoExecutionException, MavenReportException - { - propertyCollector.putAll( getHelper().getVersionPropertiesMap( getRequest( getProject() ) ) ); + protected void populateUpdateSet(Map propertyCollector) + throws MojoExecutionException, MavenReportException { + propertyCollector.putAll(getHelper().getVersionPropertiesMap(getRequest(getProject()))); } /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "property-updates-report"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java index f6278cdc66..04b043f376 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java @@ -57,16 +57,14 @@ * @author Paul Gier * @since 1.0-alpha-3 */ -@Mojo( name = "resolve-ranges", threadSafe = true ) -public class ResolveRangesMojo - extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "resolve-ranges", threadSafe = true) +public class ResolveRangesMojo extends AbstractVersionsDependencyUpdaterMojo { /** * Whether to process the properties section of the project. * * @since 1.3 */ - @Parameter( property = "processProperties", defaultValue = "true" ) + @Parameter(property = "processProperties", defaultValue = "true") private boolean processProperties; /** @@ -75,7 +73,7 @@ public class ResolveRangesMojo * @parameter property="includeProperties" * @since 1.3 */ - @Parameter( property = "includeProperties" ) + @Parameter(property = "includeProperties") private String includeProperties = null; /** @@ -83,7 +81,7 @@ public class ResolveRangesMojo * * @since 1.3 */ - @Parameter( property = "excludeProperties" ) + @Parameter(property = "excludeProperties") private String excludeProperties = null; /** @@ -91,7 +89,7 @@ public class ResolveRangesMojo * * @since 2.5 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") private boolean allowMajorUpdates; /** @@ -101,7 +99,7 @@ public class ResolveRangesMojo * * @since 2.5 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") private boolean allowMinorUpdates; /** @@ -112,7 +110,7 @@ public class ResolveRangesMojo * * @since 2.5 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") private boolean allowIncrementalUpdates; // ------------------------------ FIELDS ------------------------------ @@ -120,17 +118,17 @@ public class ResolveRangesMojo /** * Pattern to match a version range. For example 1.0-20090128.202731-1 */ - private final Pattern matchRangeRegex = Pattern.compile( "," ); + private final Pattern matchRangeRegex = Pattern.compile(","); // ------------------------------ METHODS -------------------------- @Inject - public ResolveRangesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public ResolveRangesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -140,157 +138,128 @@ public ResolveRangesMojo( RepositorySystem repositorySystem, * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { // Note we have to get the dependencies from the model because the dependencies in the // project may have already had their range resolved [MNG-4138] - if ( hasDependencyManagement() && hasDependenciesInDependencyManagement() - && isProcessingDependencyManagement() ) - { - getLog().debug( "processing dependencyManagement of " + getProject().getId() ); - resolveRanges( pom, getProject().getModel().getDependencyManagement().getDependencies() ); + if (hasDependencyManagement() + && hasDependenciesInDependencyManagement() + && isProcessingDependencyManagement()) { + getLog().debug("processing dependencyManagement of " + getProject().getId()); + resolveRanges(pom, getProject().getModel().getDependencyManagement().getDependencies()); } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - getLog().debug( "processing dependencies of " + getProject().getId() ); - resolveRanges( pom, getProject().getModel().getDependencies() ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + getLog().debug("processing dependencies of " + getProject().getId()); + resolveRanges(pom, getProject().getModel().getDependencies()); } - if ( hasParent() && isProcessingParent() ) - { - getLog().debug( "processing parent " + getProject().getId() ); - resolveRangesInParent( pom ); + if (hasParent() && isProcessingParent()) { + getLog().debug("processing parent " + getProject().getId()); + resolveRangesInParent(pom); } - if ( processProperties ) - { - getLog().debug( "processing properties of " + getProject().getId() ); - resolvePropertyRanges( pom ); + if (processProperties) { + getLog().debug("processing properties of " + getProject().getId()); + resolvePropertyRanges(pom); } } - private boolean hasParent() - { + private boolean hasParent() { return getProject().getModel().getParent() != null; } - private boolean hasDependenciesInDependencyManagement() - { + private boolean hasDependenciesInDependencyManagement() { return getProject().getModel().getDependencyManagement().getDependencies() != null; } - private boolean hasDependencyManagement() - { + private boolean hasDependencyManagement() { return getProject().getModel().getDependencyManagement() != null; } - private void resolveRangesInParent( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, VersionRetrievalException, XMLStreamException - { - Matcher versionMatcher = matchRangeRegex.matcher( getProject().getModel().getParent().getVersion() ); + private void resolveRangesInParent(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, VersionRetrievalException, XMLStreamException { + Matcher versionMatcher = + matchRangeRegex.matcher(getProject().getModel().getParent().getVersion()); - if ( versionMatcher.find() ) - { - Artifact artifact = this.toArtifact( getProject().getModel().getParent() ); + if (versionMatcher.find()) { + Artifact artifact = this.toArtifact(getProject().getModel().getParent()); - if ( artifact != null && isIncluded( artifact ) ) - { - getLog().debug( "Resolving version range for parent: " + artifact ); + if (artifact != null && isIncluded(artifact)) { + getLog().debug("Resolving version range for parent: " + artifact); String artifactVersion = artifact.getVersion(); - if ( artifactVersion == null ) - { + if (artifactVersion == null) { ArtifactVersion latestVersion = - findLatestVersion( artifact, artifact.getVersionRange(), allowSnapshots, false ); + findLatestVersion(artifact, artifact.getVersionRange(), allowSnapshots, false); - if ( latestVersion != null ) - { + if (latestVersion != null) { artifactVersion = latestVersion.toString(); - } - else - { - getLog().warn( "Not updating version " + artifact + " : could not resolve any versions" ); + } else { + getLog().warn("Not updating version " + artifact + " : could not resolve any versions"); } } - if ( artifactVersion != null ) - { - if ( PomHelper.setProjectParentVersion( pom, artifactVersion ) ) - { - getLog().debug( "Version set to " + artifactVersion + " for parent: " + artifact ); - } - else - { - getLog().warn( "Could not find the version tag for parent " + artifact + " in project " - + getProject().getId() + " so unable to set version to " + artifactVersion ); + if (artifactVersion != null) { + if (PomHelper.setProjectParentVersion(pom, artifactVersion)) { + getLog().debug("Version set to " + artifactVersion + " for parent: " + artifact); + } else { + getLog().warn("Could not find the version tag for parent " + artifact + " in project " + + getProject().getId() + " so unable to set version to " + artifactVersion); } } } } - } - private void resolveRanges( ModifiedPomXMLEventReader pom, Collection dependencies ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { + private void resolveRanges(ModifiedPomXMLEventReader pom, Collection dependencies) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { - for ( Dependency dep : dependencies ) - { - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { + for (Dependency dep : dependencies) { + if (isExcludeReactor() && isProducedByReactor(dep)) { continue; } - if ( StringUtils.isBlank( dep.getVersion() ) ) - { + if (StringUtils.isBlank(dep.getVersion())) { throw new MojoExecutionException( - "Found invalid managed dependency " + toString( dep ) + " without a version" ); + "Found invalid managed dependency " + toString(dep) + " without a version"); } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } - Matcher versionMatcher = matchRangeRegex.matcher( dep.getVersion() ); + Matcher versionMatcher = matchRangeRegex.matcher(dep.getVersion()); - if ( versionMatcher.find() ) - { - Artifact artifact = this.toArtifact( dep ); + if (versionMatcher.find()) { + Artifact artifact = this.toArtifact(dep); - if ( artifact != null && isIncluded( artifact ) ) - { - getLog().debug( "Resolving version range for dependency: " + artifact ); + if (artifact != null && isIncluded(artifact)) { + getLog().debug("Resolving version range for dependency: " + artifact); String artifactVersion = artifact.getVersion(); - if ( artifactVersion == null ) - { + if (artifactVersion == null) { ArtifactVersion latestVersion = - findLatestVersion( artifact, artifact.getVersionRange(), allowSnapshots, false ); + findLatestVersion(artifact, artifact.getVersionRange(), allowSnapshots, false); - if ( latestVersion != null ) - { + if (latestVersion != null) { artifactVersion = latestVersion.toString(); - } - else - { - getLog().warn( "Not updating version " + artifact + " : could not resolve any versions" ); + } else { + getLog().warn("Not updating version " + artifact + " : could not resolve any versions"); } } - if ( artifactVersion != null ) - { - if ( PomHelper.setDependencyVersion( pom, artifact.getGroupId(), artifact.getArtifactId(), - dep.getVersion(), artifactVersion, - getProject().getModel() ) ) - { - getLog().debug( "Version set to " + artifactVersion + " for dependency: " + artifact ); - } - else - { - getLog().debug( "Could not find the version tag for dependency " + artifact + " in project " - + getProject().getId() + " so unable to set version to " - + artifactVersion ); + if (artifactVersion != null) { + if (PomHelper.setDependencyVersion( + pom, + artifact.getGroupId(), + artifact.getArtifactId(), + dep.getVersion(), + artifactVersion, + getProject().getModel())) { + getLog().debug("Version set to " + artifactVersion + " for dependency: " + artifact); + } else { + getLog().debug("Could not find the version tag for dependency " + artifact + " in project " + + getProject().getId() + " so unable to set version to " + + artifactVersion); } } } @@ -298,42 +267,37 @@ private void resolveRanges( ModifiedPomXMLEventReader pom, Collection propertyVersions = - this.getHelper().getVersionPropertiesMap( VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( getProject() ) - .withIncludeProperties( includeProperties ) - .withExcludeProperties( excludeProperties ) - .build() ); - for ( Map.Entry entry : propertyVersions.entrySet() ) - { + private void resolvePropertyRanges(ModifiedPomXMLEventReader pom) + throws XMLStreamException, MojoExecutionException { + + Map propertyVersions = this.getHelper() + .getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(getProject()) + .withIncludeProperties(includeProperties) + .withExcludeProperties(excludeProperties) + .build()); + for (Map.Entry entry : propertyVersions.entrySet()) { Property property = entry.getKey(); PropertyVersions version = entry.getValue(); - final String currentVersion = getProject().getProperties().getProperty( property.getName() ); - if ( currentVersion == null || !matchRangeRegex.matcher( currentVersion ).find() ) - { + final String currentVersion = getProject().getProperties().getProperty(property.getName()); + if (currentVersion == null + || !matchRangeRegex.matcher(currentVersion).find()) { continue; } - property.setVersion( currentVersion ); - - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( allowMajorUpdates, - allowMinorUpdates, allowIncrementalUpdates, getLog() ); - // TODO: Check if we could add allowDowngrade ? - try - { - updatePropertyToNewestVersion( pom, property, version, currentVersion, false, unchangedSegment ); - } - catch ( InvalidSegmentException | InvalidVersionSpecificationException e ) - { - getLog().warn( String.format( "Skipping the processing of %s:%s due to: %s", property.getName(), - property.getVersion(), e.getMessage() ) ); + property.setVersion(currentVersion); + + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + // TODO: Check if we could add allowDowngrade ? + try { + updatePropertyToNewestVersion(pom, property, version, currentVersion, false, unchangedSegment); + } catch (InvalidSegmentException | InvalidVersionSpecificationException e) { + getLog().warn(String.format( + "Skipping the processing of %s:%s due to: %s", + property.getName(), property.getVersion(), e.getMessage())); } } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java index 1f232613b7..ebb64f171c 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java @@ -45,15 +45,14 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "revert", threadSafe = true ) -public class RevertMojo extends AbstractMojo -{ +@Mojo(name = "revert", threadSafe = true) +public class RevertMojo extends AbstractMojo { /** * The {@link MavenSession} instance * * @since 2.14.0 */ - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) private MavenSession session; /** @@ -63,7 +62,7 @@ public class RevertMojo extends AbstractMojo * * @since 2.13.0 */ - @Parameter( property = "processFromLocalAggregationRoot", defaultValue = "true" ) + @Parameter(property = "processFromLocalAggregationRoot", defaultValue = "true") private boolean processFromLocalAggregationRoot; /** @@ -74,46 +73,41 @@ public class RevertMojo extends AbstractMojo protected final ProjectBuilder projectBuilder; @Inject - protected RevertMojo( ProjectBuilder projectBuilder ) - { + protected RevertMojo(ProjectBuilder projectBuilder) { this.projectBuilder = projectBuilder; } - public void execute() throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { final MavenProject projectToProcess = !processFromLocalAggregationRoot - ? PomHelper.getLocalRoot( projectBuilder, session, getLog() ) + ? PomHelper.getLocalRoot(projectBuilder, session, getLog()) : session.getCurrentProject(); - getLog().info( "Local aggregation root: " + projectToProcess.getBasedir() ); - Set reactor = PomHelper.getAllChildModules( projectToProcess, getLog() ); - reactor.add( "." ); + getLog().info("Local aggregation root: " + projectToProcess.getBasedir()); + Set reactor = PomHelper.getAllChildModules(projectToProcess, getLog()); + reactor.add("."); - reactor.forEach( entry -> - { - Path pomFile = projectToProcess.getBasedir().toPath().resolve( entry ).resolve( "pom.xml" ).normalize(); - getLog().debug( "Processing:" + pomFile ); - Path backupFile = Paths.get( pomFile + ".versionsBackup" ); - if ( Files.exists( backupFile ) ) - { - getLog().info( "Restoring " + pomFile + " from " + backupFile ); - try - { - Files.copy( backupFile, pomFile, REPLACE_EXISTING ); - try - { - Files.delete( backupFile ); + reactor.forEach(entry -> { + Path pomFile = projectToProcess + .getBasedir() + .toPath() + .resolve(entry) + .resolve("pom.xml") + .normalize(); + getLog().debug("Processing:" + pomFile); + Path backupFile = Paths.get(pomFile + ".versionsBackup"); + if (Files.exists(backupFile)) { + getLog().info("Restoring " + pomFile + " from " + backupFile); + try { + Files.copy(backupFile, pomFile, REPLACE_EXISTING); + try { + Files.delete(backupFile); + } catch (IOException e) { + getLog().warn("Error deleting " + backupFile); } - catch ( IOException e ) - { - getLog().warn( "Error deleting " + backupFile ); - } - } - catch ( IOException e ) - { - getLog().warn( "Error copying " + backupFile + " onto " + pomFile ); + } catch (IOException e) { + getLog().warn("Error copying " + backupFile + " onto " + pomFile); } } - } ); + }); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetMojo.java index 1bdceacb0b..44035838b9 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetMojo.java @@ -74,9 +74,8 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "set", aggregator = true, threadSafe = true ) -public class SetMojo extends AbstractVersionsUpdaterMojo -{ +@Mojo(name = "set", aggregator = true, threadSafe = true) +public class SetMojo extends AbstractVersionsUpdaterMojo { private static final String SNAPSHOT = "-SNAPSHOT"; @@ -85,7 +84,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.0-beta-1 */ - @Parameter( property = "newVersion" ) + @Parameter(property = "newVersion") private String newVersion; /** @@ -98,7 +97,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.2 */ - @Parameter( property = "groupId", defaultValue = "${project.groupId}" ) + @Parameter(property = "groupId", defaultValue = "${project.groupId}") private String groupId; /** @@ -111,7 +110,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.2 */ - @Parameter( property = "artifactId", defaultValue = "${project.artifactId}" ) + @Parameter(property = "artifactId", defaultValue = "${project.artifactId}") private String artifactId; /** @@ -124,7 +123,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.2 */ - @Parameter( property = "oldVersion", defaultValue = "${project.version}" ) + @Parameter(property = "oldVersion", defaultValue = "${project.version}") private String oldVersion; /** @@ -132,7 +131,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.3 */ - @Parameter( property = "updateMatchingVersions", defaultValue = "true" ) + @Parameter(property = "updateMatchingVersions", defaultValue = "true") private boolean updateMatchingVersions; /** @@ -140,7 +139,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.3 */ - @Parameter( property = "processParent", defaultValue = "true" ) + @Parameter(property = "processParent", defaultValue = "true") private boolean processParent; /** @@ -148,7 +147,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.3 */ - @Parameter( property = "processProject", defaultValue = "true" ) + @Parameter(property = "processProject", defaultValue = "true") private boolean processProject; /** @@ -156,7 +155,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.3 */ - @Parameter( property = "processDependencies", defaultValue = "true" ) + @Parameter(property = "processDependencies", defaultValue = "true") private boolean processDependencies; /** @@ -164,7 +163,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 1.3 */ - @Parameter( property = "processPlugins", defaultValue = "true" ) + @Parameter(property = "processPlugins", defaultValue = "true") private boolean processPlugins; /** @@ -177,7 +176,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 2.10 */ - @Parameter( property = "removeSnapshot", defaultValue = "false" ) + @Parameter(property = "removeSnapshot", defaultValue = "false") private boolean removeSnapshot; /** @@ -187,7 +186,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 2.10 */ - @Parameter( property = "nextSnapshot", defaultValue = "false" ) + @Parameter(property = "nextSnapshot", defaultValue = "false") protected boolean nextSnapshot; /** @@ -199,7 +198,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 2.12 */ - @Parameter( property = "nextSnapshotIndexToIncrement" ) + @Parameter(property = "nextSnapshotIndexToIncrement") protected Integer nextSnapshotIndexToIncrement; /** @@ -207,7 +206,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 2.5 */ - @Parameter( property = "processAllModules", defaultValue = "false" ) + @Parameter(property = "processAllModules", defaultValue = "false") private boolean processAllModules; /** @@ -217,7 +216,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 2.9 */ - @Parameter( property = "processFromLocalAggregationRoot", defaultValue = "true" ) + @Parameter(property = "processFromLocalAggregationRoot", defaultValue = "true") private boolean processFromLocalAggregationRoot; /** @@ -226,7 +225,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * @since 2.10 * @deprecated please use {@link #updateBuildOutputTimestampPolicy} instead */ - @Parameter( property = "updateBuildOutputTimestamp", defaultValue = "true" ) + @Parameter(property = "updateBuildOutputTimestamp", defaultValue = "true") private boolean updateBuildOutputTimestamp; /** @@ -236,7 +235,7 @@ public class SetMojo extends AbstractVersionsUpdaterMojo * * @since 2.12 */ - @Parameter( property = "updateBuildOutputTimestampPolicy", defaultValue = "onchange" ) + @Parameter(property = "updateBuildOutputTimestampPolicy", defaultValue = "onchange") private String updateBuildOutputTimestampPolicy; /** @@ -252,23 +251,21 @@ public class SetMojo extends AbstractVersionsUpdaterMojo protected final ProjectBuilder projectBuilder; @Inject - public SetMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - ProjectBuilder projectBuilder, - Map wagonMap, - Map changeRecorders, - Prompter prompter ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public SetMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + ProjectBuilder projectBuilder, + Map wagonMap, + Map changeRecorders, + Prompter prompter) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); this.projectBuilder = projectBuilder; this.prompter = prompter; } - private synchronized void addChange( String groupId, String artifactId, String oldVersion, String newVersion ) - { - if ( !newVersion.equals( oldVersion ) ) - { - sourceChanges.add( new DefaultVersionChange( groupId, artifactId, oldVersion, newVersion ) ); + private synchronized void addChange(String groupId, String artifactId, String oldVersion, String newVersion) { + if (!newVersion.equals(oldVersion)) { + sourceChanges.add(new DefaultVersionChange(groupId, artifactId, oldVersion, newVersion)); } } @@ -278,131 +275,114 @@ private synchronized void addChange( String groupId, String artifactId, String o * @throws org.apache.maven.plugin.MojoExecutionException when things go wrong. * @throws org.apache.maven.plugin.MojoFailureException when things go wrong. */ - public void execute() throws MojoExecutionException, MojoFailureException - { - if ( getProject().getOriginalModel().getVersion() == null ) - { - throw new MojoExecutionException( "Project version is inherited from parent." ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (getProject().getOriginalModel().getVersion() == null) { + throw new MojoExecutionException("Project version is inherited from parent."); } - if ( removeSnapshot && !nextSnapshot ) - { + if (removeSnapshot && !nextSnapshot) { String version = getVersion(); - if ( version.endsWith( SNAPSHOT ) ) - { - String release = version.substring( 0, version.indexOf( SNAPSHOT ) ); + if (version.endsWith(SNAPSHOT)) { + String release = version.substring(0, version.indexOf(SNAPSHOT)); newVersion = release; - getLog().info( "SNAPSHOT found. BEFORE " + version + " --> AFTER: " + newVersion ); + getLog().info("SNAPSHOT found. BEFORE " + version + " --> AFTER: " + newVersion); } } - if ( !nextSnapshot && nextSnapshotIndexToIncrement != null ) - { - throw new MojoExecutionException( "nextSnapshotIndexToIncrement is not valid when nextSnapshot is false" ); + if (!nextSnapshot && nextSnapshotIndexToIncrement != null) { + throw new MojoExecutionException("nextSnapshotIndexToIncrement is not valid when nextSnapshot is false"); } - if ( !removeSnapshot && nextSnapshot ) - { + if (!removeSnapshot && nextSnapshot) { String version = getVersion(); - newVersion = getIncrementedVersion( version, nextSnapshotIndexToIncrement ); - getLog().info( "SNAPSHOT found. BEFORE " + version + " --> AFTER: " + newVersion ); + newVersion = getIncrementedVersion(version, nextSnapshotIndexToIncrement); + getLog().info("SNAPSHOT found. BEFORE " + version + " --> AFTER: " + newVersion); } - if ( isEmpty( newVersion ) ) - { - if ( removeSnapshot ) - { - getLog().info( "removeSnapshot enabled whilst the version is not a snapshot: nothing to do." ); + if (isEmpty(newVersion)) { + if (removeSnapshot) { + getLog().info("removeSnapshot enabled whilst the version is not a snapshot: nothing to do."); return; } - if ( session.getSettings().isInteractiveMode() ) - { - try - { - newVersion = prompter.prompt( "Enter the new version to set", - getProject().getOriginalModel().getVersion() ); + if (session.getSettings().isInteractiveMode()) { + try { + newVersion = prompter.prompt( + "Enter the new version to set", + getProject().getOriginalModel().getVersion()); + } catch (PrompterException e) { + throw new MojoExecutionException(e.getMessage(), e); } - catch ( PrompterException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); - } - } - else - { - throw new MojoExecutionException( "You must specify the new version, either by using the newVersion " - + "property (that is -DnewVersion=... on the command line) " - + "or run in interactive mode" ); + } else { + throw new MojoExecutionException("You must specify the new version, either by using the newVersion " + + "property (that is -DnewVersion=... on the command line) " + + "or run in interactive mode"); } } - if ( !"onchange".equals( updateBuildOutputTimestampPolicy ) && !"always".equals( - updateBuildOutputTimestampPolicy ) && !"never".equals( updateBuildOutputTimestampPolicy ) ) - { + if (!"onchange".equals(updateBuildOutputTimestampPolicy) + && !"always".equals(updateBuildOutputTimestampPolicy) + && !"never".equals(updateBuildOutputTimestampPolicy)) { throw new MojoExecutionException( - "updateBuildOutputTimestampPolicy should be one of: " + "\"onchange\", \"always\", \"never\"." ); + "updateBuildOutputTimestampPolicy should be one of: " + "\"onchange\", \"always\", \"never\"."); } - try - { + try { final MavenProject project = processFromLocalAggregationRoot - ? PomHelper.getLocalRoot( projectBuilder, session, getLog() ) + ? PomHelper.getLocalRoot(projectBuilder, session, getLog()) : getProject(); - getLog().info( "Local aggregation root: " + project.getBasedir() ); - Map reactorModels = PomHelper.getReactorModels( project, getLog() ); - final SortedMap reactor = - new TreeMap<>( new ReactorDepthComparator( reactorModels ) ); - reactor.putAll( reactorModels ); + getLog().info("Local aggregation root: " + project.getBasedir()); + Map reactorModels = PomHelper.getReactorModels(project, getLog()); + final SortedMap reactor = new TreeMap<>(new ReactorDepthComparator(reactorModels)); + reactor.putAll(reactorModels); // set of files to update final Set files = new LinkedHashSet<>(); - getLog().info( - "Processing change of " + groupId + ":" + artifactId + ":" + oldVersion + " -> " + newVersion ); + getLog().info("Processing change of " + groupId + ":" + artifactId + ":" + oldVersion + " -> " + + newVersion); Pattern groupIdRegex = - Pattern.compile( RegexUtils.convertWildcardsToRegex( fixNullOrEmpty( groupId, "*" ), true ) ); + Pattern.compile(RegexUtils.convertWildcardsToRegex(fixNullOrEmpty(groupId, "*"), true)); Pattern artifactIdRegex = - Pattern.compile( RegexUtils.convertWildcardsToRegex( fixNullOrEmpty( artifactId, "*" ), true ) ); + Pattern.compile(RegexUtils.convertWildcardsToRegex(fixNullOrEmpty(artifactId, "*"), true)); Pattern oldVersionIdRegex = - Pattern.compile( RegexUtils.convertWildcardsToRegex( fixNullOrEmpty( oldVersion, "*" ), true ) ); - - for ( Model m : reactor.values() ) - { - final String mGroupId = PomHelper.getGroupId( m ); - final String mArtifactId = PomHelper.getArtifactId( m ); - final String mVersion = PomHelper.getVersion( m ); - if ( ( processAllModules - || groupIdRegex.matcher( mGroupId ).matches() - && artifactIdRegex.matcher( mArtifactId ).matches() ) - && oldVersionIdRegex.matcher( mVersion ).matches() - && !newVersion.equals( mVersion ) ) - { - applyChange( project, reactor, files, mGroupId, m.getArtifactId(), - StringUtils.isBlank( oldVersion ) || "*".equals( oldVersion ) ? "" : mVersion ); + Pattern.compile(RegexUtils.convertWildcardsToRegex(fixNullOrEmpty(oldVersion, "*"), true)); + + for (Model m : reactor.values()) { + final String mGroupId = PomHelper.getGroupId(m); + final String mArtifactId = PomHelper.getArtifactId(m); + final String mVersion = PomHelper.getVersion(m); + if ((processAllModules + || groupIdRegex.matcher(mGroupId).matches() + && artifactIdRegex.matcher(mArtifactId).matches()) + && oldVersionIdRegex.matcher(mVersion).matches() + && !newVersion.equals(mVersion)) { + applyChange( + project, + reactor, + files, + mGroupId, + m.getArtifactId(), + StringUtils.isBlank(oldVersion) || "*".equals(oldVersion) ? "" : mVersion); } } - if ( "always".equals( updateBuildOutputTimestampPolicy ) ) - { + if ("always".equals(updateBuildOutputTimestampPolicy)) { reactor.values().parallelStream() - .map( m -> PomHelper.getModelEntry( reactor, PomHelper.getGroupId( m ), - PomHelper.getArtifactId( m ) ) ) - .filter( Objects::nonNull ) - .map( Map.Entry::getKey ) - .map( f -> getModuleProjectFile( project, f ) ) - .forEach( files::add ); + .map(m -> PomHelper.getModelEntry(reactor, PomHelper.getGroupId(m), PomHelper.getArtifactId(m))) + .filter(Objects::nonNull) + .map(Map.Entry::getKey) + .map(f -> getModuleProjectFile(project, f)) + .forEach(files::add); } // now process all the updates - for ( File file : files ) - { - process( file ); + for (File file : files) { + process(file); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } @@ -415,149 +395,133 @@ public void execute() throws MojoExecutionException, MojoFailureException * @return version with the incremented index specified by nextSnapshotIndexToIncrement or last index * @throws MojoExecutionException thrown if the input parameters are invalid */ - protected String getIncrementedVersion( String version, Integer nextSnapshotIndexToIncrement ) - throws MojoExecutionException - { + protected String getIncrementedVersion(String version, Integer nextSnapshotIndexToIncrement) + throws MojoExecutionException { String versionWithoutSnapshot = - version.endsWith( SNAPSHOT ) ? version.substring( 0, version.indexOf( SNAPSHOT ) ) : version; - List numbers = new LinkedList<>( Arrays.asList( versionWithoutSnapshot.split( "\\." ) ) ); + version.endsWith(SNAPSHOT) ? version.substring(0, version.indexOf(SNAPSHOT)) : version; + List numbers = new LinkedList<>(Arrays.asList(versionWithoutSnapshot.split("\\."))); - if ( nextSnapshotIndexToIncrement == null ) - { + if (nextSnapshotIndexToIncrement == null) { nextSnapshotIndexToIncrement = numbers.size(); - } - else if ( nextSnapshotIndexToIncrement < 1 ) - { - throw new MojoExecutionException( "nextSnapshotIndexToIncrement cannot be less than 1" ); - } - else if ( nextSnapshotIndexToIncrement > numbers.size() ) - { + } else if (nextSnapshotIndexToIncrement < 1) { + throw new MojoExecutionException("nextSnapshotIndexToIncrement cannot be less than 1"); + } else if (nextSnapshotIndexToIncrement > numbers.size()) { throw new MojoExecutionException( - "nextSnapshotIndexToIncrement cannot be greater than the last version index" ); + "nextSnapshotIndexToIncrement cannot be greater than the last version index"); } - int snapshotVersionToIncrement = Integer.parseInt( numbers.remove( nextSnapshotIndexToIncrement - 1 ) ); - numbers.add( nextSnapshotIndexToIncrement - 1, String.valueOf( snapshotVersionToIncrement + 1 ) ); + int snapshotVersionToIncrement = Integer.parseInt(numbers.remove(nextSnapshotIndexToIncrement - 1)); + numbers.add(nextSnapshotIndexToIncrement - 1, String.valueOf(snapshotVersionToIncrement + 1)); - return StringUtils.join( numbers.toArray( new String[0] ), "." ) + "-SNAPSHOT"; + return StringUtils.join(numbers.toArray(new String[0]), ".") + "-SNAPSHOT"; } - private static String fixNullOrEmpty( String value, String defaultValue ) - { - return StringUtils.isBlank( value ) ? defaultValue : value; + private static String fixNullOrEmpty(String value, String defaultValue) { + return StringUtils.isBlank(value) ? defaultValue : value; } - private void applyChange( MavenProject project, SortedMap reactor, Set files, String groupId, - String artifactId, String oldVersion ) - { + private void applyChange( + MavenProject project, + SortedMap reactor, + Set files, + String groupId, + String artifactId, + String oldVersion) { - getLog().debug( "Applying change " + groupId + ":" + artifactId + ":" + oldVersion + " -> " + newVersion ); + getLog().debug("Applying change " + groupId + ":" + artifactId + ":" + oldVersion + " -> " + newVersion); // this is a triggering change - addChange( groupId, artifactId, oldVersion, newVersion ); + addChange(groupId, artifactId, oldVersion, newVersion); // now fake out the triggering change - Map.Entry current = PomHelper.getModelEntry( reactor, groupId, artifactId ); - if ( current != null ) - { - current.getValue().setVersion( newVersion ); - files.add( getModuleProjectFile( project, current.getKey() ) ); + Map.Entry current = PomHelper.getModelEntry(reactor, groupId, artifactId); + if (current != null) { + current.getValue().setVersion(newVersion); + files.add(getModuleProjectFile(project, current.getKey())); } - for ( Map.Entry sourceEntry : reactor.entrySet() ) - { + for (Map.Entry sourceEntry : reactor.entrySet()) { final String sourcePath = sourceEntry.getKey(); final Model sourceModel = sourceEntry.getValue(); - getLog().debug( sourcePath.length() == 0 ? "Processing root module as parent" - : "Processing " + sourcePath + " as a parent." ); + getLog().debug( + sourcePath.length() == 0 + ? "Processing root module as parent" + : "Processing " + sourcePath + " as a parent."); - final String sourceGroupId = PomHelper.getGroupId( sourceModel ); - if ( sourceGroupId == null ) - { - getLog().warn( "Module " + sourcePath + " is missing a groupId." ); + final String sourceGroupId = PomHelper.getGroupId(sourceModel); + if (sourceGroupId == null) { + getLog().warn("Module " + sourcePath + " is missing a groupId."); continue; } - final String sourceArtifactId = PomHelper.getArtifactId( sourceModel ); - if ( sourceArtifactId == null ) - { - getLog().warn( "Module " + sourcePath + " is missing an artifactId." ); + final String sourceArtifactId = PomHelper.getArtifactId(sourceModel); + if (sourceArtifactId == null) { + getLog().warn("Module " + sourcePath + " is missing an artifactId."); continue; } - final String sourceVersion = PomHelper.getVersion( sourceModel ); - if ( sourceVersion == null ) - { - getLog().warn( "Module " + sourcePath + " is missing a version." ); + final String sourceVersion = PomHelper.getVersion(sourceModel); + if (sourceVersion == null) { + getLog().warn("Module " + sourcePath + " is missing a version."); continue; } - files.add( getModuleProjectFile( project, sourcePath ) ); + files.add(getModuleProjectFile(project, sourcePath)); - getLog().debug( - "Looking for modules which use " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) - + " as their parent" ); + getLog().debug("Looking for modules which use " + + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + " as their parent"); - for ( Map.Entry stringModelEntry : processAllModules ? reactor.entrySet() - : PomHelper.getChildModels( reactor, sourceGroupId, sourceArtifactId ).entrySet() ) - { + for (Map.Entry stringModelEntry : processAllModules + ? reactor.entrySet() + : PomHelper.getChildModels(reactor, sourceGroupId, sourceArtifactId) + .entrySet()) { final Model targetModel = stringModelEntry.getValue(); final Parent parent = targetModel.getParent(); - getLog().debug( "Module: " + stringModelEntry.getKey() ); - if ( parent != null && sourceVersion.equals( parent.getVersion() ) ) - { - getLog().debug( - " parent already is " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) - + ":" + sourceVersion ); + getLog().debug("Module: " + stringModelEntry.getKey()); + if (parent != null && sourceVersion.equals(parent.getVersion())) { + getLog().debug(" parent already is " + + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + ":" + sourceVersion); + } else { + getLog().debug(" parent is " + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + + ":" + (parent == null ? "" : parent.getVersion())); + getLog().debug(" will become " + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + + ":" + sourceVersion); } - else - { - getLog().debug( - " parent is " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" + ( - parent == null ? "" : parent.getVersion() ) ); - getLog().debug( - " will become " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" - + sourceVersion ); - } - final boolean targetExplicit = PomHelper.isExplicitVersion( targetModel ); - if ( ( updateMatchingVersions || !targetExplicit ) // - && ( parent != null && StringUtils.equals( parent.getVersion(), - PomHelper.getVersion( targetModel ) ) ) ) - { - getLog().debug( - " module is " + ArtifactUtils.versionlessKey( PomHelper.getGroupId( targetModel ), - PomHelper.getArtifactId( targetModel ) ) + ":" - + PomHelper.getVersion( - targetModel ) ); - getLog().debug( - " will become " + ArtifactUtils.versionlessKey( PomHelper.getGroupId( targetModel ), - PomHelper.getArtifactId( targetModel ) ) - + ":" + sourceVersion ); - addChange( PomHelper.getGroupId( targetModel ), PomHelper.getArtifactId( targetModel ), - PomHelper.getVersion( targetModel ), sourceVersion ); - targetModel.setVersion( sourceVersion ); - } - else - { - getLog().debug( - " module is " + ArtifactUtils.versionlessKey( PomHelper.getGroupId( targetModel ), - PomHelper.getArtifactId( targetModel ) ) + ":" - + PomHelper.getVersion( - targetModel ) ); + final boolean targetExplicit = PomHelper.isExplicitVersion(targetModel); + if ((updateMatchingVersions || !targetExplicit) // + && (parent != null + && StringUtils.equals(parent.getVersion(), PomHelper.getVersion(targetModel)))) { + getLog().debug(" module is " + + ArtifactUtils.versionlessKey( + PomHelper.getGroupId(targetModel), PomHelper.getArtifactId(targetModel)) + + ":" + + PomHelper.getVersion(targetModel)); + getLog().debug(" will become " + + ArtifactUtils.versionlessKey( + PomHelper.getGroupId(targetModel), PomHelper.getArtifactId(targetModel)) + + ":" + sourceVersion); + addChange( + PomHelper.getGroupId(targetModel), + PomHelper.getArtifactId(targetModel), + PomHelper.getVersion(targetModel), + sourceVersion); + targetModel.setVersion(sourceVersion); + } else { + getLog().debug(" module is " + + ArtifactUtils.versionlessKey( + PomHelper.getGroupId(targetModel), PomHelper.getArtifactId(targetModel)) + + ":" + + PomHelper.getVersion(targetModel)); } } } } - private static File getModuleProjectFile( MavenProject project, String relativePath ) - { - final File moduleDir = new File( project.getBasedir(), relativePath ); + private static File getModuleProjectFile(MavenProject project, String relativePath) { + final File moduleDir = new File(project.getBasedir(), relativePath); final File projectBaseDir = project.getBasedir(); - if ( projectBaseDir.equals( moduleDir ) ) - { + if (projectBaseDir.equals(moduleDir)) { return project.getFile(); - } - else if ( moduleDir.isDirectory() ) - { - return new File( moduleDir, "pom.xml" ); + } else if (moduleDir.isDirectory()) { + return new File(moduleDir, "pom.xml"); } // i don't think this should ever happen... but just in case // the module references the file-name @@ -572,74 +536,58 @@ else if ( moduleDir.isDirectory() ) * @throws org.apache.maven.plugin.MojoFailureException when things go wrong. * @throws javax.xml.stream.XMLStreamException when things go wrong. */ - protected synchronized void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - ContextualLog log = new DelegatingContextualLog( getLog() ); - try - { - Model model = PomHelper.getRawModel( pom ); - log.setContext( "Processing " + PomHelper.getGroupId( model ) + ":" + PomHelper.getArtifactId( model ) ); + protected synchronized void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + ContextualLog log = new DelegatingContextualLog(getLog()); + try { + Model model = PomHelper.getRawModel(pom); + log.setContext("Processing " + PomHelper.getGroupId(model) + ":" + PomHelper.getArtifactId(model)); VersionChangerFactory versionChangerFactory = new VersionChangerFactory(); - versionChangerFactory.setPom( pom ); - versionChangerFactory.setLog( log ); - versionChangerFactory.setModel( model ); + versionChangerFactory.setPom(pom); + versionChangerFactory.setLog(log); + versionChangerFactory.setModel(model); - VersionChanger changer = - versionChangerFactory.newVersionChanger( processParent, processProject, processDependencies, - processPlugins ); + VersionChanger changer = versionChangerFactory.newVersionChanger( + processParent, processProject, processDependencies, processPlugins); - for ( DefaultVersionChange versionChange : sourceChanges ) - { - changer.apply( versionChange ); + for (DefaultVersionChange versionChange : sourceChanges) { + changer.apply(versionChange); } - if ( updateBuildOutputTimestamp && !"never".equals( updateBuildOutputTimestampPolicy ) ) - { - if ( "always".equals( updateBuildOutputTimestampPolicy ) || !sourceChanges.isEmpty() ) - { + if (updateBuildOutputTimestamp && !"never".equals(updateBuildOutputTimestampPolicy)) { + if ("always".equals(updateBuildOutputTimestampPolicy) || !sourceChanges.isEmpty()) { // also update project.build.outputTimestamp - updateBuildOutputTimestamp( pom, model ); + updateBuildOutputTimestamp(pom, model); } } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } log.clearContext(); } - private void updateBuildOutputTimestamp( ModifiedPomXMLEventReader pom, Model model ) throws XMLStreamException - { - String buildOutputTimestamp = model.getProperties().getProperty( "project.build.outputTimestamp" ); + private void updateBuildOutputTimestamp(ModifiedPomXMLEventReader pom, Model model) throws XMLStreamException { + String buildOutputTimestamp = model.getProperties().getProperty("project.build.outputTimestamp"); - if ( buildOutputTimestamp == null || isEmpty( buildOutputTimestamp ) ) - { + if (buildOutputTimestamp == null || isEmpty(buildOutputTimestamp)) { // no Reproducible Builds output timestamp defined return; } - if ( StringUtils.isNumeric( buildOutputTimestamp ) ) - { + if (StringUtils.isNumeric(buildOutputTimestamp)) { // int representing seconds since the epoch, like SOURCE_DATE_EPOCH - buildOutputTimestamp = String.valueOf( System.currentTimeMillis() / 1000 ); - } - else if ( buildOutputTimestamp.length() <= 1 ) - { + buildOutputTimestamp = String.valueOf(System.currentTimeMillis() / 1000); + } else if (buildOutputTimestamp.length() <= 1) { // value length == 1 means disable Reproducible Builds return; - } - else - { + } else { // ISO-8601 - DateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" ); - df.setTimeZone( TimeZone.getTimeZone( "UTC" ) ); - buildOutputTimestamp = df.format( new Date() ); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + buildOutputTimestamp = df.format(new Date()); } - PomHelper.setPropertyVersion( pom, null, "project.build.outputTimestamp", buildOutputTimestamp ); + PomHelper.setPropertyVersion(pom, null, "project.build.outputTimestamp", buildOutputTimestamp); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetPropertyMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetPropertyMojo.java index 427cca501d..2bb6d7fc9a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetPropertyMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetPropertyMojo.java @@ -52,10 +52,8 @@ * @author Karl Heinz Marbaise * @since 2.5 */ -@Mojo( name = "set-property", threadSafe = true ) -public class SetPropertyMojo - extends AbstractVersionsUpdaterMojo -{ +@Mojo(name = "set-property", threadSafe = true) +public class SetPropertyMojo extends AbstractVersionsUpdaterMojo { // ------------------------------ FIELDS ------------------------------ @@ -63,19 +61,19 @@ public class SetPropertyMojo * A property to update. * You can also specify multiple property names separated by "," which are all set to the same new version. */ - @Parameter( property = "property" ) + @Parameter(property = "property") private String property = null; /** * The new version to set the property. */ - @Parameter( property = "newVersion" ) + @Parameter(property = "newVersion") private String newVersion = null; /** * Whether properties linking versions should be auto-detected or not. */ - @Parameter( property = "autoLinkItems", defaultValue = "true" ) + @Parameter(property = "autoLinkItems", defaultValue = "true") private boolean autoLinkItems; /** @@ -84,17 +82,16 @@ public class SetPropertyMojo * * @since 2.9 */ - - @Parameter( property = "propertiesVersionsFile" ) + @Parameter(property = "propertiesVersionsFile") private String propertiesVersionsFile; @Inject - public SetPropertyMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public SetPropertyMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -104,87 +101,69 @@ public SetPropertyMojo( RepositorySystem repositorySystem, * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { Property[] propertiesConfig; String properties; - if ( !isEmpty( propertiesVersionsFile ) ) - { + if (!isEmpty(propertiesVersionsFile)) { logWrongConfigWarning(); - getLog().debug( "Reading properties and versions to update from file: " + propertiesVersionsFile ); - PropertiesVersionsFileReader reader = new PropertiesVersionsFileReader( propertiesVersionsFile ); - try - { + getLog().debug("Reading properties and versions to update from file: " + propertiesVersionsFile); + PropertiesVersionsFileReader reader = new PropertiesVersionsFileReader(propertiesVersionsFile); + try { reader.read(); - } - catch ( IOException e ) - { - getLog().error( "Unable to read property file " + propertiesVersionsFile - + ". re-run with -X option for more details." ); - getLog().debug( "Error while reading property file " + propertiesVersionsFile, e ); - throw new MojoFailureException( "Unable to read property file " + propertiesVersionsFile ); + } catch (IOException e) { + getLog().error("Unable to read property file " + propertiesVersionsFile + + ". re-run with -X option for more details."); + getLog().debug("Error while reading property file " + propertiesVersionsFile, e); + throw new MojoFailureException("Unable to read property file " + propertiesVersionsFile); } propertiesConfig = reader.getPropertiesConfig(); properties = reader.getProperties(); - } - else if ( !isEmpty( property ) ) - { - getLog().debug( "Reading properties and versions to update from property and newVersion " ); - propertiesConfig = Arrays.stream( split( property, "," ) ).map( - prp -> - { - Property propertyConfig = new Property( prp ); - propertyConfig.setVersion( newVersion ); + } else if (!isEmpty(property)) { + getLog().debug("Reading properties and versions to update from property and newVersion "); + propertiesConfig = Arrays.stream(split(property, ",")) + .map(prp -> { + Property propertyConfig = new Property(prp); + propertyConfig.setVersion(newVersion); return propertyConfig; - } ) - .toArray( Property[]::new ); + }) + .toArray(Property[]::new); properties = property; + } else { + throw new MojoExecutionException("Please provide either 'property' or 'propertiesVersionsFile' parameter."); } - else - { - throw new MojoExecutionException( - "Please provide either 'property' or 'propertiesVersionsFile' parameter." ); - } - update( pom, propertiesConfig, properties ); + update(pom, propertiesConfig, properties); } - private void update( ModifiedPomXMLEventReader pom, Property[] propertiesConfig, String properties ) - throws MojoExecutionException, XMLStreamException - { - Map propertyVersions = - this.getHelper().getVersionPropertiesMap( VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( getProject() ) - .withPropertyDefinitions( propertiesConfig ) - .withIncludeProperties( properties ) - .withAutoLinkItems( autoLinkItems ) - .build() ); - for ( Map.Entry entry : propertyVersions.entrySet() ) - { + private void update(ModifiedPomXMLEventReader pom, Property[] propertiesConfig, String properties) + throws MojoExecutionException, XMLStreamException { + Map propertyVersions = this.getHelper() + .getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(getProject()) + .withPropertyDefinitions(propertiesConfig) + .withIncludeProperties(properties) + .withAutoLinkItems(autoLinkItems) + .build()); + for (Map.Entry entry : propertyVersions.entrySet()) { Property currentProperty = entry.getKey(); PropertyVersions version = entry.getValue(); String newVersionGiven = currentProperty.getVersion(); - final String currentVersion = getProject().getProperties().getProperty( currentProperty.getName() ); - if ( currentVersion == null ) - { + final String currentVersion = getProject().getProperties().getProperty(currentProperty.getName()); + if (currentVersion == null) { continue; } - PomHelper.setPropertyVersion( pom, version.getProfileId(), currentProperty.getName(), - defaultString( newVersionGiven ) ); + PomHelper.setPropertyVersion( + pom, version.getProfileId(), currentProperty.getName(), defaultString(newVersionGiven)); } } - private void logWrongConfigWarning() - { - if ( !isEmpty( property ) ) - { - getLog().warn( "-Dproperty provided but will be ignored as -DpropertiesVersionsFile is used" ); + private void logWrongConfigWarning() { + if (!isEmpty(property)) { + getLog().warn("-Dproperty provided but will be ignored as -DpropertiesVersionsFile is used"); } - if ( !isEmpty( newVersion ) ) - { - getLog().warn( "-DnewVersion provided but will be ignored as -DpropertiesVersionsFile is used" ); + if (!isEmpty(newVersion)) { + getLog().warn("-DnewVersion provided but will be ignored as -DpropertiesVersionsFile is used"); } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetScmTagMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetScmTagMojo.java index 5940640bec..bb1e3b13f2 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetScmTagMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/SetScmTagMojo.java @@ -28,16 +28,15 @@ * @author Anton Johansson * @since 2.5 */ -@Mojo( name = "set-scm-tag", aggregator = true, threadSafe = true ) -public class SetScmTagMojo extends AbstractVersionsUpdaterMojo -{ +@Mojo(name = "set-scm-tag", aggregator = true, threadSafe = true) +public class SetScmTagMojo extends AbstractVersionsUpdaterMojo { /** * The new SCM tag to set. * * @since 2.5 */ - @Parameter( property = "newTag" ) + @Parameter(property = "newTag") private String newTag; /** @@ -45,7 +44,7 @@ public class SetScmTagMojo extends AbstractVersionsUpdaterMojo * * @since 2.12.0 */ - @Parameter( property = "connection" ) + @Parameter(property = "connection") private String connection; /** @@ -53,7 +52,7 @@ public class SetScmTagMojo extends AbstractVersionsUpdaterMojo * * @since 2.12.0 */ - @Parameter( property = "developerConnection" ) + @Parameter(property = "developerConnection") private String developerConnection; /** @@ -61,16 +60,16 @@ public class SetScmTagMojo extends AbstractVersionsUpdaterMojo * * @since 2.12.0 */ - @Parameter( property = "url" ) + @Parameter(property = "url") private String url; @Inject - public SetScmTagMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public SetScmTagMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -80,78 +79,64 @@ public SetScmTagMojo( RepositorySystem repositorySystem, * @throws org.apache.maven.plugin.MojoFailureException when things go wrong. */ @Override - public void execute() throws MojoExecutionException, MojoFailureException - { - if ( isAllBlank( newTag, connection, developerConnection, url ) ) - { + public void execute() throws MojoExecutionException, MojoFailureException { + if (isAllBlank(newTag, connection, developerConnection, url)) { throw new MojoFailureException( - "One of: \"newTag\", \"connection\", \"developerConnection\", \"url\" should be provided." ); + "One of: \"newTag\", \"connection\", \"developerConnection\", \"url\" should be provided."); } super.execute(); } @Override - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - try - { - Scm scm = PomHelper.getRawModel( pom ).getScm(); - if ( scm == null ) - { - throw new MojoFailureException( "No was present" ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + try { + Scm scm = PomHelper.getRawModel(pom).getScm(); + if (scm == null) { + throw new MojoFailureException("No was present"); } List failures = new ArrayList<>(); - if ( !isBlank( newTag ) ) - { - getLog().info( "Updating tag: " + ( scm != null && scm.getTag() != null - ? scm.getTag() : "(empty)" ) + " -> " + newTag ); - if ( !PomHelper.setElementValue( pom, "/project/scm", "tag", newTag ) ) - { - failures.add( "tag: " + newTag ); + if (!isBlank(newTag)) { + getLog().info("Updating tag: " + (scm != null && scm.getTag() != null ? scm.getTag() : "(empty)") + + " -> " + newTag); + if (!PomHelper.setElementValue(pom, "/project/scm", "tag", newTag)) { + failures.add("tag: " + newTag); } } - if ( !isBlank( connection ) ) - { - getLog().info( "Updating connection: " + ( scm != null && scm.getConnection() != null - ? scm.getConnection() : "(empty)" ) + " -> " + connection ); - if ( !PomHelper.setElementValue( pom, "/project/scm", "connection", connection ) ) - { - failures.add( "connection: " + connection ); + if (!isBlank(connection)) { + getLog().info("Updating connection: " + + (scm != null && scm.getConnection() != null ? scm.getConnection() : "(empty)") + " -> " + + connection); + if (!PomHelper.setElementValue(pom, "/project/scm", "connection", connection)) { + failures.add("connection: " + connection); } } - if ( !isBlank( developerConnection ) ) - { - getLog().info( "Updating developerConnection: " - + ( scm != null && scm.getDeveloperConnection() != null - ? scm.getDeveloperConnection() : "(empty)" ) + " -> " - + developerConnection ); - if ( !PomHelper.setElementValue( pom, "/project/scm", "developerConnection", - developerConnection ) ) - { - failures.add( "developerConnection: " + developerConnection ); + if (!isBlank(developerConnection)) { + getLog().info("Updating developerConnection: " + + (scm != null && scm.getDeveloperConnection() != null + ? scm.getDeveloperConnection() + : "(empty)") + + " -> " + + developerConnection); + if (!PomHelper.setElementValue(pom, "/project/scm", "developerConnection", developerConnection)) { + failures.add("developerConnection: " + developerConnection); } } - if ( !isBlank( url ) ) - { - getLog().info( "Updating url: " + ( scm != null && scm.getUrl() != null - ? scm.getUrl() : "(empty)" ) + " -> " + url ); - if ( !PomHelper.setElementValue( pom, "/project/scm", "url", url ) ) - { - failures.add( "url: " + url ); + if (!isBlank(url)) { + getLog().info("Updating url: " + (scm != null && scm.getUrl() != null ? scm.getUrl() : "(empty)") + + " -> " + url); + if (!PomHelper.setElementValue(pom, "/project/scm", "url", url)) { + failures.add("url: " + url); } } - if ( !failures.isEmpty() ) - { - throw new MojoFailureException( "Could not update one or more SCM elements: " + String.join( ", ", - failures ) + ". Please make sure they are present in the original POM. " ); + if (!failures.isEmpty()) { + throw new MojoFailureException("Could not update one or more SCM elements: " + + String.join(", ", failures) + ". Please make sure they are present in the original POM. "); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UnlockSnapshotsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UnlockSnapshotsMojo.java index b490d1400c..7276940a2c 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UnlockSnapshotsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UnlockSnapshotsMojo.java @@ -52,26 +52,25 @@ * @author Paul Gier * @since 1.0-alpha-3 */ -@Mojo( name = "unlock-snapshots", threadSafe = true ) -public class UnlockSnapshotsMojo extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "unlock-snapshots", threadSafe = true) +public class UnlockSnapshotsMojo extends AbstractVersionsDependencyUpdaterMojo { // ------------------------------ FIELDS ------------------------------ /** * Pattern to match a timestamped snapshot version. For example 1.0-20090128.202731-1 */ - private static final Pattern TIMESTAMPED_SNAPSHOT_REGEX = Pattern.compile( "-(\\d{8}\\.\\d{6})-(\\d+)$" ); + private static final Pattern TIMESTAMPED_SNAPSHOT_REGEX = Pattern.compile("-(\\d{8}\\.\\d{6})-(\\d+)$"); // ------------------------------ METHODS -------------------------- @Inject - public UnlockSnapshotsMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UnlockSnapshotsMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -81,112 +80,97 @@ public UnlockSnapshotsMojo( RepositorySystem repositorySystem, * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - try - { - if ( isProcessingDependencyManagement() ) - { - DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - unlockSnapshots( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + try { + if (isProcessingDependencyManagement()) { + DependencyManagement dependencyManagement = + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + unlockSnapshots( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); + } } - } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - unlockSnapshots( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); - } - if ( getProject().getParent() != null && isProcessingParent() ) - { - unlockParentSnapshot( pom, getProject().getParent() ); - } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + unlockSnapshots(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); + } + if (getProject().getParent() != null && isProcessingParent()) { + unlockParentSnapshot(pom, getProject().getParent()); + } + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void unlockSnapshots( ModifiedPomXMLEventReader pom, List dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException - { - for ( Dependency dep : dependencies ) - { - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { - getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + private void unlockSnapshots( + ModifiedPomXMLEventReader pom, List dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException { + for (Dependency dep : dependencies) { + if (isExcludeReactor() && isProducedByReactor(dep)) { + getLog().info("Ignoring reactor dependency: " + toString(dep)); continue; } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } - if ( !isIncluded( this.toArtifact( dep ) ) ) - { + if (!isIncluded(this.toArtifact(dep))) { continue; } String version = dep.getVersion(); - Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher( version ); - if ( versionMatcher.find() && versionMatcher.end() == version.length() ) - { - String unlockedVersion = versionMatcher.replaceFirst( "-SNAPSHOT" ); - if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), - unlockedVersion, getProject().getModel() ) ) - { - - getChangeRecorder().recordChange( DefaultChangeRecord.builder() - .withKind( changeKind ) - .withDependency( dep ) - .withNewVersion( unlockedVersion ) - .build() ); - getLog().info( "Unlocked " + toString( dep ) + " to version " + unlockedVersion ); + Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher(version); + if (versionMatcher.find() && versionMatcher.end() == version.length()) { + String unlockedVersion = versionMatcher.replaceFirst("-SNAPSHOT"); + if (PomHelper.setDependencyVersion( + pom, + dep.getGroupId(), + dep.getArtifactId(), + dep.getVersion(), + unlockedVersion, + getProject().getModel())) { + + getChangeRecorder() + .recordChange(DefaultChangeRecord.builder() + .withKind(changeKind) + .withDependency(dep) + .withNewVersion(unlockedVersion) + .build()); + getLog().info("Unlocked " + toString(dep) + " to version " + unlockedVersion); } } } } - private void unlockParentSnapshot( ModifiedPomXMLEventReader pom, MavenProject parent ) - throws XMLStreamException, MojoExecutionException - { - if ( parent == null ) - { - getLog().info( "Project does not have a parent" ); + private void unlockParentSnapshot(ModifiedPomXMLEventReader pom, MavenProject parent) + throws XMLStreamException, MojoExecutionException { + if (parent == null) { + getLog().info("Project does not have a parent"); return; } - if ( reactorProjects.contains( parent ) ) - { - getLog().info( "Project's parent is part of the reactor" ); + if (reactorProjects.contains(parent)) { + getLog().info("Project's parent is part of the reactor"); return; } Artifact parentArtifact = parent.getArtifact(); String parentVersion = parentArtifact.getVersion(); - Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher( parentVersion ); - if ( versionMatcher.find() && versionMatcher.end() == parentVersion.length() ) - { - String unlockedParentVersion = versionMatcher.replaceFirst( "-SNAPSHOT" ); - if ( PomHelper.setProjectParentVersion( pom, unlockedParentVersion ) ) - { - getLog().info( "Unlocked parent " + parentArtifact + " to version " - + unlockedParentVersion ); - getChangeRecorder().recordChange( DefaultChangeRecord.builder() - .withKind( ChangeRecord.ChangeKind.PARENT ) - .withArtifact( parentArtifact ) - .withNewVersion( unlockedParentVersion ) - .build() ); + Matcher versionMatcher = TIMESTAMPED_SNAPSHOT_REGEX.matcher(parentVersion); + if (versionMatcher.find() && versionMatcher.end() == parentVersion.length()) { + String unlockedParentVersion = versionMatcher.replaceFirst("-SNAPSHOT"); + if (PomHelper.setProjectParentVersion(pom, unlockedParentVersion)) { + getLog().info("Unlocked parent " + parentArtifact + " to version " + unlockedParentVersion); + getChangeRecorder() + .recordChange(DefaultChangeRecord.builder() + .withKind(ChangeRecord.ChangeKind.PARENT) + .withArtifact(parentArtifact) + .withNewVersion(unlockedParentVersion) + .build()); } } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateChildModulesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateChildModulesMojo.java index 6a0bc41362..11fda20899 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateChildModulesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateChildModulesMojo.java @@ -47,11 +47,8 @@ * @author Stephen Connolly * @since 1.0-alpha-2 */ -@Mojo( name = "update-child-modules", aggregator = true, - threadSafe = true ) -public class UpdateChildModulesMojo - extends AbstractVersionsUpdaterMojo -{ +@Mojo(name = "update-child-modules", aggregator = true, threadSafe = true) +public class UpdateChildModulesMojo extends AbstractVersionsUpdaterMojo { /** * The groupId that we are updating. Guarded by this. */ @@ -68,12 +65,12 @@ public class UpdateChildModulesMojo private transient String sourceVersion = null; @Inject - public UpdateChildModulesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UpdateChildModulesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -82,81 +79,67 @@ public UpdateChildModulesMojo( RepositorySystem repositorySystem, * @throws MojoExecutionException when things go wrong. * @throws MojoFailureException when things go wrong. */ - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { boolean didSomething = false; - try - { - final Map reactor = PomHelper.getReactorModels( getProject(), getLog() ); - List order = new ArrayList<>( reactor.keySet() ); - order.sort( - ( o1, o2 ) -> - { - Model m1 = reactor.get( o1 ); - Model m2 = reactor.get( o2 ); - int d1 = PomHelper.getReactorParentCount( reactor, m1 ); - int d2 = PomHelper.getReactorParentCount( reactor, m2 ); - if ( d1 < d2 ) - { - return -1; - } - else if ( d1 > d2 ) - { - return 1; - } - return 0; - } ); - - for ( String sourcePath : order ) - { - Model sourceModel = reactor.get( sourcePath ); - - getLog().debug( sourcePath.length() == 0 ? "Processing root module as parent" - : "Processing " + sourcePath + " as a parent." ); - - synchronized ( this ) - { - sourceGroupId = PomHelper.getGroupId( sourceModel ); - if ( sourceGroupId == null ) - { - getLog().warn( "Module " + sourcePath + " is missing a groupId." ); + try { + final Map reactor = PomHelper.getReactorModels(getProject(), getLog()); + List order = new ArrayList<>(reactor.keySet()); + order.sort((o1, o2) -> { + Model m1 = reactor.get(o1); + Model m2 = reactor.get(o2); + int d1 = PomHelper.getReactorParentCount(reactor, m1); + int d2 = PomHelper.getReactorParentCount(reactor, m2); + if (d1 < d2) { + return -1; + } else if (d1 > d2) { + return 1; + } + return 0; + }); + + for (String sourcePath : order) { + Model sourceModel = reactor.get(sourcePath); + + getLog().debug( + sourcePath.length() == 0 + ? "Processing root module as parent" + : "Processing " + sourcePath + " as a parent."); + + synchronized (this) { + sourceGroupId = PomHelper.getGroupId(sourceModel); + if (sourceGroupId == null) { + getLog().warn("Module " + sourcePath + " is missing a groupId."); continue; } - sourceArtifactId = PomHelper.getArtifactId( sourceModel ); - if ( sourceArtifactId == null ) - { - getLog().warn( "Module " + sourcePath + " is missing an artifactId." ); + sourceArtifactId = PomHelper.getArtifactId(sourceModel); + if (sourceArtifactId == null) { + getLog().warn("Module " + sourcePath + " is missing an artifactId."); continue; } - sourceVersion = PomHelper.getVersion( sourceModel ); - if ( sourceVersion == null ) - { - getLog().warn( "Module " + sourcePath + " is missing a version." ); + sourceVersion = PomHelper.getVersion(sourceModel); + if (sourceVersion == null) { + getLog().warn("Module " + sourcePath + " is missing a version."); continue; } - getLog().debug( "Looking for modules which use " - + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) - + " as their parent to update it to " + sourceVersion ); + getLog().debug("Looking for modules which use " + + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + + " as their parent to update it to " + sourceVersion); - for ( Map.Entry target : PomHelper.getChildModels( reactor, sourceGroupId, - sourceArtifactId ).entrySet() ) - { + for (Map.Entry target : PomHelper.getChildModels( + reactor, sourceGroupId, sourceArtifactId) + .entrySet()) { String targetPath = target.getKey(); - File moduleDir = new File( getProject().getBasedir(), targetPath ); + File moduleDir = new File(getProject().getBasedir(), targetPath); File moduleProjectFile; - if ( moduleDir.isDirectory() ) - { - moduleProjectFile = new File( moduleDir, "pom.xml" ); - } - else - { + if (moduleDir.isDirectory()) { + moduleProjectFile = new File(moduleDir, "pom.xml"); + } else { // i don't think this should ever happen... but just in case // the module references the file-name moduleProjectFile = moduleDir; @@ -164,36 +147,30 @@ else if ( d1 > d2 ) Model targetModel = target.getValue(); final Parent parent = targetModel.getParent(); - if ( sourceVersion.equals( parent.getVersion() ) ) - { - getLog().debug( "Module: " + targetPath + " parent is " - + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" - + sourceVersion ); - } - else - { - getLog().info( "Module: " + targetPath ); - getLog().info( " parent was " - + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" - + parent.getVersion() ); - getLog().info( " updated to " - + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" - + sourceVersion ); - process( moduleProjectFile ); + if (sourceVersion.equals(parent.getVersion())) { + getLog().debug("Module: " + targetPath + " parent is " + + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + ":" + + sourceVersion); + } else { + getLog().info("Module: " + targetPath); + getLog().info(" parent was " + + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + ":" + + parent.getVersion()); + getLog().info(" updated to " + + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + ":" + + sourceVersion); + process(moduleProjectFile); didSomething = true; } } } } + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); - } - if ( !didSomething ) - { - getLog().info( "All child modules are up to date." ); + if (!didSomething) { + getLog().info("All child modules are up to date."); } } @@ -205,15 +182,12 @@ else if ( d1 > d2 ) * @throws MojoFailureException when things go wrong. * @throws XMLStreamException when things go wrong. */ - protected synchronized void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - getLog().debug( "Updating parent to " + sourceVersion ); - - if ( PomHelper.setProjectParentVersion( pom, sourceVersion ) ) - { - getLog().debug( "Made an update to " + sourceVersion ); + protected synchronized void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + getLog().debug("Updating parent to " + sourceVersion); + + if (PomHelper.setProjectParentVersion(pom, sourceVersion)) { + getLog().debug("Made an update to " + sourceVersion); } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java index 0841f9e865..3ede5832ac 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java @@ -59,9 +59,8 @@ * @author Stephen Connolly * @since 1.0-alpha-1 */ -@Mojo( name = "update-parent", threadSafe = true ) -public class UpdateParentMojo extends AbstractVersionsUpdaterMojo -{ +@Mojo(name = "update-parent", threadSafe = true) +public class UpdateParentMojo extends AbstractVersionsUpdaterMojo { // ------------------------------ FIELDS ------------------------------ @@ -74,7 +73,7 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * the parent artifact will be updated.

* @since 1.0-alpha-1 */ - @Parameter( property = "parentVersion" ) + @Parameter(property = "parentVersion") protected String parentVersion = null; /** @@ -82,7 +81,7 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * * @since 2.9 */ - @Parameter( property = "forceUpdate", defaultValue = "false" ) + @Parameter(property = "forceUpdate", defaultValue = "false") protected boolean forceUpdate = false; /** @@ -91,7 +90,7 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * * @since 2.13.0 */ - @Parameter( property = "skipResolution", defaultValue = "false" ) + @Parameter(property = "skipResolution", defaultValue = "false") protected boolean skipResolution = false; /** @@ -101,8 +100,7 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * * @since 2.12.0 */ - @Parameter( property = "allowDowngrade", - defaultValue = "false" ) + @Parameter(property = "allowDowngrade", defaultValue = "false") protected boolean allowDowngrade; /** @@ -110,7 +108,7 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * * @since 2.13.0 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") protected boolean allowMajorUpdates = true; /** @@ -120,7 +118,7 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * * @since 2.13.0 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") protected boolean allowMinorUpdates = true; /** @@ -131,18 +129,18 @@ public class UpdateParentMojo extends AbstractVersionsUpdaterMojo * * @since 2.13.0 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") protected boolean allowIncrementalUpdates = true; // -------------------------- OTHER METHODS -------------------------- @Inject - public UpdateParentMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UpdateParentMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -153,116 +151,94 @@ public UpdateParentMojo( RepositorySystem repositorySystem, * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - if ( getProject().getParent() == null ) - { - getLog().info( "Project does not have a parent" ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + if (getProject().getParent() == null) { + getLog().info("Project does not have a parent"); return; } - if ( reactorProjects.contains( getProject().getParent() ) ) - { - getLog().info( "Project's parent is part of the reactor" ); + if (reactorProjects.contains(getProject().getParent())) { + getLog().info("Project's parent is part of the reactor"); return; } - if ( skipResolution && isBlank( parentVersion ) ) - { - throw new MojoExecutionException( "skipResolution is only valid if parentVersion is set" ); + if (skipResolution && isBlank(parentVersion)) { + throw new MojoExecutionException("skipResolution is only valid if parentVersion is set"); } - String initialVersion = parentVersion == null - ? getProject().getParent().getVersion() - : parentVersion; - try - { - ArtifactVersion artifactVersion = skipResolution - ? new DefaultArtifactVersion( parentVersion ) - : resolveTargetVersion( initialVersion ); - if ( artifactVersion != null ) - { - getLog().info( "Updating parent from " + getProject().getParent().getVersion() - + " to " + artifactVersion ); - - if ( PomHelper.setProjectParentVersion( pom, artifactVersion.toString() ) ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Made an update from " + getProject().getParent().getVersion() - + " to " + artifactVersion ); + String initialVersion = parentVersion == null ? getProject().getParent().getVersion() : parentVersion; + try { + ArtifactVersion artifactVersion = + skipResolution ? new DefaultArtifactVersion(parentVersion) : resolveTargetVersion(initialVersion); + if (artifactVersion != null) { + getLog().info("Updating parent from " + getProject().getParent().getVersion() + " to " + + artifactVersion); + + if (PomHelper.setProjectParentVersion(pom, artifactVersion.toString())) { + if (getLog().isDebugEnabled()) { + getLog().debug("Made an update from " + + getProject().getParent().getVersion() + " to " + artifactVersion); } - getChangeRecorder().recordChange( DefaultChangeRecord.builder() - .withKind( ChangeRecord.ChangeKind.PARENT ) - .withGroupId( getProject().getParent().getGroupId() ) - .withArtifactId( getProject().getParent().getArtifactId() ) - .withOldVersion( getProject().getParent().getVersion() ) - .withNewVersion( artifactVersion.toString() ) - .build() ); + getChangeRecorder() + .recordChange(DefaultChangeRecord.builder() + .withKind(ChangeRecord.ChangeKind.PARENT) + .withGroupId(getProject().getParent().getGroupId()) + .withArtifactId(getProject().getParent().getArtifactId()) + .withOldVersion(getProject().getParent().getVersion()) + .withNewVersion(artifactVersion.toString()) + .build()); } } - } - catch ( InvalidVersionSpecificationException e ) - { - throw new MojoExecutionException( "Invalid version range specification: " + initialVersion, e ); - } - catch ( InvalidSegmentException e ) - { - throw new MojoExecutionException( "Invalid segment specification for version " + initialVersion, e ); + } catch (InvalidVersionSpecificationException e) { + throw new MojoExecutionException("Invalid version range specification: " + initialVersion, e); + } catch (InvalidSegmentException e) { + throw new MojoExecutionException("Invalid segment specification for version " + initialVersion, e); } } - protected ArtifactVersion resolveTargetVersion( String initialVersion ) + protected ArtifactVersion resolveTargetVersion(String initialVersion) throws MojoExecutionException, VersionRetrievalException, InvalidVersionSpecificationException, - InvalidSegmentException - { - Artifact artifact = getHelper().createDependencyArtifact( DependencyBuilder - .newBuilder() - .withGroupId( getProject().getParent().getGroupId() ) - .withArtifactId( getProject().getParent().getArtifactId() ) - .withVersion( initialVersion ) - .withType( "pom" ) - .build() ); - - VersionRange targetVersionRange = VersionRange.createFromVersionSpec( initialVersion ); - if ( targetVersionRange.getRecommendedVersion() != null ) - { + InvalidSegmentException { + Artifact artifact = getHelper() + .createDependencyArtifact(DependencyBuilder.newBuilder() + .withGroupId(getProject().getParent().getGroupId()) + .withArtifactId(getProject().getParent().getArtifactId()) + .withVersion(initialVersion) + .withType("pom") + .build()); + + VersionRange targetVersionRange = VersionRange.createFromVersionSpec(initialVersion); + if (targetVersionRange.getRecommendedVersion() != null) { targetVersionRange = targetVersionRange.restrict( - VersionRange.createFromVersionSpec( "[" + targetVersionRange.getRecommendedVersion() + ",)" ) ); + VersionRange.createFromVersionSpec("[" + targetVersionRange.getRecommendedVersion() + ",)")); } - final ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false ); - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( allowMajorUpdates, - allowMinorUpdates, allowIncrementalUpdates, getLog() ); + final ArtifactVersions versions = getHelper().lookupArtifactVersions(artifact, false); + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); // currentVersion (set to parentVersion here) is not included in the version range for searching upgrades // unless we set allowDowngrade to true - for ( ArtifactVersion candidate : reverse( versions.getNewerVersions( initialVersion, unchangedSegment, - allowSnapshots, !isBlank( parentVersion ) || allowDowngrade ) ) ) - { - if ( allowDowngrade + for (ArtifactVersion candidate : reverse(versions.getNewerVersions( + initialVersion, unchangedSegment, allowSnapshots, !isBlank(parentVersion) || allowDowngrade))) { + if (allowDowngrade || targetVersionRange == null - || ArtifactVersions.isVersionInRange( candidate, targetVersionRange ) ) - { - if ( shouldApplyUpdate( artifact, getProject().getParent().getVersion(), candidate, forceUpdate ) ) - { + || ArtifactVersions.isVersionInRange(candidate, targetVersionRange)) { + if (shouldApplyUpdate(artifact, getProject().getParent().getVersion(), candidate, forceUpdate)) { return candidate; - } - else - { - getLog().debug( "Update not applied. Exiting." ); + } else { + getLog().debug("Update not applied. Exiting."); return null; } } } - getLog().info( "No versions found" ); + getLog().info("No versions found"); return null; } - private static Iterable reverse( T[] array ) - { - return Arrays.stream( array ).sorted( Collections.reverseOrder() ).collect( Collectors.toList() ); + private static Iterable reverse(T[] array) { + return Arrays.stream(array).sorted(Collections.reverseOrder()).collect(Collectors.toList()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojo.java index a91837629b..12da4e4fbb 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojo.java @@ -19,6 +19,11 @@ * under the License. */ +import javax.inject.Inject; +import javax.xml.stream.XMLStreamException; + +import java.util.Map; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; @@ -30,19 +35,14 @@ import org.codehaus.mojo.versions.api.recording.ChangeRecorder; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import javax.inject.Inject; -import javax.xml.stream.XMLStreamException; -import java.util.Map; - /** * Sets properties to the latest versions of specific artifacts. * * @author Stephen Connolly * @since 1.0-alpha-1 */ -@Mojo( name = "update-properties", threadSafe = true ) -public class UpdatePropertiesMojo extends UpdatePropertiesMojoBase -{ +@Mojo(name = "update-properties", threadSafe = true) +public class UpdatePropertiesMojo extends UpdatePropertiesMojoBase { /** * Any restrictions that apply to specific properties. * @@ -56,7 +56,7 @@ public class UpdatePropertiesMojo extends UpdatePropertiesMojoBase * * @since 1.0-alpha-1 */ - @Parameter( property = "includeProperties" ) + @Parameter(property = "includeProperties") private String includeProperties = null; /** @@ -64,16 +64,16 @@ public class UpdatePropertiesMojo extends UpdatePropertiesMojoBase * * @since 1.0-alpha-1 */ - @Parameter( property = "excludeProperties" ) + @Parameter(property = "excludeProperties") private String excludeProperties = null; @Inject - public UpdatePropertiesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UpdatePropertiesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -84,18 +84,18 @@ public UpdatePropertiesMojo( RepositorySystem repositorySystem, * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - update( pom, getHelper().getVersionPropertiesMap( - VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( getProject() ) - .withPropertyDefinitions( properties ) - .withIncludeProperties( includeProperties ) - .withExcludeProperties( excludeProperties ) - .withAutoLinkItems( autoLinkItems ) - .withIncludeParent( includeParent ) - .build() ) ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + update( + pom, + getHelper() + .getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(getProject()) + .withPropertyDefinitions(properties) + .withIncludeProperties(includeProperties) + .withExcludeProperties(excludeProperties) + .withAutoLinkItems(autoLinkItems) + .withIncludeParent(includeParent) + .build())); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java index 8baa1eda0b..40f1d87aaf 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java @@ -18,6 +18,11 @@ * under the License. */ +import javax.xml.stream.XMLStreamException; + +import java.util.Map; +import java.util.Optional; + import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.plugin.MojoExecutionException; @@ -34,24 +39,19 @@ import org.codehaus.mojo.versions.recording.DefaultChangeRecord; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import javax.xml.stream.XMLStreamException; -import java.util.Map; -import java.util.Optional; - import static org.codehaus.mojo.versions.utils.SegmentUtils.determineUnchangedSegment; /** * Common base class for {@link UpdatePropertiesMojo} * and {@link UpdatePropertyMojo} */ -public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependencyUpdaterMojo -{ +public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependencyUpdaterMojo { /** * Whether properties linking versions should be auto-detected or not. * * @since 1.0-alpha-2 */ - @Parameter( property = "autoLinkItems", defaultValue = "true" ) + @Parameter(property = "autoLinkItems", defaultValue = "true") protected boolean autoLinkItems; /** @@ -61,7 +61,7 @@ public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependenc * * @since 3.0.0 */ - @Parameter( property = "allowDowngrade", defaultValue = "false" ) + @Parameter(property = "allowDowngrade", defaultValue = "false") protected boolean allowDowngrade; /** @@ -69,7 +69,7 @@ public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependenc * * @since 2.4 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") protected boolean allowMajorUpdates; /** @@ -79,7 +79,7 @@ public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependenc * * @since 2.4 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") protected boolean allowMinorUpdates; /** @@ -90,7 +90,7 @@ public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependenc * * @since 2.4 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") protected boolean allowIncrementalUpdates; /** @@ -100,80 +100,66 @@ public abstract class UpdatePropertiesMojoBase extends AbstractVersionsDependenc * * @since 2.14.0 */ - - @Parameter( property = "includeParent", defaultValue = "true" ) + @Parameter(property = "includeParent", defaultValue = "true") protected boolean includeParent = true; - public UpdatePropertiesMojoBase( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UpdatePropertiesMojoBase( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } - protected void update( ModifiedPomXMLEventReader pom, Map propertyVersions ) - throws XMLStreamException - { - for ( Map.Entry entry : propertyVersions.entrySet() ) - { + protected void update(ModifiedPomXMLEventReader pom, Map propertyVersions) + throws XMLStreamException { + for (Map.Entry entry : propertyVersions.entrySet()) { Property property = entry.getKey(); PropertyVersions version = entry.getValue(); - final String currentVersion = getProject().getProperties().getProperty( property.getName() ); - if ( currentVersion == null ) - { + final String currentVersion = getProject().getProperties().getProperty(property.getName()); + if (currentVersion == null) { continue; } boolean canUpdateProperty = true; - for ( ArtifactAssociation association : version.getAssociations() ) - { - if ( !( isIncluded( association.getArtifact() ) ) ) - { - getLog().info( - "Not updating the property ${" + property.getName() + "} because it is used by artifact " - + association.getArtifact().toString() - + " and that artifact is not included in the list of " - + " allowed artifacts to be updated." ); + for (ArtifactAssociation association : version.getAssociations()) { + if (!(isIncluded(association.getArtifact()))) { + getLog().info("Not updating the property ${" + property.getName() + + "} because it is used by artifact " + + association.getArtifact().toString() + + " and that artifact is not included in the list of " + + " allowed artifacts to be updated."); canUpdateProperty = false; break; } } - if ( canUpdateProperty ) - { - Optional unchangedSegment = determineUnchangedSegment( allowMajorUpdates, allowMinorUpdates, - allowIncrementalUpdates, getLog() ); - try - { - ArtifactVersion targetVersion = - updatePropertyToNewestVersion( pom, property, version, currentVersion, - allowDowngrade, unchangedSegment ); - - if ( targetVersion != null ) - { - for ( final ArtifactAssociation association : version.getAssociations() ) - { - if ( ( isIncluded( association.getArtifact() ) ) ) - { - getChangeRecorder().recordChange( DefaultChangeRecord.builder() - .withKind( - ChangeRecord.ChangeKind.PROPERTY ) - .withArtifact( association.getArtifact() ) - .withOldVersion( currentVersion ) - .withNewVersion( targetVersion.toString() ) - .build() ); + if (canUpdateProperty) { + Optional unchangedSegment = determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + try { + ArtifactVersion targetVersion = updatePropertyToNewestVersion( + pom, property, version, currentVersion, allowDowngrade, unchangedSegment); + + if (targetVersion != null) { + for (final ArtifactAssociation association : version.getAssociations()) { + if ((isIncluded(association.getArtifact()))) { + getChangeRecorder() + .recordChange(DefaultChangeRecord.builder() + .withKind(ChangeRecord.ChangeKind.PROPERTY) + .withArtifact(association.getArtifact()) + .withOldVersion(currentVersion) + .withNewVersion(targetVersion.toString()) + .build()); } } } - } - catch ( InvalidSegmentException | InvalidVersionSpecificationException | MojoExecutionException e ) - { - getLog().warn( String.format( "Skipping the processing of %s:%s due to: %s", property.getName(), - property.getVersion(), e.getMessage() ) ); + } catch (InvalidSegmentException | InvalidVersionSpecificationException | MojoExecutionException e) { + getLog().warn(String.format( + "Skipping the processing of %s:%s due to: %s", + property.getName(), property.getVersion(), e.getMessage())); } } - } } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertyMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertyMojo.java index 2fc55cf48e..a541fbf139 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertyMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertyMojo.java @@ -19,6 +19,11 @@ * under the License. */ +import javax.inject.Inject; +import javax.xml.stream.XMLStreamException; + +import java.util.Map; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; @@ -30,25 +35,20 @@ import org.codehaus.mojo.versions.api.recording.ChangeRecorder; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import javax.inject.Inject; -import javax.xml.stream.XMLStreamException; -import java.util.Map; - /** * Sets a property to the latest version in a given range of associated artifacts. * * @author Eric Pabst * @since 1.3 */ -@Mojo( name = "update-property", threadSafe = true ) -public class UpdatePropertyMojo extends UpdatePropertiesMojoBase -{ +@Mojo(name = "update-property", threadSafe = true) +public class UpdatePropertyMojo extends UpdatePropertiesMojoBase { /** * A property to update. * * @since 1.3 */ - @Parameter( property = "property" ) + @Parameter(property = "property") protected String property = null; /** @@ -67,16 +67,16 @@ public class UpdatePropertyMojo extends UpdatePropertiesMojoBase * * @since 1.3 */ - @Parameter( property = "newVersion" ) + @Parameter(property = "newVersion") private String newVersion = null; @Inject - public UpdatePropertyMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UpdatePropertyMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -87,20 +87,23 @@ public UpdatePropertyMojo( RepositorySystem repositorySystem, * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException - { - update( pom, getHelper().getVersionPropertiesMap( - VersionsHelper.VersionPropertiesMapRequest.builder() - .withMavenProject( getProject() ) - .withPropertyDefinitions( new Property[] { new Property( property ) - {{ - setVersion( newVersion ); - }} } ) - .withIncludeProperties( property ) - .withAutoLinkItems( autoLinkItems ) - .withIncludeParent( includeParent ) - .build() ) ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException { + update( + pom, + getHelper() + .getVersionPropertiesMap(VersionsHelper.VersionPropertiesMapRequest.builder() + .withMavenProject(getProject()) + .withPropertyDefinitions(new Property[] { + new Property(property) { + { + setVersion(newVersion); + } + } + }) + .withIncludeProperties(property) + .withAutoLinkItems(autoLinkItems) + .withIncludeParent(includeParent) + .build())); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseDepVersionMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseDepVersionMojo.java index 1972443640..70c06daf60 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseDepVersionMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseDepVersionMojo.java @@ -52,117 +52,96 @@ * @author Dan Arcari * @since 2.3 */ -@Mojo( name = "use-dep-version", threadSafe = true ) -public class UseDepVersionMojo extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "use-dep-version", threadSafe = true) +public class UseDepVersionMojo extends AbstractVersionsDependencyUpdaterMojo { /** * The exact version to be applied for the included dependencies */ - @Parameter( property = "depVersion", - required = true ) + @Parameter(property = "depVersion", required = true) protected String depVersion; /** * If set to true, will use whatever version is supplied without attempting to validate that such a version is * obtainable from the repository chain. */ - @Parameter( property = "forceVersion", - defaultValue = "false" ) + @Parameter(property = "forceVersion", defaultValue = "false") protected boolean forceVersion; @Inject - public UseDepVersionMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseDepVersionMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } @Override - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { - if ( depVersion == null || depVersion.equals( "" ) ) - { + if (depVersion == null || depVersion.equals("")) { throw new IllegalArgumentException( - "depVersion must be supplied with use-specific-version, and cannot be blank." ); + "depVersion must be supplied with use-specific-version, and cannot be blank."); } - if ( !forceVersion && !hasIncludes() ) - { + if (!forceVersion && !hasIncludes()) { throw new IllegalArgumentException( - "The use-specific-version goal is intended to be used with a single artifact. " - + "Please specify a value for the 'includes' parameter, " - + "or use -DforceVersion=true to override this check." ); + "The use-specific-version goal is intended to be used with a single artifact. " + + "Please specify a value for the 'includes' parameter, " + + "or use -DforceVersion=true to override this check."); } - try - { - if ( isProcessingDependencyManagement() ) - { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useDepVersion( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useDepVersion( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useDepVersion( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useDepVersion(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useDepVersion( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useDepVersion(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useDepVersion( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws MojoExecutionException, XMLStreamException, VersionRetrievalException - { - for ( Dependency dep : dependencies ) - { - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { - getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + private void useDepVersion( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws MojoExecutionException, XMLStreamException, VersionRetrievalException { + for (Dependency dep : dependencies) { + if (isExcludeReactor() && isProducedByReactor(dep)) { + getLog().info("Ignoring reactor dependency: " + toString(dep)); continue; } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } - Artifact artifact = this.toArtifact( dep ); + Artifact artifact = this.toArtifact(dep); - if ( isIncluded( artifact ) ) - { - if ( !forceVersion ) - { - ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false ); + if (isIncluded(artifact)) { + if (!forceVersion) { + ArtifactVersions versions = getHelper().lookupArtifactVersions(artifact, false); - if ( !versions.containsVersion( depVersion ) ) - { - throw new MojoExecutionException( - String.format( "Version %s is not available for artifact %s:%s", - depVersion, artifact.getGroupId(), artifact.getArtifactId() ) ); + if (!versions.containsVersion(depVersion)) { + throw new MojoExecutionException(String.format( + "Version %s is not available for artifact %s:%s", + depVersion, artifact.getGroupId(), artifact.getArtifactId())); } } - updateDependencyVersion( pom, dep, depVersion, changeKind ); + updateDependencyVersion(pom, dep, depVersion, changeKind); } } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java index 5202196bc5..44c5d57c7a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java @@ -62,10 +62,8 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "use-latest-releases", threadSafe = true ) -public class UseLatestReleasesMojo - extends UseLatestVersionsMojoBase -{ +@Mojo(name = "use-latest-releases", threadSafe = true) +public class UseLatestReleasesMojo extends UseLatestVersionsMojoBase { // ------------------------------ FIELDS ------------------------------ @@ -74,7 +72,7 @@ public class UseLatestReleasesMojo * * @since 1.2 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") protected boolean allowMajorUpdates = true; /** @@ -84,7 +82,7 @@ public class UseLatestReleasesMojo * * @since 1.2 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") protected boolean allowMinorUpdates = true; /** @@ -95,18 +93,18 @@ public class UseLatestReleasesMojo * * @since 1.2 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") protected boolean allowIncrementalUpdates = true; // ------------------------------ METHODS -------------------------- @Inject - public UseLatestReleasesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseLatestReleasesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -116,60 +114,50 @@ public UseLatestReleasesMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see org.codehaus.mojo.versions.AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useLatestReleases( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useLatestReleases( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useLatestReleases( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useLatestReleases(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useLatestReleases( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useLatestReleases(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useLatestReleases( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( allowMajorUpdates, - allowMinorUpdates, allowIncrementalUpdates, getLog() ); - - useLatestVersions( pom, dependencies, - ( dep, versions ) -> - { - try - { - return getLastFiltered( versions.getNewerVersions( dep.getVersion(), unchangedSegment, - false, false ), dep ); - } - catch ( InvalidSegmentException e ) - { - getLog().warn( String.format( "Skipping the processing of %s:%s:%s due to: %s", - dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), e.getMessage() ) ); + private void useLatestReleases( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + + useLatestVersions( + pom, + dependencies, + (dep, versions) -> { + try { + return getLastFiltered( + versions.getNewerVersions(dep.getVersion(), unchangedSegment, false, false), dep); + } catch (InvalidSegmentException e) { + getLog().warn(String.format( + "Skipping the processing of %s:%s:%s due to: %s", + dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), e.getMessage())); } return empty(); }, - changeKind, dep -> !SNAPSHOT_REGEX.matcher( dep.getVersion() ).matches() ); + changeKind, + dep -> !SNAPSHOT_REGEX.matcher(dep.getVersion()).matches()); } /** @@ -180,18 +168,20 @@ private void useLatestReleases( ModifiedPomXMLEventReader pom, Collection getLastFiltered( ArtifactVersion[] newer, Dependency dependency ) - { - return Arrays.stream( newer ) - .filter( version -> - { - Artifact artefactWithNewVersion = - new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), - VersionRange.createFromVersion( version.toString() ), dependency.getScope(), - dependency.getType(), null, new DefaultArtifactHandler(), false ); - return isIncluded( artefactWithNewVersion ); - } ) - .reduce( ( v1, v2 ) -> v2 ); + private Optional getLastFiltered(ArtifactVersion[] newer, Dependency dependency) { + return Arrays.stream(newer) + .filter(version -> { + Artifact artefactWithNewVersion = new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + VersionRange.createFromVersion(version.toString()), + dependency.getScope(), + dependency.getType(), + null, + new DefaultArtifactHandler(), + false); + return isIncluded(artefactWithNewVersion); + }) + .reduce((v1, v2) -> v2); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java index f1f86dfa82..4f7b38636c 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java @@ -55,17 +55,15 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "use-latest-snapshots", threadSafe = true ) -public class UseLatestSnapshotsMojo - extends UseLatestVersionsMojoBase -{ +@Mojo(name = "use-latest-snapshots", threadSafe = true) +public class UseLatestSnapshotsMojo extends UseLatestVersionsMojoBase { /** * Whether to allow the major version number to be changed. * * @since 1.0-beta-1 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "false" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "false") protected boolean allowMajorUpdates; /** @@ -74,7 +72,7 @@ public class UseLatestSnapshotsMojo *

Note: {@code false} also implies {@linkplain #allowMajorUpdates} {@code false}

* @since 1.0-beta-1 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "false" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "false") protected boolean allowMinorUpdates; /** @@ -84,18 +82,18 @@ public class UseLatestSnapshotsMojo * and {@linkplain #allowMinorUpdates} {@code false}

* @since 1.0-beta-1 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") protected boolean allowIncrementalUpdates; // ------------------------------ METHODS -------------------------- @Inject - public UseLatestSnapshotsMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseLatestSnapshotsMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -105,60 +103,49 @@ public UseLatestSnapshotsMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useLatestSnapshots( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useLatestSnapshots( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useLatestSnapshots( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useLatestSnapshots(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useLatestSnapshots( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useLatestSnapshots(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useLatestSnapshots( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( allowMajorUpdates, - allowMinorUpdates, allowIncrementalUpdates, getLog() ); + private void useLatestSnapshots( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); - useLatestVersions( pom, dependencies, - ( dep, versions ) -> - { - try - { - return Arrays.stream( versions.getNewerVersions( dep.getVersion(), unchangedSegment, - true, false ) ) - .filter( v -> SNAPSHOT_REGEX.matcher( v.toString() ).matches() ) - .max( Comparator.naturalOrder() ); - } - catch ( InvalidSegmentException e ) - { - getLog().info( "Ignoring " + toString( dep ) + " as the version number is too short" ); + useLatestVersions( + pom, + dependencies, + (dep, versions) -> { + try { + return Arrays.stream(versions.getNewerVersions(dep.getVersion(), unchangedSegment, true, false)) + .filter(v -> + SNAPSHOT_REGEX.matcher(v.toString()).matches()) + .max(Comparator.naturalOrder()); + } catch (InvalidSegmentException e) { + getLog().info("Ignoring " + toString(dep) + " as the version number is too short"); return empty(); } }, - changeKind, dep -> !SNAPSHOT_REGEX.matcher( dep.getVersion() ).matches() ); + changeKind, + dep -> !SNAPSHOT_REGEX.matcher(dep.getVersion()).matches()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java index 8021f2fb38..a600a98ce7 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java @@ -53,16 +53,14 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "use-latest-versions", threadSafe = true ) -public class UseLatestVersionsMojo - extends UseLatestVersionsMojoBase -{ +@Mojo(name = "use-latest-versions", threadSafe = true) +public class UseLatestVersionsMojo extends UseLatestVersionsMojoBase { /** * Whether to allow the major version number to be changed. * * @since 1.2 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "true") private boolean allowMajorUpdates = true; /** @@ -71,7 +69,7 @@ public class UseLatestVersionsMojo *

Note: {@code false} also implies {@linkplain #allowMajorUpdates} {@code false}

* @since 1.2 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "true" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "true") private boolean allowMinorUpdates = true; /** @@ -81,7 +79,7 @@ public class UseLatestVersionsMojo * and {@linkplain #allowMinorUpdates} {@code false}

* @since 1.2 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") private boolean allowIncrementalUpdates = true; /** @@ -91,27 +89,24 @@ public class UseLatestVersionsMojo * * @since 2.12.0 */ - @Parameter( property = "allowDowngrade", - defaultValue = "false" ) + @Parameter(property = "allowDowngrade", defaultValue = "false") private boolean allowDowngrade; // ------------------------------ METHODS -------------------------- @Inject - public UseLatestVersionsMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseLatestVersionsMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } @Override - public void execute() throws MojoExecutionException, MojoFailureException - { - if ( allowDowngrade && allowSnapshots ) - { - throw new MojoExecutionException( "allowDowngrade is only valid with allowSnapshots equal to false" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (allowDowngrade && allowSnapshots) { + throw new MojoExecutionException("allowDowngrade is only valid with allowSnapshots equal to false"); } super.execute(); } @@ -123,58 +118,48 @@ public void execute() throws MojoExecutionException, MojoFailureException * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useLatestVersions( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useLatestVersions( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useLatestVersions( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useLatestVersions(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useLatestVersions( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useLatestVersions(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useLatestVersions( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( allowMajorUpdates, - allowMinorUpdates, allowIncrementalUpdates, getLog() ); + private void useLatestVersions( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); - useLatestVersions( pom, dependencies, - ( dep, versions ) -> - { - try - { - return versions.getNewestVersion( dep.getVersion(), unchangedSegment, allowSnapshots, - allowDowngrade ); - } - catch ( InvalidSegmentException e ) - { - getLog().warn( String.format( "Skipping the processing of %s:%s:%s due to: %s", - dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), e.getMessage() ) ); + useLatestVersions( + pom, + dependencies, + (dep, versions) -> { + try { + return versions.getNewestVersion( + dep.getVersion(), unchangedSegment, allowSnapshots, allowDowngrade); + } catch (InvalidSegmentException e) { + getLog().warn(String.format( + "Skipping the processing of %s:%s:%s due to: %s", + dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), e.getMessage())); } return empty(); - }, changeKind ); + }, + changeKind); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojoBase.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojoBase.java index 1b76bd9e0c..41c7692001 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojoBase.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojoBase.java @@ -45,15 +45,13 @@ * Common base class for {@link UseLatestVersionsMojo} * and {@link UseLatestReleasesMojo} */ -public abstract class UseLatestVersionsMojoBase - extends AbstractVersionsDependencyUpdaterMojo -{ - public UseLatestVersionsMojoBase( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); +public abstract class UseLatestVersionsMojoBase extends AbstractVersionsDependencyUpdaterMojo { + public UseLatestVersionsMojoBase( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -71,50 +69,43 @@ public UseLatestVersionsMojoBase( RepositorySystem repositorySystem, * @throws VersionRetrievalException thrown if an artifact versions cannot be retrieved */ @SafeVarargs - protected final void useLatestVersions( ModifiedPomXMLEventReader pom, - Collection dependencies, - BiFunction> - newestVersionProducer, - ChangeRecord.ChangeKind changeKind, - Predicate... filters ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - for ( Dependency dep : dependencies ) - { - if ( !Arrays.stream( filters ) - .map( f -> f.test( dep ) ) - .reduce( Boolean::logicalAnd ) - .orElse( true ) ) - { + protected final void useLatestVersions( + ModifiedPomXMLEventReader pom, + Collection dependencies, + BiFunction> newestVersionProducer, + ChangeRecord.ChangeKind changeKind, + Predicate... filters) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + for (Dependency dep : dependencies) { + if (!Arrays.stream(filters) + .map(f -> f.test(dep)) + .reduce(Boolean::logicalAnd) + .orElse(true)) { continue; } - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { - getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + if (isExcludeReactor() && isProducedByReactor(dep)) { + getLog().info("Ignoring reactor dependency: " + toString(dep)); continue; } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } - Artifact artifact = toArtifact( dep ); - if ( !isIncluded( artifact ) ) - { + Artifact artifact = toArtifact(dep); + if (!isIncluded(artifact)) { continue; } - ArtifactVersion selectedVersion = new DefaultArtifactVersion( dep.getVersion() ); - getLog().debug( "Selected version:" + selectedVersion ); - getLog().debug( "Looking for newer versions of " + toString( dep ) ); - ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false ); - Optional newestVer = newestVersionProducer.apply( dep, versions ); - if ( newestVer.isPresent() ) - { - updateDependencyVersion( pom, dep, newestVer.get().toString(), changeKind ); + ArtifactVersion selectedVersion = new DefaultArtifactVersion(dep.getVersion()); + getLog().debug("Selected version:" + selectedVersion); + getLog().debug("Looking for newer versions of " + toString(dep)); + ArtifactVersions versions = getHelper().lookupArtifactVersions(artifact, false); + Optional newestVer = newestVersionProducer.apply(dep, versions); + if (newestVer.isPresent()) { + updateDependencyVersion(pom, dep, newestVer.get().toString(), changeKind); } } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextReleasesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextReleasesMojo.java index 70e86055e1..ca5bb9b027 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextReleasesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextReleasesMojo.java @@ -49,27 +49,25 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "use-next-releases", threadSafe = true ) -public class UseNextReleasesMojo - extends UseLatestVersionsMojoBase -{ +@Mojo(name = "use-next-releases", threadSafe = true) +public class UseNextReleasesMojo extends UseLatestVersionsMojoBase { // ------------------------------ FIELDS ------------------------------ /** * Pattern to match a snapshot version. */ - private static final Pattern MATCH_SNAPSHOT_REGEX = Pattern.compile( "^(.+)-((SNAPSHOT)|(\\d{8}\\.\\d{6}-\\d+))$" ); + private static final Pattern MATCH_SNAPSHOT_REGEX = Pattern.compile("^(.+)-((SNAPSHOT)|(\\d{8}\\.\\d{6}-\\d+))$"); // ------------------------------ METHODS -------------------------- @Inject - public UseNextReleasesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseNextReleasesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -79,45 +77,38 @@ public UseNextReleasesMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useNextReleases( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useNextReleases( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useNextReleases( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useNextReleases(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useNextReleases( pom, singletonList( getParentDependency() ), ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useNextReleases(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useNextReleases( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - useLatestVersions( pom, dependencies, - ( dep, versions ) -> of( versions.getNewerVersions( dep.getVersion(), false )[0] ), - changeKind, - dep -> !SNAPSHOT_REGEX.matcher( dep.getVersion() ).matches() ); + private void useNextReleases( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + useLatestVersions( + pom, + dependencies, + (dep, versions) -> of(versions.getNewerVersions(dep.getVersion(), false)[0]), + changeKind, + dep -> !SNAPSHOT_REGEX.matcher(dep.getVersion()).matches()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java index 7d5483afa1..12378ad8ca 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java @@ -54,17 +54,15 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -@Mojo( name = "use-next-snapshots", threadSafe = true ) -public class UseNextSnapshotsMojo - extends UseLatestVersionsMojoBase -{ +@Mojo(name = "use-next-snapshots", threadSafe = true) +public class UseNextSnapshotsMojo extends UseLatestVersionsMojoBase { /** * Whether to allow the major version number to be changed. * * @since 1.0-beta-1 */ - @Parameter( property = "allowMajorUpdates", defaultValue = "false" ) + @Parameter(property = "allowMajorUpdates", defaultValue = "false") private boolean allowMajorUpdates; /** @@ -73,7 +71,7 @@ public class UseNextSnapshotsMojo *

Note: {@code false} also implies {@linkplain #allowMajorUpdates} {@code false}

* @since 1.0-beta-1 */ - @Parameter( property = "allowMinorUpdates", defaultValue = "false" ) + @Parameter(property = "allowMinorUpdates", defaultValue = "false") private boolean allowMinorUpdates; /** @@ -83,18 +81,18 @@ public class UseNextSnapshotsMojo * and {@linkplain #allowMinorUpdates} {@code false}

* @since 1.0-beta-1 */ - @Parameter( property = "allowIncrementalUpdates", defaultValue = "true" ) + @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") private boolean allowIncrementalUpdates; // ------------------------------ METHODS -------------------------- @Inject - public UseNextSnapshotsMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseNextSnapshotsMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); // the below is necessary for UseLatestVersionsMojoBase.useLatestVersions to select snapshots allowSnapshots = true; } @@ -106,57 +104,47 @@ public UseNextSnapshotsMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see org.codehaus.mojo.versions.AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useNextSnapshots( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useNextSnapshots( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useNextSnapshots( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useNextSnapshots(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useNextSnapshots( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useNextSnapshots(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useNextSnapshots( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - Optional - unchangedSegment = SegmentUtils.determineUnchangedSegment( allowMajorUpdates, allowMinorUpdates, - allowIncrementalUpdates, getLog() ); + private void useNextSnapshots( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); - useLatestVersions( pom, dependencies, - ( dep, versions ) -> - { - try - { - return Arrays.stream( versions.getNewerVersions( dep.getVersion(), unchangedSegment, - true, false ) ) - .filter( v -> SNAPSHOT_REGEX.matcher( v.toString() ).matches() ) + useLatestVersions( + pom, + dependencies, + (dep, versions) -> { + try { + return Arrays.stream(versions.getNewerVersions(dep.getVersion(), unchangedSegment, true, false)) + .filter(v -> + SNAPSHOT_REGEX.matcher(v.toString()).matches()) .findFirst(); - } - catch ( InvalidSegmentException e ) - { - getLog().info( "Ignoring " + toString( dep ) + " as the version number is too short" ); + } catch (InvalidSegmentException e) { + getLog().info("Ignoring " + toString(dep) + " as the version number is too short"); return empty(); } - }, changeKind, dep -> !SNAPSHOT_REGEX.matcher( dep.getVersion() ).matches() ); + }, + changeKind, + dep -> !SNAPSHOT_REGEX.matcher(dep.getVersion()).matches()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextVersionsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextVersionsMojo.java index 67abe9b090..7e3654f79b 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextVersionsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextVersionsMojo.java @@ -48,20 +48,18 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "use-next-versions", threadSafe = true ) -public class UseNextVersionsMojo - extends UseLatestVersionsMojoBase -{ +@Mojo(name = "use-next-versions", threadSafe = true) +public class UseNextVersionsMojo extends UseLatestVersionsMojoBase { // ------------------------------ METHODS -------------------------- @Inject - public UseNextVersionsMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseNextVersionsMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -71,43 +69,35 @@ public UseNextVersionsMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see org.codehaus.mojo.versions.AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useNextVersions( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useNextVersions( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useNextVersions( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useNextVersions(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useNextVersions( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useNextVersions(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useNextVersions( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - useLatestVersions( pom, dependencies, - ( dep, versions ) -> of( versions.getNewerVersions( dep.getVersion(), allowSnapshots )[0] ), - changeKind ); + private void useNextVersions( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + useLatestVersions( + pom, + dependencies, + (dep, versions) -> of(versions.getNewerVersions(dep.getVersion(), allowSnapshots)[0]), + changeKind); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReactorMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReactorMojo.java index 552dda2e82..3ea2f47113 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReactorMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReactorMojo.java @@ -47,20 +47,18 @@ * @author Stephen Connolly * @since 2.2 */ -@Mojo( name = "use-reactor", threadSafe = true ) -public class UseReactorMojo - extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "use-reactor", threadSafe = true) +public class UseReactorMojo extends AbstractVersionsDependencyUpdaterMojo { // ------------------------------ METHODS -------------------------- @Inject - public UseReactorMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseReactorMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -70,58 +68,49 @@ public UseReactorMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingParent() && getProject().hasParent() ) - { - useReactor( pom, getProject().getParent() ); + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingParent() && getProject().hasParent()) { + useReactor(pom, getProject().getParent()); } - if ( isProcessingDependencyManagement() ) - { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useReactor( pom, dependencyManagement.getDependencies() ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useReactor(pom, dependencyManagement.getDependencies()); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useReactor( pom, getProject().getDependencies() ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useReactor(pom, getProject().getDependencies()); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useReactor( ModifiedPomXMLEventReader pom, Collection dependencies ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { + private void useReactor(ModifiedPomXMLEventReader pom, Collection dependencies) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { - for ( Dependency dep : dependencies ) - { - Artifact artifact = this.toArtifact( dep ); - if ( !isIncluded( artifact ) ) - { + for (Dependency dep : dependencies) { + Artifact artifact = this.toArtifact(dep); + if (!isIncluded(artifact)) { continue; } - for ( MavenProject reactorProject : reactorProjects ) - { + for (MavenProject reactorProject : reactorProjects) { MavenProject project = reactorProject; - if ( StringUtils.equals( project.getGroupId(), dep.getGroupId() ) - && StringUtils.equals( project.getArtifactId(), dep.getArtifactId() ) - && !StringUtils.equals( project.getVersion(), dep.getVersion() ) ) - { - if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), - project.getVersion(), getProject().getModel() ) ) - { - getLog().info( "Updated " + toString( dep ) + " to version " + project.getVersion() ); + if (StringUtils.equals(project.getGroupId(), dep.getGroupId()) + && StringUtils.equals(project.getArtifactId(), dep.getArtifactId()) + && !StringUtils.equals(project.getVersion(), dep.getVersion())) { + if (PomHelper.setDependencyVersion( + pom, + dep.getGroupId(), + dep.getArtifactId(), + dep.getVersion(), + project.getVersion(), + getProject().getModel())) { + getLog().info("Updated " + toString(dep) + " to version " + project.getVersion()); } break; } @@ -129,22 +118,16 @@ private void useReactor( ModifiedPomXMLEventReader pom, Collection d } } - private void useReactor( ModifiedPomXMLEventReader pom, MavenProject parent ) - throws XMLStreamException, VersionRetrievalException - { - for ( MavenProject project : reactorProjects ) - { - if ( StringUtils.equals( project.getGroupId(), parent.getGroupId() ) - && StringUtils.equals( project.getArtifactId(), parent.getArtifactId() ) - && !StringUtils.equals( project.getVersion(), parent.getVersion() ) ) - { - if ( PomHelper.setProjectParentVersion( pom, project.getVersion() ) ) - { - getLog().info( "Updated parent " + toString( parent ) + " to version " + project.getVersion() ); + private void useReactor(ModifiedPomXMLEventReader pom, MavenProject parent) + throws XMLStreamException, VersionRetrievalException { + for (MavenProject project : reactorProjects) { + if (StringUtils.equals(project.getGroupId(), parent.getGroupId()) + && StringUtils.equals(project.getArtifactId(), parent.getArtifactId()) + && !StringUtils.equals(project.getVersion(), parent.getVersion())) { + if (PomHelper.setProjectParentVersion(pom, project.getVersion())) { + getLog().info("Updated parent " + toString(parent) + " to version " + project.getVersion()); } } - } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReleasesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReleasesMojo.java index 89ffbf8938..7bdda8be44 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReleasesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseReleasesMojo.java @@ -54,10 +54,8 @@ * @author Stephen Connolly * @since 1.0-alpha-3 */ -@Mojo( name = "use-releases", threadSafe = true ) -public class UseReleasesMojo - extends AbstractVersionsDependencyUpdaterMojo -{ +@Mojo(name = "use-releases", threadSafe = true) +public class UseReleasesMojo extends AbstractVersionsDependencyUpdaterMojo { /** *

When set to {@code true}, will use the highest found release version matching a string @@ -68,7 +66,7 @@ public class UseReleasesMojo * * @since 2.3 */ - @Parameter( property = "allowRangeMatching", defaultValue = "false" ) + @Parameter(property = "allowRangeMatching", defaultValue = "false") private boolean allowRangeMatching; /** @@ -76,18 +74,18 @@ public class UseReleasesMojo * * @since 2.3 */ - @Parameter( property = "failIfNotReplaced", defaultValue = "false" ) + @Parameter(property = "failIfNotReplaced", defaultValue = "false") protected boolean failIfNotReplaced; // ------------------------------ METHODS -------------------------- @Inject - public UseReleasesMojo( RepositorySystem repositorySystem, - org.eclipse.aether.RepositorySystem aetherRepositorySystem, - Map wagonMap, - Map changeRecorders ) - { - super( repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders ); + public UseReleasesMojo( + RepositorySystem repositorySystem, + org.eclipse.aether.RepositorySystem aetherRepositorySystem, + Map wagonMap, + Map changeRecorders) { + super(repositorySystem, aetherRepositorySystem, wagonMap, changeRecorders); } /** @@ -97,105 +95,86 @@ public UseReleasesMojo( RepositorySystem repositorySystem, * @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming * @see org.codehaus.mojo.versions.AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ - protected void update( ModifiedPomXMLEventReader pom ) - throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException - { - try - { - if ( isProcessingDependencyManagement() ) - { + protected void update(ModifiedPomXMLEventReader pom) + throws MojoExecutionException, MojoFailureException, XMLStreamException, VersionRetrievalException { + try { + if (isProcessingDependencyManagement()) { DependencyManagement dependencyManagement = - PomHelper.getRawModel( getProject() ).getDependencyManagement(); - if ( dependencyManagement != null ) - { - useReleases( pom, dependencyManagement.getDependencies(), - ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ); + PomHelper.getRawModel(getProject()).getDependencyManagement(); + if (dependencyManagement != null) { + useReleases( + pom, dependencyManagement.getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT); } } - if ( getProject().getDependencies() != null && isProcessingDependencies() ) - { - useReleases( pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY ); + if (getProject().getDependencies() != null && isProcessingDependencies()) { + useReleases(pom, getProject().getDependencies(), ChangeRecord.ChangeKind.DEPENDENCY); } - if ( getProject().getParent() != null && isProcessingParent() ) - { - useReleases( pom, singletonList( getParentDependency() ), - ChangeRecord.ChangeKind.PARENT ); + if (getProject().getParent() != null && isProcessingParent()) { + useReleases(pom, singletonList(getParentDependency()), ChangeRecord.ChangeKind.PARENT); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - private void useReleases( ModifiedPomXMLEventReader pom, Collection dependencies, - ChangeRecord.ChangeKind changeKind ) - throws XMLStreamException, MojoExecutionException, VersionRetrievalException - { - for ( Dependency dep : dependencies ) - { - if ( isExcludeReactor() && isProducedByReactor( dep ) ) - { - getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + private void useReleases( + ModifiedPomXMLEventReader pom, Collection dependencies, ChangeRecord.ChangeKind changeKind) + throws XMLStreamException, MojoExecutionException, VersionRetrievalException { + for (Dependency dep : dependencies) { + if (isExcludeReactor() && isProducedByReactor(dep)) { + getLog().info("Ignoring reactor dependency: " + toString(dep)); continue; } - if ( isHandledByProperty( dep ) ) - { - getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) ); + if (isHandledByProperty(dep)) { + getLog().debug("Ignoring dependency with property as version: " + toString(dep)); continue; } String version = dep.getVersion(); - if ( version == null ) - { - getLog().info( "Ignoring dependency with no version: " + toString( dep ) ); + if (version == null) { + getLog().info("Ignoring dependency with no version: " + toString(dep)); continue; } - Matcher versionMatcher = SNAPSHOT_REGEX.matcher( version ); - if ( versionMatcher.matches() ) - { - String releaseVersion = versionMatcher.group( 1 ); - Artifact artifact = this.toArtifact( dep ); - if ( !isIncluded( artifact ) ) - { + Matcher versionMatcher = SNAPSHOT_REGEX.matcher(version); + if (versionMatcher.matches()) { + String releaseVersion = versionMatcher.group(1); + Artifact artifact = this.toArtifact(dep); + if (!isIncluded(artifact)) { continue; } - getLog().debug( "Looking for a release of " + toString( dep ) ); + getLog().debug("Looking for a release of " + toString(dep)); // Force releaseVersion version because org.apache.maven.artifact.metadata.MavenMetadataSource does not // retrieve release version if provided snapshot version. - artifact.setVersion( releaseVersion ); - Optional targetVersion = findReleaseVersion( pom, dep, version, releaseVersion, - getHelper().lookupArtifactVersions( artifact, false ) ); - if ( targetVersion.isPresent() ) - { - updateDependencyVersion( pom, dep, targetVersion.get(), changeKind ); - } - else - { - getLog().info( "No matching release of " + toString( dep ) + " to update." ); - if ( failIfNotReplaced ) - { - throw new MojoExecutionException( "No matching release of " + toString( dep ) - + " found for update" ); + artifact.setVersion(releaseVersion); + Optional targetVersion = findReleaseVersion( + pom, dep, version, releaseVersion, getHelper().lookupArtifactVersions(artifact, false)); + if (targetVersion.isPresent()) { + updateDependencyVersion(pom, dep, targetVersion.get(), changeKind); + } else { + getLog().info("No matching release of " + toString(dep) + " to update."); + if (failIfNotReplaced) { + throw new MojoExecutionException( + "No matching release of " + toString(dep) + " found for update"); } } } } } - private Optional findReleaseVersion( ModifiedPomXMLEventReader pom, Dependency dep, String version, - String releaseVersion, ArtifactVersions versions ) - { + private Optional findReleaseVersion( + ModifiedPomXMLEventReader pom, + Dependency dep, + String version, + String releaseVersion, + ArtifactVersions versions) { return !allowRangeMatching - ? versions.containsVersion( releaseVersion ) - ? Optional.of( releaseVersion ) - : Optional.empty() - : Arrays.stream( versions.getVersions( false ) ) - .sorted( ( v1, v2 ) -> -( v1.compareTo( v2 ) ) ) - .filter( v -> v.toString().startsWith( releaseVersion ) ) - .findFirst() - .map( ArtifactVersion::toString ); + ? versions.containsVersion(releaseVersion) ? Optional.of(releaseVersion) : Optional.empty() + : Arrays.stream(versions.getVersions(false)) + .sorted((v1, v2) -> -(v1.compareTo(v2))) + .filter(v -> v.toString().startsWith(releaseVersion)) + .findFirst() + .map(ArtifactVersion::toString); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/AbstractVersionsReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/AbstractVersionsReportRenderer.java index 0b5117d9f3..632fec930a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/AbstractVersionsReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/AbstractVersionsReportRenderer.java @@ -52,8 +52,7 @@ * @author Stephen Connolly * @since 1.0-beta-1 */ -public abstract class AbstractVersionsReportRenderer extends VersionsReportRendererBase implements ReportRenderer -{ +public abstract class AbstractVersionsReportRenderer extends VersionsReportRendererBase implements ReportRenderer { /** * Model of the object being rendered @@ -62,32 +61,29 @@ public abstract class AbstractVersionsReportRenderer extends VersionsReportRe */ protected T model; - protected final ArtifactVersionsCache newestUpdateCache - = new ArtifactVersionsCache( AbstractVersionDetails::getReportNewestUpdate ); + protected final ArtifactVersionsCache newestUpdateCache = + new ArtifactVersionsCache(AbstractVersionDetails::getReportNewestUpdate); - protected final ArtifactVersionsCache allUpdatesCache - = new ArtifactVersionsCache( AbstractVersionDetails::getReportUpdates ); + protected final ArtifactVersionsCache allUpdatesCache = + new ArtifactVersionsCache(AbstractVersionDetails::getReportUpdates); - protected final SinkEventAttributes headerAttributes - = new SinkEventAttributeSet( SinkEventAttributes.WIDTH, "30%" ); + protected final SinkEventAttributes headerAttributes = new SinkEventAttributeSet(SinkEventAttributes.WIDTH, "30%"); - protected AbstractVersionsReportRenderer( I18N i18n, Sink sink, Locale locale, String bundleName, T model ) - { - super( sink, i18n, locale, bundleName ); + protected AbstractVersionsReportRenderer(I18N i18n, Sink sink, Locale locale, String bundleName, T model) { + super(sink, i18n, locale, bundleName); this.model = model; } /** * {@inheritDoc} */ - protected void renderBody() - { + protected void renderBody() { sink.section1(); sink.sectionTitle1(); - sink.text( getText( "report.overview.title" ) ); + sink.text(getText("report.overview.title")); sink.sectionTitle1_(); sink.paragraph(); - sink.text( getText( "report.overview.text" ) ); + sink.text(getText("report.overview.text")); sink.paragraph_(); renderOverview(); @@ -99,10 +95,10 @@ protected void renderBody() sink.section1(); sink.sectionTitle1(); - sink.text( getText( "report.detail.title" ) ); + sink.text(getText("report.detail.title")); sink.sectionTitle1_(); sink.paragraph(); - sink.text( getText( "report.detail.text" ) ); + sink.text(getText("report.detail.text")); sink.paragraph_(); renderDetails(); @@ -113,11 +109,10 @@ protected void renderBody() /** * Renders the "Overview" table */ - protected void renderOverview() - { + protected void renderOverview() { sink.table(); sink.tableRow(); - renderOverviewTableRow( computeOverviewStats() ); + renderOverviewTableRow(computeOverviewStats()); sink.tableRow_(); sink.table_(); } @@ -137,13 +132,12 @@ protected void renderOverview() * @param stats summary statistics object to render * @param concrete {@linkplain OverviewStats} class */ - protected void renderOverviewTableRow( Q stats ) - { - renderStatRow( "report.overview.numUpToDate", stats.getUpToDate(), true ); - renderStatRow( "report.overview.numNewerVersionAvailable", stats.getAny(), false ); - renderStatRow( "report.overview.numNewerIncrementalAvailable", stats.getIncremental(), false ); - renderStatRow( "report.overview.numNewerMinorAvailable", stats.getMinor(), false ); - renderStatRow( "report.overview.numNewerMajorAvailable", stats.getMajor(), false ); + protected void renderOverviewTableRow(Q stats) { + renderStatRow("report.overview.numUpToDate", stats.getUpToDate(), true); + renderStatRow("report.overview.numNewerVersionAvailable", stats.getAny(), false); + renderStatRow("report.overview.numNewerIncrementalAvailable", stats.getIncremental(), false); + renderStatRow("report.overview.numNewerMinorAvailable", stats.getMinor(), false); + renderStatRow("report.overview.numNewerMajorAvailable", stats.getMajor(), false); } /** @@ -152,17 +146,16 @@ protected void renderOverviewTableRow( Q stats ) * @param statCount the number of artifacts with the given stat. * @param forceSuccessIcon if true, the success icon will be rendered regardless. */ - protected void renderStatRow( String textKey, int statCount, boolean forceSuccessIcon ) - { + protected void renderStatRow(String textKey, int statCount, boolean forceSuccessIcon) { sink.tableRow(); sink.tableCell(); - renderIcon( statCount == 0 || forceSuccessIcon ); + renderIcon(statCount == 0 || forceSuccessIcon); sink.tableCell_(); sink.tableCell(); - sink.text( getText( textKey ) ); + sink.text(getText(textKey)); sink.tableCell_(); sink.tableCell(); - sink.text( Integer.toString( statCount ) ); + sink.text(Integer.toString(statCount)); sink.tableCell_(); sink.tableRow_(); } @@ -171,14 +164,10 @@ protected void renderStatRow( String textKey, int statCount, boolean forceSucces * Renders the success or warning icon. * @param success if true, the success icon will be rendered, otherwise the warning icon will be rendered. */ - protected void renderIcon( boolean success ) - { - if ( success ) - { + protected void renderIcon(boolean success) { + if (success) { renderSuccessIcon(); - } - else - { + } else { renderWarningIcon(); } } @@ -195,59 +184,51 @@ protected void renderIcon( boolean success ) */ protected abstract void renderDetails(); - protected void renderSummaryTable( Map contents, boolean hasScope ) - { + protected void renderSummaryTable(Map contents, boolean hasScope) { sink.table(); sink.tableRow(); - renderSummaryTableHeader( hasScope, true ); + renderSummaryTableHeader(hasScope, true); sink.tableRow_(); - contents.forEach( ( artifact, artifactVersions ) -> - renderSummaryTableRow( artifact, artifactVersions, hasScope ) ); + contents.forEach((artifact, artifactVersions) -> renderSummaryTableRow(artifact, artifactVersions, hasScope)); sink.tableRow(); - renderSummaryTableHeader( hasScope, true ); + renderSummaryTableHeader(hasScope, true); sink.tableRow_(); sink.table_(); } - protected void renderSummaryTableHeader( boolean hasScope, boolean hasType ) - { - renderTableHeaderCells( "report.status", "report.groupId", "report.artifactId", - "report.currentVersion" ); - if ( hasScope ) - { - renderTableHeaderCells( "report.scope" ); + protected void renderSummaryTableHeader(boolean hasScope, boolean hasType) { + renderTableHeaderCells("report.status", "report.groupId", "report.artifactId", "report.currentVersion"); + if (hasScope) { + renderTableHeaderCells("report.scope"); } - if ( hasType ) - { - renderTableHeaderCells( "report.classifier", "report.type" ); + if (hasType) { + renderTableHeaderCells("report.classifier", "report.type"); } - renderTableHeaderCells( "report.latestSubIncremental", - "report.latestIncremental", "report.latestMinor", "report.latestMajor" ); + renderTableHeaderCells( + "report.latestSubIncremental", "report.latestIncremental", "report.latestMinor", "report.latestMajor"); } - protected void renderSummaryTableRow( Dependency artifact, ArtifactVersions details, boolean includeScope ) - { - details.setCurrentVersion( artifact.getVersion() ); - ArtifactVersion[] allUpdates = allUpdatesCache.get( details, empty() ); + protected void renderSummaryTableRow(Dependency artifact, ArtifactVersions details, boolean includeScope) { + details.setCurrentVersion(artifact.getVersion()); + ArtifactVersion[] allUpdates = allUpdatesCache.get(details, empty()); boolean upToDate = allUpdates == null || allUpdates.length == 0; sink.tableRow(); sink.tableCell(); - renderIcon( upToDate ); + renderIcon(upToDate); sink.tableCell_(); - renderCells( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() ); - if ( includeScope ) - { - renderCell( artifact.getScope() ); + renderCells(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + if (includeScope) { + renderCell(artifact.getScope()); } - renderCells( artifact.getClassifier(), artifact.getType() ); - renderNewestVersions( details ); + renderCells(artifact.getClassifier(), artifact.getType()); + renderNewestVersions(details); sink.tableRow_(); } @@ -256,35 +237,31 @@ protected void renderSummaryTableRow( Dependency artifact, ArtifactVersions deta * Renders the newest versions for the given artifact. * @param details the artifact for which to render the newest versions. */ - protected void renderNewestVersions( AbstractVersionDetails details ) - { - renderBoldCell( newestUpdateCache.get( details, of( SUBINCREMENTAL ) ) ); - renderBoldCell( newestUpdateCache.get( details, of( INCREMENTAL ) ) ); - renderBoldCell( newestUpdateCache.get( details, of( MINOR ) ) ); - renderBoldCell( newestUpdateCache.get( details, of( MAJOR ) ) ); + protected void renderNewestVersions(AbstractVersionDetails details) { + renderBoldCell(newestUpdateCache.get(details, of(SUBINCREMENTAL))); + renderBoldCell(newestUpdateCache.get(details, of(INCREMENTAL))); + renderBoldCell(newestUpdateCache.get(details, of(MINOR))); + renderBoldCell(newestUpdateCache.get(details, of(MAJOR))); } - protected void renderDependencyDetailTable( Dependency artifact, ArtifactVersions details, boolean includeScope ) - { - ArtifactVersion[] allUpdates = allUpdatesCache.get( details, empty() ); + protected void renderDependencyDetailTable(Dependency artifact, ArtifactVersions details, boolean includeScope) { + ArtifactVersion[] allUpdates = allUpdatesCache.get(details, empty()); boolean upToDate = allUpdates == null || allUpdates.length == 0; sink.table(); - sink.tableRows( new int[] { Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT }, false ); - - renderTwoCellsRow( "report.status", () -> renderStatus( details ) ); - renderTwoCellsRow( "report.groupId", artifact.getGroupId() ); - renderTwoCellsRow( "report.artifactId", artifact.getArtifactId() ); - renderTwoCellsRow( "report.currentVersion", artifact.getVersion() ); - if ( includeScope ) - { - renderTwoCellsRow( "report.scope", artifact.getScope() ); + sink.tableRows(new int[] {Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT}, false); + + renderTwoCellsRow("report.status", () -> renderStatus(details)); + renderTwoCellsRow("report.groupId", artifact.getGroupId()); + renderTwoCellsRow("report.artifactId", artifact.getArtifactId()); + renderTwoCellsRow("report.currentVersion", artifact.getVersion()); + if (includeScope) { + renderTwoCellsRow("report.scope", artifact.getScope()); } - renderTwoCellsRow( "report.classifier", artifact.getClassifier() ); - renderTwoCellsRow( "report.type", artifact.getType() ); - if ( !upToDate ) - { - renderTwoCellsRow( "report.updateVersions", () -> renderVersions( allUpdates, details ) ); + renderTwoCellsRow("report.classifier", artifact.getClassifier()); + renderTwoCellsRow("report.type", artifact.getType()); + if (!upToDate) { + renderTwoCellsRow("report.updateVersions", () -> renderVersions(allUpdates, details)); } sink.tableRows_(); @@ -296,14 +273,13 @@ protected void renderDependencyDetailTable( Dependency artifact, ArtifactVersion * @param textKey the key of the text to be rendered. * @param textValue the value of the text to be rendered. */ - protected void renderTwoCellsRow( String textKey, String textValue ) - { + protected void renderTwoCellsRow(String textKey, String textValue) { sink.tableRow(); - sink.tableHeaderCell( headerAttributes ); - sink.text( getText( textKey ) ); + sink.tableHeaderCell(headerAttributes); + sink.text(getText(textKey)); sink.tableHeaderCell_(); sink.tableCell(); - sink.text( textValue ); + sink.text(textValue); sink.tableCell_(); sink.tableRow_(); } @@ -313,11 +289,10 @@ protected void renderTwoCellsRow( String textKey, String textValue ) * @param textKey the key of the text to be rendered. * @param runnable the runnable to be executed to render the second cell content. */ - protected void renderTwoCellsRow( String textKey, Runnable runnable ) - { + protected void renderTwoCellsRow(String textKey, Runnable runnable) { sink.tableRow(); - sink.tableHeaderCell( headerAttributes ); - sink.text( getText( textKey ) ); + sink.tableHeaderCell(headerAttributes); + sink.text(getText(textKey)); sink.tableHeaderCell_(); sink.tableCell(); runnable.run(); @@ -329,37 +304,27 @@ protected void renderTwoCellsRow( String textKey, Runnable runnable ) * Renders the status of the given artifact. * @param details the artifact for which to render the status. */ - protected void renderStatus( AbstractVersionDetails details ) - { - if ( newestUpdateCache.get( details, of( SUBINCREMENTAL ) ) != null ) - { + protected void renderStatus(AbstractVersionDetails details) { + if (newestUpdateCache.get(details, of(SUBINCREMENTAL)) != null) { renderWarningIcon(); sink.nonBreakingSpace(); - sink.text( getText( "report.otherUpdatesAvailable" ) ); - } - else if ( newestUpdateCache.get( details, of( INCREMENTAL ) ) != null ) - { + sink.text(getText("report.otherUpdatesAvailable")); + } else if (newestUpdateCache.get(details, of(INCREMENTAL)) != null) { renderWarningIcon(); sink.nonBreakingSpace(); - sink.text( getText( "report.incrementalUpdatesAvailable" ) ); - } - else if ( newestUpdateCache.get( details, of( MINOR ) ) != null ) - { + sink.text(getText("report.incrementalUpdatesAvailable")); + } else if (newestUpdateCache.get(details, of(MINOR)) != null) { renderWarningIcon(); sink.nonBreakingSpace(); - sink.text( getText( "report.minorUpdatesAvailable" ) ); - } - else if ( newestUpdateCache.get( details, of( MAJOR ) ) != null ) - { + sink.text(getText("report.minorUpdatesAvailable")); + } else if (newestUpdateCache.get(details, of(MAJOR)) != null) { renderWarningIcon(); sink.nonBreakingSpace(); - sink.text( getText( "report.majorUpdatesAvailable" ) ); - } - else - { + sink.text(getText("report.majorUpdatesAvailable")); + } else { renderSuccessIcon(); sink.nonBreakingSpace(); - sink.text( getText( "report.noUpdatesAvailable" ) ); + sink.text(getText("report.noUpdatesAvailable")); } } @@ -369,17 +334,13 @@ else if ( newestUpdateCache.get( details, of( MAJOR ) ) != null ) * @param details the artifact or property for which to render the versions. * @return the list of restrictions for the spec versions range. */ - private List getArtifactVersionRange( AbstractVersionDetails details ) - { - try - { + private List getArtifactVersionRange(AbstractVersionDetails details) { + try { String spec = details.getCurrentVersion().toString(); - VersionRange range = VersionRange.createFromVersionSpec( spec ); + VersionRange range = VersionRange.createFromVersionSpec(spec); return range.getRestrictions(); - } - catch ( InvalidVersionSpecificationException ignored ) - { - ignored.printStackTrace( System.err ); + } catch (InvalidVersionSpecificationException ignored) { + ignored.printStackTrace(System.err); } return Collections.EMPTY_LIST; } @@ -389,50 +350,42 @@ private List getArtifactVersionRange( AbstractVersionDetails detail * @param allUpdates the list of all updates available. * @param details the versions details for the given artifact or property. */ - protected void renderVersions( ArtifactVersion[] allUpdates, AbstractVersionDetails details ) - { - List versionRange = getArtifactVersionRange( details ); + protected void renderVersions(ArtifactVersion[] allUpdates, AbstractVersionDetails details) { + List versionRange = getArtifactVersionRange(details); boolean someNotAllowed = false; - for ( int i = 0; i < allUpdates.length; i++ ) - { - if ( i > 0 ) - { + for (int i = 0; i < allUpdates.length; i++) { + if (i > 0) { sink.lineBreak(); } // if candidate version in range, display no star. ArtifactVersion candidate = allUpdates[i]; - boolean allowed = versionRange.stream().anyMatch( restriction -> - details.isVersionInRestriction( restriction, candidate ) ); - String label = getLabel( allUpdates[i], details ); - if ( !allowed ) - { - sink.text( "* " ); + boolean allowed = versionRange.stream() + .anyMatch(restriction -> details.isVersionInRestriction(restriction, candidate)); + String label = getLabel(allUpdates[i], details); + if (!allowed) { + sink.text("* "); someNotAllowed = true; } - if ( allowed && label != null ) - { + if (allowed && label != null) { safeBold(); } - sink.text( allUpdates[i].toString() ); - if ( label != null ) - { - if ( allowed ) - { + sink.text(allUpdates[i].toString()); + if (label != null) { + if (allowed) { safeBold_(); } sink.nonBreakingSpace(); safeItalic(); - sink.text( label ); + sink.text(label); safeItalic_(); } } - if ( someNotAllowed ) - { + if (someNotAllowed) { sink.lineBreak(); sink.lineBreak(); - sink.text( "* " ); + sink.text("* "); safeItalic(); - sink.text( getText( "report.excludedVersion" ) ); + sink.text(getText("report.excludedVersion")); safeItalic_(); } } @@ -443,30 +396,24 @@ protected void renderVersions( ArtifactVersion[] allUpdates, AbstractVersionDeta * @param details the artifact for which to render the versions. * @return a text label to describe if the given version is a major, minor, incremental or subincremental update. */ - protected String getLabel( ArtifactVersion version, AbstractVersionDetails details ) - { + protected String getLabel(ArtifactVersion version, AbstractVersionDetails details) { - if ( equals( version, newestUpdateCache.get( details, of( SUBINCREMENTAL ) ) ) ) - { - return getText( "report.latestSubIncremental" ); + if (equals(version, newestUpdateCache.get(details, of(SUBINCREMENTAL)))) { + return getText("report.latestSubIncremental"); } - if ( equals( version, newestUpdateCache.get( details, of( INCREMENTAL ) ) ) ) - { - return getText( "report.latestIncremental" ); + if (equals(version, newestUpdateCache.get(details, of(INCREMENTAL)))) { + return getText("report.latestIncremental"); } - if ( equals( version, newestUpdateCache.get( details, of( MINOR ) ) ) ) - { - return getText( "report.latestMinor" ); + if (equals(version, newestUpdateCache.get(details, of(MINOR)))) { + return getText("report.latestMinor"); } - if ( equals( version, newestUpdateCache.get( details, of( MAJOR ) ) ) ) - { - return getText( "report.latestMajor" ); + if (equals(version, newestUpdateCache.get(details, of(MAJOR)))) { + return getText("report.latestMajor"); } return null; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/DependencyUpdatesReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/DependencyUpdatesReportRenderer.java index 8072e31192..4e81d32161 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/DependencyUpdatesReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/DependencyUpdatesReportRenderer.java @@ -33,70 +33,60 @@ * @param type of the model * @since 1.0-beta-1 */ -public class DependencyUpdatesReportRenderer extends AbstractVersionsReportRenderer -{ - public DependencyUpdatesReportRenderer( I18N i18n, Sink sink, Locale locale, String bundleName, K model ) - { - super( i18n, sink, locale, bundleName, model ); +public class DependencyUpdatesReportRenderer + extends AbstractVersionsReportRenderer { + public DependencyUpdatesReportRenderer(I18N i18n, Sink sink, Locale locale, String bundleName, K model) { + super(i18n, sink, locale, bundleName, model); } /** * {@inheritDoc} */ @Override - protected void renderDetails() - { - model.getAllUpdates().forEach( this::renderDependencyDetail ); + protected void renderDetails() { + model.getAllUpdates().forEach(this::renderDependencyDetail); } @Override - protected void renderSummaryTable() - { - renderTable( "report.overview.dependency", model.getArtifactUpdates(), - "report.overview.noDependency" ); + protected void renderSummaryTable() { + renderTable("report.overview.dependency", model.getArtifactUpdates(), "report.overview.noDependency"); } @Override - protected void renderManagementSummaryTable() - { - renderTable( "report.overview.dependencyManagement", - model.getArtifactManagementUpdates(), "report.overview.noDependencyManagement" ); + protected void renderManagementSummaryTable() { + renderTable( + "report.overview.dependencyManagement", + model.getArtifactManagementUpdates(), + "report.overview.noDependencyManagement"); } - protected void renderTable( String titleKey, Map contents, String emptyKey ) - { + protected void renderTable(String titleKey, Map contents, String emptyKey) { sink.section2(); sink.sectionTitle2(); - sink.text( getText( titleKey ) ); + sink.text(getText(titleKey)); sink.sectionTitle2_(); - if ( contents.isEmpty() ) - { + if (contents.isEmpty()) { sink.paragraph(); - sink.text( getText( emptyKey ) ); + sink.text(getText(emptyKey)); sink.paragraph_(); - } - else - { - renderSummaryTable( contents, true ); + } else { + renderSummaryTable(contents, true); } sink.section2_(); } @Override - protected OverviewStats computeOverviewStats() - { - return OverviewStats.fromUpdates( model.getAllUpdates().values(), newestUpdateCache ); + protected OverviewStats computeOverviewStats() { + return OverviewStats.fromUpdates(model.getAllUpdates().values(), newestUpdateCache); } - protected void renderDependencyDetail( Dependency artifact, ArtifactVersions details ) - { + protected void renderDependencyDetail(Dependency artifact, ArtifactVersions details) { sink.section2(); sink.sectionTitle2(); - sink.text( ArtifactUtils.versionlessKey( artifact.getGroupId(), artifact.getArtifactId() ) ); + sink.text(ArtifactUtils.versionlessKey(artifact.getGroupId(), artifact.getArtifactId())); sink.sectionTitle2_(); - renderDependencyDetailTable( artifact, details, true ); + renderDependencyDetailTable(artifact, details, true); sink.section2_(); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java index d822d67b3b..cb30cc74a8 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java @@ -1,6 +1,5 @@ package org.codehaus.mojo.versions.reporting; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -40,8 +39,7 @@ * * @author Andrzej Jarmoniuk */ -public class OverviewStats -{ +public class OverviewStats { private int major; private int minor; @@ -64,90 +62,67 @@ public class OverviewStats * @param subclass of {@linkplain ArtifactVersions} * @return instance of the {@linkplain OverviewStats} */ - public static - T fromUpdates( Collection updates, ArtifactVersionsCache cache ) - { + public static T fromUpdates( + Collection updates, ArtifactVersionsCache cache) { OverviewStats stats = new OverviewStats(); - updates.forEach( details -> - { - if ( getNewestUpdate( cache, details, of( SUBINCREMENTAL ) ) != null ) - { + updates.forEach(details -> { + if (getNewestUpdate(cache, details, of(SUBINCREMENTAL)) != null) { stats.incrementAny(); - } - else if ( getNewestUpdate( cache, details, of( INCREMENTAL ) ) != null ) - { + } else if (getNewestUpdate(cache, details, of(INCREMENTAL)) != null) { stats.incrementIncremental(); - } - else if ( getNewestUpdate( cache, details, of( MINOR ) ) != null ) - { + } else if (getNewestUpdate(cache, details, of(MINOR)) != null) { stats.incrementMinor(); - } - else if ( getNewestUpdate( cache, details, of( MAJOR ) ) != null ) - { + } else if (getNewestUpdate(cache, details, of(MAJOR)) != null) { stats.incrementMajor(); - } - else - { + } else { stats.incrementUpToDate(); } - } ); + }); return (T) stats; } - protected static ArtifactVersion getNewestUpdate( ArtifactVersionsCache cache, - V details, - Optional segment ) - { - return cache != null ? cache.get( details, segment ) : details.getNewestUpdate( segment ); + protected static ArtifactVersion getNewestUpdate( + ArtifactVersionsCache cache, V details, Optional segment) { + return cache != null ? cache.get(details, segment) : details.getNewestUpdate(segment); } - public int getMajor() - { + public int getMajor() { return major; } - public void incrementMajor() - { + public void incrementMajor() { major++; } - public int getMinor() - { + public int getMinor() { return minor; } - public void incrementMinor() - { + public void incrementMinor() { minor++; } - public int getIncremental() - { + public int getIncremental() { return incremental; } - public void incrementIncremental() - { + public void incrementIncremental() { incremental++; } - public int getAny() - { + public int getAny() { return any; } - public void incrementAny() - { + public void incrementAny() { any++; } - public int getUpToDate() - { + public int getUpToDate() { return upToDate; } - public void incrementUpToDate() - { + public void incrementUpToDate() { upToDate++; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ParentUpdatesReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ParentUpdatesReportRenderer.java index 63ea6fc969..003c23e468 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ParentUpdatesReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ParentUpdatesReportRenderer.java @@ -28,21 +28,15 @@ /** * @since 1.0-beta-1 */ -public class ParentUpdatesReportRenderer extends DependencyUpdatesReportRenderer -{ - public ParentUpdatesReportRenderer( I18N i18n, Sink sink, Locale locale, String bundleName, - ParentUpdatesModel model ) - { - super( i18n, sink, locale, bundleName, model ); +public class ParentUpdatesReportRenderer extends DependencyUpdatesReportRenderer { + public ParentUpdatesReportRenderer( + I18N i18n, Sink sink, Locale locale, String bundleName, ParentUpdatesModel model) { + super(i18n, sink, locale, bundleName, model); } @Override - protected void renderOverview() - { - } + protected void renderOverview() {} @Override - protected void renderManagementSummaryTable() - { - } + protected void renderManagementSummaryTable() {} } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java index 25494f7869..57186cb688 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java @@ -33,20 +33,17 @@ import static org.codehaus.mojo.versions.api.Segment.MINOR; import static org.codehaus.mojo.versions.api.Segment.SUBINCREMENTAL; -public class PluginOverviewStats extends OverviewStats -{ +public class PluginOverviewStats extends OverviewStats { /** * Extension of the {@linkplain OverviewStats} adding dependency stats */ private int dependencies; - public int getDependencies() - { + public int getDependencies() { return dependencies; } - public void incrementDependencies() - { + public void incrementDependencies() { dependencies++; } @@ -61,37 +58,25 @@ public void incrementDependencies() * @param always equal to {@linkplain PluginUpdatesDetails} * @return instance of the {@linkplain PluginOverviewStats}, initialised with the update information */ - public static - T fromUpdates( Collection updates, ArtifactVersionsCache cache ) - { + public static T fromUpdates( + Collection updates, ArtifactVersionsCache cache) { PluginOverviewStats stats = new PluginOverviewStats(); - updates.forEach( details -> - { - if ( getNewestUpdate( cache, details, of( SUBINCREMENTAL ) ) != null ) - { + updates.forEach(details -> { + if (getNewestUpdate(cache, details, of(SUBINCREMENTAL)) != null) { stats.incrementAny(); - } - else if ( getNewestUpdate( cache, details, of( INCREMENTAL ) ) != null ) - { + } else if (getNewestUpdate(cache, details, of(INCREMENTAL)) != null) { stats.incrementIncremental(); - } - else if ( getNewestUpdate( cache, details, of( MINOR ) ) != null ) - { + } else if (getNewestUpdate(cache, details, of(MINOR)) != null) { stats.incrementMinor(); - } - else if ( getNewestUpdate( cache, details, of( MAJOR ) ) != null ) - { + } else if (getNewestUpdate(cache, details, of(MAJOR)) != null) { stats.incrementMajor(); - } - else - { + } else { stats.incrementUpToDate(); } - if ( ( ( PluginUpdatesDetails ) details ).isDependencyUpdateAvailable() ) - { + if (((PluginUpdatesDetails) details).isDependencyUpdateAvailable()) { stats.incrementDependencies(); } - } ); + }); return (T) stats; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginUpdatesReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginUpdatesReportRenderer.java index bd0e3c2b24..bf5efe6164 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginUpdatesReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginUpdatesReportRenderer.java @@ -37,80 +37,71 @@ /** * @since 1.0-beta-1 */ -public class PluginUpdatesReportRenderer extends AbstractVersionsReportRenderer -{ +public class PluginUpdatesReportRenderer extends AbstractVersionsReportRenderer { - public PluginUpdatesReportRenderer( I18N i18n, Sink sink, Locale locale, String bundleName, - PluginUpdatesModel model ) - { - super( i18n, sink, locale, bundleName, model ); + public PluginUpdatesReportRenderer( + I18N i18n, Sink sink, Locale locale, String bundleName, PluginUpdatesModel model) { + super(i18n, sink, locale, bundleName, model); } @Override - protected void renderSummaryTable() - { - renderTable( "report.overview.plugin", model.getArtifactUpdates(), - "report.overview.noPlugin" ); + protected void renderSummaryTable() { + renderTable("report.overview.plugin", model.getArtifactUpdates(), "report.overview.noPlugin"); } - protected void renderManagementSummaryTable() - { - renderTable( "report.overview.pluginManagement", model.getArtifactManagementUpdates(), - "report.overview.noPluginManagement" ); + protected void renderManagementSummaryTable() { + renderTable( + "report.overview.pluginManagement", + model.getArtifactManagementUpdates(), + "report.overview.noPluginManagement"); } /** * {@inheritDoc} */ @Override - protected void renderDetails() - { - model.getAllUpdates().forEach( this::renderPluginDetail ); + protected void renderDetails() { + model.getAllUpdates().forEach(this::renderPluginDetail); } - private void renderDependencyDetail( Dependency dependency, ArtifactVersions details ) - { + private void renderDependencyDetail(Dependency dependency, ArtifactVersions details) { sink.section3(); sink.sectionTitle3(); - sink.text( MessageFormat.format( getText( "report.pluginDependency" ), - ArtifactUtils.versionlessKey( dependency.getGroupId(), dependency.getArtifactId() ) ) ); + sink.text(MessageFormat.format( + getText("report.pluginDependency"), + ArtifactUtils.versionlessKey(dependency.getGroupId(), dependency.getArtifactId()))); sink.sectionTitle3_(); - renderDependencyDetailTable( dependency, details, false ); + renderDependencyDetailTable(dependency, details, false); sink.section3_(); } - private void renderTable( String titleKey, Map contents, String emptyKey ) - { + private void renderTable(String titleKey, Map contents, String emptyKey) { sink.section2(); sink.sectionTitle2(); - sink.text( getText( titleKey ) ); + sink.text(getText(titleKey)); sink.sectionTitle2_(); - if ( contents.isEmpty() ) - { + if (contents.isEmpty()) { sink.paragraph(); - sink.text( getText( emptyKey ) ); + sink.text(getText(emptyKey)); sink.paragraph_(); - } - else - { - renderSummaryTable( contents ); + } else { + renderSummaryTable(contents); } sink.section2_(); } - protected void renderSummaryTable( Map contents ) - { + protected void renderSummaryTable(Map contents) { sink.table(); sink.tableRow(); - renderSummaryTableHeader( false, false ); + renderSummaryTableHeader(false, false); sink.tableRow_(); - contents.forEach( this::renderSummaryTableRow ); + contents.forEach(this::renderSummaryTableRow); sink.tableRow(); - renderSummaryTableHeader( false, false ); + renderSummaryTableHeader(false, false); sink.tableRow_(); sink.table_(); @@ -120,94 +111,88 @@ protected void renderSummaryTable( Map content * {@inheritDoc} */ @Override - protected PluginOverviewStats computeOverviewStats() - { - return PluginOverviewStats.fromUpdates( model.getAllUpdates().values(), newestUpdateCache ); + protected PluginOverviewStats computeOverviewStats() { + return PluginOverviewStats.fromUpdates(model.getAllUpdates().values(), newestUpdateCache); } @Override - protected void renderSummaryTableHeader( boolean hasScope, boolean hasType ) - { - super.renderSummaryTableHeader( hasScope, hasType ); - renderTableHeaderCells( "report.dependencyStatus" ); + protected void renderSummaryTableHeader(boolean hasScope, boolean hasType) { + super.renderSummaryTableHeader(hasScope, hasType); + renderTableHeaderCells("report.dependencyStatus"); } @Override - protected void renderOverviewTableRow( T stats ) - { - super.renderOverviewTableRow( stats ); - super.renderStatRow( "report.overview.numNewerDependenciesAvailable", - ( (PluginOverviewStats) stats ).getDependencies(), false ); + protected void renderOverviewTableRow(T stats) { + super.renderOverviewTableRow(stats); + super.renderStatRow( + "report.overview.numNewerDependenciesAvailable", + ((PluginOverviewStats) stats).getDependencies(), + false); } - protected void renderSummaryTableRow( Dependency artifact, PluginUpdatesDetails details ) - { + protected void renderSummaryTableRow(Dependency artifact, PluginUpdatesDetails details) { boolean upToDate = !details.isUpdateAvailable(); sink.tableRow(); sink.tableCell(); - renderIcon( upToDate ); + renderIcon(upToDate); sink.tableCell_(); - renderCells( artifact.getGroupId(), artifact.getArtifactId() ); - renderBoldCell( upToDate, artifact.getVersion() ); - renderNewestVersions( details ); + renderCells(artifact.getGroupId(), artifact.getArtifactId()); + renderBoldCell(upToDate, artifact.getVersion()); + renderNewestVersions(details); sink.tableCell(); - renderIcon( !details.isDependencyUpdateAvailable() ); + renderIcon(!details.isDependencyUpdateAvailable()); sink.tableCell_(); sink.tableRow_(); } - private void renderPluginDetail( Dependency artifact, PluginUpdatesDetails details ) - { + private void renderPluginDetail(Dependency artifact, PluginUpdatesDetails details) { sink.section2(); sink.sectionTitle2(); - sink.text( MessageFormat.format( getText( "report.plugin" ), - ArtifactUtils.versionlessKey( details.getGroupId(), details.getArtifactId() ) ) ); + sink.text(MessageFormat.format( + getText("report.plugin"), ArtifactUtils.versionlessKey(details.getGroupId(), details.getArtifactId()))); sink.sectionTitle2_(); - renderPluginDetailTable( details ); + renderPluginDetailTable(details); - if ( !details.getDependencyVersions().isEmpty() ) - { + if (!details.getDependencyVersions().isEmpty()) { sink.section3(); sink.sectionTitle3(); - sink.text( MessageFormat.format( getText( "report.pluginDependencies" ), - ArtifactUtils.versionlessKey( details.getGroupId(), details.getArtifactId() ) ) ); + sink.text(MessageFormat.format( + getText("report.pluginDependencies"), + ArtifactUtils.versionlessKey(details.getGroupId(), details.getArtifactId()))); sink.sectionTitle3_(); - renderSummaryTable( details.getDependencyVersions(), false ); + renderSummaryTable(details.getDependencyVersions(), false); sink.section3_(); - details.getDependencyVersions().forEach( this::renderDependencyDetail ); + details.getDependencyVersions().forEach(this::renderDependencyDetail); } sink.section2_(); } - private void renderPluginDetailTable( PluginUpdatesDetails details ) - { + private void renderPluginDetailTable(PluginUpdatesDetails details) { // warning: using caches here might break plugin report - ArtifactVersion[] allUpdates = details.getAllUpdates( empty() ); + ArtifactVersion[] allUpdates = details.getAllUpdates(empty()); boolean upToDate = allUpdates == null || allUpdates.length == 0; sink.table(); - sink.tableRows( new int[] { Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT }, false ); - - renderTwoCellsRow( "report.status", () -> renderStatus( details ) ); - renderTwoCellsRow( "report.groupId", details.getGroupId() ); - renderTwoCellsRow( "report.artifactId", details.getArtifactId() ); - renderTwoCellsRow( "report.currentVersion", details.getVersion() ); - if ( !upToDate ) - { - renderTwoCellsRow( "report.updateVersions", () -> renderVersions( allUpdates, details ) ); + sink.tableRows(new int[] {Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT}, false); + + renderTwoCellsRow("report.status", () -> renderStatus(details)); + renderTwoCellsRow("report.groupId", details.getGroupId()); + renderTwoCellsRow("report.artifactId", details.getArtifactId()); + renderTwoCellsRow("report.currentVersion", details.getVersion()); + if (!upToDate) { + renderTwoCellsRow("report.updateVersions", () -> renderVersions(allUpdates, details)); } sink.tableRows_(); sink.table_(); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PropertyUpdatesReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PropertyUpdatesReportRenderer.java index 8b79da27b1..88f5ad05c4 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PropertyUpdatesReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PropertyUpdatesReportRenderer.java @@ -25,8 +25,8 @@ import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.doxia.sink.Sink; -import org.codehaus.mojo.versions.api.Property; import org.codehaus.mojo.versions.api.ArtifactAssociation; +import org.codehaus.mojo.versions.api.Property; import org.codehaus.mojo.versions.api.PropertyVersions; import org.codehaus.mojo.versions.reporting.model.PropertyUpdatesModel; import org.codehaus.plexus.i18n.I18N; @@ -36,110 +36,95 @@ /** * @since 1.0-beta-1 */ -public class PropertyUpdatesReportRenderer extends AbstractVersionsReportRenderer -{ - public PropertyUpdatesReportRenderer( I18N i18n, Sink sink, Locale locale, String bundleName, - PropertyUpdatesModel model ) - { - super( i18n, sink, locale, bundleName, model ); +public class PropertyUpdatesReportRenderer extends AbstractVersionsReportRenderer { + public PropertyUpdatesReportRenderer( + I18N i18n, Sink sink, Locale locale, String bundleName, PropertyUpdatesModel model) { + super(i18n, sink, locale, bundleName, model); } @Override - protected void renderManagementSummaryTable() - { - } + protected void renderManagementSummaryTable() {} @Override - protected void renderSummaryTable() - { - renderTable( "report.overview.property", model.getAllUpdates(), - "report.overview.noProperty" ); + protected void renderSummaryTable() { + renderTable("report.overview.property", model.getAllUpdates(), "report.overview.noProperty"); } /** * {@inheritDoc} */ @Override - protected void renderDetails() - { - model.getAllUpdates().forEach( this::renderPropertyDetail ); + protected void renderDetails() { + model.getAllUpdates().forEach(this::renderPropertyDetail); } - protected void renderTable( String titleKey, Map contents, String emptyKey ) - { + protected void renderTable(String titleKey, Map contents, String emptyKey) { sink.section2(); sink.sectionTitle2(); - sink.text( getText( titleKey ) ); + sink.text(getText(titleKey)); sink.sectionTitle2_(); - if ( contents.isEmpty() ) - { + if (contents.isEmpty()) { sink.paragraph(); - sink.text( getText( emptyKey ) ); + sink.text(getText(emptyKey)); sink.paragraph_(); - } - else - { - renderSummaryTable( contents ); + } else { + renderSummaryTable(contents); } sink.section2_(); } - protected void renderSummaryTable( Map contents ) - { + protected void renderSummaryTable(Map contents) { sink.table(); sink.tableRow(); - renderSummaryTableHeader( false, false ); + renderSummaryTableHeader(false, false); sink.tableRow_(); - contents.forEach( this::renderPropertySummaryTableRow ); + contents.forEach(this::renderPropertySummaryTableRow); sink.tableRow(); - renderSummaryTableHeader( false, false ); + renderSummaryTableHeader(false, false); sink.tableRow_(); sink.table_(); } - private void renderPropertySummaryTableRow( Property property, PropertyVersions details ) - { - ArtifactVersion[] allUpdates = allUpdatesCache.get( details, empty() ); + private void renderPropertySummaryTableRow(Property property, PropertyVersions details) { + ArtifactVersion[] allUpdates = allUpdatesCache.get(details, empty()); boolean upToDate = allUpdates == null || allUpdates.length == 0; sink.tableRow(); sink.tableCell(); - renderIcon( upToDate ); + renderIcon(upToDate); sink.tableCell_(); - renderCells( "${" + property.getName() + "}", details.getCurrentVersion() ); - renderNewestVersions( details ); + renderCells("${" + property.getName() + "}", details.getCurrentVersion()); + renderNewestVersions(details); sink.tableRow_(); } - protected void renderPropertyDetailTable( Property property, PropertyVersions details ) - { - ArtifactVersion[] allUpdates = allUpdatesCache.get( details, empty() ); + protected void renderPropertyDetailTable(Property property, PropertyVersions details) { + ArtifactVersion[] allUpdates = allUpdatesCache.get(details, empty()); boolean upToDate = allUpdates == null || allUpdates.length == 0; sink.table(); - sink.tableRows( new int[] { Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT }, false ); - - renderTwoCellsRow( "report.status", () -> renderStatus( details ) ); - renderTwoCellsRow( "report.property", "${" + property.getName() + "}" ); - renderTwoCellsRow( "report.associations", () -> renderAssociations( details ) ); - renderTwoCellsRow( "report.currentVersion", details.getCurrentVersion().toString() ); - if ( !upToDate ) - { - renderTwoCellsRow( "report.updateVersions", () -> renderVersions( allUpdates, details ) ); + sink.tableRows(new int[] {Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT}, false); + + renderTwoCellsRow("report.status", () -> renderStatus(details)); + renderTwoCellsRow("report.property", "${" + property.getName() + "}"); + renderTwoCellsRow("report.associations", () -> renderAssociations(details)); + renderTwoCellsRow("report.currentVersion", details.getCurrentVersion().toString()); + if (!upToDate) { + renderTwoCellsRow("report.updateVersions", () -> renderVersions(allUpdates, details)); } - renderTwoCellsRow( "report.versionRange", details.getCurrentVersion().toString() ); - renderTwoCellsRow( "report.autoLinkDependencies", property.isAutoLinkDependencies() ); - renderTwoCellsRow( "report.banSnapshots", property.isBanSnapshots() ); - renderTwoCellsRow( "report.searchReactor", property.isSearchReactor() ); - renderTwoCellsRow( "report.preferReactor", property.isPreferReactor() ); + renderTwoCellsRow("report.versionRange", details.getCurrentVersion().toString()); + renderTwoCellsRow("report.autoLinkDependencies", property.isAutoLinkDependencies()); + renderTwoCellsRow("report.banSnapshots", property.isBanSnapshots()); + renderTwoCellsRow("report.searchReactor", property.isSearchReactor()); + renderTwoCellsRow("report.preferReactor", property.isPreferReactor()); sink.tableRows_(); sink.table_(); @@ -150,46 +135,43 @@ protected void renderPropertyDetailTable( Property property, PropertyVersions de * @param textKey the key of the text to be rendered in the header cell. * @param b a yes/no value to be rendered in the non-header cell. */ - private void renderTwoCellsRow( String textKey, boolean b ) - { - renderTwoCellsRow( textKey, getText( b ? "report.yes" : "report.no" ) ); + private void renderTwoCellsRow(String textKey, boolean b) { + renderTwoCellsRow(textKey, getText(b ? "report.yes" : "report.no")); } - private void renderAssociations( PropertyVersions details ) - { + private void renderAssociations(PropertyVersions details) { ArtifactAssociation[] associations = details.getAssociations(); - for ( int i = 0; i < associations.length; i++ ) - { - if ( i > 0 ) - { + for (int i = 0; i < associations.length; i++) { + if (i > 0) { sink.lineBreak(); } - sink.text( ArtifactUtils.versionlessKey( associations[i].getArtifact() ) ); + sink.text(ArtifactUtils.versionlessKey(associations[i].getArtifact())); } } @Override - protected void renderSummaryTableHeader( boolean hasScope, boolean hasType ) - { - renderTableHeaderCells( "report.status", "report.property", "report.currentVersion", - "report.latestSubIncremental", "report.latestIncremental", "report.latestMinor", - "report.latestMajor" ); + protected void renderSummaryTableHeader(boolean hasScope, boolean hasType) { + renderTableHeaderCells( + "report.status", + "report.property", + "report.currentVersion", + "report.latestSubIncremental", + "report.latestIncremental", + "report.latestMinor", + "report.latestMajor"); } @Override - protected OverviewStats computeOverviewStats() - { - return OverviewStats.fromUpdates( model.getAllUpdates().values(), newestUpdateCache ); + protected OverviewStats computeOverviewStats() { + return OverviewStats.fromUpdates(model.getAllUpdates().values(), newestUpdateCache); } - private void renderPropertyDetail( Property property, PropertyVersions details ) - { + private void renderPropertyDetail(Property property, PropertyVersions details) { sink.section2(); sink.sectionTitle2(); - sink.text( "${" + property.getName() + "}" ); + sink.text("${" + property.getName() + "}"); sink.sectionTitle2_(); - renderPropertyDetailTable( property, details ); + renderPropertyDetailTable(property, details); sink.section2_(); } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactory.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactory.java index 1b977ecc5c..56dd9d33cc 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactory.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactory.java @@ -27,8 +27,7 @@ /** * Factory for report renderers */ -public interface ReportRendererFactory -{ +public interface ReportRendererFactory { /** * Creates a new {@linkplain ReportRenderer} instance for the given report renderer name. * @@ -41,6 +40,6 @@ public interface ReportRendererFactory * @return new report renderer * @throws IllegalArgumentException thrown if the report with the given name could not be found */ - T createReportRenderer( String reportName, Sink sink, Locale locale, U model ) + T createReportRenderer(String reportName, Sink sink, Locale locale, U model) throws IllegalArgumentException; } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactoryImpl.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactoryImpl.java index e66a1ad422..81af9c857d 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactoryImpl.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/ReportRendererFactoryImpl.java @@ -38,8 +38,7 @@ */ @Named @Singleton -public class ReportRendererFactoryImpl implements ReportRendererFactory -{ +public class ReportRendererFactoryImpl implements ReportRendererFactory { public static final String DEPENDENCY_UPDATES_REPORT = "dependency-updates-report"; public static final String DEPENDENCY_UPDATES_AGGREGATE_REPORT = "dependency-updates-aggregate-report"; public static final String PLUGIN_UPDATES_REPORT = "plugin-updates-report"; @@ -50,8 +49,7 @@ public class ReportRendererFactoryImpl implements ReportRendererFactory private final I18N i18N; @Inject - public ReportRendererFactoryImpl( I18N i18N ) - { + public ReportRendererFactoryImpl(I18N i18N) { this.i18N = i18N; } @@ -59,31 +57,22 @@ public ReportRendererFactoryImpl( I18N i18N ) * {@inheritDoc} */ @Override - @SuppressWarnings( "unchecked" ) - public T createReportRenderer( String reportName, Sink sink, Locale locale, U model ) - throws IllegalArgumentException - { - if ( DEPENDENCY_UPDATES_REPORT.equals( reportName ) - || DEPENDENCY_UPDATES_AGGREGATE_REPORT.equals( reportName ) ) - { - return (T) new DependencyUpdatesReportRenderer<>( i18N, sink, locale, reportName, - (DependencyUpdatesModel) model ); + @SuppressWarnings("unchecked") + public T createReportRenderer(String reportName, Sink sink, Locale locale, U model) + throws IllegalArgumentException { + if (DEPENDENCY_UPDATES_REPORT.equals(reportName) || DEPENDENCY_UPDATES_AGGREGATE_REPORT.equals(reportName)) { + return (T) new DependencyUpdatesReportRenderer<>( + i18N, sink, locale, reportName, (DependencyUpdatesModel) model); } - if ( PLUGIN_UPDATES_REPORT.equals( reportName ) || PLUGIN_UPDATES_AGGREGATE_REPORT.equals( reportName ) ) - { - return (T) new PluginUpdatesReportRenderer( i18N, sink, locale, reportName, - (PluginUpdatesModel) model ); + if (PLUGIN_UPDATES_REPORT.equals(reportName) || PLUGIN_UPDATES_AGGREGATE_REPORT.equals(reportName)) { + return (T) new PluginUpdatesReportRenderer(i18N, sink, locale, reportName, (PluginUpdatesModel) model); } - if ( PROPERTY_UPDATES_REPORT.equals( reportName ) || PROPERTY_UPDATES_AGGREGATE_REPORT.equals( reportName ) ) - { - return (T) new PropertyUpdatesReportRenderer( i18N, sink, locale, reportName, - (PropertyUpdatesModel) model ); + if (PROPERTY_UPDATES_REPORT.equals(reportName) || PROPERTY_UPDATES_AGGREGATE_REPORT.equals(reportName)) { + return (T) new PropertyUpdatesReportRenderer(i18N, sink, locale, reportName, (PropertyUpdatesModel) model); } - if ( PARENT_UPDATES_REPORT.equals( reportName ) ) - { - return (T) new ParentUpdatesReportRenderer( i18N, sink, locale, reportName, - (ParentUpdatesModel) model ); + if (PARENT_UPDATES_REPORT.equals(reportName)) { + return (T) new ParentUpdatesReportRenderer(i18N, sink, locale, reportName, (ParentUpdatesModel) model); } - throw new IllegalArgumentException( "Invalid report name: " + reportName ); + throw new IllegalArgumentException("Invalid report name: " + reportName); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/VersionsReportRendererBase.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/VersionsReportRendererBase.java index 82472b4eec..9719639752 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/VersionsReportRendererBase.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/VersionsReportRendererBase.java @@ -1,6 +1,5 @@ package org.codehaus.mojo.versions.reporting; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -32,8 +31,7 @@ * Base class over AbstractVersionsReportRenderer providing base * utility methods */ -public abstract class VersionsReportRendererBase extends AbstractMavenReportRenderer -{ +public abstract class VersionsReportRendererBase extends AbstractMavenReportRenderer { /** * Internationalization component. * @@ -53,17 +51,15 @@ public abstract class VersionsReportRendererBase extends AbstractMavenReportRend */ protected String bundleName; - public VersionsReportRendererBase( Sink sink, I18N i18n, Locale locale, String bundleName ) - { - super( sink ); + public VersionsReportRendererBase(Sink sink, I18N i18n, Locale locale, String bundleName) { + super(sink); this.i18n = i18n; this.locale = locale; this.bundleName = bundleName; } - public String getTitle() - { - return getText( "report.title" ); + public String getTitle() { + return getText("report.title"); } /** @@ -72,73 +68,54 @@ public String getTitle() * @param key the message key. * @return the message. */ - public String getText( String key ) - { - return i18n.getString( bundleName, locale, key ); + public String getText(String key) { + return i18n.getString(bundleName, locale, key); } - protected void renderWarningIcon() - { - sink.figureGraphics( "images/icon_warning_sml.gif" ); + protected void renderWarningIcon() { + sink.figureGraphics("images/icon_warning_sml.gif"); } - protected void renderSuccessIcon() - { - sink.figureGraphics( "images/icon_success_sml.gif" ); + protected void renderSuccessIcon() { + sink.figureGraphics("images/icon_success_sml.gif"); } - protected boolean equals( ArtifactVersion v1, ArtifactVersion v2 ) - { - return v1 == v2 || ( v1 != null && v1.equals( v2 ) ) - || ( v1 != null && v2 != null && v1.toString().equals( v2.toString() ) ); + protected boolean equals(ArtifactVersion v1, ArtifactVersion v2) { + return v1 == v2 + || (v1 != null && v1.equals(v2)) + || (v1 != null && v2 != null && v1.toString().equals(v2.toString())); } - protected void safeBold() - { - try - { + protected void safeBold() { + try { sink.bold(); - } - catch ( NoSuchMethodError e ) - { + } catch (NoSuchMethodError e) { // ignore Maven 2.1.0 } } - @SuppressWarnings( "checkstyle:MethodName" ) - protected void safeBold_() - { - try - { + @SuppressWarnings("checkstyle:MethodName") + protected void safeBold_() { + try { sink.bold_(); - } - catch ( NoSuchMethodError e ) - { + } catch (NoSuchMethodError e) { // ignore Maven 2.1.0 } } - protected void safeItalic() - { - try - { + protected void safeItalic() { + try { sink.italic(); - } - catch ( NoSuchMethodError e ) - { + } catch (NoSuchMethodError e) { // ignore Maven 2.1.0 } } - @SuppressWarnings( "checkstyle:MethodName" ) - protected void safeItalic_() - { - try - { + @SuppressWarnings("checkstyle:MethodName") + protected void safeItalic_() { + try { sink.italic_(); - } - catch ( NoSuchMethodError e ) - { + } catch (NoSuchMethodError e) { // ignore Maven 2.1.0 } } @@ -148,43 +125,35 @@ protected void safeItalic_() * @param keys variable argument list containing keys of the property file to retrieve the * headers from */ - protected void renderTableHeaderCells( String... keys ) - { - Arrays.stream( keys ) - .map( this::getText ) - .forEachOrdered( str -> - { - sink.tableHeaderCell(); - sink.text( str ); - sink.tableHeaderCell_(); - } ); + protected void renderTableHeaderCells(String... keys) { + Arrays.stream(keys).map(this::getText).forEachOrdered(str -> { + sink.tableHeaderCell(); + sink.text(str); + sink.tableHeaderCell_(); + }); } /** * Renders a bold table cell containing the given text. * @param object the text to be rendered, or null for an empty cell. */ - protected void renderBoldCell( Object object ) - { - renderBoldCell( true, object ); + protected void renderBoldCell(Object object) { + renderBoldCell(true, object); } /** * Renders a table cell containing the given text. * @param object the text to be rendered, or null for an empty cell. */ - protected void renderCell( Object object ) - { - renderBoldCell( false, object ); + protected void renderCell(Object object) { + renderBoldCell(false, object); } /** * Renders multiple cells containing the given texts. * @param objects the texts to be rendered, null for empty cells. */ - protected void renderCells( Object... objects ) - { - for ( Object object : objects ) - { - renderBoldCell( false, object ); + protected void renderCells(Object... objects) { + for (Object object : objects) { + renderBoldCell(false, object); } } @@ -193,10 +162,9 @@ protected void renderCells( Object... objects ) * @param bold true to render the cell in bold, false otherwise. * @param object the text to be rendered, or null for an empty cell. */ - protected void renderBoldCell( boolean bold, Object object ) - { + protected void renderBoldCell(boolean bold, Object object) { sink.tableCell(); - renderBoldText( bold, object ); + renderBoldText(bold, object); sink.tableCell_(); } @@ -205,24 +173,18 @@ protected void renderBoldCell( boolean bold, Object object ) * @param bold true to render the text in bold, false otherwise. * @param object the text to be rendered, or null for an empty cell. */ - protected void renderBoldText( boolean bold, Object object ) - { - if ( object != null ) - { + protected void renderBoldText(boolean bold, Object object) { + if (object != null) { String text = object.toString(); - if ( !text.isEmpty() ) - { - if ( bold ) - { + if (!text.isEmpty()) { + if (bold) { safeBold(); } - sink.text( text ); - if ( bold ) - { + sink.text(text); + if (bold) { safeBold_(); } } } } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/AbstractUpdatesModel.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/AbstractUpdatesModel.java index f3a6ba6365..d6855b9a31 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/AbstractUpdatesModel.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/AbstractUpdatesModel.java @@ -31,42 +31,38 @@ * Base class for using with the {@linkplain org.codehaus.mojo.versions.api.ReportRenderer} API * @param class extending ArtifactVersion in the constructor */ -public abstract class AbstractUpdatesModel -{ +public abstract class AbstractUpdatesModel { private final Map artifactUpdates; private final Map artifactManagementUpdates; private final Map allUpdates; - public AbstractUpdatesModel( Map artifactUpdates, - Map artifactManagementUpdates, - Function supplier ) - { - this.artifactUpdates = artifactUpdates.entrySet().stream().collect( - () -> new TreeMap<>( DependencyComparator.INSTANCE ), - ( map, entry ) -> map.put( supplier.apply( entry.getKey() ), entry.getValue() ), - Map::putAll ); - this.artifactManagementUpdates = artifactManagementUpdates.entrySet().stream().collect( - () -> new TreeMap<>( DependencyComparator.INSTANCE ), - ( map, entry ) -> map.put( supplier.apply( entry.getKey() ), entry.getValue() ), - Map::putAll ); - allUpdates = new TreeMap<>( DependencyComparator.INSTANCE ); + public AbstractUpdatesModel( + Map artifactUpdates, Map artifactManagementUpdates, Function supplier) { + this.artifactUpdates = artifactUpdates.entrySet().stream() + .collect( + () -> new TreeMap<>(DependencyComparator.INSTANCE), + (map, entry) -> map.put(supplier.apply(entry.getKey()), entry.getValue()), + Map::putAll); + this.artifactManagementUpdates = artifactManagementUpdates.entrySet().stream() + .collect( + () -> new TreeMap<>(DependencyComparator.INSTANCE), + (map, entry) -> map.put(supplier.apply(entry.getKey()), entry.getValue()), + Map::putAll); + allUpdates = new TreeMap<>(DependencyComparator.INSTANCE); // overriding entries from dependencyManagementUpdates with dependencyUpdates - allUpdates.putAll( this.artifactManagementUpdates ); - allUpdates.putAll( this.artifactUpdates ); + allUpdates.putAll(this.artifactManagementUpdates); + allUpdates.putAll(this.artifactUpdates); } - public Map getArtifactUpdates() - { + public Map getArtifactUpdates() { return artifactUpdates; } - public Map getArtifactManagementUpdates() - { + public Map getArtifactManagementUpdates() { return artifactManagementUpdates; } - public Map getAllUpdates() - { + public Map getAllUpdates() { return allUpdates; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/DependencyUpdatesModel.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/DependencyUpdatesModel.java index fd4ebadb85..c80c4ba6d7 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/DependencyUpdatesModel.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/DependencyUpdatesModel.java @@ -27,11 +27,10 @@ /** * Model class for using with the {@linkplain org.codehaus.mojo.versions.api.ReportRenderer} API */ -public class DependencyUpdatesModel extends AbstractUpdatesModel -{ - public DependencyUpdatesModel( Map dependencyUpdates, - Map dependencyManagementUpdates ) - { - super( dependencyUpdates, dependencyManagementUpdates, id -> id ); +public class DependencyUpdatesModel extends AbstractUpdatesModel { + public DependencyUpdatesModel( + Map dependencyUpdates, + Map dependencyManagementUpdates) { + super(dependencyUpdates, dependencyManagementUpdates, id -> id); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/ParentUpdatesModel.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/ParentUpdatesModel.java index 9924a64154..a4bd329975 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/ParentUpdatesModel.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/ParentUpdatesModel.java @@ -28,10 +28,8 @@ /** * Model class for using with the {@linkplain org.codehaus.mojo.versions.api.ReportRenderer} API */ -public class ParentUpdatesModel extends DependencyUpdatesModel -{ - public ParentUpdatesModel( Dependency parent, ArtifactVersions dependencyUpdates ) - { - super( singletonMap( parent, dependencyUpdates ), emptyMap() ); +public class ParentUpdatesModel extends DependencyUpdatesModel { + public ParentUpdatesModel(Dependency parent, ArtifactVersions dependencyUpdates) { + super(singletonMap(parent, dependencyUpdates), emptyMap()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PluginUpdatesModel.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PluginUpdatesModel.java index fd3186aa27..2d67f31a20 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PluginUpdatesModel.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PluginUpdatesModel.java @@ -28,20 +28,19 @@ /** * Model class for using with the {@linkplain org.codehaus.mojo.versions.api.ReportRenderer} API */ -public class PluginUpdatesModel extends AbstractUpdatesModel -{ +public class PluginUpdatesModel extends AbstractUpdatesModel { /** * Creates a new instance * @param pluginUpdates map of plugin updates per plugin * @param pluginManagementUpdates map of plugin management updates per plugin */ - public PluginUpdatesModel( Map pluginUpdates, - Map pluginManagementUpdates ) - { - super( pluginUpdates, pluginManagementUpdates, p -> DependencyBuilder.newBuilder() - .withGroupId( p.getGroupId() ) - .withArtifactId( p.getArtifactId() ) - .withVersion( p.getVersion() ) - .build() ); + public PluginUpdatesModel( + Map pluginUpdates, + Map pluginManagementUpdates) { + super(pluginUpdates, pluginManagementUpdates, p -> DependencyBuilder.newBuilder() + .withGroupId(p.getGroupId()) + .withArtifactId(p.getArtifactId()) + .withVersion(p.getVersion()) + .build()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PropertyUpdatesModel.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PropertyUpdatesModel.java index 44058e6982..53cba990d6 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PropertyUpdatesModel.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/model/PropertyUpdatesModel.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.TreeMap; + import org.codehaus.mojo.versions.api.Property; import org.codehaus.mojo.versions.api.PropertyVersions; import org.codehaus.mojo.versions.utils.PropertyComparator; @@ -28,19 +29,15 @@ /** * Model class for using with the {@linkplain org.codehaus.mojo.versions.api.ReportRenderer} API */ -public class PropertyUpdatesModel -{ +public class PropertyUpdatesModel { private final Map allUpdates; - public PropertyUpdatesModel( PropertyComparator comparator, Map propertyUpdates ) - { - this.allUpdates = new TreeMap<>( comparator ); - this.allUpdates.putAll( propertyUpdates ); + public PropertyUpdatesModel(PropertyComparator comparator, Map propertyUpdates) { + this.allUpdates = new TreeMap<>(comparator); + this.allUpdates.putAll(propertyUpdates); } - public Map getAllUpdates() - { + public Map getAllUpdates() { return allUpdates; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/util/AggregateReportUtils.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/util/AggregateReportUtils.java index 12ff25b558..d2791ffc87 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/util/AggregateReportUtils.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/util/AggregateReportUtils.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; + import org.apache.maven.project.MavenProject; /** @@ -27,8 +28,7 @@ * * @since 2.14.0 * */ -public class AggregateReportUtils -{ +public class AggregateReportUtils { /** * Returns an aggregated list of {@link MavenProject} for the given project. @@ -37,17 +37,14 @@ public class AggregateReportUtils * * @return aggregated list of MavenProject objects for the given project(also containing the project itself) * */ - public static List getProjectsToProcess( final MavenProject project ) - { - if ( project == null ) - { + public static List getProjectsToProcess(final MavenProject project) { + if (project == null) { return Collections.emptyList(); } List result = new ArrayList<>(); - result.add( project ); - result.addAll( project.getCollectedProjects() ); + result.add(project); + result.addAll(project.getCollectedProjects()); return result; } - } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/CommonXmlReportRendererUtils.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/CommonXmlReportRendererUtils.java index e828d3d785..e282381011 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/CommonXmlReportRendererUtils.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/CommonXmlReportRendererUtils.java @@ -35,25 +35,18 @@ /** * Common utils for Xml report renderers */ -class CommonXmlReportRendererUtils -{ - static void setSection( AbstractVersionDetails versions, Segment segment, Consumer> setterFunction ) - { - ofNullable( versions.getAllUpdates( of( segment ) ) ) - .map( v -> Arrays.stream( v ) - .map( ArtifactVersion::toString ) - .collect( Collectors.toList() ) ) - .ifPresent( setterFunction ); +class CommonXmlReportRendererUtils { + static void setSection(AbstractVersionDetails versions, Segment segment, Consumer> setterFunction) { + ofNullable(versions.getAllUpdates(of(segment))) + .map(v -> Arrays.stream(v).map(ArtifactVersion::toString).collect(Collectors.toList())) + .ifPresent(setterFunction); } - static String statusFor( String lastVersion, Collection incrementals, Collection minors ) - { + static String statusFor(String lastVersion, Collection incrementals, Collection minors) { return lastVersion == null ? "no new available" : incrementals != null && !incrementals.isEmpty() - ? "incremental available" - : minors != null && !minors.isEmpty() - ? "minor available" - : "major available"; + ? "incremental available" + : minors != null && !minors.isEmpty() ? "minor available" : "major available"; } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java index d360a92ab1..863329ed21 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java @@ -56,19 +56,17 @@ * @author Illia Dubinin * @since 2.4 */ -public class DependencyUpdatesXmlReportRenderer implements ReportRenderer -{ +public class DependencyUpdatesXmlReportRenderer implements ReportRenderer { private final DependencyUpdatesModel model; private final Path outputFile; - private final ArtifactVersionsCache newestUpdateCache - = new ArtifactVersionsCache( AbstractVersionDetails::getNewestUpdate ); + private final ArtifactVersionsCache newestUpdateCache = + new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdate); /** * Creates a new instance * @param model object containing the updates model * @param outputFile output file for the report */ - public DependencyUpdatesXmlReportRenderer( DependencyUpdatesModel model, Path outputFile ) - { + public DependencyUpdatesXmlReportRenderer(DependencyUpdatesModel model, Path outputFile) { this.model = model; this.outputFile = outputFile; } @@ -77,53 +75,52 @@ public DependencyUpdatesXmlReportRenderer( DependencyUpdatesModel model, Path ou * Creates an XML report */ @Override - public void render() - { - try ( BufferedWriter writer = Files.newBufferedWriter( outputFile, - StandardCharsets.UTF_8 ) ) - { - new DependencyUpdatesReportXpp3Writer().write( writer, new DependencyUpdatesReport() - {{ - setSummary( new DependencyReportSummary() - {{ - OverviewStats overviewStats = OverviewStats.fromUpdates( model.getAllUpdates().values(), - newestUpdateCache ); - setUsingLastVersion( String.valueOf( overviewStats.getUpToDate() ) ); - setNextVersionAvailable( String.valueOf( overviewStats.getAny() ) ); - setNextIncrementalAvailable( String.valueOf( overviewStats.getIncremental() ) ); - setNextMinorAvailable( String.valueOf( overviewStats.getMinor() ) ); - setNextMajorAvailable( String.valueOf( overviewStats.getMajor() ) ); - }} ); - setDependencyManagements( createDependencyInfo( model.getArtifactManagementUpdates() ) ); - setDependencies( createDependencyInfo( model.getArtifactUpdates() ) ); - }} ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + public void render() { + try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { + new DependencyUpdatesReportXpp3Writer().write(writer, new DependencyUpdatesReport() { + { + setSummary(new DependencyReportSummary() { + { + OverviewStats overviewStats = OverviewStats.fromUpdates( + model.getAllUpdates().values(), newestUpdateCache); + setUsingLastVersion(String.valueOf(overviewStats.getUpToDate())); + setNextVersionAvailable(String.valueOf(overviewStats.getAny())); + setNextIncrementalAvailable(String.valueOf(overviewStats.getIncremental())); + setNextMinorAvailable(String.valueOf(overviewStats.getMinor())); + setNextMajorAvailable(String.valueOf(overviewStats.getMajor())); + } + }); + setDependencyManagements(createDependencyInfo(model.getArtifactManagementUpdates())); + setDependencies(createDependencyInfo(model.getArtifactUpdates())); + } + }); + } catch (IOException e) { + throw new RuntimeException(e); } } - private static List createDependencyInfo( Map versions ) - { - return versions.entrySet().stream().map( e -> - new DependencyInfo() - {{ - setGroupId( e.getKey().getGroupId() ); - setArtifactId( e.getKey().getArtifactId() ); - setCurrentVersion( e.getKey().getVersion() ); - setScope( e.getKey().getScope() ); - setType( e.getKey().getType() ); - setClassifier( e.getKey().getClassifier() ); + private static List createDependencyInfo(Map versions) { + return versions.entrySet().stream() + .map(e -> new DependencyInfo() { + { + setGroupId(e.getKey().getGroupId()); + setArtifactId(e.getKey().getArtifactId()); + setCurrentVersion(e.getKey().getVersion()); + setScope(e.getKey().getScope()); + setType(e.getKey().getType()); + setClassifier(e.getKey().getClassifier()); - ofNullable( e.getValue().getNewestUpdate( empty() ) ) - .map( ArtifactVersion::toString ).ifPresent( this::setLastVersion ); + ofNullable(e.getValue().getNewestUpdate(empty())) + .map(ArtifactVersion::toString) + .ifPresent(this::setLastVersion); - setSection( e.getValue(), INCREMENTAL, this::setIncrementals ); - setSection( e.getValue(), MINOR, this::setMinors ); - setSection( e.getValue(), MAJOR, this::setMajors ); + setSection(e.getValue(), INCREMENTAL, this::setIncrementals); + setSection(e.getValue(), MINOR, this::setMinors); + setSection(e.getValue(), MAJOR, this::setMajors); - setStatus( statusFor( getLastVersion(), getIncrementals(), getMinors() ) ); - }} ).collect( Collectors.toList() ); + setStatus(statusFor(getLastVersion(), getIncrementals(), getMinors())); + } + }) + .collect(Collectors.toList()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java index 42173d048b..b80fc6ee6c 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java @@ -56,19 +56,17 @@ * @author Illia Dubinin * @since 2.4 */ -public class PluginUpdatesXmlReportRenderer implements ReportRenderer -{ +public class PluginUpdatesXmlReportRenderer implements ReportRenderer { private final PluginUpdatesModel model; private final Path outputFile; - private final ArtifactVersionsCache newestUpdateCache - = new ArtifactVersionsCache( AbstractVersionDetails::getNewestUpdate ); + private final ArtifactVersionsCache newestUpdateCache = + new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdate); /** * Creates a new instance * @param model object containing the updates model * @param outputFile output file for the report */ - public PluginUpdatesXmlReportRenderer( PluginUpdatesModel model, Path outputFile ) - { + public PluginUpdatesXmlReportRenderer(PluginUpdatesModel model, Path outputFile) { this.model = model; this.outputFile = outputFile; } @@ -77,54 +75,53 @@ public PluginUpdatesXmlReportRenderer( PluginUpdatesModel model, Path outputFile * Creates an XML report */ @Override - public void render() - { - try ( BufferedWriter writer = Files.newBufferedWriter( outputFile, - StandardCharsets.UTF_8 ) ) - { - new PluginUpdatesReportXpp3Writer().write( writer, new PluginUpdatesReport() - {{ - setSummary( new PluginReportSummary() - {{ - PluginOverviewStats overviewStats = PluginOverviewStats.fromUpdates( - model.getAllUpdates().values(), newestUpdateCache ); - setUsingLastVersion( String.valueOf( overviewStats.getUpToDate() ) ); - setNextVersionAvailable( String.valueOf( overviewStats.getAny() ) ); - setNextIncrementalAvailable( String.valueOf( overviewStats.getIncremental() ) ); - setNextMinorAvailable( String.valueOf( overviewStats.getMinor() ) ); - setNextMajorAvailable( String.valueOf( overviewStats.getMajor() ) ); - setDependencyUpdates( String.valueOf( overviewStats.getDependencies() ) ); - }} ); - setPluginManagements( createPluginInfo( model.getArtifactManagementUpdates() ) ); - setPlugins( createPluginInfo( model.getArtifactUpdates() ) ); - }} ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + public void render() { + try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { + new PluginUpdatesReportXpp3Writer().write(writer, new PluginUpdatesReport() { + { + setSummary(new PluginReportSummary() { + { + PluginOverviewStats overviewStats = PluginOverviewStats.fromUpdates( + model.getAllUpdates().values(), newestUpdateCache); + setUsingLastVersion(String.valueOf(overviewStats.getUpToDate())); + setNextVersionAvailable(String.valueOf(overviewStats.getAny())); + setNextIncrementalAvailable(String.valueOf(overviewStats.getIncremental())); + setNextMinorAvailable(String.valueOf(overviewStats.getMinor())); + setNextMajorAvailable(String.valueOf(overviewStats.getMajor())); + setDependencyUpdates(String.valueOf(overviewStats.getDependencies())); + } + }); + setPluginManagements(createPluginInfo(model.getArtifactManagementUpdates())); + setPlugins(createPluginInfo(model.getArtifactUpdates())); + } + }); + } catch (IOException e) { + throw new RuntimeException(e); } } - private static List createPluginInfo( Map versions ) - { - return versions.entrySet().stream().map( e -> - new PluginInfo() - {{ - setGroupId( e.getKey().getGroupId() ); - setArtifactId( e.getKey().getArtifactId() ); - setCurrentVersion( e.getKey().getVersion() ); - setScope( e.getKey().getScope() ); - setType( e.getKey().getType() ); - setClassifier( e.getKey().getClassifier() ); + private static List createPluginInfo(Map versions) { + return versions.entrySet().stream() + .map(e -> new PluginInfo() { + { + setGroupId(e.getKey().getGroupId()); + setArtifactId(e.getKey().getArtifactId()); + setCurrentVersion(e.getKey().getVersion()); + setScope(e.getKey().getScope()); + setType(e.getKey().getType()); + setClassifier(e.getKey().getClassifier()); - ofNullable( e.getValue().getNewestUpdate( empty() ) ) - .map( ArtifactVersion::toString ).ifPresent( this::setLastVersion ); + ofNullable(e.getValue().getNewestUpdate(empty())) + .map(ArtifactVersion::toString) + .ifPresent(this::setLastVersion); - setSection( e.getValue(), INCREMENTAL, this::setIncrementals ); - setSection( e.getValue(), MINOR, this::setMinors ); - setSection( e.getValue(), MAJOR, this::setMajors ); + setSection(e.getValue(), INCREMENTAL, this::setIncrementals); + setSection(e.getValue(), MINOR, this::setMinors); + setSection(e.getValue(), MAJOR, this::setMajors); - setStatus( statusFor( getLastVersion(), getIncrementals(), getMinors() ) ); - }} ).collect( Collectors.toList() ); + setStatus(statusFor(getLastVersion(), getIncrementals(), getMinors())); + } + }) + .collect(Collectors.toList()); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java index 2042858614..0068c32ee5 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java @@ -30,9 +30,9 @@ import java.util.stream.Collectors; import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.codehaus.mojo.versions.api.Property; import org.codehaus.mojo.versions.api.AbstractVersionDetails; import org.codehaus.mojo.versions.api.ArtifactVersionsCache; +import org.codehaus.mojo.versions.api.Property; import org.codehaus.mojo.versions.api.PropertyVersions; import org.codehaus.mojo.versions.api.ReportRenderer; import org.codehaus.mojo.versions.reporting.OverviewStats; @@ -55,19 +55,17 @@ * XML renderer for PropertyUpdatesReport creates an xml file in target directory and writes report about available * dependency/dependency management updates. */ -public class PropertyUpdatesXmlReportRenderer implements ReportRenderer -{ +public class PropertyUpdatesXmlReportRenderer implements ReportRenderer { private final PropertyUpdatesModel model; private final Path outputFile; - private final ArtifactVersionsCache newestUpdateCache - = new ArtifactVersionsCache( AbstractVersionDetails::getNewestUpdate ); + private final ArtifactVersionsCache newestUpdateCache = + new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdate); /** * Creates a new instance * @param model object containing the updates model * @param outputFile output file for the report */ - public PropertyUpdatesXmlReportRenderer( PropertyUpdatesModel model, Path outputFile ) - { + public PropertyUpdatesXmlReportRenderer(PropertyUpdatesModel model, Path outputFile) { this.model = model; this.outputFile = outputFile; } @@ -76,59 +74,57 @@ public PropertyUpdatesXmlReportRenderer( PropertyUpdatesModel model, Path output * Creates an XML report */ @Override - public void render() - { - try ( BufferedWriter writer = Files.newBufferedWriter( outputFile, - StandardCharsets.UTF_8 ) ) - { - new PropertyUpdatesReportXpp3Writer().write( writer, new PropertyUpdatesReport() - {{ - setSummary( new PropertyReportSummary() - {{ - OverviewStats overviewStats = OverviewStats.fromUpdates( model.getAllUpdates().values(), - newestUpdateCache ); - setUsingLastVersion( String.valueOf( overviewStats.getUpToDate() ) ); - setNextVersionAvailable( String.valueOf( overviewStats.getAny() ) ); - setNextIncrementalAvailable( String.valueOf( overviewStats.getIncremental() ) ); - setNextMinorAvailable( String.valueOf( overviewStats.getMinor() ) ); - setNextMajorAvailable( String.valueOf( overviewStats.getMajor() ) ); - }} ); - setProperties( createPropertyInfo( model.getAllUpdates() ) ); - }} ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + public void render() { + try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) { + new PropertyUpdatesReportXpp3Writer().write(writer, new PropertyUpdatesReport() { + { + setSummary(new PropertyReportSummary() { + { + OverviewStats overviewStats = OverviewStats.fromUpdates( + model.getAllUpdates().values(), newestUpdateCache); + setUsingLastVersion(String.valueOf(overviewStats.getUpToDate())); + setNextVersionAvailable(String.valueOf(overviewStats.getAny())); + setNextIncrementalAvailable(String.valueOf(overviewStats.getIncremental())); + setNextMinorAvailable(String.valueOf(overviewStats.getMinor())); + setNextMajorAvailable(String.valueOf(overviewStats.getMajor())); + } + }); + setProperties(createPropertyInfo(model.getAllUpdates())); + } + }); + } catch (IOException e) { + throw new RuntimeException(e); } } - private static List createPropertyInfo( Map versions ) - { - return versions.entrySet().stream().map( e -> - new PropertyInfo() - {{ - setPropertyName( e.getKey().getName() ); - if ( e.getValue().getAssociations() != null - && e.getValue().getAssociations().length != 0 ) + private static List createPropertyInfo(Map versions) { + return versions.entrySet().stream() + .map(e -> new PropertyInfo() { { - setPropertyAssociations( Arrays.stream( e.getValue().getAssociations() ) - .map( a -> - { - PropertyAssociation pa = new PropertyAssociation(); - pa.setGroupId( a.getGroupId() ); - pa.setArtifactId( a.getArtifactId() ); - return pa; - } ).collect( Collectors.toList() ) ); - } - setCurrentVersion( e.getKey().getVersion() ); - ofNullable( e.getValue().getNewestUpdate( empty() ) ) - .map( ArtifactVersion::toString ).ifPresent( this::setLastVersion ); + setPropertyName(e.getKey().getName()); + if (e.getValue().getAssociations() != null + && e.getValue().getAssociations().length != 0) { + setPropertyAssociations(Arrays.stream(e.getValue().getAssociations()) + .map(a -> { + PropertyAssociation pa = new PropertyAssociation(); + pa.setGroupId(a.getGroupId()); + pa.setArtifactId(a.getArtifactId()); + return pa; + }) + .collect(Collectors.toList())); + } + setCurrentVersion(e.getKey().getVersion()); + ofNullable(e.getValue().getNewestUpdate(empty())) + .map(ArtifactVersion::toString) + .ifPresent(this::setLastVersion); - setSection( e.getValue(), INCREMENTAL, this::setIncrementals ); - setSection( e.getValue(), MINOR, this::setMinors ); - setSection( e.getValue(), MAJOR, this::setMajors ); + setSection(e.getValue(), INCREMENTAL, this::setIncrementals); + setSection(e.getValue(), MINOR, this::setMinors); + setSection(e.getValue(), MAJOR, this::setMajors); - setStatus( statusFor( getLastVersion(), getIncrementals(), getMinors() ) ); - }} ).collect( Collectors.toList() ); + setStatus(statusFor(getLastVersion(), getIncrementals(), getMinors())); + } + }) + .collect(Collectors.toList()); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojoTest.java index b09a77f364..b7945227a1 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojoTest.java @@ -31,14 +31,12 @@ * * @author Stephen Connolly */ -public class AbstractVersionsUpdaterMojoTest -{ +public class AbstractVersionsUpdaterMojoTest { private NumericVersionComparator instance = new NumericVersionComparator(); - private int instanceCompare( String v1, String v2 ) - { - return instance.compare( new DefaultArtifactVersion( v1 ), new DefaultArtifactVersion( v2 ) ); + private int instanceCompare(String v1, String v2) { + return instance.compare(new DefaultArtifactVersion(v1), new DefaultArtifactVersion(v2)); } /** @@ -46,15 +44,14 @@ private int instanceCompare( String v1, String v2 ) * */ @Test - public void testBasic() - { - assertEquals( 0, instanceCompare( "1", "1" ) ); - assertTrue( instanceCompare( "1", "2" ) < 0 ); - assertTrue( instanceCompare( "2", "1" ) > 0 ); - assertTrue( instanceCompare( "1", "1-SNAPSHOT" ) > 0 ); - assertTrue( instanceCompare( "1", "1.0" ) > 0 ); - assertTrue( instanceCompare( "1.1", "1" ) > 0 ); - assertTrue( instanceCompare( "5.1.0.0.24", "5.1.0.0.9" ) > 0 ); - assertTrue( instanceCompare( "5.1.0.0.2a4", "5.1.0.0.9" ) < 0 ); + public void testBasic() { + assertEquals(0, instanceCompare("1", "1")); + assertTrue(instanceCompare("1", "2") < 0); + assertTrue(instanceCompare("2", "1") > 0); + assertTrue(instanceCompare("1", "1-SNAPSHOT") > 0); + assertTrue(instanceCompare("1", "1.0") > 0); + assertTrue(instanceCompare("1.1", "1") > 0); + assertTrue(instanceCompare("5.1.0.0.24", "5.1.0.0.9") > 0); + assertTrue(instanceCompare("5.1.0.0.2a4", "5.1.0.0.9") < 0); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojoTest.java index 81d7f92e51..110bf9e123 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesReportMojoTest.java @@ -60,240 +60,221 @@ * * @author Andrzej Jarmoniuk */ -public class DependencyUpdatesReportMojoTest -{ - private static class TestDependencyUpdatesReportMojo extends DependencyUpdatesReportMojo - { +public class DependencyUpdatesReportMojoTest { + private static class TestDependencyUpdatesReportMojo extends DependencyUpdatesReportMojo { private static final I18N MOCK_I18N = mockI18N(); - TestDependencyUpdatesReportMojo() - { - super( MOCK_I18N, mockRepositorySystem(), mockAetherRepositorySystem(), null, - new ReportRendererFactoryImpl( MOCK_I18N ) ); + TestDependencyUpdatesReportMojo() { + super( + MOCK_I18N, + mockRepositorySystem(), + mockAetherRepositorySystem(), + null, + new ReportRendererFactoryImpl(MOCK_I18N)); siteTool = MockUtils.mockSiteTool(); project = new MavenProject(); - project.setOriginalModel( new Model() ); - project.getOriginalModel().setDependencyManagement( new DependencyManagement() ); - project.getModel().setDependencyManagement( new DependencyManagement() ); + project.setOriginalModel(new Model()); + project.getOriginalModel().setDependencyManagement(new DependencyManagement()); + project.getModel().setDependencyManagement(new DependencyManagement()); session = mockMavenSession(); } - public TestDependencyUpdatesReportMojo withDependencies( Dependency... dependencies ) - { - project.setDependencies( Arrays.asList( dependencies ) ); + public TestDependencyUpdatesReportMojo withDependencies(Dependency... dependencies) { + project.setDependencies(Arrays.asList(dependencies)); return this; } public TestDependencyUpdatesReportMojo withAetherRepositorySystem( - org.eclipse.aether.RepositorySystem repositorySystem ) - { + org.eclipse.aether.RepositorySystem repositorySystem) { this.aetherRepositorySystem = repositorySystem; return this; } public TestDependencyUpdatesReportMojo withOriginalDependencyManagement( - Dependency... originalDependencyManagement ) - { - project.getOriginalModel().getDependencyManagement() - .setDependencies( Arrays.asList( originalDependencyManagement ) ); + Dependency... originalDependencyManagement) { + project.getOriginalModel() + .getDependencyManagement() + .setDependencies(Arrays.asList(originalDependencyManagement)); return this; } - public TestDependencyUpdatesReportMojo withDependencyManagement( Dependency... dependencyManagement ) - { - project.getModel().getDependencyManagement().setDependencies( Arrays.asList( dependencyManagement ) ); + public TestDependencyUpdatesReportMojo withDependencyManagement(Dependency... dependencyManagement) { + project.getModel().getDependencyManagement().setDependencies(Arrays.asList(dependencyManagement)); return this; } - public TestDependencyUpdatesReportMojo withOnlyUpgradable( boolean onlyUpgradable ) - { + public TestDependencyUpdatesReportMojo withOnlyUpgradable(boolean onlyUpgradable) { this.onlyUpgradable = onlyUpgradable; return this; } - public TestDependencyUpdatesReportMojo withProcessDependencyManagement( boolean processDependencyManagement ) - { + public TestDependencyUpdatesReportMojo withProcessDependencyManagement(boolean processDependencyManagement) { this.processDependencyManagement = processDependencyManagement; return this; } public TestDependencyUpdatesReportMojo withProcessDependencyManagementTransitive( - boolean processDependencyManagementTransitive ) - { + boolean processDependencyManagementTransitive) { this.processDependencyManagementTransitive = processDependencyManagementTransitive; return this; } - public TestDependencyUpdatesReportMojo withOnlyProjectDependencies( - boolean onlyProjectDependencies ) - { + public TestDependencyUpdatesReportMojo withOnlyProjectDependencies(boolean onlyProjectDependencies) { this.onlyProjectDependencies = onlyProjectDependencies; return this; } - public TestDependencyUpdatesReportMojo withRuleSet( - RuleSet ruleSet ) - { + public TestDependencyUpdatesReportMojo withRuleSet(RuleSet ruleSet) { this.ruleSet = ruleSet; return this; } - public TestDependencyUpdatesReportMojo withIgnoredVersions( - Set ignoredVersions ) - { + public TestDependencyUpdatesReportMojo withIgnoredVersions(Set ignoredVersions) { this.ignoredVersions = ignoredVersions; return this; } - public TestDependencyUpdatesReportMojo withAllowSnapshots( boolean allowSnapshots ) - { + public TestDependencyUpdatesReportMojo withAllowSnapshots(boolean allowSnapshots) { this.allowSnapshots = allowSnapshots; return this; } - public TestDependencyUpdatesReportMojo withOriginalProperty( String name, String value ) - { - project.getOriginalModel().getProperties().put( name, value ); + public TestDependencyUpdatesReportMojo withOriginalProperty(String name, String value) { + project.getOriginalModel().getProperties().put(name, value); return this; } } - private static Dependency dependencyOf( String artifactId ) - { - return DependencyBuilder.dependencyWith( "groupA", artifactId, "1.0.0", - "default", "pom", SCOPE_COMPILE ); + private static Dependency dependencyOf(String artifactId) { + return DependencyBuilder.dependencyWith("groupA", artifactId, "1.0.0", "default", "pom", SCOPE_COMPILE); } - private static Dependency dependencyOf( String artifactId, String version ) - { - return DependencyBuilder.dependencyWith( "groupA", artifactId, version, - "default", "pom", SCOPE_COMPILE ); + private static Dependency dependencyOf(String artifactId, String version) { + return DependencyBuilder.dependencyWith("groupA", artifactId, version, "default", "pom", SCOPE_COMPILE); } @Test - public void testOnlyUpgradableDependencies() throws IOException, MavenReportException, IllegalAccessException - { + public void testOnlyUpgradableDependencies() throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withOnlyUpgradable( true ) - .withAetherRepositorySystem( mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0" } ); - put( "artifactC", new String[] { "1.0.0", "2.0.0" } ); - }} ) ) - .withDependencies( - dependencyOf( "artifactA", "1.0.0" ), - dependencyOf( "artifactB", "1.0.0" ), - dependencyOf( "artifactC", "2.0.0" ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withOnlyUpgradable(true) + .withAetherRepositorySystem(mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0"}); + put("artifactC", new String[] {"1.0.0", "2.0.0"}); + } + })) + .withDependencies( + dependencyOf("artifactA", "1.0.0"), + dependencyOf("artifactB", "1.0.0"), + dependencyOf("artifactC", "2.0.0")) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, containsString( "artifactA" ) ); - assertThat( output, not( containsString( "artifactB" ) ) ); - assertThat( output, not( containsString( "artifactC" ) ) ); + assertThat(output, containsString("artifactA")); + assertThat(output, not(containsString("artifactB"))); + assertThat(output, not(containsString("artifactC"))); } @Test public void testOnlyUpgradableWithOriginalDependencyManagement() - throws IOException, MavenReportException, IllegalAccessException - { + throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withOriginalDependencyManagement( dependencyOf( "artifactA" ), dependencyOf( "artifactB" ), - dependencyOf( "artifactC" ) ) - .withProcessDependencyManagement( true ) - .withOnlyUpgradable( true ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withOriginalDependencyManagement( + dependencyOf("artifactA"), dependencyOf("artifactB"), dependencyOf("artifactC")) + .withProcessDependencyManagement(true) + .withOnlyUpgradable(true) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, allOf( containsString( "artifactA" ), containsString( "artifactB" ) ) ); - assertThat( output, not( containsString( "artifactC" ) ) ); + assertThat(output, allOf(containsString("artifactA"), containsString("artifactB"))); + assertThat(output, not(containsString("artifactC"))); } @Test public void testOnlyUpgradableWithTransitiveDependencyManagement() - throws IOException, MavenReportException, IllegalAccessException - { + throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withDependencyManagement( - dependencyOf( "artifactA" ), dependencyOf( "artifactB" ), - dependencyOf( "artifactC" ) ) - .withProcessDependencyManagement( true ) - .withProcessDependencyManagementTransitive( true ) - .withOnlyUpgradable( true ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withDependencyManagement( + dependencyOf("artifactA"), dependencyOf("artifactB"), dependencyOf("artifactC")) + .withProcessDependencyManagement(true) + .withProcessDependencyManagementTransitive(true) + .withOnlyUpgradable(true) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, allOf( containsString( "artifactA" ), containsString( "artifactB" ) ) ); - assertThat( output, not( containsString( "artifactC" ) ) ); + assertThat(output, allOf(containsString("artifactA"), containsString("artifactB"))); + assertThat(output, not(containsString("artifactC"))); } @Test - public void testOnlyProjectDependencies() throws IOException, MavenReportException, IllegalAccessException - { + public void testOnlyProjectDependencies() throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withDependencies( dependencyOf( "artifactA" ) ) - .withDependencyManagement( dependencyOf( "artifactA" ), dependencyOf( "artifactB" ), - dependencyOf( "artifactC" ) ) - .withProcessDependencyManagement( true ) - .withOnlyProjectDependencies( true ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withDependencies(dependencyOf("artifactA")) + .withDependencyManagement( + dependencyOf("artifactA"), dependencyOf("artifactB"), dependencyOf("artifactC")) + .withProcessDependencyManagement(true) + .withOnlyProjectDependencies(true) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, containsString( "artifactA" ) ); - assertThat( output, not( anyOf( containsString( "artifactB" ), containsString( "artifactC" ) ) ) ); + assertThat(output, containsString("artifactA")); + assertThat(output, not(anyOf(containsString("artifactB"), containsString("artifactC")))); } @Test public void testOnlyProjectDependenciesWithIgnoredVersions() - throws IOException, MavenReportException, IllegalAccessException - { + throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withDependencies( dependencyOf( "artifactA" ) ) - .withDependencyManagement( dependencyOf( "artifactA" ), dependencyOf( "artifactB" ), - dependencyOf( "artifactC" ) ) - .withProcessDependencyManagement( true ) - .withOnlyProjectDependencies( true ) - .withIgnoredVersions( Collections.singleton( "2.0.0" ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); - - String output = os.toString().replaceAll( "\n", "" ); - assertThat( output, containsString( "report.noUpdatesAvailable" ) ); + .withDependencies(dependencyOf("artifactA")) + .withDependencyManagement( + dependencyOf("artifactA"), dependencyOf("artifactB"), dependencyOf("artifactC")) + .withProcessDependencyManagement(true) + .withOnlyProjectDependencies(true) + .withIgnoredVersions(Collections.singleton("2.0.0")) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); + + String output = os.toString().replaceAll("\n", ""); + assertThat(output, containsString("report.noUpdatesAvailable")); } /** * Dependencies should be rendered in alphabetical order */ @Test - public void testDependenciesInAlphabeticalOrder() throws IOException, MavenReportException, IllegalAccessException - { + public void testDependenciesInAlphabeticalOrder() throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withAetherRepositorySystem( mockAetherRepositorySystem( new HashMap() - {{ - put( "amstrad", new String[] {"1.0.0", "2.0.0"} ); - put( "atari", new String[] {"1.0.0", "2.0.0"} ); - put( "commodore", new String[] {"1.0.0", "2.0.0"} ); - put( "spectrum", new String[] {"1.0.0", "2.0.0"} ); - }} ) ) - .withDependencies( dependencyOf( "spectrum" ), dependencyOf( "atari" ), - dependencyOf( "amstrad" ), dependencyOf( "commodore" ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); - - String output = os.toString().replaceAll( "\n", "" ); - assertThat( output, Matchers.stringContainsInOrder( "amstrad", "atari", "commodore", "spectrum" ) ); + .withAetherRepositorySystem(mockAetherRepositorySystem(new HashMap() { + { + put("amstrad", new String[] {"1.0.0", "2.0.0"}); + put("atari", new String[] {"1.0.0", "2.0.0"}); + put("commodore", new String[] {"1.0.0", "2.0.0"}); + put("spectrum", new String[] {"1.0.0", "2.0.0"}); + } + })) + .withDependencies( + dependencyOf("spectrum"), + dependencyOf("atari"), + dependencyOf("amstrad"), + dependencyOf("commodore")) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); + + String output = os.toString().replaceAll("\n", ""); + assertThat(output, Matchers.stringContainsInOrder("amstrad", "atari", "commodore", "spectrum")); } /** @@ -301,88 +282,86 @@ public void testDependenciesInAlphabeticalOrder() throws IOException, MavenRepor */ @Test public void testDependenciesShouldOverrideDependencyManagement() - throws IOException, MavenReportException, IllegalAccessException - { + throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withProcessDependencyManagement( true ) - .withProcessDependencyManagementTransitive( true ) - .withDependencies( dependencyOf( "artifactA", "2.0.0" ), - dependencyOf( "artifactB" ) ) - .withDependencyManagement( dependencyOf( "artifactA" ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); - - String output = os.toString().replaceAll( "\n", "" ); - assertThat( output, Matchers.stringContainsInOrder( "artifactB" ) ); + .withProcessDependencyManagement(true) + .withProcessDependencyManagementTransitive(true) + .withDependencies(dependencyOf("artifactA", "2.0.0"), dependencyOf("artifactB")) + .withDependencyManagement(dependencyOf("artifactA")) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); + + String output = os.toString().replaceAll("\n", ""); + assertThat(output, Matchers.stringContainsInOrder("artifactB")); } @Test - public void testWrongReportBounds() throws IOException, MavenReportException, IllegalAccessException - { + public void testWrongReportBounds() throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withOnlyUpgradable( true ) - .withDependencies( - dependencyOf( "test-artifact" ) ) - .withAetherRepositorySystem( mockAetherRepositorySystem( new HashMap() - {{ - put( "test-artifact", new String[] { "1.0.0", "2.0.0-M1" } ); - }} ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); - - String output = os.toString().replaceAll( "\n", "" ).replaceAll( "\r", "" ); - assertThat( output, allOf( - matchesPattern( ".*report.overview.numNewerMajorAvailable\\s*1.*" ), - matchesPattern( ".*report.overview.numUpToDate\\s*0.*" ) ) ); + .withOnlyUpgradable(true) + .withDependencies(dependencyOf("test-artifact")) + .withAetherRepositorySystem(mockAetherRepositorySystem(new HashMap() { + { + put("test-artifact", new String[] {"1.0.0", "2.0.0-M1"}); + } + })) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); + + String output = os.toString().replaceAll("\n", "").replaceAll("\r", ""); + assertThat( + output, + allOf( + matchesPattern(".*report.overview.numNewerMajorAvailable\\s*1.*"), + matchesPattern(".*report.overview.numUpToDate\\s*0.*"))); } @Test - public void testIt001Overview() throws IOException, MavenReportException, IllegalAccessException - { + public void testIt001Overview() throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withOnlyUpgradable( true ) - .withDependencies( - dependencyOf( "test-artifact", "1.1" ) ) - .withAetherRepositorySystem( mockAetherRepositorySystem( new HashMap() - {{ - put( "test-artifact", new String[] { "1.1.0-2", "1.1", "1.1.1", "1.1.1-2", - "1.1.2", "1.1.3", "1.2", "1.2.1", "1.2.2", "1.3", "2.0", "2.1", "3.0"} ); - }} ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withOnlyUpgradable(true) + .withDependencies(dependencyOf("test-artifact", "1.1")) + .withAetherRepositorySystem(mockAetherRepositorySystem(new HashMap() { + { + put("test-artifact", new String[] { + "1.1.0-2", "1.1", "1.1.1", "1.1.1-2", "1.1.2", "1.1.3", "1.2", "1.2.1", "1.2.2", "1.3", + "2.0", "2.1", "3.0" + }); + } + })) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString() - .replaceAll( "<[^>]+>", " " ) - .replaceAll( "&[^;]+;", " " ) - .replaceAll( "\\s+", " " ); - assertThat( "Did not generate summary correctly", output, - containsString( "groupA test-artifact 1.1 compile pom default 1.1.0-2 1.1.3 1.3 3.0" ) ); + .replaceAll("<[^>]+>", " ") + .replaceAll("&[^;]+;", " ") + .replaceAll("\\s+", " "); + assertThat( + "Did not generate summary correctly", + output, + containsString("groupA test-artifact 1.1 compile pom default 1.1.0-2 1.1.3 1.3 3.0")); } @Test public void testResolvedVersionsWithoutTransitiveDependencyManagement() - throws IOException, MavenReportException, IllegalAccessException - { + throws IOException, MavenReportException, IllegalAccessException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestDependencyUpdatesReportMojo() - .withOriginalDependencyManagement( - dependencyOf( "artifactA", "1.0.0" ), - dependencyOf( "artifactB", "${mycomponent.version}" ) ) - .withDependencyManagement( - dependencyOf( "artifactA", "1.0.0" ), - dependencyOf( "artifactB", "${mycomponent.version}" ) ) - .withProcessDependencyManagement( true ) - .withProcessDependencyManagementTransitive( false ) - .withOnlyUpgradable( false ) - .withOriginalProperty( "mycomponent.version", "1.2.3" ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withOriginalDependencyManagement( + dependencyOf("artifactA", "1.0.0"), dependencyOf("artifactB", "${mycomponent.version}")) + .withDependencyManagement( + dependencyOf("artifactA", "1.0.0"), dependencyOf("artifactB", "${mycomponent.version}")) + .withProcessDependencyManagement(true) + .withProcessDependencyManagementTransitive(false) + .withOnlyUpgradable(false) + .withOriginalProperty("mycomponent.version", "1.2.3") + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, Matchers - .stringContainsInOrder( "artifactA", "1.0.0", "artifactB", "1.2.3" ) ); + assertThat(output, Matchers.stringContainsInOrder("artifactA", "1.0.0", "artifactB", "1.2.3")); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesXmlRendererTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesXmlRendererTest.java index bb8d851ae6..a398282d6d 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesXmlRendererTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DependencyUpdatesXmlRendererTest.java @@ -46,59 +46,62 @@ * * @author Andrzej Jarmoniuk */ -public class DependencyUpdatesXmlRendererTest -{ +public class DependencyUpdatesXmlRendererTest { private Path tempFile; @Before - public void setUp() throws IOException - { - tempFile = Files.createTempFile( "xml-dependency-report", "" ); + public void setUp() throws IOException { + tempFile = Files.createTempFile("xml-dependency-report", ""); } @After - public void tearDown() throws IOException - { - if ( tempFile != null && Files.exists( tempFile ) ) - { - Files.delete( tempFile ); + public void tearDown() throws IOException { + if (tempFile != null && Files.exists(tempFile)) { + Files.delete(tempFile); } } @Test - public void testReportGeneration() throws IOException - { - new DependencyUpdatesXmlReportRenderer( new DependencyUpdatesModel( - singletonMap( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "artifactA" ) - .withVersion( "1.0.0" ) - .build(), new ArtifactVersions( - new DefaultArtifact( "default-group", "artifactA", - "1.0.0", SCOPE_COMPILE, "jar", "default", - null ), - Arrays.asList( - new DefaultArtifactVersion( "1.0.0" ), - new DefaultArtifactVersion( "1.0.1" ), - new DefaultArtifactVersion( "1.1.0" ), - new DefaultArtifactVersion( "2.0.0" ) - ), - new MavenVersionComparator() ) ), - emptyMap() ), tempFile ).render(); - String output = String.join( "", Files.readAllLines( tempFile ) ) - .replaceAll( ">\\s*<", "><" ); + public void testReportGeneration() throws IOException { + new DependencyUpdatesXmlReportRenderer( + new DependencyUpdatesModel( + singletonMap( + DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("artifactA") + .withVersion("1.0.0") + .build(), + new ArtifactVersions( + new DefaultArtifact( + "default-group", + "artifactA", + "1.0.0", + SCOPE_COMPILE, + "jar", + "default", + null), + Arrays.asList( + new DefaultArtifactVersion("1.0.0"), + new DefaultArtifactVersion("1.0.1"), + new DefaultArtifactVersion("1.1.0"), + new DefaultArtifactVersion("2.0.0")), + new MavenVersionComparator())), + emptyMap()), + tempFile) + .render(); + String output = String.join("", Files.readAllLines(tempFile)).replaceAll(">\\s*<", "><"); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "1" ) ); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "0" ) ); + assertThat(output, containsString("0")); + assertThat(output, containsString("0")); + assertThat(output, containsString("1")); + assertThat(output, containsString("0")); + assertThat(output, containsString("0")); - assertThat( output, containsString( "1.0.0" ) ); - assertThat( output, containsString( "2.0.0" ) ); - assertThat( output, containsString( "1.0.1" ) ); - assertThat( output, containsString( "1.1.0" ) ); - assertThat( output, containsString( "2.0.0" ) ); - assertThat( output, containsString( "incremental available" ) ); + assertThat(output, containsString("1.0.0")); + assertThat(output, containsString("2.0.0")); + assertThat(output, containsString("1.0.1")); + assertThat(output, containsString("1.1.0")); + assertThat(output, containsString("2.0.0")); + assertThat(output, containsString("incremental available")); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java index 1119b5636b..035268371c 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java @@ -61,385 +61,374 @@ * * @author Andrzej Jarmoniuk */ -public class DisplayDependencyUpdatesMojoTest extends AbstractMojoTestCase -{ +public class DisplayDependencyUpdatesMojoTest extends AbstractMojoTestCase { @Rule - public final MojoRule mojoRule = new MojoRule( this ); + public final MojoRule mojoRule = new MojoRule(this); @Test - public void testValidateGAVListSuccessful() throws MojoExecutionException - { - DisplayDependencyUpdatesMojo.validateGAVList( Arrays.asList( "group", "group:artifact", - "group:artifact:version" ), 3, "" ); + public void testValidateGAVListSuccessful() throws MojoExecutionException { + DisplayDependencyUpdatesMojo.validateGAVList( + Arrays.asList("group", "group:artifact", "group:artifact:version"), 3, ""); } @Test - public void testValidateGAVListFailed() - { - try - { - DisplayDependencyUpdatesMojo.validateGAVList( Arrays.asList( "group:artifact:version", - "group:artifact:version:type" ), 3, "" ); - fail( "Method should have thrown a MojoExecutionException" ); - } - catch ( MojoExecutionException ignored ) - { + public void testValidateGAVListFailed() { + try { + DisplayDependencyUpdatesMojo.validateGAVList( + Arrays.asList("group:artifact:version", "group:artifact:version:type"), 3, ""); + fail("Method should have thrown a MojoExecutionException"); + } catch (MojoExecutionException ignored) { } } @Test - public void testRuleSetPresentAndWorking() throws Exception - { + public void testRuleSetPresentAndWorking() throws Exception { File outputFile = null; - try - { - outputFile = File.createTempFile( "display-dependency-updates", "" ); + try { + outputFile = File.createTempFile("display-dependency-updates", ""); assert outputFile.exists(); DisplayDependencyUpdatesMojo mojo = (DisplayDependencyUpdatesMojo) mojoRule.lookupConfiguredMojo( - new File( "target/test-classes/org/codehaus/mojo/display-dependency-updates/ruleset" ), - "display-dependency-updates" ); - assertThat( mojo.ruleSet, notNullValue() ); - assertThat( mojo.ruleSet.getIgnoreVersions(), notNullValue() ); - assertThat( mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize( 3 ) ); - assertThat( mojo.ruleSet.getIgnoreVersions(), hasItem( matches( - new TestIgnoreVersions().withVersion( "1.0.1" ) ) ) ); - assertThat( mojo.ruleSet.getIgnoreVersions(), containsInAnyOrder( - matches( new TestIgnoreVersions().withVersion( "1.0.1" ) ), - matches( new TestIgnoreVersions().withType( TYPE_REGEX ).withVersion( ".+-SNAPSHOT" ) ), - matches( new TestIgnoreVersions().withType( TYPE_REGEX ).withVersion( ".+-M\\d+" ) ) ) ); + new File("target/test-classes/org/codehaus/mojo/display-dependency-updates/ruleset"), + "display-dependency-updates"); + assertThat(mojo.ruleSet, notNullValue()); + assertThat(mojo.ruleSet.getIgnoreVersions(), notNullValue()); + assertThat(mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize(3)); + assertThat( + mojo.ruleSet.getIgnoreVersions(), hasItem(matches(new TestIgnoreVersions().withVersion("1.0.1")))); + assertThat( + mojo.ruleSet.getIgnoreVersions(), + containsInAnyOrder( + matches(new TestIgnoreVersions().withVersion("1.0.1")), + matches(new TestIgnoreVersions() + .withType(TYPE_REGEX) + .withVersion(".+-SNAPSHOT")), + matches(new TestIgnoreVersions() + .withType(TYPE_REGEX) + .withVersion(".+-M\\d+")))); // This is just an example of how to create it-style tests as unit tests; the advantage is easier debugging mojo.outputFile = outputFile; - mojo.aetherRepositorySystem = mockAetherRepositorySystem( new HashMap() - {{ - put( "dummy-api", new String[] { "1.0.0", "1.0.1", "1.1.0-M1", "1.2.0-SNAPSHOT" } ); - }} ); + mojo.aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { + { + put("dummy-api", new String[] {"1.0.0", "1.0.1", "1.1.0-M1", "1.2.0-SNAPSHOT"}); + } + }); - assertThat( mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize( 3 ) ); + assertThat(mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize(3)); mojo.execute(); - List output = Files.readAllLines( outputFile.toPath(), UTF_8 ); - assertThat( output, not( hasItem( containsString( "1.1.0-M1" ) ) ) ); - } - finally - { + List output = Files.readAllLines(outputFile.toPath(), UTF_8); + assertThat(output, not(hasItem(containsString("1.1.0-M1")))); + } finally { assert outputFile == null || !outputFile.exists() || outputFile.delete(); } } - private MavenProject createProject() - { - return new MavenProject( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "default-artifact" ); - setVersion( "1.0.0-SNAPSHOT" ); - - setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "default-dependency" ) - .withVersion( "1.0.0" ) - .build() ) ); - }} ) - {{ - setOriginalModel( getModel() ); - }}; + private MavenProject createProject() { + return new MavenProject(new Model() { + { + setGroupId("default-group"); + setArtifactId("default-artifact"); + setVersion("1.0.0-SNAPSHOT"); + + setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("default-dependency") + .withVersion("1.0.0") + .build())); + } + }) { + { + setOriginalModel(getModel()); + } + }; } @Test public void testVersionsWithQualifiersNotConsideredAsMinorUpdates() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException - { + throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { Path tempPath = null; - try - { - tempPath = Files.createTempFile( "display-dependency-updates", "" ); + try { + tempPath = Files.createTempFile("display-dependency-updates", ""); final File tempFile = tempPath.toFile(); - new DisplayDependencyUpdatesMojo( mockRepositorySystem(), - mockAetherRepositorySystem( new HashMap() - {{ - put( "default-dependency", new String[] {"1.0.0", "1.1.0", "2.0.0-SNAPSHOT", "2.0.0-beta", - "2.0.0-rc1"} ); - }} ), + new DisplayDependencyUpdatesMojo( + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put( + "default-dependency", + new String[] {"1.0.0", "1.1.0", "2.0.0-SNAPSHOT", "2.0.0-beta", "2.0.0-rc1"}); + } + }), null, - null ) - {{ - setProject( createProject() ); - setVariableValueToObject( this, "allowAnyUpdates", false ); - setVariableValueToObject( this, "allowMajorUpdates", false ); - setVariableValueToObject( this, "processDependencies", true ); - setVariableValueToObject( this, "dependencyIncludes", - singletonList( WildcardMatcher.WILDCARD ) ); - setVariableValueToObject( this, "dependencyExcludes", emptyList() ); - this.allowSnapshots = true; - this.outputFile = tempFile; - setPluginContext( new HashMap<>() ); - - session = mockMavenSession(); - }}.execute(); - - assertThat( String.join( "", Files.readAllLines( tempPath ) ), - not( anyOf( containsString( "2.0.0-SNAPSHOT" ), - containsString( "2.0.0-beta" ), - containsString( "2.0.0-rc1" ) ) ) ); - } - finally - { - if ( tempPath != null && Files.exists( tempPath ) ) - { - Files.delete( tempPath ); + null) { + { + setProject(createProject()); + setVariableValueToObject(this, "allowAnyUpdates", false); + setVariableValueToObject(this, "allowMajorUpdates", false); + setVariableValueToObject(this, "processDependencies", true); + setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); + setVariableValueToObject(this, "dependencyExcludes", emptyList()); + this.allowSnapshots = true; + this.outputFile = tempFile; + setPluginContext(new HashMap<>()); + + session = mockMavenSession(); + } + }.execute(); + + assertThat( + String.join("", Files.readAllLines(tempPath)), + not(anyOf( + containsString("2.0.0-SNAPSHOT"), + containsString("2.0.0-beta"), + containsString("2.0.0-rc1")))); + } finally { + if (tempPath != null && Files.exists(tempPath)) { + Files.delete(tempPath); } } } @Test public void testAllowMajorUpdatesFalse() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException - { + throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { Path tempPath = null; - try - { - tempPath = Files.createTempFile( "display-dependency-updates", "" ); + try { + tempPath = Files.createTempFile("display-dependency-updates", ""); final File tempFile = tempPath.toFile(); - new DisplayDependencyUpdatesMojo( mockRepositorySystem(), - mockAetherRepositorySystem( new HashMap() - {{ - put( "default-dependency", new String[] {"1.0.0", "1.1.0", "2.0.0"} ); - }} ), + new DisplayDependencyUpdatesMojo( + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put("default-dependency", new String[] {"1.0.0", "1.1.0", "2.0.0"}); + } + }), null, - null ) - {{ - setProject( createProject() ); - setVariableValueToObject( this, "allowAnyUpdates", false ); - setVariableValueToObject( this, "allowMajorUpdates", false ); - setVariableValueToObject( this, "processDependencies", true ); - setVariableValueToObject( this, "dependencyIncludes", - singletonList( WildcardMatcher.WILDCARD ) ); - setVariableValueToObject( this, "dependencyExcludes", emptyList() ); - this.outputFile = tempFile; - setPluginContext( new HashMap<>() ); - - session = mockMavenSession(); - }}.execute(); - - String output = String.join( "", Files.readAllLines( tempPath ) ); - - assertThat( output, containsString( "1.1.0" ) ); - assertThat( output, not( containsString( "2.0.0" ) ) ); - } - finally - { - if ( tempPath != null && Files.exists( tempPath ) ) - { - Files.delete( tempPath ); + null) { + { + setProject(createProject()); + setVariableValueToObject(this, "allowAnyUpdates", false); + setVariableValueToObject(this, "allowMajorUpdates", false); + setVariableValueToObject(this, "processDependencies", true); + setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); + setVariableValueToObject(this, "dependencyExcludes", emptyList()); + this.outputFile = tempFile; + setPluginContext(new HashMap<>()); + + session = mockMavenSession(); + } + }.execute(); + + String output = String.join("", Files.readAllLines(tempPath)); + + assertThat(output, containsString("1.1.0")); + assertThat(output, not(containsString("2.0.0"))); + } finally { + if (tempPath != null && Files.exists(tempPath)) { + Files.delete(tempPath); } } } @Test public void testAllowMinorUpdatesFalse() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException - { + throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { Path tempPath = null; - try - { - tempPath = Files.createTempFile( "display-dependency-updates", "" ); + try { + tempPath = Files.createTempFile("display-dependency-updates", ""); final File tempFile = tempPath.toFile(); - new DisplayDependencyUpdatesMojo( mockRepositorySystem(), - mockAetherRepositorySystem( new HashMap() - {{ - put( "default-dependency", new String[] {"1.0.0", "1.0.1", "1.1.0", "2.0.0"} ); - }} ), + new DisplayDependencyUpdatesMojo( + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put("default-dependency", new String[] {"1.0.0", "1.0.1", "1.1.0", "2.0.0"}); + } + }), null, - null ) - {{ - setProject( createProject() ); - setVariableValueToObject( this, "allowAnyUpdates", false ); - setVariableValueToObject( this, "allowMinorUpdates", false ); - setVariableValueToObject( this, "processDependencies", true ); - setVariableValueToObject( this, "dependencyIncludes", - singletonList( WildcardMatcher.WILDCARD ) ); - setVariableValueToObject( this, "dependencyExcludes", emptyList() ); - this.outputFile = tempFile; - setPluginContext( new HashMap<>() ); - - session = mockMavenSession(); - }}.execute(); - - String output = String.join( "", Files.readAllLines( tempPath ) ); - - assertThat( output, containsString( "1.0.1" ) ); - assertThat( output, not( containsString( "1.1.0" ) ) ); - assertThat( output, not( containsString( "2.0.0" ) ) ); - } - finally - { - if ( tempPath != null && Files.exists( tempPath ) ) - { - Files.delete( tempPath ); + null) { + { + setProject(createProject()); + setVariableValueToObject(this, "allowAnyUpdates", false); + setVariableValueToObject(this, "allowMinorUpdates", false); + setVariableValueToObject(this, "processDependencies", true); + setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); + setVariableValueToObject(this, "dependencyExcludes", emptyList()); + this.outputFile = tempFile; + setPluginContext(new HashMap<>()); + + session = mockMavenSession(); + } + }.execute(); + + String output = String.join("", Files.readAllLines(tempPath)); + + assertThat(output, containsString("1.0.1")); + assertThat(output, not(containsString("1.1.0"))); + assertThat(output, not(containsString("2.0.0"))); + } finally { + if (tempPath != null && Files.exists(tempPath)) { + Files.delete(tempPath); } } } @Test public void testAllowIncrementalUpdatesFalse() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException - { + throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { Path tempPath = null; - try - { - tempPath = Files.createTempFile( "display-dependency-updates", "" ); + try { + tempPath = Files.createTempFile("display-dependency-updates", ""); final File tempFile = tempPath.toFile(); - new DisplayDependencyUpdatesMojo( mockRepositorySystem(), - mockAetherRepositorySystem( new HashMap() - {{ - put( "default-dependency", new String[] {"1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0"} ); - }} ), + new DisplayDependencyUpdatesMojo( + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put("default-dependency", new String[] {"1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0"}); + } + }), null, - null ) - {{ - setProject( createProject() ); - setVariableValueToObject( this, "allowAnyUpdates", false ); - setVariableValueToObject( this, "allowIncrementalUpdates", false ); - setVariableValueToObject( this, "processDependencies", true ); - setVariableValueToObject( this, "dependencyIncludes", - singletonList( WildcardMatcher.WILDCARD ) ); - setVariableValueToObject( this, "dependencyExcludes", emptyList() ); - this.outputFile = tempFile; - setPluginContext( new HashMap<>() ); - - session = mockMavenSession(); - }}.execute(); - - String output = String.join( "", Files.readAllLines( tempPath ) ); - - assertThat( output, containsString( "1.0.0-1" ) ); - assertThat( output, not( containsString( "1.0.1" ) ) ); - assertThat( output, not( containsString( "1.1.0" ) ) ); - assertThat( output, not( containsString( "2.0.0" ) ) ); - } - finally - { - if ( tempPath != null && Files.exists( tempPath ) ) - { - Files.delete( tempPath ); + null) { + { + setProject(createProject()); + setVariableValueToObject(this, "allowAnyUpdates", false); + setVariableValueToObject(this, "allowIncrementalUpdates", false); + setVariableValueToObject(this, "processDependencies", true); + setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); + setVariableValueToObject(this, "dependencyExcludes", emptyList()); + this.outputFile = tempFile; + setPluginContext(new HashMap<>()); + + session = mockMavenSession(); + } + }.execute(); + + String output = String.join("", Files.readAllLines(tempPath)); + + assertThat(output, containsString("1.0.0-1")); + assertThat(output, not(containsString("1.0.1"))); + assertThat(output, not(containsString("1.1.0"))); + assertThat(output, not(containsString("2.0.0"))); + } finally { + if (tempPath != null && Files.exists(tempPath)) { + Files.delete(tempPath); } } } @Test public void testVersionsWithQualifiersNotConsideredAsIncrementalUpdates() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException - { + throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { Path tempPath = null; - try - { - tempPath = Files.createTempFile( "display-dependency-updates", "" ); + try { + tempPath = Files.createTempFile("display-dependency-updates", ""); final File tempFile = tempPath.toFile(); - new DisplayDependencyUpdatesMojo( mockRepositorySystem(), - mockAetherRepositorySystem( new HashMap() - {{ - put( "default-dependency", new String[] {"1.0.0", "1.1.0", "1.9.0-SNAPSHOT", "1.9.0-beta", - "1.9.0-rc1"} ); - }} ), + new DisplayDependencyUpdatesMojo( + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put( + "default-dependency", + new String[] {"1.0.0", "1.1.0", "1.9.0-SNAPSHOT", "1.9.0-beta", "1.9.0-rc1"}); + } + }), null, - null ) - {{ - setProject( createProject() ); - setVariableValueToObject( this, "allowAnyUpdates", false ); - setVariableValueToObject( this, "allowMinorUpdates", false ); - setVariableValueToObject( this, "processDependencies", true ); - setVariableValueToObject( this, "dependencyIncludes", - singletonList( WildcardMatcher.WILDCARD ) ); - setVariableValueToObject( this, "dependencyExcludes", emptyList() ); - this.allowSnapshots = true; - this.outputFile = tempFile; - setPluginContext( new HashMap<>() ); - - session = mockMavenSession(); - }}.execute(); - - assertThat( String.join( "", Files.readAllLines( tempPath ) ), - not( anyOf( containsString( "1.9.0-SNAPSHOT" ), - containsString( "1.9.0-beta" ), - containsString( "1.9.0-rc1" ) ) ) ); - } - finally - { - if ( tempPath != null && Files.exists( tempPath ) ) - { - Files.delete( tempPath ); + null) { + { + setProject(createProject()); + setVariableValueToObject(this, "allowAnyUpdates", false); + setVariableValueToObject(this, "allowMinorUpdates", false); + setVariableValueToObject(this, "processDependencies", true); + setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); + setVariableValueToObject(this, "dependencyExcludes", emptyList()); + this.allowSnapshots = true; + this.outputFile = tempFile; + setPluginContext(new HashMap<>()); + + session = mockMavenSession(); + } + }.execute(); + + assertThat( + String.join("", Files.readAllLines(tempPath)), + not(anyOf( + containsString("1.9.0-SNAPSHOT"), + containsString("1.9.0-beta"), + containsString("1.9.0-rc1")))); + } finally { + if (tempPath != null && Files.exists(tempPath)) { + Files.delete(tempPath); } } } @Test - public void testDetermineUpdatedSegment() throws Exception - { + public void testDetermineUpdatedSegment() throws Exception { File outputFile = null; - try - { - outputFile = File.createTempFile( "display-dependency-updates", "" ); + try { + outputFile = File.createTempFile("display-dependency-updates", ""); assert outputFile.exists(); DisplayDependencyUpdatesMojo mojo = (DisplayDependencyUpdatesMojo) mojoRule.lookupConfiguredMojo( - new File( "target/test-classes/org/codehaus/mojo/display-dependency-updates/ruleset" ), - "display-dependency-updates" ); - - assertThat( mojo.ruleSet, notNullValue() ); - assertThat( mojo.ruleSet.getIgnoreVersions(), notNullValue() ); - assertThat( mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize( 3 ) ); - assertThat( mojo.ruleSet.getIgnoreVersions(), hasItem( matches( - new TestIgnoreVersions().withVersion( "1.0.1" ) ) ) ); - assertThat( mojo.ruleSet.getIgnoreVersions(), containsInAnyOrder( - matches( new TestIgnoreVersions().withVersion( "1.0.1" ) ), - matches( new TestIgnoreVersions().withType( TYPE_REGEX ).withVersion( ".+-SNAPSHOT" ) ), - matches( new TestIgnoreVersions().withType( TYPE_REGEX ).withVersion( ".+-M\\d+" ) ) ) ); + new File("target/test-classes/org/codehaus/mojo/display-dependency-updates/ruleset"), + "display-dependency-updates"); + + assertThat(mojo.ruleSet, notNullValue()); + assertThat(mojo.ruleSet.getIgnoreVersions(), notNullValue()); + assertThat(mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize(3)); + assertThat( + mojo.ruleSet.getIgnoreVersions(), hasItem(matches(new TestIgnoreVersions().withVersion("1.0.1")))); + assertThat( + mojo.ruleSet.getIgnoreVersions(), + containsInAnyOrder( + matches(new TestIgnoreVersions().withVersion("1.0.1")), + matches(new TestIgnoreVersions() + .withType(TYPE_REGEX) + .withVersion(".+-SNAPSHOT")), + matches(new TestIgnoreVersions() + .withType(TYPE_REGEX) + .withVersion(".+-M\\d+")))); // This is just an example of how to create it-style tests as unit tests; the advantage is easier debugging mojo.outputFile = outputFile; - mojo.aetherRepositorySystem = mockAetherRepositorySystem( new HashMap() - {{ - put( "dummy-api", new String[] { "1.0.0", "1.0.1", "1.1.0-M1", "1.2.0-SNAPSHOT" } ); - }} ); + mojo.aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { + { + put("dummy-api", new String[] {"1.0.0", "1.0.1", "1.1.0-M1", "1.2.0-SNAPSHOT"}); + } + }); - assertThat( mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize( 3 ) ); + assertThat(mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize(3)); mojo.execute(); - List output = Files.readAllLines( outputFile.toPath(), UTF_8 ); - assertThat( output, not( hasItem( containsString( "1.1.0-M1" ) ) ) ); - } - finally - { + List output = Files.readAllLines(outputFile.toPath(), UTF_8); + assertThat(output, not(hasItem(containsString("1.1.0-M1")))); + } finally { assert outputFile == null || !outputFile.exists() || outputFile.delete(); } } @Test - public void testVersionInterpolation() throws Exception - { + public void testVersionInterpolation() throws Exception { File outputFile = null; - try - { - outputFile = File.createTempFile( "display-dependency-updates", "" ); + try { + outputFile = File.createTempFile("display-dependency-updates", ""); assert outputFile.exists(); DisplayDependencyUpdatesMojo mojo = (DisplayDependencyUpdatesMojo) mojoRule.lookupConfiguredMojo( - new File( "target/test-classes/org/codehaus/mojo/display-dependency-updates/version-interpolation" ), - "display-dependency-updates" ); + new File("target/test-classes/org/codehaus/mojo/display-dependency-updates/version-interpolation"), + "display-dependency-updates"); // This is just an example of how to create it-style tests as unit tests; the advantage is easier debugging mojo.outputFile = outputFile; - mojo.aetherRepositorySystem = mockAetherRepositorySystem( new HashMap() - {{ - put( "dummy-api", new String[] { "2.0.1" } ); - }} ); - setVariableValueToObject( mojo, "processDependencyManagementTransitive", false ); + mojo.aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { + { + put("dummy-api", new String[] {"2.0.1"}); + } + }); + setVariableValueToObject(mojo, "processDependencyManagementTransitive", false); mojo.execute(); - List output = Files.readAllLines( outputFile.toPath(), UTF_8 ); - assertThat( output, not( hasItem( containsString( "mycomponent.version" ) ) ) ); - } - finally - { + List output = Files.readAllLines(outputFile.toPath(), UTF_8); + assertThat(output, not(hasItem(containsString("mycomponent.version")))); + } finally { assert outputFile == null || !outputFile.exists() || outputFile.delete(); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojoTest.java index a1e78b1a3f..fabb909a41 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojoTest.java @@ -40,72 +40,64 @@ /** * Unit tests for {@link DisplayPropertyUpdatesMojo} */ -public class DisplayPropertyUpdatesMojoTest extends AbstractMojoTestCase -{ +public class DisplayPropertyUpdatesMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); private Path tempDir; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - tempDir = TestUtils.createTempDir( "display-property-updates" ); + tempDir = TestUtils.createTempDir("display-property-updates"); } @After - public void tearDown() throws Exception - { - try - { - TestUtils.tearDownTempDir( tempDir ); - } - finally - { + public void tearDown() throws Exception { + try { + TestUtils.tearDownTempDir(tempDir); + } finally { super.tearDown(); } } @Test - public void testPropertiesFromParent() throws Exception - { - Path tempFile = Files.createTempFile( tempDir, "output", "" ); + public void testPropertiesFromParent() throws Exception { + Path tempFile = Files.createTempFile(tempDir, "output", ""); - TestUtils.copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/display-property-updates/issue-367" ), - tempDir ); - DisplayPropertyUpdatesMojo mojo = - (DisplayPropertyUpdatesMojo) mojoRule.lookupConfiguredMojo( tempDir.resolve( "child" ).toFile(), - "display-property-updates" ); + TestUtils.copyDir( + Paths.get("src/test/resources/org/codehaus/mojo/display-property-updates/issue-367"), tempDir); + DisplayPropertyUpdatesMojo mojo = (DisplayPropertyUpdatesMojo) + mojoRule.lookupConfiguredMojo(tempDir.resolve("child").toFile(), "display-property-updates"); mojo.outputEncoding = UTF_8; mojo.outputFile = tempFile.toFile(); - mojo.setPluginContext( new HashMap<>() ); + mojo.setPluginContext(new HashMap<>()); mojo.aetherRepositorySystem = mockAetherRepositorySystem(); mojo.includeParent = true; mojo.execute(); - assertThat( String.join( "", Files.readAllLines( tempFile ) ), - matchesPattern( ".*\\$\\{ver} \\.* 1\\.0\\.0 -> 2\\.0\\.0.*" ) ); + assertThat( + String.join("", Files.readAllLines(tempFile)), + matchesPattern(".*\\$\\{ver} \\.* 1\\.0\\.0 -> 2\\.0\\.0.*")); } @Test - public void testDisablePropertiesFromParent() throws Exception - { - Path tempFile = Files.createTempFile( tempDir, "output", "" ); + public void testDisablePropertiesFromParent() throws Exception { + Path tempFile = Files.createTempFile(tempDir, "output", ""); - TestUtils.copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/display-property-updates/issue-367" ), - tempDir ); - DisplayPropertyUpdatesMojo mojo = - (DisplayPropertyUpdatesMojo) mojoRule.lookupConfiguredMojo( tempDir.resolve( "child" ).toFile(), - "display-property-updates" ); + TestUtils.copyDir( + Paths.get("src/test/resources/org/codehaus/mojo/display-property-updates/issue-367"), tempDir); + DisplayPropertyUpdatesMojo mojo = (DisplayPropertyUpdatesMojo) + mojoRule.lookupConfiguredMojo(tempDir.resolve("child").toFile(), "display-property-updates"); mojo.outputEncoding = UTF_8; mojo.outputFile = tempFile.toFile(); - mojo.setPluginContext( new HashMap<>() ); + mojo.setPluginContext(new HashMap<>()); mojo.aetherRepositorySystem = mockAetherRepositorySystem(); mojo.includeParent = false; mojo.execute(); - assertThat( String.join( "", Files.readAllLines( tempFile ) ), - not( matchesPattern( ".*\\$\\{ver} \\.* 1\\.0\\.0 -> 2\\.0\\.0.*" ) ) ); + assertThat( + String.join("", Files.readAllLines(tempFile)), + not(matchesPattern(".*\\$\\{ver} \\.* 1\\.0\\.0 -> 2\\.0\\.0.*"))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ForceReleasesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ForceReleasesMojoTest.java index 5f1aee06b8..6dd54904aa 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ForceReleasesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ForceReleasesMojoTest.java @@ -53,158 +53,167 @@ /** * Unit tests for {@link ForceReleasesMojo} */ -public class ForceReleasesMojoTest extends AbstractMojoTestCase -{ +public class ForceReleasesMojoTest extends AbstractMojoTestCase { private TestChangeRecorder changeRecorder; private ForceReleasesMojo mojo; @Before - public void setUp() throws IllegalAccessException - { + public void setUp() throws IllegalAccessException { changeRecorder = new TestChangeRecorder(); - mojo = new ForceReleasesMojo( mockRepositorySystem(), - mockAetherRepositorySystem(), - null, - changeRecorder.asTestMap() ); - setVariableValueToObject( mojo, "reactorProjects", emptyList() ); - mojo.project = new MavenProject() - {{ - setModel( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "default-artifact" ); - setVersion( "1.0.0" ); - }} ); - }}; + mojo = new ForceReleasesMojo( + mockRepositorySystem(), mockAetherRepositorySystem(), null, changeRecorder.asTestMap()); + setVariableValueToObject(mojo, "reactorProjects", emptyList()); + mojo.project = new MavenProject() { + { + setModel(new Model() { + { + setGroupId("default-group"); + setArtifactId("default-artifact"); + setVersion("1.0.0"); + } + }); + } + }; mojo.session = mockMavenSession(); } @Test public void testProcessParent() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processParent", true ); - mojo.getProject().setParent( new MavenProject( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "artifactA" ); - setVersion( "1.0.0-SNAPSHOT" ); - }} ) ); - mojo.getProject().setParentArtifact( new DefaultArtifact( "default-group", "artifactA", - "1.0.0-SNAPSHOT", SCOPE_COMPILE, "pom", "default", null ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), anyString() ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processParent", true); + mojo.getProject().setParent(new MavenProject(new Model() { + { + setGroupId("default-group"); + setArtifactId("artifactA"); + setVersion("1.0.0-SNAPSHOT"); + } + })); + mojo.getProject() + .setParentArtifact(new DefaultArtifact( + "default-group", "artifactA", "1.0.0-SNAPSHOT", SCOPE_COMPILE, "pom", "default", null)); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), anyString())) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "artifactA", - "1.0.0-SNAPSHOT", "1.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "artifactA", + "1.0.0-SNAPSHOT", "1.0.0"))); } @Test public void testReplaceSnapshotWithRelease() - throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException - { - mojo.getProject().setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "artifactA" ) - .withVersion( "1.0.0-SNAPSHOT" ) - .build() ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), anyString(), anyString(), anyString(), - anyString(), any( Model.class ) ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject() + .setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("artifactA") + .withVersion("1.0.0-SNAPSHOT") + .build())); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion( + any(), anyString(), anyString(), anyString(), anyString(), any(Model.class))) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "artifactA", - "1.0.0-SNAPSHOT", "1.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "artifactA", + "1.0.0-SNAPSHOT", "1.0.0"))); } @Test public void testUpgrade() - throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException - { - mojo.getProject().setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "artifactA" ) - .withVersion( "1.1.0-SNAPSHOT" ) - .build() ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), anyString(), anyString(), anyString(), - anyString(), any( Model.class ) ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject() + .setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("artifactA") + .withVersion("1.1.0-SNAPSHOT") + .build())); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion( + any(), anyString(), anyString(), anyString(), anyString(), any(Model.class))) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "artifactA", - "1.1.0-SNAPSHOT", "2.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "artifactA", + "1.1.0-SNAPSHOT", "2.0.0"))); } @Test public void testDowngrade() - throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException - { - mojo.getProject().setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "artifactA" ) - .withVersion( "2.1.0-SNAPSHOT" ) - .build() ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), anyString(), anyString(), anyString(), - anyString(), any( Model.class ) ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject() + .setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("artifactA") + .withVersion("2.1.0-SNAPSHOT") + .build())); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion( + any(), anyString(), anyString(), anyString(), anyString(), any(Model.class))) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "artifactA", - "2.1.0-SNAPSHOT", "2.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "artifactA", + "2.1.0-SNAPSHOT", "2.0.0"))); } @Test public void testFailIfNotReplaced() - throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException - { - mojo.aetherRepositorySystem = mockAetherRepositorySystem( singletonMap( "test-artifact", - new String[] {} ) ); - mojo.getProject().setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "test-artifact" ) - .withVersion( "1.0.0-SNAPSHOT" ) - .build() ) ); + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.aetherRepositorySystem = mockAetherRepositorySystem(singletonMap("test-artifact", new String[] {})); + mojo.getProject() + .setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("test-artifact") + .withVersion("1.0.0-SNAPSHOT") + .build())); mojo.failIfNotReplaced = true; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), anyString(), anyString(), anyString(), - anyString(), any( Model.class ) ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); - fail( "MojoExecutionException is expected" ); - } - catch ( MojoExecutionException e ) - { - assertThat( e.getMessage(), startsWith( "No matching" ) ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion( + any(), anyString(), anyString(), anyString(), anyString(), any(Model.class))) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); + fail("MojoExecutionException is expected"); + } catch (MojoExecutionException e) { + assertThat(e.getMessage(), startsWith("No matching")); } } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinderTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinderTest.java index 73bb50082d..a2caf7a981 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinderTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/MinimalMavenBuildVersionFinderTest.java @@ -9,40 +9,32 @@ /** * Unit tests for MinimalMavenBuildVersionFinder. */ -public class MinimalMavenBuildVersionFinderTest -{ +public class MinimalMavenBuildVersionFinderTest { @Test - public void testValidVersionRanges() - { - DefaultArtifactVersion expectedMinimumVersion = new DefaultArtifactVersion( "1.0" ); - assertEquals( expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "1.0" ) ); - assertEquals( expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "[1.0]" ) ); - assertEquals( expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "[1.0,)" ) ); - assertEquals( expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(1.0,)" ) ); - assertEquals( expectedMinimumVersion, - MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "[1.0,2.0]" ) ); - assertEquals( expectedMinimumVersion, - MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(1.0,2.0)" ) ); - assertEquals( expectedMinimumVersion, - MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(1.0,2.0]" ) ); - assertEquals( expectedMinimumVersion, - MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "[1.0,2.0)" ) ); + public void testValidVersionRanges() { + DefaultArtifactVersion expectedMinimumVersion = new DefaultArtifactVersion("1.0"); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("1.0")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("[1.0]")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("[1.0,)")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(1.0,)")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("[1.0,2.0]")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(1.0,2.0)")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(1.0,2.0]")); + assertEquals(expectedMinimumVersion, MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("[1.0,2.0)")); } @Test - public void testInvalidVersionRanges() - { - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(,1.0]" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(,1.0)" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(,1.0],[1.2,)" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(,1.1),(1.1,)" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(,1.1),[1.1,)" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(1.0" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "1.0)" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "1.0()" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "()1.0" ) ); - assertNull( MinimalMavenBuildVersionFinder.getMinimumVersionFromRange( "(1.0]" ) ); + public void testInvalidVersionRanges() { + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(,1.0]")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(,1.0)")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(,1.0],[1.2,)")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(,1.1),(1.1,)")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(,1.1),[1.1,)")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(1.0")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("1.0)")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("1.0()")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("()1.0")); + assertNull(MinimalMavenBuildVersionFinder.getMinimumVersionFromRange("(1.0]")); } - } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ParentUpdatesReportMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ParentUpdatesReportMojoTest.java index 449f3d025c..78a82608a6 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ParentUpdatesReportMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/ParentUpdatesReportMojoTest.java @@ -51,45 +51,61 @@ * * @author Andrzej Jarmoniuk */ -public class ParentUpdatesReportMojoTest -{ +public class ParentUpdatesReportMojoTest { private static final I18N MOCK_I18N = mockI18N(); + @Test - public void testAllowSnapshots() throws IOException, MavenReportException - { + public void testAllowSnapshots() throws IOException, MavenReportException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); - new ParentUpdatesReportMojo( MOCK_I18N, mockRepositorySystem(), - mockAetherRepositorySystem( new HashMap() - {{ - put( "default-artifact", new String[] {"1.0.0", "1.0.1", "1.1.0", "2.0.0", "2.0.1-SNAPSHOT"} ); - }} ), null, new ReportRendererFactoryImpl( MOCK_I18N ) ) - {{ - allowSnapshots = true; - project = new MavenProject( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "child-artifact" ); - setVersion( "1.0.0" ); - }} ); - project.setParent( new MavenProject( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "default-artifact" ); - setVersion( "1.0.0" ); - }} ) ); - reactorProjects = new ArrayList<>(); - project.setParentArtifact( new DefaultArtifact( project.getParent().getGroupId(), - project.getParent().getArtifactId(), project.getParent().getVersion(), - Artifact.SCOPE_COMPILE, "pom", "default", - new DefaultArtifactHandlerStub( "default" ) ) ); + new ParentUpdatesReportMojo( + MOCK_I18N, + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put("default-artifact", new String[] {"1.0.0", "1.0.1", "1.1.0", "2.0.0", "2.0.1-SNAPSHOT"}); + } + }), + null, + new ReportRendererFactoryImpl(MOCK_I18N)) { + { + allowSnapshots = true; + project = new MavenProject(new Model() { + { + setGroupId("default-group"); + setArtifactId("child-artifact"); + setVersion("1.0.0"); + } + }); + project.setParent(new MavenProject(new Model() { + { + setGroupId("default-group"); + setArtifactId("default-artifact"); + setVersion("1.0.0"); + } + })); + reactorProjects = new ArrayList<>(); + project.setParentArtifact(new DefaultArtifact( + project.getParent().getGroupId(), + project.getParent().getArtifactId(), + project.getParent().getVersion(), + Artifact.SCOPE_COMPILE, + "pom", + "default", + new DefaultArtifactHandlerStub("default"))); - session = mockMavenSession(); - }}.generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + session = mockMavenSession(); + } + }.generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, allOf( containsString( "1.0.0" ), - containsString( "1.0.1" ), containsString( "1.1.0" ), - containsString( "2.0.0" ), containsString( "2.0.1-SNAPSHOT" ) ) ); + assertThat( + output, + allOf( + containsString("1.0.0"), + containsString("1.0.1"), + containsString("1.1.0"), + containsString("2.0.0"), + containsString("2.0.1-SNAPSHOT"))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesReportMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesReportMojoTest.java index 2342f299bd..4a752b081f 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesReportMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesReportMojoTest.java @@ -62,183 +62,169 @@ * * @author Andrzej Jarmoniuk */ -public class PluginUpdatesReportMojoTest -{ - private static class TestPluginUpdatesReportMojo extends PluginUpdatesReportMojo - { +public class PluginUpdatesReportMojoTest { + private static class TestPluginUpdatesReportMojo extends PluginUpdatesReportMojo { static final I18N MOCK_I18N = mockI18N(); - TestPluginUpdatesReportMojo() - { - super( MOCK_I18N, mockRepositorySystem(), mockAetherRepositorySystem(), - null, new ReportRendererFactoryImpl( MOCK_I18N ) ); + + TestPluginUpdatesReportMojo() { + super( + MOCK_I18N, + mockRepositorySystem(), + mockAetherRepositorySystem(), + null, + new ReportRendererFactoryImpl(MOCK_I18N)); siteTool = MockUtils.mockSiteTool(); project = new MavenProject(); - project.setBuild( new Build() ); - project.getBuild().setPluginManagement( new PluginManagement() ); + project.setBuild(new Build()); + project.getBuild().setPluginManagement(new PluginManagement()); session = mockMavenSession(); } - public TestPluginUpdatesReportMojo withPlugins( Plugin... plugins ) - { - project.getBuild().setPlugins( Arrays.asList( plugins ) ); + public TestPluginUpdatesReportMojo withPlugins(Plugin... plugins) { + project.getBuild().setPlugins(Arrays.asList(plugins)); return this; } public TestPluginUpdatesReportMojo withAetherRepositorySystem( - org.eclipse.aether.RepositorySystem repositorySystem ) - { + org.eclipse.aether.RepositorySystem repositorySystem) { this.aetherRepositorySystem = repositorySystem; return this; } - public TestPluginUpdatesReportMojo withPluginManagement( Plugin... pluginManagement ) - { - project.getBuild().getPluginManagement().setPlugins( Arrays.asList( pluginManagement ) ); + public TestPluginUpdatesReportMojo withPluginManagement(Plugin... pluginManagement) { + project.getBuild().getPluginManagement().setPlugins(Arrays.asList(pluginManagement)); return this; } - public TestPluginUpdatesReportMojo withOnlyUpgradable( boolean onlyUpgradable ) - { + public TestPluginUpdatesReportMojo withOnlyUpgradable(boolean onlyUpgradable) { this.onlyUpgradable = onlyUpgradable; return this; } - public TestPluginUpdatesReportMojo withOnlyProjectPlugins( boolean onlyProjectPlugins ) - { + public TestPluginUpdatesReportMojo withOnlyProjectPlugins(boolean onlyProjectPlugins) { this.onlyProjectPlugins = onlyProjectPlugins; return this; } - public TestPluginUpdatesReportMojo withRuleSet( - RuleSet ruleSet ) - { + public TestPluginUpdatesReportMojo withRuleSet(RuleSet ruleSet) { this.ruleSet = ruleSet; return this; } - public TestPluginUpdatesReportMojo withIgnoredVersions( - Set ignoredVersions ) - { + public TestPluginUpdatesReportMojo withIgnoredVersions(Set ignoredVersions) { this.ignoredVersions = ignoredVersions; return this; } - private static RepositorySystem mockRepositorySystem() - { - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - when( repositorySystem.createPluginArtifact( any( Plugin.class ) ) ).thenAnswer( - invocation -> - { - Plugin plugin = invocation.getArgument( 0 ); - return new DefaultArtifact( plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion(), - SCOPE_RUNTIME, "maven-plugin", "jar", - new DefaultArtifactHandlerStub( "default" ) ); - } ); + private static RepositorySystem mockRepositorySystem() { + RepositorySystem repositorySystem = mock(RepositorySystem.class); + when(repositorySystem.createPluginArtifact(any(Plugin.class))).thenAnswer(invocation -> { + Plugin plugin = invocation.getArgument(0); + return new DefaultArtifact( + plugin.getGroupId(), + plugin.getArtifactId(), + plugin.getVersion(), + SCOPE_RUNTIME, + "maven-plugin", + "jar", + new DefaultArtifactHandlerStub("default")); + }); return repositorySystem; } } - private static Plugin pluginOf( String artifactId ) - { - return pluginOf( artifactId, "1.0.0" ); + private static Plugin pluginOf(String artifactId) { + return pluginOf(artifactId, "1.0.0"); } - private static Plugin pluginOf( String artifactId, String version ) - { - return new Plugin() - { + private static Plugin pluginOf(String artifactId, String version) { + return new Plugin() { { - setGroupId( "defaultGroup" ); - setArtifactId( artifactId ); - setVersion( version ); + setGroupId("defaultGroup"); + setArtifactId(artifactId); + setVersion(version); } }; } @Test - public void testOnlyUpgradablePlugins() throws IOException, MavenReportException - { + public void testOnlyUpgradablePlugins() throws IOException, MavenReportException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestPluginUpdatesReportMojo() - .withAetherRepositorySystem( mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0" } ); - put( "artifactC", new String[] { "1.0.0", "2.0.0" } ); - }} ) ) - .withPlugins( pluginOf( "artifactA", "1.0.0" ), - pluginOf( "artifactB", "1.0.0" ), - pluginOf( "artifactC", "2.0.0" ) ) - .withOnlyUpgradable( true ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withAetherRepositorySystem(mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0"}); + put("artifactC", new String[] {"1.0.0", "2.0.0"}); + } + })) + .withPlugins( + pluginOf("artifactA", "1.0.0"), pluginOf("artifactB", "1.0.0"), pluginOf("artifactC", "2.0.0")) + .withOnlyUpgradable(true) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, containsString( "artifactA" ) ); - assertThat( output, not( containsString( "artifactB" ) ) ); - assertThat( output, not( containsString( "artifactC" ) ) ); + assertThat(output, containsString("artifactA")); + assertThat(output, not(containsString("artifactB"))); + assertThat(output, not(containsString("artifactC"))); } @Test - public void testOnlyUpgradableWithPluginManagement() throws IOException, MavenReportException - { + public void testOnlyUpgradableWithPluginManagement() throws IOException, MavenReportException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestPluginUpdatesReportMojo() - .withAetherRepositorySystem( mockAetherRepositorySystem( new HashMap() - {{ - put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); - put( "artifactB", new String[] { "1.0.0" } ); - put( "artifactC", new String[] { "1.0.0", "2.0.0" } ); - }} ) ) - .withPluginManagement( pluginOf( "artifactA", "1.0.0" ), - pluginOf( "artifactB", "1.0.0" ), - pluginOf( "artifactC", "2.0.0" ) ) - .withOnlyUpgradable( true ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withAetherRepositorySystem(mockAetherRepositorySystem(new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0"}); + put("artifactC", new String[] {"1.0.0", "2.0.0"}); + } + })) + .withPluginManagement( + pluginOf("artifactA", "1.0.0"), pluginOf("artifactB", "1.0.0"), pluginOf("artifactC", "2.0.0")) + .withOnlyUpgradable(true) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, containsString( "artifactA" ) ); - assertThat( output, not( containsString( "artifactB" ) ) ); - assertThat( output, not( containsString( "artifactC" ) ) ); + assertThat(output, containsString("artifactA")); + assertThat(output, not(containsString("artifactB"))); + assertThat(output, not(containsString("artifactC"))); } @Test - public void testOnlyProjectPlugins() throws IOException, MavenReportException - { + public void testOnlyProjectPlugins() throws IOException, MavenReportException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestPluginUpdatesReportMojo() - .withPlugins( pluginOf( "artifactA" ) ) - .withPluginManagement( pluginOf( "artifactA" ), pluginOf( "artifactB" ), - pluginOf( "artifactC" ) ) - .withOnlyUpgradable( true ) - .withOnlyProjectPlugins( true ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + .withPlugins(pluginOf("artifactA")) + .withPluginManagement(pluginOf("artifactA"), pluginOf("artifactB"), pluginOf("artifactC")) + .withOnlyUpgradable(true) + .withOnlyProjectPlugins(true) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString(); - assertThat( output, containsString( "artifactA" ) ); - assertThat( output, not( anyOf( containsString( "artifactB" ), containsString( "artifactC" ) ) ) ); + assertThat(output, containsString("artifactA")); + assertThat(output, not(anyOf(containsString("artifactB"), containsString("artifactC")))); } @Test - public void testOnlyProjectPluginsWithIgnoredVersions() throws IOException, MavenReportException - { + public void testOnlyProjectPluginsWithIgnoredVersions() throws IOException, MavenReportException { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); new TestPluginUpdatesReportMojo() - .withPlugins( pluginOf( "artifactA" ) ) - .withPluginManagement( pluginOf( "artifactA" ), pluginOf( "artifactB" ), - pluginOf( "artifactC" ) ) - .withOnlyUpgradable( true ) - .withOnlyProjectPlugins( true ) - .withIgnoredVersions( Collections.singleton( "2.0.0" ) ) - .generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); - - String output = os.toString().replaceAll( "\\s", " " ) - .replaceAll( "<[^>]+>", " " ).replaceAll( "&[^;]+;", " " ); - assertThat( output, matchesPattern( ".*\\breport.overview.numNewerVersionAvailable\\s+0\\b.*" ) ); + .withPlugins(pluginOf("artifactA")) + .withPluginManagement(pluginOf("artifactA"), pluginOf("artifactB"), pluginOf("artifactC")) + .withOnlyUpgradable(true) + .withOnlyProjectPlugins(true) + .withIgnoredVersions(Collections.singleton("2.0.0")) + .generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); + + String output = + os.toString().replaceAll("\\s", " ").replaceAll("<[^>]+>", " ").replaceAll("&[^;]+;", " "); + assertThat(output, matchesPattern(".*\\breport.overview.numNewerVersionAvailable\\s+0\\b.*")); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesXmlRendererTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesXmlRendererTest.java index a0b9cb2e15..a25b092bc0 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesXmlRendererTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PluginUpdatesXmlRendererTest.java @@ -50,80 +50,73 @@ * * @author Andrzej Jarmoniuk */ -public class PluginUpdatesXmlRendererTest -{ +public class PluginUpdatesXmlRendererTest { private Path tempFile; @Before - public void setUp() throws IOException - { - tempFile = Files.createTempFile( "xml-plugin-report", "" ); + public void setUp() throws IOException { + tempFile = Files.createTempFile("xml-plugin-report", ""); } @After - public void tearDown() throws IOException - { - if ( tempFile != null && Files.exists( tempFile ) ) - { - Files.delete( tempFile ); + public void tearDown() throws IOException { + if (tempFile != null && Files.exists(tempFile)) { + Files.delete(tempFile); } } @Test - public void testReportGeneration() throws IOException - { + public void testReportGeneration() throws IOException { PluginUpdatesModel pluginUpdates = new PluginUpdatesModel( singletonMap( - pluginOf( "default-group", "artifactA", "1.0.0" ), + pluginOf("default-group", "artifactA", "1.0.0"), new PluginUpdatesDetails( new ArtifactVersions( - artifactOf( "default-group", "artifactA", "1.0.0" ), - Stream.of( "1.0.0", "1.0.1", "1.1.0", "2.0.0" ) - .map( DefaultArtifactVersion::new ) - .collect( Collectors.toList() ), - new MavenVersionComparator() ), - singletonMap( DependencyBuilder.dependencyWith( "default-group", "artifactB", - "1.0.0" ), + artifactOf("default-group", "artifactA", "1.0.0"), + Stream.of("1.0.0", "1.0.1", "1.1.0", "2.0.0") + .map(DefaultArtifactVersion::new) + .collect(Collectors.toList()), + new MavenVersionComparator()), + singletonMap( + DependencyBuilder.dependencyWith("default-group", "artifactB", "1.0.0"), new ArtifactVersions( - artifactOf( "default-group", "artifactB", "1.0.0" ), - Stream.of( "1.0.0", "1.0.1-SNAPSHOT", "1.1.0-rc1", "2.0.0" ) - .map( DefaultArtifactVersion::new ) - .collect( Collectors.toList() ), - new MavenVersionComparator() ) ), false ) ), - emptyMap() ); - new PluginUpdatesXmlReportRenderer( pluginUpdates, tempFile ).render(); + artifactOf("default-group", "artifactB", "1.0.0"), + Stream.of("1.0.0", "1.0.1-SNAPSHOT", "1.1.0-rc1", "2.0.0") + .map(DefaultArtifactVersion::new) + .collect(Collectors.toList()), + new MavenVersionComparator())), + false)), + emptyMap()); + new PluginUpdatesXmlReportRenderer(pluginUpdates, tempFile).render(); - String output = String.join( "", Files.readAllLines( tempFile ) ) - .replaceAll( ">\\s*<", "><" ); + String output = String.join("", Files.readAllLines(tempFile)).replaceAll(">\\s*<", "><"); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "1" ) ); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "0" ) ); - assertThat( output, containsString( "1" ) ); + assertThat(output, containsString("0")); + assertThat(output, containsString("0")); + assertThat(output, containsString("1")); + assertThat(output, containsString("0")); + assertThat(output, containsString("0")); + assertThat(output, containsString("1")); - assertThat( output, containsString( "1.0.0" ) ); - assertThat( output, containsString( "2.0.0" ) ); - assertThat( output, containsString( "1.0.1" ) ); - assertThat( output, containsString( "1.1.0" ) ); - assertThat( output, containsString( "2.0.0" ) ); - assertThat( output, containsString( "incremental available" ) ); + assertThat(output, containsString("1.0.0")); + assertThat(output, containsString("2.0.0")); + assertThat(output, containsString("1.0.1")); + assertThat(output, containsString("1.1.0")); + assertThat(output, containsString("2.0.0")); + assertThat(output, containsString("incremental available")); } - private static DefaultArtifact artifactOf( String groupId, String artifactId, String version ) - { - return new DefaultArtifact( groupId, artifactId, version, SCOPE_COMPILE, "jar", "default", - null ); + private static DefaultArtifact artifactOf(String groupId, String artifactId, String version) { + return new DefaultArtifact(groupId, artifactId, version, SCOPE_COMPILE, "jar", "default", null); } - private static Plugin pluginOf( String groupId, String artifactId, String version ) - { - return new Plugin() - {{ - setGroupId( groupId ); - setArtifactId( artifactId ); - setVersion( version ); - }}; + private static Plugin pluginOf(String groupId, String artifactId, String version) { + return new Plugin() { + { + setGroupId(groupId); + setArtifactId(artifactId); + setVersion(version); + } + }; } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java index 89f0a75cc7..7dba45d2e7 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java @@ -40,54 +40,50 @@ /** * Unit tests for {@link PropertyUpdatesReportMojo} */ -public class PropertyUpdatesReportMojoTest extends AbstractMojoTestCase -{ +public class PropertyUpdatesReportMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); + private static final org.eclipse.aether.RepositorySystem AETHER_REPOSITORY_SYSTEM = mockAetherRepositorySystem(); private static final SiteTool SITE_TOOL = mockSiteTool(); @Test - public void testIncludeParentTrueShouldContainProperty() throws Exception - { + public void testIncludeParentTrueShouldContainProperty() throws Exception { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); - PropertyUpdatesReportMojo mojo = - (PropertyUpdatesReportMojo) mojoRule.lookupConfiguredMojo( - new File( "src/test/resources/org/codehaus/mojo/display-property-updates/issue-367/child" ), - "property-updates-report" ); - setVariableValueToObject( mojo, "siteTool", SITE_TOOL ); - setVariableValueToObject( mojo, "aetherRepositorySystem", AETHER_REPOSITORY_SYSTEM ); - setVariableValueToObject( mojo, "includeParent", true ); - mojo.generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + PropertyUpdatesReportMojo mojo = (PropertyUpdatesReportMojo) mojoRule.lookupConfiguredMojo( + new File("src/test/resources/org/codehaus/mojo/display-property-updates/issue-367/child"), + "property-updates-report"); + setVariableValueToObject(mojo, "siteTool", SITE_TOOL); + setVariableValueToObject(mojo, "aetherRepositorySystem", AETHER_REPOSITORY_SYSTEM); + setVariableValueToObject(mojo, "includeParent", true); + mojo.generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString() - .replaceAll( "<[^>]+>", " " ) - .replaceAll( "&[^;]+;", " " ) - .replaceAll( "\\s+", " " ); - assertThat( output, containsString( "${ver}" ) ); + .replaceAll("<[^>]+>", " ") + .replaceAll("&[^;]+;", " ") + .replaceAll("\\s+", " "); + assertThat(output, containsString("${ver}")); } @Test - public void testIncludeParentFalseShouldNotContainProperty() throws Exception - { + public void testIncludeParentFalseShouldNotContainProperty() throws Exception { OutputStream os = new ByteArrayOutputStream(); SinkFactory sinkFactory = new Xhtml5SinkFactory(); - PropertyUpdatesReportMojo mojo = - (PropertyUpdatesReportMojo) mojoRule.lookupConfiguredMojo( - new File( "src/test/resources/org/codehaus/mojo/display-property-updates/issue-367/child" ), - "property-updates-report" ); - setVariableValueToObject( mojo, "siteTool", SITE_TOOL ); - setVariableValueToObject( mojo, "aetherRepositorySystem", AETHER_REPOSITORY_SYSTEM ); - setVariableValueToObject( mojo, "includeParent", false ); - mojo.generate( sinkFactory.createSink( os ), sinkFactory, Locale.getDefault() ); + PropertyUpdatesReportMojo mojo = (PropertyUpdatesReportMojo) mojoRule.lookupConfiguredMojo( + new File("src/test/resources/org/codehaus/mojo/display-property-updates/issue-367/child"), + "property-updates-report"); + setVariableValueToObject(mojo, "siteTool", SITE_TOOL); + setVariableValueToObject(mojo, "aetherRepositorySystem", AETHER_REPOSITORY_SYSTEM); + setVariableValueToObject(mojo, "includeParent", false); + mojo.generate(sinkFactory.createSink(os), sinkFactory, Locale.getDefault()); String output = os.toString() - .replaceAll( "<[^>]+>", " " ) - .replaceAll( "&[^;]+;", " " ) - .replaceAll( "\\s+", " " ); - assertThat( output, not( containsString( "${ver}" ) ) ); + .replaceAll("<[^>]+>", " ") + .replaceAll("&[^;]+;", " ") + .replaceAll("\\s+", " "); + assertThat(output, not(containsString("${ver}"))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RevertMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RevertMojoTest.java index ceb31ea1e6..8e84921307 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RevertMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RevertMojoTest.java @@ -42,52 +42,43 @@ * * @author Andrzej Jarmoniuk */ -public class RevertMojoTest extends AbstractMojoTestCase -{ +public class RevertMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); + private Path pomDir; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - pomDir = Files.createTempDirectory( "revert-" ); + pomDir = Files.createTempDirectory("revert-"); } @After - public void tearDown() throws Exception - { - try - { - if ( pomDir != null && pomDir.toFile().exists() ) - { - Arrays.stream( Objects.requireNonNull( pomDir.toFile().listFiles() ) ).forEach( File::delete ); + public void tearDown() throws Exception { + try { + if (pomDir != null && pomDir.toFile().exists()) { + Arrays.stream(Objects.requireNonNull(pomDir.toFile().listFiles())) + .forEach(File::delete); pomDir.toFile().delete(); } - } - finally - { + } finally { super.tearDown(); } } - public void testRevert() throws Exception - { - copyDirectory( new File( getBasedir(), - "target/test-classes/org/codehaus/mojo/revert/issue-265" ), pomDir.toFile() ); - RevertMojo myMojo = (RevertMojo) mojoRule.lookupConfiguredMojo( - new File( pomDir.toString(), "aggregate" ), "revert" ); + public void testRevert() throws Exception { + copyDirectory( + new File(getBasedir(), "target/test-classes/org/codehaus/mojo/revert/issue-265"), pomDir.toFile()); + RevertMojo myMojo = + (RevertMojo) mojoRule.lookupConfiguredMojo(new File(pomDir.toString(), "aggregate"), "revert"); myMojo.execute(); - assertThat( join( "\n", Files.readAllLines( pomDir.resolve( "aggregate/pom.xml" ) ) ), - containsString( "OLD" ) ); - assertThat( Files.exists( pomDir.resolve( "aggregate/pom.xml.versionsBackup" ) ), is( false ) ); - assertThat( join( "\n", Files.readAllLines( pomDir.resolve( "module-a/pom.xml" ) ) ), - containsString( "OLD" ) ); - assertThat( Files.exists( pomDir.resolve( "module-a/pom.xml.versionsBackup" ) ), is( false ) ); - assertThat( join( "\n", Files.readAllLines( pomDir.resolve( "module-b/pom.xml" ) ) ), - containsString( "OLD" ) ); - assertThat( Files.exists( pomDir.resolve( "module-b/pom.xml.versionsBackup" ) ), is( false ) ); + assertThat(join("\n", Files.readAllLines(pomDir.resolve("aggregate/pom.xml"))), containsString("OLD")); + assertThat(Files.exists(pomDir.resolve("aggregate/pom.xml.versionsBackup")), is(false)); + assertThat(join("\n", Files.readAllLines(pomDir.resolve("module-a/pom.xml"))), containsString("OLD")); + assertThat(Files.exists(pomDir.resolve("module-a/pom.xml.versionsBackup")), is(false)); + assertThat(join("\n", Files.readAllLines(pomDir.resolve("module-b/pom.xml"))), containsString("OLD")); + assertThat(Files.exists(pomDir.resolve("module-b/pom.xml.versionsBackup")), is(false)); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RewriteWithStAXTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RewriteWithStAXTest.java index 76a70b1471..459a55ea71 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RewriteWithStAXTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/RewriteWithStAXTest.java @@ -44,199 +44,205 @@ * * @author Stephen Connolly */ -public class RewriteWithStAXTest -{ +public class RewriteWithStAXTest { @Test - public void testBasic() - throws Exception - { + public void testBasic() throws Exception { String input = "\n" + "\n\r\n\r\n\r\n\r" + " \r\n" - + " org.codehaus.mojo\n" - + " mojo-&sandbox-parent\n" + " 5-SNAPSHOT\r" - + " \r" + ""; + + " org.codehaus.mojo\n" + + " mojo-&sandbox-parent\n" + " 5-SNAPSHOT\r" + + " \r" + ""; - byte[] rawInput = input.getBytes( StandardCharsets.UTF_8 ); - ByteArrayInputStream source = new ByteArrayInputStream( rawInput ); + byte[] rawInput = input.getBytes(StandardCharsets.UTF_8); + ByteArrayInputStream source = new ByteArrayInputStream(rawInput); ByteArrayOutputStream dest = new ByteArrayOutputStream(); XMLInputFactory inputFactory = XMLInputFactory2.newInstance(); - inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE ); + inputFactory.setProperty(XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); - XMLEventReader eventReader = inputFactory.createXMLEventReader( source ); - XMLEventWriter eventWriter = outputFactory.createXMLEventWriter( dest, "utf-8" ); - while ( eventReader.hasNext() ) - { - eventWriter.add( eventReader.nextEvent() ); + XMLEventReader eventReader = inputFactory.createXMLEventReader(source); + XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(dest, "utf-8"); + while (eventReader.hasNext()) { + eventWriter.add(eventReader.nextEvent()); } - String output = dest.toString( "utf-8" ); + String output = dest.toString("utf-8"); - assertNotEquals( "StAX implementation is not good enough", input, output ); + assertNotEquals("StAX implementation is not good enough", input, output); } @Test - public void testReplace() - throws Exception - { + public void testReplace() throws Exception { String input = "\n" + "\n\r\n\r\n\r\n\r" + " \r\n" - + " org.codehaus.mojo\n" - + " mojo-&sandbox-parent\n" + " 5-SNAPSHOT\r" - + " \r" + ""; + + " org.codehaus.mojo\n" + + " mojo-&sandbox-parent\n" + " 5-SNAPSHOT\r" + + " \r" + ""; String expected = "\n" + "\n\r\n\r\n\r\n\r" + " \r\n" - + " org.codehaus.mojo\n" + " my-artifact\n" - + " 5-SNAPSHOT\r" + " \r" + ""; + + " org.codehaus.mojo\n" + + " my-artifact\n" + + " 5-SNAPSHOT\r" + " \r" + ""; - StringBuilder output = new StringBuilder( input ); + StringBuilder output = new StringBuilder(input); XMLInputFactory inputFactory = XMLInputFactory2.newInstance(); - inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE ); - ModifiedPomXMLEventReader eventReader = new ModifiedPomXMLEventReader( output, inputFactory, null ); - while ( eventReader.hasNext() ) - { + inputFactory.setProperty(XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE); + ModifiedPomXMLEventReader eventReader = new ModifiedPomXMLEventReader(output, inputFactory, null); + while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); - if ( event instanceof StartElement - && event.asStartElement().getName().getLocalPart().equals( "artifactId" ) ) - { - eventReader.mark( 0 ); + if (event instanceof StartElement + && event.asStartElement().getName().getLocalPart().equals("artifactId")) { + eventReader.mark(0); } - if ( event instanceof EndElement && event.asEndElement().getName().getLocalPart().equals( "artifactId" ) ) - { - eventReader.mark( 1 ); - if ( eventReader.hasMark( 0 ) ) - { - eventReader.replaceBetween( 0, 1, "my-artifact" ); + if (event instanceof EndElement + && event.asEndElement().getName().getLocalPart().equals("artifactId")) { + eventReader.mark(1); + if (eventReader.hasMark(0)) { + eventReader.replaceBetween(0, 1, "my-artifact"); } } } - assertEquals( expected, output.toString() ); + assertEquals(expected, output.toString()); } - @SuppressWarnings( {"checkstyle:MethodLength", "checkstyle:LineLength"} ) + @SuppressWarnings({"checkstyle:MethodLength", "checkstyle:LineLength"}) @Test - public void testReplaceFancy() - throws Exception - { + public void testReplaceFancy() throws Exception { String input = - "\n" - + " 4.0.0\n" + "\n" + " \n" - + " org.codehaus.mojo\n" + " mojo-sandbox-parent\n" - + " 5-SNAPSHOT\n" + " \n" + "\n" - + " org.codehaus.mojo\n" + " versions-maven-plugin\n" - + " 1.0.0-alpha-1-SNAPSHOT\n" + " maven-plugin\n" + "\n" - + " Versions Maven Plugin\n" + " \n" - + " Versions plugin for Maven 2. The versions plugin updates the versions of components in the pom.\n" - + " \n" + " 2008\n" + " \n" - + " \n" + " The Apache Software License, Version 2.0\n" - + " http://www.apache.org/licenses/LICENSE-2.0\n" - + " repo\n" + " \n" + " \n" + "\n" - + " \n" - + " scm:svn:http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" - + " scm:svn:https://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" - + " http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + " \n" - + "\n" + " \n" + " \n" + " Stephen Connolly\n" - + " stephen.alan.connolly@gmail.com\n" + " \n" - + " Java Developer\n" + " \n" + " 0\n" - + " \n" + " \n" + "\n" + " \n" - + " 2.0.6\n" + " \n" + "\n" + " \n" - + " \n" + " junit\n" + " junit\n" - + " 3.8.1\n" + " test\n" + " \n" - + " \n" + " org.apache.maven\n" - + " maven-project\n" + " 2.0\n" - + " \n" + " \n" + " org.apache.maven\n" - + " maven-settings\n" + " 2.0\n" - + " \n" + " \n" + " org.apache.maven\n" - + " maven-plugin-api\n" + " 2.0\n" - + " \n" + " \n" + " org.codehaus.plexus\n" - + " plexus-utils\n" + " 1.3\n" - + " \n" + " \n" + " org.codehaus.plexus\n" - + " plexus-interactivity-api\n" + " 1.0-alpha-6\n" - + " \n" + " \n" + " plexus-utils\n" - + " plexus\n" + " \n" + " \n" - + " \n" + " \n" + " javax.xml.stream\n" - + " stax-api\n" + " 1.0-2\n" - + " \n" + " \n" + " stax\n" - + " stax\n" + " 1.1.1-dev\n" - + " \n" + " \n" + "\n" + " \n" + " \n" - + " \n" + " maven-plugin-plugin\n" - + " 2.3\n" + " \n" - + " versions\n" + " \n" + " \n" - + " \n" + " \n" + "\n" + ""; + "\n" + + " 4.0.0\n" + "\n" + " \n" + + " org.codehaus.mojo\n" + + " mojo-sandbox-parent\n" + + " 5-SNAPSHOT\n" + " \n" + "\n" + + " org.codehaus.mojo\n" + + " versions-maven-plugin\n" + + " 1.0.0-alpha-1-SNAPSHOT\n" + " maven-plugin\n" + + "\n" + + " Versions Maven Plugin\n" + " \n" + + " Versions plugin for Maven 2. The versions plugin updates the versions of components in the pom.\n" + + " \n" + " 2008\n" + " \n" + + " \n" + " The Apache Software License, Version 2.0\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + " repo\n" + " \n" + " \n" + "\n" + + " \n" + + " scm:svn:http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + + " scm:svn:https://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + + " http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + + " \n" + + "\n" + " \n" + " \n" + " Stephen Connolly\n" + + " stephen.alan.connolly@gmail.com\n" + " \n" + + " Java Developer\n" + " \n" + + " 0\n" + + " \n" + " \n" + "\n" + " \n" + + " 2.0.6\n" + " \n" + "\n" + " \n" + + " \n" + " junit\n" + + " junit\n" + + " 3.8.1\n" + " test\n" + " \n" + + " \n" + " org.apache.maven\n" + + " maven-project\n" + " 2.0\n" + + " \n" + " \n" + " org.apache.maven\n" + + " maven-settings\n" + " 2.0\n" + + " \n" + " \n" + " org.apache.maven\n" + + " maven-plugin-api\n" + " 2.0\n" + + " \n" + " \n" + + " org.codehaus.plexus\n" + + " plexus-utils\n" + " 1.3\n" + + " \n" + " \n" + + " org.codehaus.plexus\n" + + " plexus-interactivity-api\n" + + " 1.0-alpha-6\n" + + " \n" + " \n" + + " plexus-utils\n" + + " plexus\n" + " \n" + " \n" + + " \n" + " \n" + " javax.xml.stream\n" + + " stax-api\n" + " 1.0-2\n" + + " \n" + " \n" + " stax\n" + + " stax\n" + " 1.1.1-dev\n" + + " \n" + " \n" + "\n" + " \n" + " \n" + + " \n" + " maven-plugin-plugin\n" + + " 2.3\n" + " \n" + + " versions\n" + " \n" + + " \n" + + " \n" + " \n" + "\n" + ""; String expected = - "\n" - + " 4.0.0\n" + "\n" + " \n" - + " org.codehaus.mojo\n" + " mojo-sandbox-parent\n" - + " 4\n" + " \n" + "\n" + " org.codehaus.mojo\n" - + " versions-maven-plugin\n" + " 1.0.0-alpha-1-SNAPSHOT\n" - + " maven-plugin\n" + "\n" + " Versions Maven Plugin\n" - + " \n" - + " Versions plugin for Maven 2. The versions plugin updates the versions of components in the pom.\n" - + " \n" + " 2008\n" + " \n" - + " \n" + " The Apache Software License, Version 2.0\n" - + " http://www.apache.org/licenses/LICENSE-2.0\n" - + " repo\n" + " \n" + " \n" + "\n" - + " \n" - + " scm:svn:http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" - + " scm:svn:https://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" - + " http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + " \n" - + "\n" + " \n" + " \n" + " Stephen Connolly\n" - + " stephen.alan.connolly@gmail.com\n" + " \n" - + " Java Developer\n" + " \n" + " 0\n" - + " \n" + " \n" + "\n" + " \n" - + " 2.0.6\n" + " \n" + "\n" + " \n" - + " \n" + " junit\n" + " junit\n" - + " 3.8.2\n" + " test\n" + " \n" - + " \n" + " org.apache.maven\n" - + " maven-project\n" + " 2.0\n" - + " \n" + " \n" + " org.apache.maven\n" - + " maven-settings\n" + " 2.0\n" - + " \n" + " \n" + " org.apache.maven\n" - + " maven-plugin-api\n" + " 2.0\n" - + " \n" + " \n" + " org.codehaus.plexus\n" - + " plexus-utils\n" + " 1.3\n" - + " \n" + " \n" + " org.codehaus.plexus\n" - + " plexus-interactivity-api\n" + " 1.0-alpha-6\n" - + " \n" + " \n" + " plexus-utils\n" - + " plexus\n" + " \n" + " \n" - + " \n" + " \n" + " javax.xml.stream\n" - + " stax-api\n" + " 1.0-2\n" - + " \n" + " \n" + " stax\n" - + " stax\n" + " 1.1.1-dev\n" - + " \n" + " \n" + "\n" + " \n" + " \n" - + " \n" + " maven-plugin-plugin\n" - + " 2.3\n" + " \n" - + " versions\n" + " \n" + " \n" - + " \n" + " \n" + "\n" + ""; + "\n" + + " 4.0.0\n" + "\n" + " \n" + + " org.codehaus.mojo\n" + + " mojo-sandbox-parent\n" + + " 4\n" + " \n" + "\n" + + " org.codehaus.mojo\n" + + " versions-maven-plugin\n" + + " 1.0.0-alpha-1-SNAPSHOT\n" + + " maven-plugin\n" + "\n" + " Versions Maven Plugin\n" + + " \n" + + " Versions plugin for Maven 2. The versions plugin updates the versions of components in the pom.\n" + + " \n" + " 2008\n" + " \n" + + " \n" + " The Apache Software License, Version 2.0\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + " repo\n" + " \n" + " \n" + "\n" + + " \n" + + " scm:svn:http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + + " scm:svn:https://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + + " http://svn.codehaus.org/mojo/trunk/sandbox/versions-maven-plugin\n" + + " \n" + + "\n" + " \n" + " \n" + " Stephen Connolly\n" + + " stephen.alan.connolly@gmail.com\n" + " \n" + + " Java Developer\n" + " \n" + + " 0\n" + + " \n" + " \n" + "\n" + " \n" + + " 2.0.6\n" + " \n" + "\n" + " \n" + + " \n" + " junit\n" + + " junit\n" + + " 3.8.2\n" + " test\n" + " \n" + + " \n" + " org.apache.maven\n" + + " maven-project\n" + " 2.0\n" + + " \n" + " \n" + " org.apache.maven\n" + + " maven-settings\n" + " 2.0\n" + + " \n" + " \n" + " org.apache.maven\n" + + " maven-plugin-api\n" + " 2.0\n" + + " \n" + " \n" + + " org.codehaus.plexus\n" + + " plexus-utils\n" + " 1.3\n" + + " \n" + " \n" + + " org.codehaus.plexus\n" + + " plexus-interactivity-api\n" + + " 1.0-alpha-6\n" + + " \n" + " \n" + + " plexus-utils\n" + + " plexus\n" + " \n" + " \n" + + " \n" + " \n" + " javax.xml.stream\n" + + " stax-api\n" + " 1.0-2\n" + + " \n" + " \n" + " stax\n" + + " stax\n" + " 1.1.1-dev\n" + + " \n" + " \n" + "\n" + " \n" + " \n" + + " \n" + " maven-plugin-plugin\n" + + " 2.3\n" + " \n" + + " versions\n" + " \n" + + " \n" + + " \n" + " \n" + "\n" + ""; - StringBuilder output = new StringBuilder( input ); + StringBuilder output = new StringBuilder(input); XMLInputFactory inputFactory = XMLInputFactory2.newInstance(); - inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE ); - ModifiedPomXMLEventReader eventReader = new ModifiedPomXMLEventReader( output, inputFactory, null ); + inputFactory.setProperty(XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE); + ModifiedPomXMLEventReader eventReader = new ModifiedPomXMLEventReader(output, inputFactory, null); Stack stack = new Stack<>(); String path = ""; - while ( eventReader.hasNext() ) - { + while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); - if ( event.isStartElement() ) - { - stack.push( path ); + if (event.isStartElement()) { + stack.push(path); path += "/" + event.asStartElement().getName().getLocalPart(); - if ( "/project/parent/version".equals( path ) ) - { - eventReader.mark( 0 ); + if ("/project/parent/version".equals(path)) { + eventReader.mark(0); } } - if ( event.isEndElement() ) - { - if ( "/project/parent/version".equals( path ) ) - { - eventReader.mark( 1 ); - if ( eventReader.hasMark( 0 ) ) - { - eventReader.replaceBetween( 0, 1, "4" ); + if (event.isEndElement()) { + if ("/project/parent/version".equals(path)) { + eventReader.mark(1); + if (eventReader.hasMark(0)) { + eventReader.replaceBetween(0, 1, "4"); } } path = stack.pop(); @@ -248,50 +254,33 @@ public void testReplaceFancy() boolean artifactIdMatches = false; eventReader.rewind(); - while ( eventReader.hasNext() ) - { + while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); - if ( event.isStartElement() ) - { + if (event.isStartElement()) { String name = event.asStartElement().getName().getLocalPart(); - if ( inDependency ) - { - if ( "groupId".equals( name ) ) - { - groupIdMatches = "junit".equals( eventReader.getElementText() ); + if (inDependency) { + if ("groupId".equals(name)) { + groupIdMatches = "junit".equals(eventReader.getElementText()); + } else if ("artifactId".equals(name)) { + artifactIdMatches = "junit".equals(eventReader.getElementText()); + } else if ("version".equals(name)) { + eventReader.mark(1); } - else if ( "artifactId".equals( name ) ) - { - artifactIdMatches = "junit".equals( eventReader.getElementText() ); - } - else if ( "version".equals( name ) ) - { - eventReader.mark( 1 ); - } - } - else if ( "dependency".equals( name ) ) - { + } else if ("dependency".equals(name)) { inDependency = true; groupIdMatches = false; artifactIdMatches = false; } } - if ( event.isEndElement() ) - { + if (event.isEndElement()) { String name = event.asEndElement().getName().getLocalPart(); - if ( inDependency ) - { - if ( "version".equals( name ) ) - { - eventReader.mark( 2 ); + if (inDependency) { + if ("version".equals(name)) { + eventReader.mark(2); - } - else if ( "dependency".equals( name ) ) - { - if ( groupIdMatches && artifactIdMatches && eventReader.hasMark( 1 ) - && eventReader.hasMark( 2 ) ) - { - eventReader.replaceBetween( 1, 2, "3.8.2" ); + } else if ("dependency".equals(name)) { + if (groupIdMatches && artifactIdMatches && eventReader.hasMark(1) && eventReader.hasMark(2)) { + eventReader.replaceBetween(1, 2, "3.8.2"); } inDependency = false; } @@ -299,7 +288,6 @@ else if ( "dependency".equals( name ) ) } } - assertEquals( expected, output.toString() ); + assertEquals(expected, output.toString()); } - } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SeparatePatternsForIncludesAnExcludesTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SeparatePatternsForIncludesAnExcludesTest.java index d5a4f51e34..eddda8473c 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SeparatePatternsForIncludesAnExcludesTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SeparatePatternsForIncludesAnExcludesTest.java @@ -8,80 +8,67 @@ import static org.junit.Assert.assertEquals; -public class SeparatePatternsForIncludesAnExcludesTest -{ +public class SeparatePatternsForIncludesAnExcludesTest { AbstractVersionsDependencyUpdaterMojo mojo; @Before - public void setUp() - throws Exception - { - mojo = new AbstractVersionsDependencyUpdaterMojo( null, null, null, null ) - { + public void setUp() throws Exception { + mojo = new AbstractVersionsDependencyUpdaterMojo(null, null, null, null) { @Override - protected void update( ModifiedPomXMLEventReader pom ) - { - } + protected void update(ModifiedPomXMLEventReader pom) {} }; } @Test - public void testSeparatePatternsWithNull() - { - List patterns = mojo.separatePatterns( null ); - assertEquals( 0, patterns.size() ); + public void testSeparatePatternsWithNull() { + List patterns = mojo.separatePatterns(null); + assertEquals(0, patterns.size()); } @Test - public void testSeparatePatternsWithSinglePattern() - { - List patterns = mojo.separatePatterns( "group:artifact:type:version" ); - assertEquals( 1, patterns.size() ); - assertEquals( "group:artifact:type:version", patterns.get( 0 ) ); + public void testSeparatePatternsWithSinglePattern() { + List patterns = mojo.separatePatterns("group:artifact:type:version"); + assertEquals(1, patterns.size()); + assertEquals("group:artifact:type:version", patterns.get(0)); } @Test - public void testSeparatePatternWithSingleRange() - { - List patterns = mojo.separatePatterns( "group:artifact:type:[1.0.2,2.0.0]" ); - assertEquals( 1, patterns.size() ); - assertEquals( "group:artifact:type:[1.0.2,2.0.0]", patterns.get( 0 ) ); + public void testSeparatePatternWithSingleRange() { + List patterns = mojo.separatePatterns("group:artifact:type:[1.0.2,2.0.0]"); + assertEquals(1, patterns.size()); + assertEquals("group:artifact:type:[1.0.2,2.0.0]", patterns.get(0)); - patterns = mojo.separatePatterns( "group:artifact:type:(1.0.2,2.0.0]" ); - assertEquals( 1, patterns.size() ); - assertEquals( "group:artifact:type:(1.0.2,2.0.0]", patterns.get( 0 ) ); + patterns = mojo.separatePatterns("group:artifact:type:(1.0.2,2.0.0]"); + assertEquals(1, patterns.size()); + assertEquals("group:artifact:type:(1.0.2,2.0.0]", patterns.get(0)); } @Test - public void testSeparatePatternWithSeveralPatternsAndRanges() - { - List patterns = mojo.separatePatterns( - "group:artifact:type:[1.0.2,2.0.0),group2:artifact:type:(1.0.2,2.0.0]" ); - assertEquals( 2, patterns.size() ); - assertEquals( "group:artifact:type:[1.0.2,2.0.0)", patterns.get( 0 ) ); - assertEquals( "group2:artifact:type:(1.0.2,2.0.0]", patterns.get( 1 ) ); + public void testSeparatePatternWithSeveralPatternsAndRanges() { + List patterns = + mojo.separatePatterns("group:artifact:type:[1.0.2,2.0.0),group2:artifact:type:(1.0.2,2.0.0]"); + assertEquals(2, patterns.size()); + assertEquals("group:artifact:type:[1.0.2,2.0.0)", patterns.get(0)); + assertEquals("group2:artifact:type:(1.0.2,2.0.0]", patterns.get(1)); } @Test - public void testSeparatePatternsWithTwoCommaSeparatedPatterns() - { - List patterns = mojo.separatePatterns( "group:artifact:type:version,group:artifact:type:version2" ); - assertEquals( 2, patterns.size() ); - assertEquals( "group:artifact:type:version", patterns.get( 0 ) ); - assertEquals( "group:artifact:type:version2", patterns.get( 1 ) ); + public void testSeparatePatternsWithTwoCommaSeparatedPatterns() { + List patterns = mojo.separatePatterns("group:artifact:type:version,group:artifact:type:version2"); + assertEquals(2, patterns.size()); + assertEquals("group:artifact:type:version", patterns.get(0)); + assertEquals("group:artifact:type:version2", patterns.get(1)); } @Test - public void testSeparatePatternsWithSeveralCommaSeparatedPatterns() - { - List patterns = mojo.separatePatterns( "group:artifact:type:version,group:artifact:type:version2," - + "group:artifact:type:version3,group:artifact:type:version4" ); - assertEquals( 4, patterns.size() ); - assertEquals( "group:artifact:type:version", patterns.get( 0 ) ); - assertEquals( "group:artifact:type:version2", patterns.get( 1 ) ); - assertEquals( "group:artifact:type:version3", patterns.get( 2 ) ); - assertEquals( "group:artifact:type:version4", patterns.get( 3 ) ); + public void testSeparatePatternsWithSeveralCommaSeparatedPatterns() { + List patterns = mojo.separatePatterns("group:artifact:type:version,group:artifact:type:version2," + + "group:artifact:type:version3,group:artifact:type:version4"); + assertEquals(4, patterns.size()); + assertEquals("group:artifact:type:version", patterns.get(0)); + assertEquals("group:artifact:type:version2", patterns.get(1)); + assertEquals("group:artifact:type:version3", patterns.get(2)); + assertEquals("group:artifact:type:version4", patterns.get(3)); } - } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetMojoTest.java index 0342773f0e..1decf8f987 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetMojoTest.java @@ -24,155 +24,138 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -public class SetMojoTest extends AbstractMojoTestCase -{ +public class SetMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); private Path tempDir; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - tempDir = TestUtils.createTempDir( "set" ); + tempDir = TestUtils.createTempDir("set"); } @After - public void tearDown() throws IOException - { - TestUtils.tearDownTempDir( tempDir ); + public void tearDown() throws IOException { + TestUtils.tearDownTempDir(tempDir); } @Test - public void testGetIncrementedVersion() throws MojoExecutionException - { - new SetMojo( null, null, null, null, null, null ) - { + public void testGetIncrementedVersion() throws MojoExecutionException { + new SetMojo(null, null, null, null, null, null) { { - assertThat( getIncrementedVersion( "1.0.0", null ), is( "1.0.1-SNAPSHOT" ) ); - assertThat( getIncrementedVersion( "1.0.0-SNAPSHOT", null ), is( "1.0.1-SNAPSHOT" ) ); - assertThat( getIncrementedVersion( "1.0.0-SNAPSHOT", 1 ), is( "2.0.0-SNAPSHOT" ) ); - assertThat( getIncrementedVersion( "1.0.0-SNAPSHOT", 2 ), is( "1.1.0-SNAPSHOT" ) ); - assertThat( getIncrementedVersion( "1.0.0-SNAPSHOT", 3 ), is( "1.0.1-SNAPSHOT" ) ); + assertThat(getIncrementedVersion("1.0.0", null), is("1.0.1-SNAPSHOT")); + assertThat(getIncrementedVersion("1.0.0-SNAPSHOT", null), is("1.0.1-SNAPSHOT")); + assertThat(getIncrementedVersion("1.0.0-SNAPSHOT", 1), is("2.0.0-SNAPSHOT")); + assertThat(getIncrementedVersion("1.0.0-SNAPSHOT", 2), is("1.1.0-SNAPSHOT")); + assertThat(getIncrementedVersion("1.0.0-SNAPSHOT", 3), is("1.0.1-SNAPSHOT")); } }; } @Test - public void testNextSnapshotIndexLowerBound() - { - new SetMojo( null, null, null, null, null, null ) - { + public void testNextSnapshotIndexLowerBound() { + new SetMojo(null, null, null, null, null, null) { { - try - { - getIncrementedVersion( "1.0.0", 0 ); + try { + getIncrementedVersion("1.0.0", 0); fail(); - } - catch ( MojoExecutionException e ) - { - assertThat( e.getMessage(), - containsString( "nextSnapshotIndexToIncrement cannot be less than 1" ) ); + } catch (MojoExecutionException e) { + assertThat(e.getMessage(), containsString("nextSnapshotIndexToIncrement cannot be less than 1")); } } }; } @Test - public void testNextSnapshotIndexUpperBound() - { - new SetMojo( null, null, null, null, null, null ) - { + public void testNextSnapshotIndexUpperBound() { + new SetMojo(null, null, null, null, null, null) { { - try - { - getIncrementedVersion( "1.0.0", 4 ); + try { + getIncrementedVersion("1.0.0", 4); fail(); - } - catch ( MojoExecutionException e ) - { - assertThat( e.getMessage(), containsString( - "nextSnapshotIndexToIncrement cannot be greater than the last version index" ) ); + } catch (MojoExecutionException e) { + assertThat( + e.getMessage(), + containsString( + "nextSnapshotIndexToIncrement cannot be greater than the last version index")); } } }; } @Test - public void testNextSnapshotIndexWithoutNextSnapshot() throws MojoFailureException - { - try - { - new SetMojo( null, null, null, null, null, null ) - { + public void testNextSnapshotIndexWithoutNextSnapshot() throws MojoFailureException { + try { + new SetMojo(null, null, null, null, null, null) { { project = new MavenProject(); - project.setParent( new MavenProject() ); - project.setOriginalModel( new Model() ); - project.getOriginalModel().setVersion( "1.2.3-SNAPSHOT" ); + project.setParent(new MavenProject()); + project.setOriginalModel(new Model()); + project.getOriginalModel().setVersion("1.2.3-SNAPSHOT"); nextSnapshotIndexToIncrement = 4; } }.execute(); - } - catch ( MojoExecutionException e ) - { - assertThat( e.getMessage(), - containsString( "nextSnapshotIndexToIncrement is not valid when nextSnapshot is false" ) ); + } catch (MojoExecutionException e) { + assertThat( + e.getMessage(), + containsString("nextSnapshotIndexToIncrement is not valid when nextSnapshot is false")); } } @Test - public void testVersionlessDependency() throws Exception - { + public void testVersionlessDependency() throws Exception { SetMojo myMojo = (SetMojo) mojoRule.lookupConfiguredMojo( - new File( "target/test-classes/org/codehaus/mojo/set/versionless-01" ), "set" ); + new File("target/test-classes/org/codehaus/mojo/set/versionless-01"), "set"); myMojo.execute(); } @Test - public void testRemoveSnapshotIdempotency() - throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/set/remove-snapshot/pom.xml" ), - Paths.get( tempDir.toString(), "pom.xml" ), REPLACE_EXISTING ); + public void testRemoveSnapshotIdempotency() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/set/remove-snapshot/pom.xml"), + Paths.get(tempDir.toString(), "pom.xml"), + REPLACE_EXISTING); - SetMojo firstRun = (SetMojo) mojoRule.lookupConfiguredMojo( tempDir.toFile(), "set" ); + SetMojo firstRun = (SetMojo) mojoRule.lookupConfiguredMojo(tempDir.toFile(), "set"); firstRun.execute(); - assertThat( String.join( "", Files.readAllLines( tempDir.resolve( "pom.xml" ) ) ), - containsString( "1.0" ) ); + assertThat( + String.join("", Files.readAllLines(tempDir.resolve("pom.xml"))), + containsString("1.0")); // no exception should be thrown, the file should stay with version "1.0" - SetMojo secondRun = (SetMojo) mojoRule.lookupConfiguredMojo( tempDir.toFile(), "set" ); - secondRun.session.getSettings().setInteractiveMode( false ); + SetMojo secondRun = (SetMojo) mojoRule.lookupConfiguredMojo(tempDir.toFile(), "set"); + secondRun.session.getSettings().setInteractiveMode(false); secondRun.execute(); - assertThat( String.join( "", Files.readAllLines( tempDir.resolve( "pom.xml" ) ) ), - containsString( "1.0" ) ); + assertThat( + String.join("", Files.readAllLines(tempDir.resolve("pom.xml"))), + containsString("1.0")); } @Test - public void testSetOldVersionMismatch() throws Exception - { - TestUtils.copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/set/issue-794" ), tempDir ); - SetMojo mojo = (SetMojo) mojoRule.lookupConfiguredMojo( tempDir.toFile(), "set" ); - setVariableValueToObject( mojo, "oldVersion", "foo" ); - setVariableValueToObject( mojo, "newVersion", "bar" ); + public void testSetOldVersionMismatch() throws Exception { + TestUtils.copyDir(Paths.get("src/test/resources/org/codehaus/mojo/set/issue-794"), tempDir); + SetMojo mojo = (SetMojo) mojoRule.lookupConfiguredMojo(tempDir.toFile(), "set"); + setVariableValueToObject(mojo, "oldVersion", "foo"); + setVariableValueToObject(mojo, "newVersion", "bar"); mojo.execute(); - assertThat( String.join( "", Files.readAllLines( tempDir.resolve( "pom.xml" ) ) ), - not( containsString( "bar" ) ) ); + assertThat( + String.join("", Files.readAllLines(tempDir.resolve("pom.xml"))), + not(containsString("bar"))); } @Test - public void testSetOldVersionMismatchProcessAllModules() throws Exception - { - TestUtils.copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/set/issue-794" ), tempDir ); - SetMojo mojo = (SetMojo) mojoRule.lookupConfiguredMojo( tempDir.toFile(), "set" ); - setVariableValueToObject( mojo, "oldVersion", "foo" ); - setVariableValueToObject( mojo, "newVersion", "bar" ); - setVariableValueToObject( mojo, "processAllModules", true ); + public void testSetOldVersionMismatchProcessAllModules() throws Exception { + TestUtils.copyDir(Paths.get("src/test/resources/org/codehaus/mojo/set/issue-794"), tempDir); + SetMojo mojo = (SetMojo) mojoRule.lookupConfiguredMojo(tempDir.toFile(), "set"); + setVariableValueToObject(mojo, "oldVersion", "foo"); + setVariableValueToObject(mojo, "newVersion", "bar"); + setVariableValueToObject(mojo, "processAllModules", true); mojo.execute(); - assertThat( String.join( "", Files.readAllLines( tempDir.resolve( "pom.xml" ) ) ), - not( containsString( "bar" ) ) ); + assertThat( + String.join("", Files.readAllLines(tempDir.resolve("pom.xml"))), + not(containsString("bar"))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetPropertyMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetPropertyMojoTest.java index b4cffc0894..c2890ebcbc 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetPropertyMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetPropertyMojoTest.java @@ -48,93 +48,77 @@ * * @author Andrzej Jarmoniuk */ -public class SetPropertyMojoTest extends AbstractMojoTestCase -{ +public class SetPropertyMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); private Path pomDir; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - pomDir = createTempDir( "set-property" ); + pomDir = createTempDir("set-property"); } @After - public void tearDown() throws Exception - { - try - { - tearDownTempDir( pomDir ); - } - finally - { + public void tearDown() throws Exception { + try { + tearDownTempDir(pomDir); + } finally { super.tearDown(); } } + @Test - public void testNullNewVersion() - throws Exception - { - copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/set-property/null-new-version" ), pomDir ); - SetPropertyMojo mojo = (SetPropertyMojo) mojoRule.lookupConfiguredMojo( pomDir.toFile(), - "set-property" ); + public void testNullNewVersion() throws Exception { + copyDir(Paths.get("src/test/resources/org/codehaus/mojo/set-property/null-new-version"), pomDir); + SetPropertyMojo mojo = (SetPropertyMojo) mojoRule.lookupConfiguredMojo(pomDir.toFile(), "set-property"); - mojo.aetherRepositorySystem = mock( org.eclipse.aether.RepositorySystem.class ); - when( mojo.aetherRepositorySystem.resolveVersionRange( any(), any( VersionRangeRequest.class ) ) ) - .then( i -> new VersionRangeResult( i.getArgument( 1 ) ) ); + mojo.aetherRepositorySystem = mock(org.eclipse.aether.RepositorySystem.class); + when(mojo.aetherRepositorySystem.resolveVersionRange(any(), any(VersionRangeRequest.class))) + .then(i -> new VersionRangeResult(i.getArgument(1))); - setVariableValueToObject( mojo, "newVersion", null ); + setVariableValueToObject(mojo, "newVersion", null); mojo.execute(); - String output = String.join( "", Files.readAllLines( mojo.getProject().getFile().toPath() ) ) - .replaceAll( "\\s*", "" ); - assertThat( output, - matchesPattern( ".*.*.*.*" ) ); + String output = String.join( + "", Files.readAllLines(mojo.getProject().getFile().toPath())) + .replaceAll("\\s*", ""); + assertThat(output, matchesPattern(".*.*.*.*")); } @Test - public void testNewVersionEmpty() - throws Exception - { - copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/set-property/null-new-version" ), pomDir ); - SetPropertyMojo mojo = (SetPropertyMojo) mojoRule.lookupConfiguredMojo( pomDir.toFile(), - "set-property" ); + public void testNewVersionEmpty() throws Exception { + copyDir(Paths.get("src/test/resources/org/codehaus/mojo/set-property/null-new-version"), pomDir); + SetPropertyMojo mojo = (SetPropertyMojo) mojoRule.lookupConfiguredMojo(pomDir.toFile(), "set-property"); - mojo.aetherRepositorySystem = mock( org.eclipse.aether.RepositorySystem.class ); - when( mojo.aetherRepositorySystem.resolveVersionRange( any(), any( VersionRangeRequest.class ) ) ) - .then( i -> new VersionRangeResult( i.getArgument( 1 ) ) ); + mojo.aetherRepositorySystem = mock(org.eclipse.aether.RepositorySystem.class); + when(mojo.aetherRepositorySystem.resolveVersionRange(any(), any(VersionRangeRequest.class))) + .then(i -> new VersionRangeResult(i.getArgument(1))); - setVariableValueToObject( mojo, "newVersion", "" ); + setVariableValueToObject(mojo, "newVersion", ""); mojo.execute(); - String output = String.join( "", Files.readAllLines( mojo.getProject().getFile().toPath() ) ) - .replaceAll( "\\s*", "" ); - assertThat( output, - matchesPattern( ".*.*.*.*" ) ); + String output = String.join( + "", Files.readAllLines(mojo.getProject().getFile().toPath())) + .replaceAll("\\s*", ""); + assertThat(output, matchesPattern(".*.*.*.*")); } @Test - public void testNullProperty() - throws Exception - { - copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/set-property/null-property" ), pomDir ); - SetPropertyMojo mojo = (SetPropertyMojo) mojoRule.lookupConfiguredMojo( pomDir.toFile(), - "set-property" ); - - try - { - mojo.update( null ); + public void testNullProperty() throws Exception { + copyDir(Paths.get("src/test/resources/org/codehaus/mojo/set-property/null-property"), pomDir); + SetPropertyMojo mojo = (SetPropertyMojo) mojoRule.lookupConfiguredMojo(pomDir.toFile(), "set-property"); + + try { + mojo.update(null); fail(); - } - catch ( MojoExecutionException e ) - { - assertThat( e.getMessage(), - containsString( "Please provide either 'property' or 'propertiesVersionsFile' parameter." ) ); + } catch (MojoExecutionException e) { + assertThat( + e.getMessage(), + containsString("Please provide either 'property' or 'propertiesVersionsFile' parameter.")); } } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetScmTagMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetScmTagMojoTest.java index ebe2d50833..fdc12dcb52 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetScmTagMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/SetScmTagMojoTest.java @@ -37,26 +37,23 @@ * * @author Andrzej Jarmoniuk */ -public class SetScmTagMojoTest extends AbstractMojoTestCase -{ +public class SetScmTagMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); @Test - public void testNewScmValues() throws Exception - { - Path pomFile = Paths.get( "target/test-classes/org/codehaus/mojo/set-scm-tag/pom.xml" ); - mojoRule.lookupConfiguredMojo( pomFile.toFile().getParentFile(), "set-scm-tag" ) + public void testNewScmValues() throws Exception { + Path pomFile = Paths.get("target/test-classes/org/codehaus/mojo/set-scm-tag/pom.xml"); + mojoRule.lookupConfiguredMojo(pomFile.toFile().getParentFile(), "set-scm-tag") .execute(); - String output = String.join( "", Files.readAllLines( pomFile ) ) - .replaceAll( "\\s*", "" ); - assertThat( output, allOf( - matchesPattern( ".*.*\\s*newTag\\s*.*.*" ), - matchesPattern( ".*.*\\s*url\\s*.*.*" ), - matchesPattern( ".*.*\\s*connection\\s*.*.*" ), - matchesPattern( ".*.*\\s*" - + "developerConnection\\s*.*.*" ) - ) - ); + String output = String.join("", Files.readAllLines(pomFile)).replaceAll("\\s*", ""); + assertThat( + output, + allOf( + matchesPattern(".*.*\\s*newTag\\s*.*.*"), + matchesPattern(".*.*\\s*url\\s*.*.*"), + matchesPattern(".*.*\\s*connection\\s*.*.*"), + matchesPattern(".*.*\\s*" + + "developerConnection\\s*.*.*"))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java index f7a25407ee..56619688b3 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java @@ -43,8 +43,7 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -public class UpdateParentMojoTest -{ +public class UpdateParentMojoTest { private TestChangeRecorder changeRecorder; private UpdateParentMojo mojo; @@ -54,355 +53,358 @@ public class UpdateParentMojoTest private static org.eclipse.aether.RepositorySystem aetherRepositorySystem; @BeforeClass - public static void setUpStatic() - { + public static void setUpStatic() { repositorySystem = mockRepositorySystem(); - aetherRepositorySystem = mockAetherRepositorySystem( new HashMap() - {{ - put( "parent-artifact", new String[] { "0.9.0", "1.0.0", "1.0.1-SNAPSHOT" } ); - put( "issue-670-artifact", new String[] { "0.0.1-1", "0.0.1-1-impl-SNAPSHOT" } ); - put( "dummy-parent2", new String[] { "1.0", "2.0", "3.0", "3.0-alpha-1", "3.0-beta-1" } ); - put( "test-incremental", new String[] { "1.0.0", "1.1.0", "1.1.1", "2.0.0" } ); - put( "unknown-artifact", new String[0] ); - }} ); + aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { + { + put("parent-artifact", new String[] {"0.9.0", "1.0.0", "1.0.1-SNAPSHOT"}); + put("issue-670-artifact", new String[] {"0.0.1-1", "0.0.1-1-impl-SNAPSHOT"}); + put("dummy-parent2", new String[] {"1.0", "2.0", "3.0", "3.0-alpha-1", "3.0-beta-1"}); + put("test-incremental", new String[] {"1.0.0", "1.1.0", "1.1.1", "2.0.0"}); + put("unknown-artifact", new String[0]); + } + }); } @Before - public void setUp() throws IllegalAccessException - { + public void setUp() throws IllegalAccessException { changeRecorder = new TestChangeRecorder(); - mojo = new UpdateParentMojo( repositorySystem, aetherRepositorySystem, null, changeRecorder.asTestMap() ) - {{ - setProject( createProject() ); - reactorProjects = Collections.emptyList(); - session = mockMavenSession(); - }}; + mojo = new UpdateParentMojo(repositorySystem, aetherRepositorySystem, null, changeRecorder.asTestMap()) { + { + setProject(createProject()); + reactorProjects = Collections.emptyList(); + session = mockMavenSession(); + } + }; } - private MavenProject createProject() - { - return new MavenProject() - {{ - setModel( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "project-artifact" ); - setVersion( "1.0.1-SNAPSHOT" ); - }} ); - - setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "parent-artifact" ); - setVersion( "1.0.1-SNAPSHOT" ); - }} ); - }}; + private MavenProject createProject() { + return new MavenProject() { + { + setModel(new Model() { + { + setGroupId("default-group"); + setArtifactId("project-artifact"); + setVersion("1.0.1-SNAPSHOT"); + } + }); + + setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + setVersion("1.0.1-SNAPSHOT"); + } + }); + } + }; } - private static RepositorySystem mockRepositorySystem() - { - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( invocation -> - { - Dependency dependency = invocation.getArgument( 0 ); - return new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), - dependency.getScope(), dependency.getType(), dependency.getClassifier() != null - ? dependency.getClassifier() : "default", - new DefaultArtifactHandlerStub( "default" ) ); - } ); + private static RepositorySystem mockRepositorySystem() { + RepositorySystem repositorySystem = mock(RepositorySystem.class); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(invocation -> { + Dependency dependency = invocation.getArgument(0); + return new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + dependency.getScope(), + dependency.getType(), + dependency.getClassifier() != null ? dependency.getClassifier() : "default", + new DefaultArtifactHandlerStub("default")); + }); return repositorySystem; } @Test - @SuppressWarnings( "deprecation" ) + @SuppressWarnings("deprecation") public void testArtifactIdDoesNotExist() - throws VersionRetrievalException, MojoExecutionException, - XMLStreamException, MojoFailureException, InvalidVersionSpecificationException, - VersionRetrievalException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "unknown-artifact" ); - setVersion( "1.0.1-SNAPSHOT" ); - }} ); - - Artifact artifact = - new DefaultArtifact( "default-group", "unknown-artifact", "1.0.1-SNAPSHOT", SCOPE_COMPILE, "pom", - "default", new DefaultArtifactHandlerStub( "default" ) ); + throws VersionRetrievalException, MojoExecutionException, XMLStreamException, MojoFailureException, + InvalidVersionSpecificationException, VersionRetrievalException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("unknown-artifact"); + setVersion("1.0.1-SNAPSHOT"); + } + }); + + Artifact artifact = new DefaultArtifact( + "default-group", + "unknown-artifact", + "1.0.1-SNAPSHOT", + SCOPE_COMPILE, + "pom", + "default", + new DefaultArtifactHandlerStub("default")); assertThat( - mojo.findLatestVersion( artifact, VersionRange.createFromVersionSpec( "1.0.1-SNAPSHOT" ), null, false ), - is( nullValue() ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ).thenReturn( true ); - mojo.update( null ); + mojo.findLatestVersion(artifact, VersionRange.createFromVersionSpec("1.0.1-SNAPSHOT"), null, false), + is(nullValue())); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } } @Test public void testParentDowngradeAllowed() - throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { mojo.allowDowngrade = true; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "parent-artifact", "1.0.1-SNAPSHOT", - "1.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "parent-artifact", "1.0.1-SNAPSHOT", "1.0.0"))); } @Test public void testParentDowngradeForbidden() - throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { mojo.allowDowngrade = false; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), is( empty() ) ); + assertThat(changeRecorder.getChanges(), is(empty())); } @Test public void testParentDowngradeAllowedWithRange() - throws MojoExecutionException, VersionRetrievalException, - InvalidVersionSpecificationException, InvalidSegmentException - { + throws MojoExecutionException, VersionRetrievalException, InvalidVersionSpecificationException, + InvalidSegmentException { mojo.allowDowngrade = true; - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "parent-artifact" ); - }} ); - - ArtifactVersion newVersion = mojo.resolveTargetVersion( "[1.0.1-SNAPSHOT,)" ); - assertThat( newVersion, notNullValue() ); - assertThat( newVersion.toString(), is( "1.0.0" ) ); + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + } + }); + + ArtifactVersion newVersion = mojo.resolveTargetVersion("[1.0.1-SNAPSHOT,)"); + assertThat(newVersion, notNullValue()); + assertThat(newVersion.toString(), is("1.0.0")); } @Test public void testParentDowngradeForbiddenWithRange() - throws MojoExecutionException, VersionRetrievalException, - InvalidVersionSpecificationException, InvalidSegmentException - { + throws MojoExecutionException, VersionRetrievalException, InvalidVersionSpecificationException, + InvalidSegmentException { mojo.allowDowngrade = false; - ArtifactVersion newVersion = mojo.resolveTargetVersion( "[1.0.1-SNAPSHOT,)" ); - assertThat( newVersion, nullValue() ); + ArtifactVersion newVersion = mojo.resolveTargetVersion("[1.0.1-SNAPSHOT,)"); + assertThat(newVersion, nullValue()); } @Test public void testAllowSnapshots() - throws MojoExecutionException, VersionRetrievalException, - InvalidVersionSpecificationException, InvalidSegmentException - { + throws MojoExecutionException, VersionRetrievalException, InvalidVersionSpecificationException, + InvalidSegmentException { mojo.allowSnapshots = true; - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "issue-670-artifact" ); - }} ); - - ArtifactVersion newVersion = mojo.resolveTargetVersion( "0.0.1-1" ); - assertThat( newVersion, notNullValue() ); - assertThat( newVersion.toString(), is( "0.0.1-1-impl-SNAPSHOT" ) ); + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("issue-670-artifact"); + } + }); + + ArtifactVersion newVersion = mojo.resolveTargetVersion("0.0.1-1"); + assertThat(newVersion, notNullValue()); + assertThat(newVersion.toString(), is("0.0.1-1-impl-SNAPSHOT")); } @Test public void testAllowSnapshotsWithParentVersion() - throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { mojo.allowSnapshots = true; mojo.parentVersion = "0.0.1-1-impl-SNAPSHOT"; - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "issue-670-artifact" ); - setVersion( "0.0.1-1" ); - }} ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("issue-670-artifact"); + setVersion("0.0.1-1"); + } + }); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), hasItem( new DefaultVersionChange( "default-group", - "issue-670-artifact", "0.0.1-1", - "0.0.1-1-impl-SNAPSHOT" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "issue-670-artifact", "0.0.1-1", "0.0.1-1-impl-SNAPSHOT"))); } @Test public void testIgnoredVersions() - throws MojoExecutionException, IllegalAccessException, - VersionRetrievalException, InvalidVersionSpecificationException, InvalidSegmentException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "parent-artifact" ); - }} ); - setVariableValueToObject( mojo, "ignoredVersions", singleton( "1.0.0" ) ); - assertThat( mojo.resolveTargetVersion( "0.9.0" ), nullValue() ); + throws MojoExecutionException, IllegalAccessException, VersionRetrievalException, + InvalidVersionSpecificationException, InvalidSegmentException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + } + }); + setVariableValueToObject(mojo, "ignoredVersions", singleton("1.0.0")); + assertThat(mojo.resolveTargetVersion("0.9.0"), nullValue()); } @Test - public void testSkipResolutionDowngradeUnknownVersion() throws VersionRetrievalException - { - testSkipResolution( "0.8.0" ); + public void testSkipResolutionDowngradeUnknownVersion() throws VersionRetrievalException { + testSkipResolution("0.8.0"); } @Test - public void testSkipResolutionDowngrade() throws VersionRetrievalException - { - testSkipResolution( "0.9.0" ); + public void testSkipResolutionDowngrade() throws VersionRetrievalException { + testSkipResolution("0.9.0"); } @Test - public void testSkipResolutionUpgradeUnknownVersion() throws VersionRetrievalException - { - testSkipResolution( "2.0.0" ); + public void testSkipResolutionUpgradeUnknownVersion() throws VersionRetrievalException { + testSkipResolution("2.0.0"); } - private void testSkipResolution( String version ) throws VersionRetrievalException - { + private void testSkipResolution(String version) throws VersionRetrievalException { mojo.parentVersion = version; mojo.skipResolution = true; - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "parent-artifact" ); - setVersion( "1.0.0" ); - }} ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); - } - catch ( MojoExecutionException | XMLStreamException | MojoFailureException e ) - { - throw new RuntimeException( e ); + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + setVersion("1.0.0"); + } + }); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); + } catch (MojoExecutionException | XMLStreamException | MojoFailureException e) { + throw new RuntimeException(e); } - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "parent-artifact", "1.0.0", version ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "parent-artifact", "1.0.0", version))); } @Test - public void testShouldUpgradeToSnapshot() throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "parent-artifact" ); - setVersion( "0.9.0" ); - }} ); + public void testShouldUpgradeToSnapshot() + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + setVersion("0.9.0"); + } + }); mojo.allowSnapshots = true; mojo.parentVersion = "[0,1.0.1-SNAPSHOT]"; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ).thenReturn( true ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "parent-artifact", "0.9.0", - "1.0.1-SNAPSHOT" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "parent-artifact", "0.9.0", "1.0.1-SNAPSHOT"))); } @Test public void testAllowMinorUpdates() - throws MojoExecutionException, VersionRetrievalException, - InvalidVersionSpecificationException, InvalidSegmentException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "parent-artifact" ); - setVersion( "0.8.0" ); - }} ); + throws MojoExecutionException, VersionRetrievalException, InvalidVersionSpecificationException, + InvalidSegmentException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + setVersion("0.8.0"); + } + }); mojo.allowMajorUpdates = false; mojo.allowMinorUpdates = true; mojo.allowIncrementalUpdates = true; - ArtifactVersion newVersion = mojo.resolveTargetVersion( "0.8.0" ); + ArtifactVersion newVersion = mojo.resolveTargetVersion("0.8.0"); - assertThat( newVersion, notNullValue() ); - assertThat( newVersion.toString(), is( "0.9.0" ) ); + assertThat(newVersion, notNullValue()); + assertThat(newVersion.toString(), is("0.9.0")); } @Test public void testAllowIncrementalUpdates() - throws MojoExecutionException, VersionRetrievalException, - InvalidVersionSpecificationException, InvalidSegmentException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "test-incremental" ); - }} ); + throws MojoExecutionException, VersionRetrievalException, InvalidVersionSpecificationException, + InvalidSegmentException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("test-incremental"); + } + }); mojo.allowMajorUpdates = false; mojo.allowMinorUpdates = false; mojo.allowIncrementalUpdates = true; - ArtifactVersion newVersion = mojo.resolveTargetVersion( "1.1.0" ); + ArtifactVersion newVersion = mojo.resolveTargetVersion("1.1.0"); - assertThat( newVersion, notNullValue() ); - assertThat( newVersion.toString(), is( "1.1.1" ) ); + assertThat(newVersion, notNullValue()); + assertThat(newVersion.toString(), is("1.1.1")); } @Test - public void testParentVersionRange() throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "dummy-parent2" ); - setVersion( "1.0" ); - }} ); + public void testParentVersionRange() + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("dummy-parent2"); + setVersion("1.0"); + } + }); mojo.allowSnapshots = true; mojo.parentVersion = "[,3.0-!)"; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ).thenReturn( true ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "dummy-parent2", "1.0", - "2.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "dummy-parent2", "1.0", "2.0"))); } @Test - public void testParentVersionRange2() throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( "default-group" ); - setArtifactId( "dummy-parent2" ); - setVersion( "2.0" ); - }} ); + public void testParentVersionRange2() + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject().setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("dummy-parent2"); + setVersion("2.0"); + } + }); mojo.allowSnapshots = true; mojo.parentVersion = "[,3.0-!)"; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), any() ) ).thenReturn( true ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), empty() ); + assertThat(changeRecorder.getChanges(), empty()); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTest.java index 2da6749d03..af9be7435c 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTest.java @@ -35,56 +35,59 @@ /** * Unit tests for {@link UpdatePropertiesMojo} */ -public class UpdatePropertiesMojoTest extends UpdatePropertiesMojoTestBase -{ +public class UpdatePropertiesMojoTest extends UpdatePropertiesMojoTestBase { @Test - public void testAllowMajorUpdates() throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml" ), - Paths.get( pomDir.toString(), "pom.xml" ), REPLACE_EXISTING ); - setUpMojo( "update-properties" ).execute(); - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "default-artifact", "1.0.0", "2.0.0-M1" ) ) ); + public void testAllowMajorUpdates() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml"), + Paths.get(pomDir.toString(), "pom.xml"), + REPLACE_EXISTING); + setUpMojo("update-properties").execute(); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "default-artifact", "1.0.0", "2.0.0-M1"))); } @Test - public void testAllowMinorUpdates() throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml" ), - Paths.get( pomDir.toString(), "pom.xml" ), REPLACE_EXISTING ); - UpdatePropertiesMojo mojo = setUpMojo( "update-properties" ); + public void testAllowMinorUpdates() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml"), + Paths.get(pomDir.toString(), "pom.xml"), + REPLACE_EXISTING); + UpdatePropertiesMojo mojo = setUpMojo("update-properties"); mojo.allowMajorUpdates = false; mojo.execute(); - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "default-artifact", "1.0.0", "1.1.0-alpha" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "default-artifact", "1.0.0", "1.1.0-alpha"))); } @Test - public void testAllowIncrementalUpdates() throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml" ), - Paths.get( pomDir.toString(), "pom.xml" ), REPLACE_EXISTING ); - UpdatePropertiesMojo mojo = setUpMojo( "update-properties" ); + public void testAllowIncrementalUpdates() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml"), + Paths.get(pomDir.toString(), "pom.xml"), + REPLACE_EXISTING); + UpdatePropertiesMojo mojo = setUpMojo("update-properties"); mojo.allowMajorUpdates = false; mojo.allowMinorUpdates = false; mojo.execute(); - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "default-artifact", "1.0.0", "1.0.1-rc1" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "default-artifact", "1.0.0", "1.0.1-rc1"))); } @Test - public void testChangesNotRegisteredIfNoUpdatesInPom() - throws Exception - { - TestUtils.copyDir( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-837" ), - pomDir ); - UpdatePropertiesMojo mojo = setUpMojo( "update-properties" ); + public void testChangesNotRegisteredIfNoUpdatesInPom() throws Exception { + TestUtils.copyDir(Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-837"), pomDir); + UpdatePropertiesMojo mojo = setUpMojo("update-properties"); TestChangeRecorder changeRecorder = new TestChangeRecorder(); - setVariableValueToObject( mojo, "changeRecorders", changeRecorder.asTestMap() ); - setVariableValueToObject( mojo, "changeRecorderFormat", "none" ); -// pomHelperClass.when( () -> PomHelper.setPropertyVersion( any(), anyString(), anyString(), anyString() ) ) -// .thenReturn( false ); - mojo.execute( ); - assertThat( changeRecorder.getChanges(), is( empty() ) ); + setVariableValueToObject(mojo, "changeRecorders", changeRecorder.asTestMap()); + setVariableValueToObject(mojo, "changeRecorderFormat", "none"); + // pomHelperClass.when( () -> PomHelper.setPropertyVersion( any(), anyString(), anyString(), + // anyString() ) ) + // .thenReturn( false ); + mojo.execute(); + assertThat(changeRecorder.getChanges(), is(empty())); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTestBase.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTestBase.java index ba3b7b8c7a..c4b971f18a 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTestBase.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertiesMojoTestBase.java @@ -38,48 +38,42 @@ /** * Base class for {@link UpdatePropertiesMojo} and {@link UpdatePropertyMojo} test suites */ -public abstract class UpdatePropertiesMojoTestBase extends AbstractMojoTestCase -{ +public abstract class UpdatePropertiesMojoTestBase extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); + protected Path pomDir; protected org.eclipse.aether.RepositorySystem aetherRepositorySystem; protected TestChangeRecorder changeRecorder; @Before - public void setUp() throws Exception - { + public void setUp() throws Exception { super.setUp(); - pomDir = createTempDir( "update-property" ); - aetherRepositorySystem = mockAetherRepositorySystem( new HashMap() - {{ - put( "default-artifact", new String[] {"1.0.0", "1.0.1-rc1", "1.1.0-alpha", "2.0.0-M1"} ); - }} ); + pomDir = createTempDir("update-property"); + aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { + { + put("default-artifact", new String[] {"1.0.0", "1.0.1-rc1", "1.1.0-alpha", "2.0.0-M1"}); + } + }); } @After - public void tearDown() throws Exception - { - try - { - tearDownTempDir( pomDir ); - } - finally - { + public void tearDown() throws Exception { + try { + tearDownTempDir(pomDir); + } finally { super.tearDown(); } } - @SuppressWarnings( "unchecked" ) - protected T setUpMojo( String goal ) throws Exception - { - T mojo = (T) mojoRule.lookupConfiguredMojo( pomDir.toFile(), goal ); - setVariableValueToObject( mojo, "aetherRepositorySystem", aetherRepositorySystem ); - setVariableValueToObject( mojo, "generateBackupPoms", false ); - setVariableValueToObject( mojo, "changeRecorderFormat", "test" ); + @SuppressWarnings("unchecked") + protected T setUpMojo(String goal) throws Exception { + T mojo = (T) mojoRule.lookupConfiguredMojo(pomDir.toFile(), goal); + setVariableValueToObject(mojo, "aetherRepositorySystem", aetherRepositorySystem); + setVariableValueToObject(mojo, "generateBackupPoms", false); + setVariableValueToObject(mojo, "changeRecorderFormat", "test"); changeRecorder = (TestChangeRecorder) - ( (Map) getVariableValueFromObject( mojo, "changeRecorders" ) ) - .get( "test" ); + ((Map) getVariableValueFromObject(mojo, "changeRecorders")).get("test"); return (T) mojo; } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertyMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertyMojoTest.java index 1a63831a8d..3005da328b 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertyMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdatePropertyMojoTest.java @@ -31,44 +31,50 @@ /** * Unit tests for {@link UpdatePropertiesMojo} */ -public class UpdatePropertyMojoTest extends UpdatePropertiesMojoTestBase -{ +public class UpdatePropertyMojoTest extends UpdatePropertiesMojoTestBase { @Test - public void testAllowMajorUpdates() throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml" ), - Paths.get( pomDir.toString(), "pom.xml" ), REPLACE_EXISTING ); - UpdatePropertyMojo mojo = setUpMojo( "update-property" ); + public void testAllowMajorUpdates() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml"), + Paths.get(pomDir.toString(), "pom.xml"), + REPLACE_EXISTING); + UpdatePropertyMojo mojo = setUpMojo("update-property"); mojo.property = "artifact-version"; mojo.execute(); - assertThat( changeRecorder.getChanges(), Matchers.hasItem( - new DefaultVersionChange( "default-group", "default-artifact", "1.0.0", "2.0.0-M1" ) ) ); + assertThat( + changeRecorder.getChanges(), + Matchers.hasItem(new DefaultVersionChange("default-group", "default-artifact", "1.0.0", "2.0.0-M1"))); } @Test - public void testAllowMinorUpdates() throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml" ), - Paths.get( pomDir.toString(), "pom.xml" ), REPLACE_EXISTING ); - UpdatePropertyMojo mojo = setUpMojo( "update-property" ); + public void testAllowMinorUpdates() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml"), + Paths.get(pomDir.toString(), "pom.xml"), + REPLACE_EXISTING); + UpdatePropertyMojo mojo = setUpMojo("update-property"); mojo.property = "artifact-version"; mojo.allowMajorUpdates = false; mojo.execute(); - assertThat( changeRecorder.getChanges(), Matchers.hasItem( - new DefaultVersionChange( "default-group", "default-artifact", "1.0.0", "1.1.0-alpha" ) ) ); + assertThat( + changeRecorder.getChanges(), + Matchers.hasItem( + new DefaultVersionChange("default-group", "default-artifact", "1.0.0", "1.1.0-alpha"))); } @Test - public void testAllowIncrementalUpdates() throws Exception - { - Files.copy( Paths.get( "src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml" ), - Paths.get( pomDir.toString(), "pom.xml" ), REPLACE_EXISTING ); - UpdatePropertyMojo mojo = setUpMojo( "update-property" ); + public void testAllowIncrementalUpdates() throws Exception { + Files.copy( + Paths.get("src/test/resources/org/codehaus/mojo/update-properties/issue-454-pom.xml"), + Paths.get(pomDir.toString(), "pom.xml"), + REPLACE_EXISTING); + UpdatePropertyMojo mojo = setUpMojo("update-property"); mojo.property = "artifact-version"; mojo.allowMajorUpdates = false; mojo.allowMinorUpdates = false; mojo.execute(); - assertThat( changeRecorder.getChanges(), Matchers.hasItem( - new DefaultVersionChange( "default-group", "default-artifact", "1.0.0", "1.0.1-rc1" ) ) ); + assertThat( + changeRecorder.getChanges(), + Matchers.hasItem(new DefaultVersionChange("default-group", "default-artifact", "1.0.0", "1.0.1-rc1"))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseDepVersionMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseDepVersionMojoTest.java index 290a021942..31c04aa7cb 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseDepVersionMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseDepVersionMojoTest.java @@ -32,23 +32,20 @@ * * @author Andrzej Jarmoniuk */ -public class UseDepVersionMojoTest extends AbstractMojoTestCase -{ +public class UseDepVersionMojoTest extends AbstractMojoTestCase { @Rule - public MojoRule mojoRule = new MojoRule( this ); + public MojoRule mojoRule = new MojoRule(this); @Test - public void testIssue673() throws Exception - { + public void testIssue673() throws Exception { UseDepVersionMojo mojo = (UseDepVersionMojo) mojoRule.lookupConfiguredMojo( - new File( "target/test-classes/org/codehaus/mojo/use-dep-version/issue-637" ), - "use-dep-version" ); - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "processDependencyManagement", true ); - setVariableValueToObject( mojo, "excludeReactor", true ); - setVariableValueToObject( mojo, "serverId", "serverId" ); - setVariableValueToObject( mojo, "reactorProjects", Collections.singletonList( mojo.getProject() ) ); + new File("target/test-classes/org/codehaus/mojo/use-dep-version/issue-637"), "use-dep-version"); + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "processDependencyManagement", true); + setVariableValueToObject(mojo, "excludeReactor", true); + setVariableValueToObject(mojo, "serverId", "serverId"); + setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(mojo.getProject())); mojo.execute(); } -} \ No newline at end of file +} diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestReleasesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestReleasesMojoTest.java index a02eef31f3..f103df7359 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestReleasesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestReleasesMojoTest.java @@ -33,82 +33,86 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -public class UseLatestReleasesMojoTest -{ +public class UseLatestReleasesMojoTest { private UseLatestReleasesMojo mojo; private TestChangeRecorder changeRecorder; @Before - public void setUp() throws Exception - { - RepositorySystem repositorySystemMock = mock( RepositorySystem.class ); - when( repositorySystemMock.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( invocation -> - { - Dependency dependency = invocation.getArgument( 0 ); - return new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), - dependency.getScope(), dependency.getType(), - dependency.getClassifier() != null ? dependency.getClassifier() : "default", - new DefaultArtifactHandlerStub( "default" ) ); - } ); + public void setUp() throws Exception { + RepositorySystem repositorySystemMock = mock(RepositorySystem.class); + when(repositorySystemMock.createDependencyArtifact(any(Dependency.class))) + .thenAnswer(invocation -> { + Dependency dependency = invocation.getArgument(0); + return new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + dependency.getScope(), + dependency.getType(), + dependency.getClassifier() != null ? dependency.getClassifier() : "default", + new DefaultArtifactHandlerStub("default")); + }); - org.eclipse.aether.RepositorySystem aetherRepositorySystem = mockAetherRepositorySystem( - new HashMap() - {{ - put( "dependency-artifact", new String[] {"0.9.0", "1.0.0-beta"} ); - }} ); + org.eclipse.aether.RepositorySystem aetherRepositorySystem = + mockAetherRepositorySystem(new HashMap() { + { + put("dependency-artifact", new String[] {"0.9.0", "1.0.0-beta"}); + } + }); changeRecorder = new TestChangeRecorder(); - mojo = new UseLatestReleasesMojo( repositorySystemMock, - aetherRepositorySystem, - null, - changeRecorder.asTestMap() ) - {{ - reactorProjects = emptyList(); - MavenProject project = new MavenProject() - {{ - setModel( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "project-artifact" ); - setVersion( "1.0.0-SNAPSHOT" ); + mojo = + new UseLatestReleasesMojo( + repositorySystemMock, aetherRepositorySystem, null, changeRecorder.asTestMap()) { + { + reactorProjects = emptyList(); + MavenProject project = new MavenProject() { + { + setModel(new Model() { + { + setGroupId("default-group"); + setArtifactId("project-artifact"); + setVersion("1.0.0-SNAPSHOT"); - setDependencies( singletonList( - DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "dependency-artifact" ) - .withVersion( "0.9.0" ) - .withScope( SCOPE_COMPILE ) - .withType( "jar" ) - .withClassifier( "default" ) - .build() ) ); - }} ); - }}; - setProject( project ); + setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("dependency-artifact") + .withVersion("0.9.0") + .withScope(SCOPE_COMPILE) + .withType("jar") + .withClassifier("default") + .build())); + } + }); + } + }; + setProject(project); - session = mockMavenSession(); - }}; + session = mockMavenSession(); + } + }; } @Test public void testDontUpgradeToBeta() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", false ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", false ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", false); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", false); - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), Matchers.empty() ); + assertThat(changeRecorder.getChanges(), Matchers.empty()); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestVersionsMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestVersionsMojoTest.java index 9a3db80a40..0c3095af84 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestVersionsMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseLatestVersionsMojoTest.java @@ -41,295 +41,325 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -@SuppressWarnings( "deprecation" ) -public class UseLatestVersionsMojoTest -{ +@SuppressWarnings("deprecation") +public class UseLatestVersionsMojoTest { private UseLatestVersionsMojo mojo; private TestChangeRecorder changeRecorder; @Before - public void setUp() throws Exception - { - RepositorySystem repositorySystemMock = mock( RepositorySystem.class ); - when( repositorySystemMock.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( invocation -> - { - Dependency dependency = invocation.getArgument( 0 ); - return new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), - dependency.getScope(), dependency.getType(), - dependency.getClassifier() != null ? dependency.getClassifier() : "default", - new DefaultArtifactHandlerStub( "default" ) ); - } ); - - org.eclipse.aether.RepositorySystem aetherRepositorySystem = mockAetherRepositorySystem( - new HashMap() - {{ - put( "dependency-artifact", new String[] {"1.1.1-SNAPSHOT", "1.1.0", "1.1.0-SNAPSHOT", "1.0.0", - "1.0.0-SNAPSHOT", "0.9.0"} ); - put( "poison-artifact", new String[] {"1.1.1.1-SNAPSHOT", "1.1.1.0", "1.1.1.0-SNAPSHOT", "1.0.0.0", - "1.0.0.0-SNAPSHOT", "0.9.0.0"} ); - put( "other-artifact", new String[] {"1.0", "2.0"} ); - }} ); + public void setUp() throws Exception { + RepositorySystem repositorySystemMock = mock(RepositorySystem.class); + when(repositorySystemMock.createDependencyArtifact(any(Dependency.class))) + .thenAnswer(invocation -> { + Dependency dependency = invocation.getArgument(0); + return new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + dependency.getScope(), + dependency.getType(), + dependency.getClassifier() != null ? dependency.getClassifier() : "default", + new DefaultArtifactHandlerStub("default")); + }); + + org.eclipse.aether.RepositorySystem aetherRepositorySystem = + mockAetherRepositorySystem(new HashMap() { + { + put("dependency-artifact", new String[] { + "1.1.1-SNAPSHOT", "1.1.0", "1.1.0-SNAPSHOT", "1.0.0", "1.0.0-SNAPSHOT", "0.9.0" + }); + put("poison-artifact", new String[] { + "1.1.1.1-SNAPSHOT", "1.1.1.0", "1.1.1.0-SNAPSHOT", "1.0.0.0", "1.0.0.0-SNAPSHOT", "0.9.0.0" + }); + put("other-artifact", new String[] {"1.0", "2.0"}); + } + }); changeRecorder = new TestChangeRecorder(); - mojo = new UseLatestVersionsMojo( repositorySystemMock, - aetherRepositorySystem, - null, - changeRecorder.asTestMap() ) - {{ - reactorProjects = emptyList(); - MavenProject project = new MavenProject() - {{ - setModel( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "project-artifact" ); - setVersion( "1.0.0-SNAPSHOT" ); - - setDependencies( Collections.singletonList( - DependencyBuilder.dependencyWith( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", - "default", "pom", SCOPE_COMPILE ) ) ); - - setDependencyManagement( new DependencyManagement() ); - getDependencyManagement().setDependencies( Collections.singletonList( - DependencyBuilder.dependencyWith( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", - "default", "pom", SCOPE_COMPILE ) ) ); - }} ); - }}; - setProject( project ); - - session = mockMavenSession(); - }}; - setVariableValueToObject( mojo, "processDependencyManagement", false ); + mojo = + new UseLatestVersionsMojo( + repositorySystemMock, aetherRepositorySystem, null, changeRecorder.asTestMap()) { + { + reactorProjects = emptyList(); + MavenProject project = new MavenProject() { + { + setModel(new Model() { + { + setGroupId("default-group"); + setArtifactId("project-artifact"); + setVersion("1.0.0-SNAPSHOT"); + + setDependencies(Collections.singletonList(DependencyBuilder.dependencyWith( + "default-group", + "dependency-artifact", + "1.1.1-SNAPSHOT", + "default", + "pom", + SCOPE_COMPILE))); + + setDependencyManagement(new DependencyManagement()); + getDependencyManagement() + .setDependencies( + Collections.singletonList(DependencyBuilder.dependencyWith( + "default-group", + "dependency-artifact", + "1.1.1-SNAPSHOT", + "default", + "pom", + SCOPE_COMPILE))); + } + }); + } + }; + setProject(project); + + session = mockMavenSession(); + } + }; + setVariableValueToObject(mojo, "processDependencyManagement", false); } @Test public void testDependenciesDowngradeIncremental() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", false ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", true ); - setVariableValueToObject( mojo, "allowDowngrade", true ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", false); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", true); + setVariableValueToObject(mojo, "allowDowngrade", true); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0"))); } @Test public void testDependenciesDowngradeMinor() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", false ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", true ); - setVariableValueToObject( mojo, "allowDowngrade", true ); - - mojo.getProject().getModel().setDependencies( Collections.singletonList( - DependencyBuilder.dependencyWith( "default-group", "dependency-artifact", "1.1.0-SNAPSHOT", - "default", "pom", SCOPE_COMPILE ) ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", false); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", true); + setVariableValueToObject(mojo, "allowDowngrade", true); + + mojo.getProject() + .getModel() + .setDependencies(Collections.singletonList(DependencyBuilder.dependencyWith( + "default-group", "dependency-artifact", "1.1.0-SNAPSHOT", "default", "pom", SCOPE_COMPILE))); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "dependency-artifact", - "1.1.0-SNAPSHOT", "1.1.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "dependency-artifact", + "1.1.0-SNAPSHOT", "1.1.0"))); } @Test public void testDependenciesDowngradeMajor() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", true ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", true ); - setVariableValueToObject( mojo, "allowDowngrade", true ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", true); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", true); + setVariableValueToObject(mojo, "allowDowngrade", true); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "dependency-artifact", - "1.1.1-SNAPSHOT", "1.1.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "dependency-artifact", + "1.1.1-SNAPSHOT", "1.1.0"))); } @Test public void testDependencyManagementDowngrade() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processDependencyManagement", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", false ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", true ); - setVariableValueToObject( mojo, "allowDowngrade", true ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processDependencyManagement", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", false); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", true); + setVariableValueToObject(mojo, "allowDowngrade", true); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0"))); } @Test public void testParentDowngrade() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processParent", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", false ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", true ); - setVariableValueToObject( mojo, "allowDowngrade", true ); - - mojo.getProject().setParentArtifact( - new DefaultArtifact( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "compile", "pom", - "default", null ) ); - mojo.getProject().setParent( new MavenProject() - {{ - setGroupId( mojo.getProject().getParentArtifact().getGroupId() ); - setArtifactId( mojo.getProject().getParentArtifact().getArtifactId() ); - setVersion( mojo.getProject().getParentArtifact().getVersion() ); - }} ); - - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processParent", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", false); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", true); + setVariableValueToObject(mojo, "allowDowngrade", true); + + mojo.getProject() + .setParentArtifact(new DefaultArtifact( + "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "compile", "pom", "default", null)); + mojo.getProject().setParent(new MavenProject() { + { + setGroupId(mojo.getProject().getParentArtifact().getGroupId()); + setArtifactId(mojo.getProject().getParentArtifact().getArtifactId()); + setVersion(mojo.getProject().getParentArtifact().getVersion()); + } + }); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0"))); } @Test public void testPoisonDependencyVersion() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - mojo.getProject().getModel().setDependencies( Arrays.asList( - DependencyBuilder.dependencyWith( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", - "default", "pom", SCOPE_COMPILE ), - DependencyBuilder.dependencyWith( "default-group", "poison-artifact", "1.1.1.1-SNAPSHOT", - "default", "pom", SCOPE_COMPILE ) - ) ); - - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "allowSnapshots", false ); - setVariableValueToObject( mojo, "allowMajorUpdates", false ); - setVariableValueToObject( mojo, "allowMinorUpdates", true ); - setVariableValueToObject( mojo, "allowIncrementalUpdates", true ); - setVariableValueToObject( mojo, "allowDowngrade", true ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + mojo.getProject() + .getModel() + .setDependencies(Arrays.asList( + DependencyBuilder.dependencyWith( + "default-group", + "dependency-artifact", + "1.1.1-SNAPSHOT", + "default", + "pom", + SCOPE_COMPILE), + DependencyBuilder.dependencyWith( + "default-group", + "poison-artifact", + "1.1.1.1-SNAPSHOT", + "default", + "pom", + SCOPE_COMPILE))); + + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "allowSnapshots", false); + setVariableValueToObject(mojo, "allowMajorUpdates", false); + setVariableValueToObject(mojo, "allowMinorUpdates", true); + setVariableValueToObject(mojo, "allowIncrementalUpdates", true); + setVariableValueToObject(mojo, "allowDowngrade", true); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } // So, the regular update should take place despite an irregular, or — if I may — "poison", dependency // being present in the dependency list - assertThat( changeRecorder.getChanges(), hasItem( - new DefaultVersionChange( "default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "dependency-artifact", "1.1.1-SNAPSHOT", "1.1.0"))); } @Test public void testIgnoredVersions() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "ignoredVersions", singleton( "1.1.0" ) ); - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "ignoredVersions", singleton("1.1.0")); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), Is.is( empty() ) ); + assertThat(changeRecorder.getChanges(), Is.is(empty())); } @Test public void testIncludeFilter() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - mojo.getProject().getModel().setDependencies( Arrays.asList( - DependencyBuilder.dependencyWith( "default-group", "dependency-artifact", "0.9.0", - "default", "pom", SCOPE_COMPILE ), - DependencyBuilder.dependencyWith( "default-group", "other-artifact", "1.0", - "default", "pom", SCOPE_COMPILE ) - ) ); - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "includes", new String[] {"default-group:other-artifact"} ); - - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + mojo.getProject() + .getModel() + .setDependencies(Arrays.asList( + DependencyBuilder.dependencyWith( + "default-group", "dependency-artifact", "0.9.0", "default", "pom", SCOPE_COMPILE), + DependencyBuilder.dependencyWith( + "default-group", "other-artifact", "1.0", "default", "pom", SCOPE_COMPILE))); + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "includes", new String[] {"default-group:other-artifact"}); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), hasSize( 1 ) ); - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "other-artifact", "1.0", "2.0" ) ) ); + assertThat(changeRecorder.getChanges(), hasSize(1)); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange("default-group", "other-artifact", "1.0", "2.0"))); } @Test public void testExcludeFilter() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - mojo.getProject().getModel().setDependencies( Arrays.asList( - DependencyBuilder.dependencyWith( "default-group", "dependency-artifact", "0.9.0", - "default", "pom", SCOPE_COMPILE ), - DependencyBuilder.dependencyWith( "default-group", "other-artifact", "1.0", - "default", "pom", SCOPE_COMPILE ) - ) ); - setVariableValueToObject( mojo, "processDependencies", true ); - setVariableValueToObject( mojo, "excludes", new String[] {"default-group:other-artifact"} ); - - - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), any(), any(), any(), any(), any() ) ) - .thenReturn( true ); - mojo.update( null ); + VersionRetrievalException { + mojo.getProject() + .getModel() + .setDependencies(Arrays.asList( + DependencyBuilder.dependencyWith( + "default-group", "dependency-artifact", "0.9.0", "default", "pom", SCOPE_COMPILE), + DependencyBuilder.dependencyWith( + "default-group", "other-artifact", "1.0", "default", "pom", SCOPE_COMPILE))); + setVariableValueToObject(mojo, "processDependencies", true); + setVariableValueToObject(mojo, "excludes", new String[] {"default-group:other-artifact"}); + + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion(any(), any(), any(), any(), any(), any())) + .thenReturn(true); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), hasSize( 1 ) ); - assertThat( changeRecorder.getChanges(), - not( hasItem( new DefaultVersionChange( "default-group", "other-artifact", "1.0", - "2.0" ) ) ) ); + assertThat(changeRecorder.getChanges(), hasSize(1)); + assertThat( + changeRecorder.getChanges(), + not(hasItem(new DefaultVersionChange("default-group", "other-artifact", "1.0", "2.0")))); } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseReleasesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseReleasesMojoTest.java index 8f108b7447..cfac64c8c1 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseReleasesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UseReleasesMojoTest.java @@ -53,112 +53,113 @@ /** * Unit tests for {@link UseReleasesMojo} */ -public class UseReleasesMojoTest extends AbstractMojoTestCase -{ +public class UseReleasesMojoTest extends AbstractMojoTestCase { private TestChangeRecorder changeRecorder; private UseReleasesMojo mojo; @Before - public void setUp() throws IllegalAccessException - { + public void setUp() throws IllegalAccessException { changeRecorder = new TestChangeRecorder(); - mojo = new UseReleasesMojo( mockRepositorySystem(), - mockAetherRepositorySystem(), - null, - changeRecorder.asTestMap() ); - setVariableValueToObject( mojo, "reactorProjects", emptyList() ); - mojo.project = new MavenProject() - {{ - setModel( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "default-artifact" ); - setVersion( "1.0.0" ); - }} ); - }}; + mojo = new UseReleasesMojo( + mockRepositorySystem(), mockAetherRepositorySystem(), null, changeRecorder.asTestMap()); + setVariableValueToObject(mojo, "reactorProjects", emptyList()); + mojo.project = new MavenProject() { + { + setModel(new Model() { + { + setGroupId("default-group"); + setArtifactId("default-artifact"); + setVersion("1.0.0"); + } + }); + } + }; mojo.session = mockMavenSession(); } @Test public void testProcessParent() throws MojoExecutionException, XMLStreamException, MojoFailureException, IllegalAccessException, - VersionRetrievalException - { - setVariableValueToObject( mojo, "processParent", true ); - mojo.getProject().setParent( new MavenProject( new Model() - {{ - setGroupId( "default-group" ); - setArtifactId( "artifactA" ); - setVersion( "1.0.0-SNAPSHOT" ); - }} ) ); - mojo.getProject().setParentArtifact( new DefaultArtifact( "default-group", "artifactA", - "1.0.0-SNAPSHOT", SCOPE_COMPILE, "pom", "default", null ) ); + VersionRetrievalException { + setVariableValueToObject(mojo, "processParent", true); + mojo.getProject().setParent(new MavenProject(new Model() { + { + setGroupId("default-group"); + setArtifactId("artifactA"); + setVersion("1.0.0-SNAPSHOT"); + } + })); + mojo.getProject() + .setParentArtifact(new DefaultArtifact( + "default-group", "artifactA", "1.0.0-SNAPSHOT", SCOPE_COMPILE, "pom", "default", null)); - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setProjectParentVersion( any(), anyString() ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setProjectParentVersion(any(), anyString())) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "artifactA", - "1.0.0-SNAPSHOT", "1.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "artifactA", + "1.0.0-SNAPSHOT", "1.0.0"))); } @Test public void testReplaceSnapshotWithRelease() - throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { - mojo.getProject().setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "artifactA" ) - .withVersion( "1.0.0-SNAPSHOT" ) - .build() ) ); + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.getProject() + .setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("artifactA") + .withVersion("1.0.0-SNAPSHOT") + .build())); - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), anyString(), anyString(), anyString(), - anyString(), any( Model.class ) ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion( + any(), anyString(), anyString(), anyString(), anyString(), any(Model.class))) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); } - assertThat( changeRecorder.getChanges(), - hasItem( new DefaultVersionChange( "default-group", "artifactA", - "1.0.0-SNAPSHOT", "1.0.0" ) ) ); + assertThat( + changeRecorder.getChanges(), + hasItem(new DefaultVersionChange( + "default-group", "artifactA", + "1.0.0-SNAPSHOT", "1.0.0"))); } @Test public void testFailIfNotReplaced() - throws MojoExecutionException, XMLStreamException, MojoFailureException, - VersionRetrievalException - { - mojo.aetherRepositorySystem = mockAetherRepositorySystem( singletonMap( "test-artifact", - new String[] {} ) ); - mojo.getProject().setDependencies( singletonList( DependencyBuilder.newBuilder() - .withGroupId( "default-group" ) - .withArtifactId( "test-artifact" ) - .withVersion( "1.0.0-SNAPSHOT" ) - .build() ) ); + throws MojoExecutionException, XMLStreamException, MojoFailureException, VersionRetrievalException { + mojo.aetherRepositorySystem = mockAetherRepositorySystem(singletonMap("test-artifact", new String[] {})); + mojo.getProject() + .setDependencies(singletonList(DependencyBuilder.newBuilder() + .withGroupId("default-group") + .withArtifactId("test-artifact") + .withVersion("1.0.0-SNAPSHOT") + .build())); mojo.failIfNotReplaced = true; - try ( MockedStatic pomHelper = mockStatic( PomHelper.class ) ) - { - pomHelper.when( () -> PomHelper.setDependencyVersion( any(), anyString(), anyString(), anyString(), - anyString(), any( Model.class ) ) ) - .thenReturn( true ); - pomHelper.when( () -> PomHelper.getRawModel( any( MavenProject.class ) ) ) - .thenReturn( mojo.getProject().getModel() ); - mojo.update( null ); - fail( "MojoExecutionException is expected" ); - } - catch ( MojoExecutionException e ) - { - assertThat( e.getMessage(), startsWith( "No matching" ) ); + try (MockedStatic pomHelper = mockStatic(PomHelper.class)) { + pomHelper + .when(() -> PomHelper.setDependencyVersion( + any(), anyString(), anyString(), anyString(), anyString(), any(Model.class))) + .thenReturn(true); + pomHelper + .when(() -> PomHelper.getRawModel(any(MavenProject.class))) + .thenReturn(mojo.getProject().getModel()); + mojo.update(null); + fail("MojoExecutionException is expected"); + } catch (MojoExecutionException e) { + assertThat(e.getMessage(), startsWith("No matching")); } } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/model/TestIgnoreVersions.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/model/TestIgnoreVersions.java index e70da476ea..fcd2b9cd6f 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/model/TestIgnoreVersions.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/model/TestIgnoreVersions.java @@ -28,8 +28,7 @@ /** * Convenience class for quickly creating {@link IgnoreVersion} instances. */ -public class TestIgnoreVersions extends IgnoreVersion -{ +public class TestIgnoreVersions extends IgnoreVersion { public static final String TYPE_REGEX = "regex"; public static final String TYPE_EXACT = "exact"; @@ -40,9 +39,8 @@ public class TestIgnoreVersions extends IgnoreVersion * @param type required type * @return modified instance */ - public TestIgnoreVersions withType( String type ) - { - setType( type ); + public TestIgnoreVersions withType(String type) { + setType(type); return this; } @@ -52,9 +50,8 @@ public TestIgnoreVersions withType( String type ) * @param version required version * @return modified instance */ - public TestIgnoreVersions withVersion( String version ) - { - setVersion( version ); + public TestIgnoreVersions withVersion(String version) { + setVersion(version); return this; } @@ -65,29 +62,23 @@ public TestIgnoreVersions withVersion( String version ) * @return Matcher returning true if another object matches the given instance * @param

class of the ignoreVersion instance */ - public static

Matcher

matches( P ignoreVersion ) - { - return new TypeSafeMatcher

() - { + public static

Matcher

matches(P ignoreVersion) { + return new TypeSafeMatcher

() { @Override - public void describeTo( Description description ) - { - description.appendText( Objects.toString( ignoreVersion ) ); + public void describeTo(Description description) { + description.appendText(Objects.toString(ignoreVersion)); } @Override - protected void describeMismatchSafely( P other, Description description ) - { - description.appendText( Objects.toString( other ) ); + protected void describeMismatchSafely(P other, Description description) { + description.appendText(Objects.toString(other)); } @Override - protected boolean matchesSafely( P other ) - { - return Objects.equals( ignoreVersion.getType(), other.getType() ) - && Objects.equals( ignoreVersion.getVersion(), other.getVersion() ); + protected boolean matchesSafely(P other) { + return Objects.equals(ignoreVersion.getType(), other.getType()) + && Objects.equals(ignoreVersion.getVersion(), other.getVersion()); } }; } - } diff --git a/versions-model-report/pom.xml b/versions-model-report/pom.xml index 6ba1fbb1bf..f92e09bb0b 100644 --- a/versions-model-report/pom.xml +++ b/versions-model-report/pom.xml @@ -1,83 +1,81 @@ - - - versions - org.codehaus.mojo.versions - 2.14.0-SNAPSHOT - - 4.0.0 + + 4.0.0 + + org.codehaus.mojo.versions + versions + 2.14.0-SNAPSHOT + - versions-model-report + versions-model-report - Versions Model Report - Modello models used in reports + Versions Model Report + Modello models used in reports - - - org.codehaus.plexus - plexus-utils - 3.5.0 - - + + + org.codehaus.plexus + plexus-utils + 3.5.0 + + - - - - org.codehaus.modello - modello-maven-plugin - - - generate-rule - generate-sources - - - xpp3-reader - - xpp3-writer - - java - - - - site-doc - pre-site - - xdoc - - - - site-xsd - pre-site - - xsd - - - ${project.build.directory}/generated-site/resources/xsd - - - - - - src/main/mdo/dependency-updates-report.mdo - src/main/mdo/plugin-updates-report.mdo - src/main/mdo/property-updates-report.mdo - - ${modelloNamespaceReportVersion} - - + + + + org.codehaus.modello + modello-maven-plugin + + + src/main/mdo/dependency-updates-report.mdo + src/main/mdo/plugin-updates-report.mdo + src/main/mdo/property-updates-report.mdo + + ${modelloNamespaceReportVersion} + + + + generate-rule + + + xpp3-reader + + xpp3-writer + + java + + generate-sources + + + site-doc + + xdoc + + pre-site + + + site-xsd + + xsd + + pre-site + + ${project.build.directory}/generated-site/resources/xsd + + + + - - org.apache.maven.plugins - maven-checkstyle-plugin - - true - - + + org.apache.maven.plugins + maven-checkstyle-plugin + + true + + - + - + diff --git a/versions-model/pom.xml b/versions-model/pom.xml index b813ea9eb8..3abd59ef69 100644 --- a/versions-model/pom.xml +++ b/versions-model/pom.xml @@ -1,77 +1,75 @@ - - - versions - org.codehaus.mojo.versions - 2.14.0-SNAPSHOT - - 4.0.0 + + 4.0.0 + + org.codehaus.mojo.versions + versions + 2.14.0-SNAPSHOT + - versions-model + versions-model - Versions Model - Modello models used in plugin + Versions Model + Modello models used in plugin - - - org.codehaus.plexus - plexus-utils - 3.5.0 - - + + + org.codehaus.plexus + plexus-utils + 3.5.0 + + - - - - org.codehaus.modello - modello-maven-plugin - - - generate-rule - generate-sources - - - xpp3-reader - - java - - - - site-doc - pre-site - - xdoc - - - - site-xsd - pre-site - - xsd - - - ${project.build.directory}/generated-site/resources/xsd - - - - - - src/main/mdo/rule.mdo - - ${modelloNamespaceRuleVersion} - - + + + + org.codehaus.modello + modello-maven-plugin + + + src/main/mdo/rule.mdo + + ${modelloNamespaceRuleVersion} + + + + generate-rule + + + xpp3-reader + + java + + generate-sources + + + site-doc + + xdoc + + pre-site + + + site-xsd + + xsd + + pre-site + + ${project.build.directory}/generated-site/resources/xsd + + + + - - org.apache.maven.plugins - maven-checkstyle-plugin - - true - - - - + + org.apache.maven.plugins + maven-checkstyle-plugin + + true + + + + diff --git a/versions-test/pom.xml b/versions-test/pom.xml index 3c81525f99..1f1d02f1c2 100644 --- a/versions-test/pom.xml +++ b/versions-test/pom.xml @@ -17,61 +17,58 @@ ~ specific language governing permissions and limitations ~ under the License. --> + + 4.0.0 + + org.codehaus.mojo.versions + versions + 2.14.0-SNAPSHOT + - - 4.0.0 - - versions - org.codehaus.mojo.versions - 2.14.0-SNAPSHOT - + versions-test - versions-test + Versions Test + Internal test utilities used in project - Versions Test - Internal test utilities used in project + + + org.apache.maven + maven-core + ${mavenVersion} + provided + + + org.eclipse.aether + aether-api + 1.1.0 + + + org.apache.maven.doxia + doxia-integration-tools + ${doxiaVersion} + + + org.apache.maven.doxia + doxia-site-renderer + ${doxia-sitetoolsVersion} + + + org.codehaus.mojo.versions + versions-common + ${project.version} + + + org.apache.commons + commons-text + + + org.mockito + mockito-inline + + + org.apache.maven.plugin-testing + maven-plugin-testing-harness + + - - - org.apache.maven - maven-core - ${mavenVersion} - provided - - - org.eclipse.aether - aether-api - 1.1.0 - - - org.apache.maven.doxia - doxia-integration-tools - ${doxiaVersion} - - - org.apache.maven.doxia - doxia-site-renderer - ${doxia-sitetoolsVersion} - - - org.codehaus.mojo.versions - versions-common - ${project.version} - - - org.apache.commons - commons-text - - - org.mockito - mockito-inline - - - org.apache.maven.plugin-testing - maven-plugin-testing-harness - - - - \ No newline at end of file + diff --git a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/MockUtils.java b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/MockUtils.java index b19b3a2ead..92a1d0cab7 100644 --- a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/MockUtils.java +++ b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/MockUtils.java @@ -53,22 +53,21 @@ /** * Various mock creating utilities */ -public class MockUtils -{ - private static final Map DEFAULT_VERSION_MAP = new HashMap() - {{ - put( "artifactA", new String[] {"1.0.0", "2.0.0"} ); - put( "artifactB", new String[] {"1.0.0", "1.1.0"} ); - put( "artifactC", new String[] {"1.0.0"} ); - }}; +public class MockUtils { + private static final Map DEFAULT_VERSION_MAP = new HashMap() { + { + put("artifactA", new String[] {"1.0.0", "2.0.0"}); + put("artifactB", new String[] {"1.0.0", "1.1.0"}); + put("artifactC", new String[] {"1.0.0"}); + } + }; /** * Creates a mocked {@linkplain org.eclipse.aether.RepositorySystem}, providing the default version set * @return mocked {@linkplain org.eclipse.aether.RepositorySystem} */ - public static org.eclipse.aether.RepositorySystem mockAetherRepositorySystem() - { - return mockAetherRepositorySystem( DEFAULT_VERSION_MAP ); + public static org.eclipse.aether.RepositorySystem mockAetherRepositorySystem() { + return mockAetherRepositorySystem(DEFAULT_VERSION_MAP); } /** @@ -77,84 +76,73 @@ public static org.eclipse.aether.RepositorySystem mockAetherRepositorySystem() * @param versionMap requested version map * @return mocked {@linkplain org.eclipse.aether.RepositorySystem} */ - public static org.eclipse.aether.RepositorySystem mockAetherRepositorySystem( Map versionMap ) - { - org.eclipse.aether.RepositorySystem repositorySystem = mock( org.eclipse.aether.RepositorySystem.class ); - try - { - when( repositorySystem.resolveVersionRange( any(), any( VersionRangeRequest.class ) ) ) - .then( invocation -> - { - VersionRangeRequest request = invocation.getArgument( 1 ); + public static org.eclipse.aether.RepositorySystem mockAetherRepositorySystem(Map versionMap) { + org.eclipse.aether.RepositorySystem repositorySystem = mock(org.eclipse.aether.RepositorySystem.class); + try { + when(repositorySystem.resolveVersionRange(any(), any(VersionRangeRequest.class))) + .then(invocation -> { + VersionRangeRequest request = invocation.getArgument(1); return versionMap.entrySet().stream() - .filter( e -> e.getKey().equals( request.getArtifact().getArtifactId() ) ) + .filter(e -> + e.getKey().equals(request.getArtifact().getArtifactId())) .findAny() - .map( e -> Arrays.stream( e.getValue() ) - .map( VersionStub::new ) - .collect( () -> new ArrayList(), ArrayList::add, ArrayList::addAll ) ) - .map( versions -> new VersionRangeResult( request ).setVersions( versions ) ) - .orElse( null ); // should tell us if we haven't populated all cases in the test - } ); - when( repositorySystem.resolveArtifact( any( RepositorySystemSession.class ), - any( ArtifactRequest.class ) ) ) - .then( invocation -> - { - ArtifactRequest request = invocation.getArgument( 1 ); + .map(e -> Arrays.stream(e.getValue()) + .map(VersionStub::new) + .collect(() -> new ArrayList(), ArrayList::add, ArrayList::addAll)) + .map(versions -> new VersionRangeResult(request).setVersions(versions)) + .orElse(null); // should tell us if we haven't populated all cases in the test + }); + when(repositorySystem.resolveArtifact(any(RepositorySystemSession.class), any(ArtifactRequest.class))) + .then(invocation -> { + ArtifactRequest request = invocation.getArgument(1); org.eclipse.aether.artifact.Artifact copiedArtifact = new org.eclipse.aether.artifact.DefaultArtifact( request.getArtifact().getGroupId(), request.getArtifact().getArtifactId(), request.getArtifact().getClassifier(), request.getArtifact().getExtension(), - request.getArtifact().getVersion() ); - copiedArtifact.setFile( mock( File.class ) ); - return new ArtifactResult( request ) - .setArtifact( copiedArtifact ); - } ); - } - catch ( VersionRangeResolutionException | ArtifactResolutionException e ) - { - throw new RuntimeException( e ); + request.getArtifact().getVersion()); + copiedArtifact.setFile(mock(File.class)); + return new ArtifactResult(request).setArtifact(copiedArtifact); + }); + } catch (VersionRangeResolutionException | ArtifactResolutionException e) { + throw new RuntimeException(e); } return repositorySystem; } - public static I18N mockI18N() - { - I18N i18n = mock( I18N.class ); - when( i18n.getString( anyString(), any(), anyString() ) ).thenAnswer( - invocation -> invocation.getArgument( 2 ) ); + public static I18N mockI18N() { + I18N i18n = mock(I18N.class); + when(i18n.getString(anyString(), any(), anyString())).thenAnswer(invocation -> invocation.getArgument(2)); return i18n; } - public static SiteTool mockSiteTool() - { - Artifact skinArtifact = mock( Artifact.class ); - when( skinArtifact.getId() ).thenReturn( "" ); - SiteTool siteTool = mock( SiteTool.class ); - try - { - when( siteTool.getSkinArtifactFromRepository( any(), any(), any() ) ).thenReturn( skinArtifact ); - } - catch ( SiteToolException e ) - { - throw new RuntimeException( e ); + public static SiteTool mockSiteTool() { + Artifact skinArtifact = mock(Artifact.class); + when(skinArtifact.getId()).thenReturn(""); + SiteTool siteTool = mock(SiteTool.class); + try { + when(siteTool.getSkinArtifactFromRepository(any(), any(), any())).thenReturn(skinArtifact); + } catch (SiteToolException e) { + throw new RuntimeException(e); } return siteTool; } - public static RepositorySystem mockRepositorySystem() - { - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( - invocation -> - { - Dependency dependency = invocation.getArgument( 0 ); - return new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), - dependency.getVersion(), dependency.getScope(), dependency.getType(), - dependency.getClassifier(), new DefaultArtifactHandlerStub( "default" ) ); - } ); + public static RepositorySystem mockRepositorySystem() { + RepositorySystem repositorySystem = mock(RepositorySystem.class); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(invocation -> { + Dependency dependency = invocation.getArgument(0); + return new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + dependency.getScope(), + dependency.getType(), + dependency.getClassifier(), + new DefaultArtifactHandlerStub("default")); + }); return repositorySystem; } @@ -163,14 +151,12 @@ public static RepositorySystem mockRepositorySystem() * by providing only a non-{@code null} implementation of its {@link MavenSession#getRepositorySession()} method. * @return mocked {@link MavenSession} */ - public static MavenSession mockMavenSession() - { - MavenSession session = mock( MavenSession.class ); - when( session.getRepositorySession() ) - .thenReturn( mock( RepositorySystemSession.class ) ); - when( session.getCurrentProject() ).thenReturn( mock( MavenProject.class ) ); - when( session.getCurrentProject().getRemotePluginRepositories() ).thenReturn( emptyList() ); - when( session.getCurrentProject().getRemoteProjectRepositories() ).thenReturn( emptyList() ); + public static MavenSession mockMavenSession() { + MavenSession session = mock(MavenSession.class); + when(session.getRepositorySession()).thenReturn(mock(RepositorySystemSession.class)); + when(session.getCurrentProject()).thenReturn(mock(MavenProject.class)); + when(session.getCurrentProject().getRemotePluginRepositories()).thenReturn(emptyList()); + when(session.getCurrentProject().getRemoteProjectRepositories()).thenReturn(emptyList()); return session; } } diff --git a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestChangeRecorder.java b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestChangeRecorder.java index 93dad6ec69..b591d600b6 100644 --- a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestChangeRecorder.java +++ b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestChangeRecorder.java @@ -31,31 +31,25 @@ import org.codehaus.mojo.versions.api.recording.ChangeRecord; import org.codehaus.mojo.versions.api.recording.ChangeRecorder; -@Named( "test" ) -public class TestChangeRecorder implements ChangeRecorder -{ +@Named("test") +public class TestChangeRecorder implements ChangeRecorder { private final List changes = new LinkedList<>(); @Override - public void recordChange( ChangeRecord changeRecord ) - { - changes.add( changeRecord.getVersionChange() ); + public void recordChange(ChangeRecord changeRecord) { + changes.add(changeRecord.getVersionChange()); } @Override - public void writeReport( Path outputPath ) - { - } + public void writeReport(Path outputPath) {} - public List getChanges() - { + public List getChanges() { return changes; } - public Map asTestMap() - { + public Map asTestMap() { HashMap map = new HashMap<>(); - map.put( "none", this ); + map.put("none", this); return map; } } diff --git a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestUtils.java b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestUtils.java index 950a9d184d..7a97591f2d 100644 --- a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestUtils.java +++ b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/TestUtils.java @@ -32,8 +32,7 @@ /** * Auxiliary test utilities */ -public class TestUtils -{ +public class TestUtils { /** * Creates a temporary directory with the given name * @@ -41,9 +40,8 @@ public class TestUtils * @return {@linkplain Path} object pointing to the directory * @throws IOException should the I/O operation fail */ - public static Path createTempDir( String name ) throws IOException - { - return Files.createTempDirectory( toCamelCase( name, false ) ); + public static Path createTempDir(String name) throws IOException { + return Files.createTempDirectory(toCamelCase(name, false)); } /** @@ -52,26 +50,21 @@ public static Path createTempDir( String name ) throws IOException * @param dir directory to delete * @throws IOException should an I/O operation fail */ - public static void tearDownTempDir( Path dir ) throws IOException - { - if ( dir != null && Files.exists( dir ) ) - { - Files.walkFileTree( dir, new SimpleFileVisitor() - { + public static void tearDownTempDir(Path dir) throws IOException { + if (dir != null && Files.exists(dir)) { + Files.walkFileTree(dir, new SimpleFileVisitor() { @Override - public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException - { - Files.delete( file ); + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); return CONTINUE; } @Override - public FileVisitResult postVisitDirectory( Path dir, IOException exc ) throws IOException - { - Files.delete( dir ); + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); return CONTINUE; } - } ); + }); } } @@ -83,25 +76,19 @@ public FileVisitResult postVisitDirectory( Path dir, IOException exc ) throws IO * @param dst destination directory path * @throws IOException should an I/O error occur */ - public static void copyDir( Path src, Path dst ) throws IOException - { - Files.walkFileTree( src, new SimpleFileVisitor() - { + public static void copyDir(Path src, Path dst) throws IOException { + Files.walkFileTree(src, new SimpleFileVisitor() { @Override - public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) - throws IOException - { - Files.createDirectories( dst.resolve( src.relativize( dir ) ) ); + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Files.createDirectories(dst.resolve(src.relativize(dir))); return CONTINUE; } @Override - public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) - throws IOException - { - Files.copy( file, dst.resolve( src.relativize( file ) ), REPLACE_EXISTING ); + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.copy(file, dst.resolve(src.relativize(file)), REPLACE_EXISTING); return CONTINUE; } - } ); + }); } } diff --git a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/VersionStub.java b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/VersionStub.java index 807e21574f..925d38fe01 100644 --- a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/VersionStub.java +++ b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/VersionStub.java @@ -24,53 +24,43 @@ /** * Stubs the {@link Version} */ -public class VersionStub implements Version -{ +public class VersionStub implements Version { private final String version; /** * Creates a new instance with the given version string * @param version version to be set */ - public VersionStub( String version ) - { + public VersionStub(String version) { assert version != null; this.version = version; } @Override - public String toString() - { + public String toString() { return version; } @Override - public int compareTo( Version o ) - { - return o != null - ? version.compareTo( o.toString() ) - : 1; + public int compareTo(Version o) { + return o != null ? version.compareTo(o.toString()) : 1; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof Version ) ) - { + if (!(o instanceof Version)) { return false; } - return version.equals( o.toString() ); + return version.equals(o.toString()); } @Override - public int hashCode() - { + public int hashCode() { return version.hashCode(); } }