From de19cfcd2bc8e774818d87472e8e64dc37c0b93d Mon Sep 17 00:00:00 2001 From: Guillaume Nodet Date: Tue, 22 Nov 2022 11:21:12 +0100 Subject: [PATCH] [MNG-7601] Reformat sources --- apache-maven/pom.xml | 52 +- .../maven/settings/GlobalSettingsTest.java | 27 +- api/maven-api-core/pom.xml | 2 +- .../java/org/apache/maven/api/Artifact.java | 23 +- .../apache/maven/api/ArtifactCoordinate.java | 14 +- .../java/org/apache/maven/api/Dependency.java | 9 +- .../maven/api/DependencyCoordinate.java | 16 +- .../main/java/org/apache/maven/api/Event.java | 12 +- .../java/org/apache/maven/api/EventType.java | 6 +- .../java/org/apache/maven/api/Exclusion.java | 7 +- .../org/apache/maven/api/JavaToolchain.java | 9 +- .../java/org/apache/maven/api/Listener.java | 13 +- .../org/apache/maven/api/LocalRepository.java | 8 +- .../org/apache/maven/api/MetadataStorage.java | 6 +- .../org/apache/maven/api/MojoExecution.java | 10 +- .../main/java/org/apache/maven/api/Node.java | 25 +- .../org/apache/maven/api/NodeVisitor.java | 17 +- .../java/org/apache/maven/api/Project.java | 21 +- .../apache/maven/api/RemoteRepository.java | 7 +- .../java/org/apache/maven/api/Repository.java | 9 +- .../org/apache/maven/api/ResolutionScope.java | 42 +- .../main/java/org/apache/maven/api/Scope.java | 30 +- .../java/org/apache/maven/api/Service.java | 11 +- .../java/org/apache/maven/api/Session.java | 79 +- .../org/apache/maven/api/SessionData.java | 35 +- .../java/org/apache/maven/api/Toolchain.java | 15 +- .../main/java/org/apache/maven/api/Type.java | 9 +- .../java/org/apache/maven/api/Version.java | 10 +- .../org/apache/maven/api/VersionRange.java | 10 +- .../java/org/apache/maven/api/plugin/Log.java | 49 +- .../org/apache/maven/api/plugin/Mojo.java | 12 +- .../maven/api/plugin/MojoException.java | 36 +- .../api/plugin/annotations/Component.java | 11 +- .../maven/api/plugin/annotations/Execute.java | 11 +- .../annotations/InstantiationStrategy.java | 20 +- .../plugin/annotations/LifecyclePhase.java | 76 +- .../maven/api/plugin/annotations/Mojo.java | 14 +- .../api/plugin/annotations/Parameter.java | 15 +- .../services/ArtifactCoordinateFactory.java | 45 +- .../ArtifactCoordinateFactoryRequest.java | 146 +- .../maven/api/services/ArtifactDeployer.java | 24 +- .../services/ArtifactDeployerException.java | 17 +- .../api/services/ArtifactDeployerRequest.java | 91 +- .../maven/api/services/ArtifactFactory.java | 31 +- .../api/services/ArtifactFactoryRequest.java | 131 +- .../maven/api/services/ArtifactInstaller.java | 24 +- .../services/ArtifactInstallerException.java | 17 +- .../services/ArtifactInstallerRequest.java | 66 +- .../maven/api/services/ArtifactManager.java | 19 +- .../maven/api/services/ArtifactResolver.java | 18 +- .../services/ArtifactResolverException.java | 15 +- .../api/services/ArtifactResolverRequest.java | 59 +- .../api/services/ArtifactResolverResult.java | 12 +- .../maven/api/services/BaseRequest.java | 36 +- .../maven/api/services/BuilderProblem.java | 11 +- .../api/services/DependencyCollector.java | 38 +- .../DependencyCollectorException.java | 14 +- .../services/DependencyCollectorRequest.java | 143 +- .../services/DependencyCollectorResult.java | 34 +- .../services/DependencyCoordinateFactory.java | 54 +- .../DependencyCoordinateFactoryRequest.java | 196 +- .../api/services/LocalRepositoryManager.java | 14 +- .../org/apache/maven/api/services/Lookup.java | 16 +- .../maven/api/services/LookupException.java | 20 +- .../maven/api/services/MavenException.java | 30 +- .../maven/api/services/MessageBuilder.java | 43 +- .../api/services/MessageBuilderFactory.java | 15 +- .../maven/api/services/ProjectBuilder.java | 41 +- .../api/services/ProjectBuilderException.java | 15 +- .../api/services/ProjectBuilderRequest.java | 155 +- .../api/services/ProjectBuilderResult.java | 13 +- .../maven/api/services/ProjectManager.java | 59 +- .../apache/maven/api/services/Prompter.java | 34 +- .../maven/api/services/PrompterException.java | 15 +- .../maven/api/services/RepositoryFactory.java | 16 +- .../maven/api/services/SettingsBuilder.java | 27 +- .../services/SettingsBuilderException.java | 14 +- .../api/services/SettingsBuilderRequest.java | 106 +- .../api/services/SettingsBuilderResult.java | 10 +- .../org/apache/maven/api/services/Source.java | 7 +- .../maven/api/services/ToolchainFactory.java | 8 +- .../maven/api/services/ToolchainManager.java | 19 +- .../services/ToolchainManagerException.java | 15 +- .../maven/api/services/ToolchainsBuilder.java | 12 +- .../services/ToolchainsBuilderException.java | 14 +- .../services/ToolchainsBuilderRequest.java | 106 +- .../api/services/ToolchainsBuilderResult.java | 10 +- .../maven/api/services/TypeRegistry.java | 11 +- .../maven/api/services/VersionParser.java | 19 +- .../api/services/VersionParserException.java | 15 +- .../api/services/xml/ModelXmlFactory.java | 10 +- .../api/services/xml/SettingsXmlFactory.java | 10 +- .../services/xml/ToolchainsXmlFactory.java | 10 +- .../maven/api/services/xml/XmlFactory.java | 84 +- .../api/services/xml/XmlReaderException.java | 15 +- .../api/services/xml/XmlReaderRequest.java | 102 +- .../api/services/xml/XmlWriterException.java | 15 +- .../api/services/xml/XmlWriterRequest.java | 50 +- api/maven-api-meta/pom.xml | 2 +- .../maven/api/annotations/Consumer.java | 13 +- .../maven/api/annotations/Experimental.java | 11 +- .../maven/api/annotations/Generated.java | 13 +- .../maven/api/annotations/Immutable.java | 13 +- .../apache/maven/api/annotations/Nonnull.java | 13 +- .../maven/api/annotations/NotThreadSafe.java | 13 +- .../maven/api/annotations/Nullable.java | 11 +- .../maven/api/annotations/Provider.java | 13 +- .../maven/api/annotations/ThreadSafe.java | 13 +- .../maven/api/annotations/package-info.java | 20 - api/maven-api-model/pom.xml | 2 - .../maven/api/model/ImmutableCollections.java | 488 ++-- .../apache/maven/api/model/InputLocation.java | 134 +- .../maven/api/model/InputLocationTracker.java | 9 +- .../apache/maven/api/model/InputSource.java | 19 +- .../apache/maven/api/model/package-info.java | 19 - api/maven-api-settings/pom.xml | 2 - .../api/settings/ImmutableCollections.java | 488 ++-- api/maven-api-toolchain/pom.xml | 156 +- .../api/toolchain/ImmutableCollections.java | 488 ++-- api/maven-api-xml/pom.xml | 2 +- .../java/org/apache/maven/api/xml/Dom.java | 38 +- api/modello-plugin-velocity/pom.xml | 6 +- .../modello/plugin/velocity/Helper.java | 113 +- .../plugin/velocity/ModelloVelocityMojo.java | 43 +- .../plugin/velocity/VelocityGenerator.java | 127 +- api/pom.xml | 4 +- maven-artifact/pom.xml | 2 - .../org/apache/maven/artifact/Artifact.java | 61 +- .../apache/maven/artifact/ArtifactUtils.java | 178 +- .../maven/artifact/DefaultArtifact.java | 445 ++-- .../artifact/InvalidArtifactRTException.java | 49 +- .../artifact/handler/ArtifactHandler.java | 8 +- .../artifact/metadata/ArtifactMetadata.java | 11 +- .../repository/ArtifactRepository.java | 40 +- .../repository/ArtifactRepositoryPolicy.java | 161 +- .../artifact/repository/Authentication.java | 34 +- .../layout/ArtifactRepositoryLayout.java | 14 +- .../layout/ArtifactRepositoryLayout2.java | 13 +- .../RepositoryMetadataStoreException.java | 20 +- .../AbstractArtifactResolutionException.java | 374 ++- .../resolver/ArtifactNotFoundException.java | 116 +- .../resolver/ArtifactResolutionException.java | 64 +- .../resolver/CyclicDependencyException.java | 18 +- .../MultipleArtifactsNotFoundException.java | 83 +- .../resolver/filter/ArtifactFilter.java | 10 +- .../artifact/versioning/ArtifactVersion.java | 11 +- .../versioning/ComparableVersion.java | 524 ++-- .../versioning/DefaultArtifactVersion.java | 176 +- .../InvalidVersionSpecificationException.java | 14 +- .../OverConstrainedVersionException.java | 24 +- .../artifact/versioning/Restriction.java | 121 +- .../artifact/versioning/VersionRange.java | 446 ++-- .../org/apache/maven/repository/Proxy.java | 54 +- .../legacy/metadata/ArtifactMetadata.java | 17 +- .../maven/artifact/ArtifactUtilsTest.java | 73 +- .../maven/artifact/DefaultArtifactTest.java | 137 +- .../artifact/handler/ArtifactHandlerMock.java | 53 +- .../versioning/ComparableVersionIT.java | 65 +- .../versioning/ComparableVersionTest.java | 340 ++- .../DefaultArtifactVersionTest.java | 272 +- .../artifact/versioning/VersionRangeTest.java | 1133 ++++----- maven-builder-support/pom.xml | 2 - .../apache/maven/building/DefaultProblem.java | 97 +- .../building/DefaultProblemCollector.java | 26 +- .../org/apache/maven/building/FileSource.java | 46 +- .../org/apache/maven/building/Problem.java | 12 +- .../maven/building/ProblemCollector.java | 11 +- .../building/ProblemCollectorFactory.java | 12 +- .../org/apache/maven/building/Source.java | 10 +- .../apache/maven/building/StringSource.java | 51 +- .../org/apache/maven/building/UrlSource.java | 44 +- .../building/DefaultProblemCollectorTest.java | 68 +- .../maven/building/DefaultProblemTest.java | 133 +- .../apache/maven/building/FileSourceTest.java | 60 +- .../building/ProblemCollectorFactoryTest.java | 29 +- .../maven/building/StringSourceTest.java | 53 +- .../apache/maven/building/UrlSourceTest.java | 48 +- maven-compat/pom.xml | 2 - .../maven/artifact/ArtifactScopeEnum.java | 82 +- .../apache/maven/artifact/ArtifactStatus.java | 56 +- .../UnknownRepositoryLayoutException.java | 23 +- .../artifact/deployer/ArtifactDeployer.java | 25 +- .../deployer/ArtifactDeploymentException.java | 25 +- .../deployer/DefaultArtifactDeployer.java | 118 +- .../ArtifactInstallationException.java | 25 +- .../artifact/installer/ArtifactInstaller.java | 17 +- .../installer/DefaultArtifactInstaller.java | 89 +- .../artifact/manager/DefaultWagonManager.java | 112 +- .../manager/WagonConfigurationException.java | 17 +- .../maven/artifact/manager/WagonManager.java | 25 +- .../repository/ArtifactRepositoryFactory.java | 43 +- .../repository/DefaultArtifactRepository.java | 172 +- .../DefaultArtifactRepositoryFactory.java | 98 +- .../layout/FlatRepositoryLayout.java | 53 +- .../DefaultRepositoryMetadataManager.java | 546 ++-- .../metadata/GroupRepositoryMetadata.java | 73 +- .../repository/metadata/MetadataBridge.java | 104 +- .../repository/metadata/MetadataUtils.java | 13 +- .../RepositoryMetadataReadException.java | 20 +- .../SnapshotArtifactRepositoryMetadata.java | 52 +- .../artifact/resolver/ArtifactCollector.java | 25 +- .../artifact/resolver/ArtifactResolver.java | 107 +- .../resolver/DebugResolutionListener.java | 116 +- .../resolver/DefaultArtifactCollector.java | 14 +- .../resolver/DefaultArtifactResolver.java | 650 +++-- .../ResolutionListenerForDepMgmt.java | 17 +- .../resolver/UnresolvedArtifacts.java | 24 +- .../resolver/WarningResolutionListener.java | 62 +- .../filter/InversionArtifactFilter.java | 32 +- .../resolver/filter/OrArtifactFilter.java | 45 +- .../resolver/filter/TypeArtifactFilter.java | 32 +- .../versioning/ManagedVersionMap.java | 33 +- .../execution/DefaultRuntimeInformation.java | 26 +- .../maven/execution/RuntimeInformation.java | 8 +- .../profiles/DefaultMavenProfilesBuilder.java | 64 +- .../maven/profiles/DefaultProfileManager.java | 179 +- .../maven/profiles/MavenProfilesBuilder.java | 14 +- .../apache/maven/profiles/ProfileManager.java | 29 +- .../profiles/ProfilesConversionUtils.java | 112 +- .../activation/DetectedProfileActivator.java | 17 +- .../activation/FileProfileActivator.java | 69 +- .../activation/JdkPrefixProfileActivator.java | 68 +- .../OperatingSystemProfileActivator.java | 109 +- .../ProfileActivationException.java | 20 +- .../profiles/activation/ProfileActivator.java | 14 +- .../SystemPropertyProfileActivator.java | 70 +- .../project/DefaultMavenProjectBuilder.java | 287 +-- .../DefaultProjectBuilderConfiguration.java | 48 +- .../project/InvalidProjectModelException.java | 38 +- .../maven/project/MavenProjectBuilder.java | 63 +- .../MissingRepositoryElementException.java | 21 +- .../org/apache/maven/project/ModelUtils.java | 27 +- .../project/ProjectBuilderConfiguration.java | 20 +- .../apache/maven/project/ProjectUtils.java | 79 +- .../DefaultModelInheritanceAssembler.java | 25 +- .../ModelInheritanceAssembler.java | 16 +- .../AbstractStringBasedModelInterpolator.java | 346 +-- .../BuildTimestampValueSource.java | 27 +- .../ModelInterpolationException.java | 38 +- .../interpolation/ModelInterpolator.java | 35 +- .../PathTranslatingPostProcessor.java | 36 +- .../RegexBasedModelInterpolator.java | 31 +- .../StringSearchModelInterpolator.java | 396 ++- .../project/path/DefaultPathTranslator.java | 185 +- .../validation/DefaultModelValidator.java | 35 +- .../validation/ModelValidationResult.java | 70 +- .../project/validation/ModelValidator.java | 11 +- .../maven/reporting/MavenReportException.java | 18 +- .../repository/DefaultMirrorSelector.java | 139 +- .../repository/MavenArtifactMetadata.java | 56 +- .../maven/repository/MetadataGraph.java | 38 +- .../maven/repository/MetadataGraphNode.java | 52 +- .../repository/MetadataResolutionRequest.java | 106 +- .../repository/MetadataResolutionResult.java | 209 +- .../maven/repository/MirrorSelector.java | 10 +- .../UserLocalArtifactRepository.java | 36 +- .../repository/VersionNotFoundException.java | 38 +- .../legacy/ChecksumFailedException.java | 20 +- .../legacy/DefaultUpdateCheckManager.java | 362 ++- .../legacy/DefaultWagonManager.java | 816 +++--- .../legacy/LegacyRepositorySystem.java | 811 +++--- .../repository/legacy/MavenArtifact.java | 49 +- .../legacy/TransferListenerAdapter.java | 149 +- .../repository/legacy/UpdateCheckManager.java | 20 +- .../legacy/WagonConfigurationException.java | 29 +- .../maven/repository/legacy/WagonManager.java | 65 +- .../repository/ArtifactRepositoryFactory.java | 41 +- .../DefaultArtifactRepositoryFactory.java | 121 +- .../DefaultLegacyArtifactCollector.java | 769 +++--- .../resolver/LegacyArtifactCollector.java | 55 +- .../resolver/conflict/ConflictResolver.java | 10 +- .../conflict/ConflictResolverFactory.java | 11 +- .../ConflictResolverNotFoundException.java | 14 +- .../conflict/DefaultConflictResolver.java | 12 +- .../DefaultConflictResolverFactory.java | 36 +- .../conflict/FarthestConflictResolver.java | 20 +- .../conflict/NearestConflictResolver.java | 20 +- .../conflict/NewestConflictResolver.java | 29 +- .../conflict/OldestConflictResolver.java | 29 +- .../AbstractVersionTransformation.java | 88 +- .../transform/ArtifactTransformation.java | 33 +- .../ArtifactTransformationManager.java | 29 +- .../DefaultArtifactTransformationManager.java | 63 +- .../LatestArtifactTransformation.java | 50 +- .../ReleaseArtifactTransformation.java | 70 +- .../transform/SnapshotTransformation.java | 133 +- .../repository/metadata/ArtifactMetadata.java | 261 +- .../metadata/ClasspathContainer.java | 89 +- .../metadata/ClasspathTransformation.java | 12 +- .../DefaultClasspathTransformation.java | 154 +- .../DefaultGraphConflictResolutionPolicy.java | 36 +- .../DefaultGraphConflictResolver.java | 195 +- .../GraphConflictResolutionException.java | 31 +- .../GraphConflictResolutionPolicy.java | 11 +- .../metadata/GraphConflictResolver.java | 12 +- .../repository/metadata/MetadataGraph.java | 426 ++-- .../metadata/MetadataGraphEdge.java | 128 +- .../MetadataGraphTransformationException.java | 31 +- .../metadata/MetadataGraphVertex.java | 148 +- .../metadata/MetadataResolution.java | 41 +- .../metadata/MetadataResolutionException.java | 28 +- .../metadata/MetadataResolutionRequest.java | 46 +- .../MetadataResolutionRequestTypeEnum.java | 29 +- .../metadata/MetadataResolutionResult.java | 141 +- .../metadata/MetadataRetrievalException.java | 34 +- .../repository/metadata/MetadataSource.java | 17 +- .../repository/metadata/MetadataTreeNode.java | 95 +- .../ExpressionDocumentationException.java | 20 +- .../plugin/ExpressionDocumenter.java | 104 +- .../AbstractArtifactComponentTestCase.java | 271 +- .../deployer/ArtifactDeployerTest.java | 55 +- .../SimpleArtifactMetadataSource.java | 45 +- .../factory/DefaultArtifactFactoryTest.java | 62 +- .../installer/ArtifactInstallerTest.java | 45 +- .../artifact/metadata/TestMetadataSource.java | 89 +- .../MavenArtifactRepositoryTest.java | 41 +- .../ArtifactResolutionExceptionTest.java | 29 +- .../resolver/ArtifactResolverTest.java | 232 +- .../resolver/DefaultArtifactResolverTest.java | 65 +- .../artifact/resolver/TestFileWagon.java | 64 +- .../resolver/TestTransferListener.java | 19 +- .../filter/AndArtifactFilterTest.java | 32 +- .../resolver/filter/FilterHashEqualsTest.java | 32 +- .../resolver/filter/OrArtifactFilterTest.java | 32 +- .../filter/ScopeArtifactFilterTest.java | 93 +- .../artifact/testutils/TestFileManager.java | 189 +- .../transform/TransformationManagerTest.java | 62 +- .../manager/DefaultProfileManagerTest.java | 148 +- .../project/AbstractMavenProjectTestCase.java | 141 +- .../project/ClasspathArtifactResolver.java | 66 +- .../maven/project/EmptyLifecycleExecutor.java | 68 +- .../project/EmptyLifecyclePluginAnalyzer.java | 47 +- .../project/LegacyLocalRepositoryManager.java | 138 +- .../maven/project/ProjectClasspathTest.java | 151 +- .../maven/project/TestArtifactResolver.java | 40 +- .../project/TestMavenRepositorySystem.java | 38 +- .../maven/project/TestProjectBuilder.java | 77 +- .../AbstractProjectInheritanceTestCase.java | 36 +- .../t00/ProjectInheritanceTest.java | 33 +- .../t01/ProjectInheritanceTest.java | 37 +- .../t02/ProjectInheritanceTest.java | 88 +- .../t03/ProjectInheritanceTest.java | 28 +- .../t04/ProjectInheritanceTest.java | 61 +- .../t05/ProjectInheritanceTest.java | 55 +- .../t06/ProjectInheritanceTest.java | 58 +- .../t07/ProjectInheritanceTest.java | 58 +- .../t08/ProjectInheritanceTest.java | 59 +- .../t09/ProjectInheritanceTest.java | 77 +- .../t10/ProjectInheritanceTest.java | 57 +- .../t11/ProjectInheritanceTest.java | 39 +- .../t12/ProjectInheritanceTest.java | 47 +- .../t12scm/ProjectInheritanceTest.java | 128 +- .../path/DefaultPathTranslatorTest.java | 46 +- .../repository/DefaultMirrorSelectorTest.java | 19 +- .../LegacyRepositorySystemTest.java | 195 +- .../maven/repository/MirrorProcessorTest.java | 265 +- .../legacy/DefaultUpdateCheckManagerTest.java | 200 +- .../legacy/DefaultWagonManagerTest.java | 329 ++- .../legacy/LegacyRepositorySystemTest.java | 74 +- .../repository/legacy/PerLookupWagon.java | 17 +- .../maven/repository/legacy/StringWagon.java | 68 +- .../maven/repository/legacy/WagonA.java | 16 +- .../maven/repository/legacy/WagonB.java | 16 +- .../maven/repository/legacy/WagonC.java | 16 +- .../maven/repository/legacy/WagonMock.java | 16 +- .../DefaultArtifactCollectorTest.java | 1099 ++++---- .../AbstractConflictResolverTest.java | 84 +- .../FarthestConflictResolverTest.java | 53 +- .../conflict/NearestConflictResolverTest.java | 53 +- .../conflict/NewestConflictResolverTest.java | 53 +- .../conflict/OldestConflictResolverTest.java | 54 +- .../DefaultClasspathTransformationTest.java | 128 +- ...aultGraphConflictResolutionPolicyTest.java | 76 +- .../DefaultGraphConflictResolverTest.java | 221 +- .../metadata/TestMetadataSource.java | 79 +- maven-core/pom.xml | 8 +- .../AbstractMavenLifecycleParticipant.java | 20 +- .../apache/maven/ArtifactFilterManager.java | 12 +- .../maven/ArtifactFilterManagerDelegate.java | 13 +- .../java/org/apache/maven/BuildAbort.java | 18 +- .../apache/maven/BuildFailureException.java | 19 +- .../maven/DefaultArtifactFilterManager.java | 58 +- .../java/org/apache/maven/DefaultMaven.java | 642 ++--- .../DefaultProjectDependenciesResolver.java | 172 +- .../maven/DuplicateProjectException.java | 18 +- .../apache/maven/InternalErrorException.java | 13 +- .../src/main/java/org/apache/maven/Maven.java | 14 +- .../apache/maven/MavenExecutionException.java | 28 +- .../apache/maven/MissingModuleException.java | 21 +- .../maven/MissingProfilesException.java | 14 +- .../maven/ProjectBuildFailureException.java | 20 +- .../apache/maven/ProjectCycleException.java | 19 +- .../maven/ProjectDependenciesResolver.java | 36 +- .../java/org/apache/maven/ReactorReader.java | 281 +- .../org/apache/maven/RepositoryUtils.java | 376 ++- .../java/org/apache/maven/SessionScoped.java | 14 +- ...DependencyResolutionRequiredException.java | 14 +- .../artifact/InvalidRepositoryException.java | 33 +- .../artifact/factory/ArtifactFactory.java | 63 +- .../factory/DefaultArtifactFactory.java | 179 +- .../handler/DefaultArtifactHandler.java | 105 +- .../manager/ArtifactHandlerManager.java | 13 +- .../DefaultArtifactHandlerManager.java | 44 +- .../providers/EarArtifactHandlerProvider.java | 29 +- .../providers/EjbArtifactHandlerProvider.java | 29 +- .../EjbClientArtifactHandlerProvider.java | 30 +- .../providers/JarArtifactHandlerProvider.java | 29 +- .../JavaSourceArtifactHandlerProvider.java | 30 +- .../JavadocArtifactHandlerProvider.java | 29 +- .../MavenPluginArtifactHandlerProvider.java | 29 +- .../providers/PomArtifactHandlerProvider.java | 29 +- .../providers/RarArtifactHandlerProvider.java | 29 +- .../TestJarArtifactHandlerProvider.java | 29 +- .../providers/WarArtifactHandlerProvider.java | 29 +- .../metadata/AbstractArtifactMetadata.java | 15 +- .../ArtifactMetadataRetrievalException.java | 29 +- .../metadata/ArtifactMetadataSource.java | 38 +- .../artifact/metadata/ResolutionGroup.java | 29 +- .../repository/DefaultRepositoryRequest.java | 64 +- .../LegacyLocalRepositoryManager.java | 302 +-- .../repository/MavenArtifactRepository.java | 281 +- .../artifact/repository/RepositoryCache.java | 11 +- .../repository/RepositoryRequest.java | 15 +- .../layout/DefaultRepositoryLayout.java | 78 +- .../metadata/AbstractRepositoryMetadata.java | 174 +- .../metadata/ArtifactRepositoryMetadata.java | 68 +- .../metadata/RepositoryMetadata.java | 16 +- ...RepositoryMetadataDeploymentException.java | 20 +- ...positoryMetadataInstallationException.java | 20 +- .../metadata/RepositoryMetadataManager.java | 36 +- ...RepositoryMetadataResolutionException.java | 20 +- .../metadata/io/DefaultMetadataReader.java | 59 +- .../metadata/io/MetadataParseException.java | 26 +- .../metadata/io/MetadataReader.java | 17 +- .../resolver/ArtifactResolutionRequest.java | 151 +- .../resolver/ArtifactResolutionResult.java | 215 +- .../DefaultResolutionErrorHandler.java | 59 +- .../resolver/ResolutionErrorHandler.java | 11 +- .../artifact/resolver/ResolutionListener.java | 40 +- .../artifact/resolver/ResolutionNode.java | 152 +- .../filter/AbstractScopeArtifactFilter.java | 58 +- .../resolver/filter/AndArtifactFilter.java | 51 +- .../filter/CumulativeScopeArtifactFilter.java | 61 +- .../filter/ExcludesArtifactFilter.java | 20 +- .../filter/ExclusionArtifactFilter.java | 42 +- .../resolver/filter/ExclusionSetFilter.java | 41 +- .../filter/IncludesArtifactFilter.java | 43 +- .../resolver/filter/ScopeArtifactFilter.java | 34 +- .../maven/bridge/MavenRepositorySystem.java | 789 +++--- .../ArtifactClassRealmConstituent.java | 33 +- .../classrealm/ClassRealmConstituent.java | 7 +- .../maven/classrealm/ClassRealmManager.java | 20 +- .../classrealm/ClassRealmManagerDelegate.java | 10 +- .../maven/classrealm/ClassRealmRequest.java | 10 +- .../classrealm/DefaultClassRealmManager.java | 321 +-- .../classrealm/DefaultClassRealmRequest.java | 35 +- ...asedirBeanConfigurationPathTranslator.java | 30 +- .../BeanConfigurationException.java | 18 +- .../BeanConfigurationPathTranslator.java | 9 +- .../BeanConfigurationRequest.java | 19 +- .../BeanConfigurationValuePreprocessor.java | 10 +- .../maven/configuration/BeanConfigurator.java | 10 +- .../DefaultBeanConfigurationRequest.java | 101 +- .../internal/DefaultBeanConfigurator.java | 137 +- .../EnhancedComponentConfigurator.java | 45 +- .../EnhancedConfigurationConverter.java | 114 +- .../internal/EnhancedConverterLookup.java | 26 +- .../maven/eventspy/AbstractEventSpy.java | 23 +- .../org/apache/maven/eventspy/EventSpy.java | 20 +- .../eventspy/internal/EventSpyDispatcher.java | 104 +- .../internal/EventSpyExecutionListener.java | 130 +- .../internal/EventSpyRepositoryListener.java | 144 +- .../exception/DefaultExceptionHandler.java | 223 +- .../maven/exception/ExceptionHandler.java | 10 +- .../maven/exception/ExceptionSummary.java | 38 +- .../execution/AbstractExecutionListener.java | 59 +- .../maven/execution/ActivationSettings.java | 29 +- .../apache/maven/execution/BuildFailure.java | 16 +- .../execution/BuildResumptionAnalyzer.java | 8 +- .../maven/execution/BuildResumptionData.java | 13 +- .../BuildResumptionDataRepository.java | 13 +- .../BuildResumptionPersistenceException.java | 11 +- .../apache/maven/execution/BuildSuccess.java | 13 +- .../apache/maven/execution/BuildSummary.java | 19 +- .../DefaultBuildResumptionAnalyzer.java | 48 +- .../DefaultBuildResumptionDataRepository.java | 115 +- .../DefaultMavenExecutionRequest.java | 713 ++---- ...DefaultMavenExecutionRequestPopulator.java | 221 +- .../DefaultMavenExecutionResult.java | 63 +- .../maven/execution/ExecutionEvent.java | 10 +- .../maven/execution/ExecutionListener.java | 41 +- .../execution/MavenExecutionRequest.java | 135 +- ...enExecutionRequestPopulationException.java | 25 +- .../MavenExecutionRequestPopulator.java | 20 +- .../maven/execution/MavenExecutionResult.java | 25 +- .../apache/maven/execution/MavenSession.java | 316 ++- .../maven/execution/MojoExecutionEvent.java | 31 +- .../execution/MojoExecutionListener.java | 14 +- .../maven/execution/ProfileActivation.java | 92 +- .../maven/execution/ProjectActivation.java | 109 +- .../execution/ProjectDependencyGraph.java | 12 +- .../execution/ProjectExecutionEvent.java | 40 +- .../execution/ProjectExecutionListener.java | 17 +- .../maven/execution/ReactorManager.java | 134 +- .../execution/scope/MojoExecutionScoped.java | 14 +- .../scope/WeakMojoExecutionListener.java | 14 +- .../scope/internal/MojoExecutionScope.java | 141 +- .../MojoExecutionScopeCoreModule.java | 21 +- .../internal/MojoExecutionScopeModule.java | 45 +- .../maven/extension/internal/CoreExports.java | 35 +- .../internal/CoreExportsProvider.java | 21 +- .../internal/CoreExtensionEntry.java | 80 +- .../maven/graph/DefaultGraphBuilder.java | 342 ++- .../graph/DefaultProjectDependencyGraph.java | 97 +- .../graph/FilteredProjectDependencyGraph.java | 60 +- .../org/apache/maven/graph/GraphBuilder.java | 10 +- .../apache/maven/graph/ProjectSelector.java | 122 +- .../internal/MultilineMessageHelper.java | 73 +- .../ConsumerModelSourceTransformer.java | 24 +- ...DefaultRepositorySystemSessionFactory.java | 288 +-- .../aether/LoggingRepositoryListener.java | 119 +- .../aether/MavenChainedWorkspaceReader.java | 53 +- .../maven/internal/impl/AbstractNode.java | 46 +- .../maven/internal/impl/AbstractSession.java | 387 ++- .../maven/internal/impl/DefaultArtifact.java | 76 +- .../impl/DefaultArtifactCoordinate.java | 67 +- .../DefaultArtifactCoordinateFactory.java | 51 +- .../impl/DefaultArtifactDeployer.java | 57 +- .../internal/impl/DefaultArtifactFactory.java | 52 +- .../impl/DefaultArtifactInstaller.java | 44 +- .../internal/impl/DefaultArtifactManager.java | 86 +- .../impl/DefaultArtifactResolver.java | 71 +- .../internal/impl/DefaultDependency.java | 96 +- .../impl/DefaultDependencyCollector.java | 82 +- .../impl/DefaultDependencyCoordinate.java | 77 +- .../DefaultDependencyCoordinateFactory.java | 44 +- .../maven/internal/impl/DefaultEvent.java | 33 +- .../internal/impl/DefaultLocalRepository.java | 38 +- .../impl/DefaultLocalRepositoryManager.java | 45 +- .../maven/internal/impl/DefaultLog.java | 162 +- .../maven/internal/impl/DefaultLookup.java | 75 +- .../internal/impl/DefaultMessageBuilder.java | 77 +- .../impl/DefaultMessageBuilderFactory.java | 31 +- .../internal/impl/DefaultModelXmlFactory.java | 114 +- .../internal/impl/DefaultMojoExecution.java | 33 +- .../maven/internal/impl/DefaultNode.java | 132 +- .../maven/internal/impl/DefaultProject.java | 147 +- .../internal/impl/DefaultProjectBuilder.java | 213 +- .../internal/impl/DefaultProjectManager.java | 132 +- .../maven/internal/impl/DefaultPrompter.java | 79 +- .../impl/DefaultRemoteRepository.java | 29 +- .../impl/DefaultRepositoryFactory.java | 58 +- .../maven/internal/impl/DefaultSession.java | 251 +- .../internal/impl/DefaultSessionFactory.java | 32 +- .../internal/impl/DefaultSettingsBuilder.java | 120 +- .../impl/DefaultSettingsXmlFactory.java | 86 +- .../impl/DefaultToolchainManager.java | 94 +- .../impl/DefaultToolchainsBuilder.java | 127 +- .../impl/DefaultToolchainsXmlFactory.java | 87 +- .../internal/impl/DefaultTypeRegistry.java | 42 +- .../internal/impl/DefaultVersionParser.java | 117 +- .../maven/internal/impl/EventSpyImpl.java | 42 +- .../maven/internal/impl/MappedCollection.java | 28 +- .../maven/internal/impl/MappedList.java | 19 +- .../maven/internal/impl/PropertiesAsMap.java | 68 +- .../org/apache/maven/internal/impl/Utils.java | 33 +- .../maven/internal/impl/WrapperNode.java | 34 +- .../lifecycle/DefaultLifecycleExecutor.java | 83 +- .../maven/lifecycle/DefaultLifecycles.java | 104 +- .../lifecycle/LifeCyclePluginAnalyzer.java | 10 +- .../org/apache/maven/lifecycle/Lifecycle.java | 34 +- .../LifecycleExecutionException.java | 83 +- .../maven/lifecycle/LifecycleExecutor.java | 49 +- .../lifecycle/LifecycleMappingDelegate.java | 17 +- .../lifecycle/LifecycleNotFoundException.java | 18 +- .../LifecyclePhaseNotFoundException.java | 18 +- .../maven/lifecycle/MavenExecutionPlan.java | 124 +- .../lifecycle/MissingProjectException.java | 13 +- .../lifecycle/MojoExecutionConfigurator.java | 8 +- .../lifecycle/NoGoalSpecifiedException.java | 13 +- .../internal/BuildListCalculator.java | 47 +- .../internal/BuildThreadFactory.java | 12 +- .../CompoundProjectExecutionListener.java | 48 +- .../internal/DefaultExecutionEvent.java | 26 +- .../DefaultExecutionEventCatapult.java | 63 +- ...faultLifecycleExecutionPlanCalculator.java | 543 ++-- .../DefaultLifecycleMappingDelegate.java | 102 +- .../DefaultLifecyclePluginAnalyzer.java | 208 +- ...DefaultLifecycleTaskSegmentCalculator.java | 95 +- .../DefaultMojoExecutionConfigurator.java | 154 +- .../DefaultProjectArtifactFactory.java | 24 +- .../lifecycle/internal/DependencyContext.java | 57 +- .../internal/ExecutionEventCatapult.java | 11 +- .../lifecycle/internal/ExecutionPlanItem.java | 44 +- .../maven/lifecycle/internal/GoalTask.java | 14 +- .../internal/LifecycleDebugLogger.java | 125 +- .../internal/LifecycleDependencyResolver.java | 348 ++- .../LifecycleExecutionPlanCalculator.java | 53 +- .../internal/LifecycleModuleBuilder.java | 89 +- .../internal/LifecyclePluginResolver.java | 57 +- .../lifecycle/internal/LifecycleStarter.java | 99 +- .../lifecycle/internal/LifecycleTask.java | 17 +- .../LifecycleTaskSegmentCalculator.java | 30 +- .../internal/MojoDescriptorCreator.java | 192 +- .../lifecycle/internal/MojoExecutor.java | 452 ++-- .../lifecycle/internal/PhaseRecorder.java | 42 +- .../internal/ProjectArtifactFactory.java | 12 +- .../lifecycle/internal/ProjectBuildList.java | 91 +- .../lifecycle/internal/ProjectIndex.java | 37 +- .../lifecycle/internal/ProjectSegment.java | 36 +- .../internal/ReactorBuildStatus.java | 48 +- .../lifecycle/internal/ReactorContext.java | 29 +- .../maven/lifecycle/internal/TaskSegment.java | 25 +- .../lifecycle/internal/builder/Builder.java | 19 +- .../internal/builder/BuilderCommon.java | 175 +- .../builder/BuilderNotFoundException.java | 14 +- .../ConcurrencyDependencyGraph.java | 84 +- .../multithreaded/MultiThreadedBuilder.java | 194 +- .../multithreaded/ThreadOutputMuxer.java | 339 +-- .../singlethreaded/SingleThreadedBuilder.java | 45 +- .../mapping/DefaultLifecycleMapping.java | 88 +- .../maven/lifecycle/mapping/Lifecycle.java | 44 +- .../lifecycle/mapping/LifecycleMapping.java | 13 +- .../lifecycle/mapping/LifecycleMojo.java | 27 +- .../lifecycle/mapping/LifecyclePhase.java | 76 +- .../providers/AbstractLifecycleProvider.java | 39 +- .../providers/CleanLifecycleProvider.java | 22 +- .../providers/DefaultLifecycleProvider.java | 23 +- .../providers/SiteLifecycleProvider.java | 25 +- .../providers/WrapperLifecycleProvider.java | 25 +- .../AbstractLifecycleMappingProvider.java | 41 +- .../EarLifecycleMappingProvider.java | 33 +- .../EjbLifecycleMappingProvider.java | 41 +- .../JarLifecycleMappingProvider.java | 41 +- .../MavenPluginLifecycleMappingProvider.java | 47 +- .../PomLifecycleMappingProvider.java | 25 +- .../RarLifecycleMappingProvider.java | 41 +- .../WarLifecycleMappingProvider.java | 41 +- .../DefaultLifecycleBindingsInjector.java | 158 +- .../maven/monitor/event/EventDispatcher.java | 19 +- .../maven/monitor/event/EventMonitor.java | 17 +- .../maven/plugin/BuildPluginManager.java | 32 +- .../org/apache/maven/plugin/CacheUtils.java | 104 +- .../plugin/CompoundMojoExecutionListener.java | 40 +- .../CycleDetectedInPluginGraphException.java | 17 +- .../plugin/DebugConfigurationListener.java | 60 +- .../plugin/DefaultBuildPluginManager.java | 224 +- .../plugin/DefaultExtensionRealmCache.java | 108 +- .../plugin/DefaultMojosExecutionStrategy.java | 24 +- .../plugin/DefaultPluginArtifactsCache.java | 141 +- .../plugin/DefaultPluginDescriptorCache.java | 181 +- .../maven/plugin/DefaultPluginRealmCache.java | 184 +- .../maven/plugin/ExtensionRealmCache.java | 36 +- .../InvalidPluginDescriptorException.java | 25 +- .../maven/plugin/InvalidPluginException.java | 25 +- .../apache/maven/plugin/LegacySupport.java | 9 +- .../maven/plugin/MavenPluginManager.java | 46 +- .../MavenPluginPrerequisitesChecker.java | 13 +- .../apache/maven/plugin/MojoExecution.java | 121 +- .../maven/plugin/MojoExecutionRunner.java | 8 +- .../maven/plugin/MojosExecutionStrategy.java | 14 +- .../maven/plugin/PluginArtifactsCache.java | 41 +- .../plugin/PluginConfigurationException.java | 40 +- .../plugin/PluginContainerException.java | 45 +- .../maven/plugin/PluginDescriptorCache.java | 22 +- .../PluginDescriptorParsingException.java | 27 +- .../plugin/PluginExecutionException.java | 59 +- .../plugin/PluginIncompatibleException.java | 19 +- .../maven/plugin/PluginLoaderException.java | 78 +- .../apache/maven/plugin/PluginManager.java | 56 +- .../maven/plugin/PluginManagerException.java | 90 +- .../maven/plugin/PluginNotFoundException.java | 44 +- .../plugin/PluginParameterException.java | 200 +- .../PluginParameterExpressionEvaluator.java | 383 +-- .../PluginParameterExpressionEvaluatorV4.java | 398 ++- .../apache/maven/plugin/PluginRealmCache.java | 45 +- .../plugin/PluginResolutionException.java | 21 +- ...bstractMavenPluginParametersValidator.java | 104 +- .../plugin/internal/DefaultLegacySupport.java | 38 +- .../internal/DefaultMavenPluginManager.java | 903 +++---- .../internal/DefaultMavenPluginValidator.java | 33 +- .../DefaultPluginDependenciesResolver.java | 289 +-- .../plugin/internal/DefaultPluginManager.java | 201 +- .../internal/DeprecatedPluginValidator.java | 67 +- .../MavenPluginConfigurationValidator.java | 15 +- .../MavenPluginJavaPrerequisiteChecker.java | 27 +- .../MavenPluginMavenPrerequisiteChecker.java | 46 +- .../plugin/internal/MavenPluginValidator.java | 11 +- .../maven/plugin/internal/MojoLogWrapper.java | 100 +- .../internal/PluginDependenciesResolver.java | 22 +- .../ReadOnlyPluginParametersValidator.java | 44 +- .../ValidatingConfigurationListener.java | 55 +- .../prefix/DefaultPluginPrefixRequest.java | 77 +- .../NoPluginFoundForPrefixException.java | 54 +- .../plugin/prefix/PluginPrefixRequest.java | 18 +- .../plugin/prefix/PluginPrefixResolver.java | 10 +- .../plugin/prefix/PluginPrefixResult.java | 9 +- .../internal/DefaultPluginPrefixResolver.java | 233 +- .../internal/DefaultPluginPrefixResult.java | 35 +- .../version/DefaultPluginVersionRequest.java | 79 +- .../PluginVersionNotFoundException.java | 21 +- .../plugin/version/PluginVersionRequest.java | 18 +- .../PluginVersionResolutionException.java | 74 +- .../plugin/version/PluginVersionResolver.java | 10 +- .../plugin/version/PluginVersionResult.java | 7 +- .../DefaultPluginVersionResolver.java | 383 ++- .../internal/DefaultPluginVersionResult.java | 26 +- .../DefaultDependencyResolutionRequest.java | 36 +- .../DefaultDependencyResolutionResult.java | 63 +- .../project/DefaultMavenProjectHelper.java | 99 +- .../project/DefaultModelBuildingListener.java | 95 +- .../maven/project/DefaultProjectBuilder.java | 983 ++++--- .../project/DefaultProjectBuildingHelper.java | 184 +- .../DefaultProjectBuildingRequest.java | 215 +- .../project/DefaultProjectBuildingResult.java | 45 +- .../DefaultProjectDependenciesResolver.java | 295 +-- .../project/DefaultProjectRealmCache.java | 86 +- .../DependencyResolutionException.java | 16 +- .../project/DependencyResolutionRequest.java | 13 +- .../project/DependencyResolutionResult.java | 10 +- .../DuplicateArtifactAttachmentException.java | 23 +- .../project/DuplicateProjectException.java | 35 +- .../maven/project/ExtensionDescriptor.java | 46 +- .../project/ExtensionDescriptorBuilder.java | 94 +- .../InvalidProjectVersionException.java | 38 +- .../apache/maven/project/MavenProject.java | 1320 ++++------ .../maven/project/MavenProjectHelper.java | 20 +- .../apache/maven/project/ProjectBuilder.java | 29 +- .../project/ProjectBuildingException.java | 63 +- .../maven/project/ProjectBuildingHelper.java | 24 +- .../maven/project/ProjectBuildingRequest.java | 47 +- .../maven/project/ProjectBuildingResult.java | 8 +- .../project/ProjectDependenciesResolver.java | 10 +- .../maven/project/ProjectModelResolver.java | 286 +-- .../maven/project/ProjectRealmCache.java | 32 +- .../apache/maven/project/ProjectSorter.java | 261 +- .../maven/project/ReactorModelPool.java | 97 +- .../project/RepositorySessionDecorator.java | 8 +- .../artifact/ActiveProjectArtifact.java | 251 +- .../artifact/ArtifactWithDependencies.java | 10 +- .../project/artifact/AttachedArtifact.java | 153 +- .../artifact/DefaultMavenMetadataCache.java | 287 +-- .../artifact/DefaultMetadataSource.java | 18 +- .../DefaultProjectArtifactsCache.java | 185 +- .../InvalidDependencyVersionException.java | 25 +- .../project/artifact/MavenMetadataCache.java | 26 +- .../project/artifact/MavenMetadataSource.java | 639 ++--- .../project/artifact/PluginArtifact.java | 59 +- .../project/artifact/ProjectArtifact.java | 67 +- .../artifact/ProjectArtifactMetadata.java | 78 +- .../artifact/ProjectArtifactsCache.java | 43 +- .../collector/DefaultProjectsSelector.java | 72 +- .../MultiModuleCollectionStrategy.java | 172 +- .../collector/PomlessCollectionStrategy.java | 38 +- .../collector/ProjectCollectionStrategy.java | 12 +- .../project/collector/ProjectsSelector.java | 14 +- .../RequestPomCollectionStrategy.java | 31 +- .../maven/project/path/PathTranslator.java | 17 +- .../properties/internal/EnvironmentUtils.java | 30 +- .../properties/internal/SystemProperties.java | 25 +- .../ArtifactDoesNotExistException.java | 17 +- .../repository/ArtifactTransferEvent.java | 166 +- .../ArtifactTransferFailedException.java | 18 +- .../repository/ArtifactTransferListener.java | 19 +- .../repository/ArtifactTransferResource.java | 7 +- .../DelegatingLocalArtifactRepository.java | 118 +- .../repository/LocalArtifactRepository.java | 9 +- ...LocalRepositoryNotAccessibleException.java | 20 +- .../maven/repository/RepositorySystem.java | 88 +- .../metadata/AbstractArtifactMetadata.java | 34 +- .../ArtifactMetadataRetrievalException.java | 35 +- .../metadata/ArtifactMetadataSource.java | 34 +- .../DefaultMetadataResolutionRequest.java | 66 +- .../metadata/MetadataResolutionRequest.java | 19 +- .../legacy/metadata/ResolutionGroup.java | 41 +- .../maven/rtinfo/RuntimeInformation.java | 9 +- .../internal/DefaultRuntimeInformation.java | 108 +- .../session/scope/internal/SessionScope.java | 103 +- .../scope/internal/SessionScopeModule.java | 40 +- .../settings/DefaultMavenSettingsBuilder.java | 109 +- .../maven/settings/MavenSettingsBuilder.java | 25 +- .../SettingsConfigurationException.java | 37 +- .../apache/maven/settings/SettingsUtils.java | 242 +- .../maven/toolchain/DefaultToolchain.java | 100 +- .../toolchain/DefaultToolchainManager.java | 112 +- .../DefaultToolchainManagerPrivate.java | 68 +- .../toolchain/DefaultToolchainsBuilder.java | 46 +- .../MisconfiguredToolchainException.java | 21 +- .../maven/toolchain/RequirementMatcher.java | 12 +- .../toolchain/RequirementMatcherFactory.java | 78 +- .../org/apache/maven/toolchain/Toolchain.java | 12 +- .../maven/toolchain/ToolchainFactory.java | 14 +- .../maven/toolchain/ToolchainManager.java | 14 +- .../toolchain/ToolchainManagerPrivate.java | 14 +- .../maven/toolchain/ToolchainPrivate.java | 15 +- .../maven/toolchain/ToolchainsBuilder.java | 11 +- .../toolchain/java/DefaultJavaToolChain.java | 25 +- .../maven/toolchain/java/JavaToolchain.java | 75 +- .../toolchain/java/JavaToolchainFactory.java | 86 +- .../toolchain/java/JavaToolchainImpl.java | 52 +- .../DefaultConsumerPomXMLFilterFactory.java | 13 +- .../AbstractCoreMavenComponentTestCase.java | 279 +- .../org/apache/maven/DefaultMavenTest.java | 90 +- .../maven/MavenLifecycleParticipantTest.java | 176 +- .../test/java/org/apache/maven/MavenTest.java | 72 +- .../ProjectDependenciesResolverTest.java | 91 +- .../artifact/handler/ArtifactHandlerTest.java | 113 +- .../filter/ExclusionArtifactFilterTest.java | 142 +- .../DefaultBeanConfiguratorPathTest.java | 87 +- .../DefaultBeanConfiguratorTest.java | 86 +- .../DefaultExceptionHandlerTest.java | 56 +- .../DefaultBuildResumptionAnalyzerTest.java | 143 +- ...aultBuildResumptionDataRepositoryTest.java | 78 +- ...ultMavenExecutionRequestPopulatorTest.java | 38 +- .../execution/DefaultMavenExecutionTest.java | 32 +- .../internal/MojoExecutionScopeTest.java | 97 +- .../maven/graph/DefaultGraphBuilderTest.java | 597 ++--- .../DefaultProjectDependencyGraphTest.java | 183 +- .../maven/graph/ProjectSelectorTest.java | 215 +- .../internal/MultilineMessageHelperTest.java | 76 +- .../ConsumerModelSourceTransformerTest.java | 38 +- .../internal/impl/PropertiesAsMapTest.java | 50 +- .../apache/maven/internal/impl/TestApi.java | 81 +- .../internal/impl/TestArtifactHandler.java | 37 +- .../internal/impl/TestRepositorySystem.java | 307 +-- .../lifecycle/DefaultLifecyclesTest.java | 142 +- .../DelegatingMojoExecutionListener.java | 48 +- .../DelegatingProjectExecutionListener.java | 56 +- .../EmptyLifecyclePluginAnalyzer.java | 47 +- .../LifecycleExecutorSubModulesTest.java | 65 +- .../lifecycle/LifecycleExecutorTest.java | 709 +++--- .../lifecycle/MavenExecutionPlanTest.java | 77 +- .../MojoExecutionXPathContainer.java | 48 +- .../internal/BuildListCalculatorTest.java | 70 +- .../ConcurrencyDependencyGraphTest.java | 114 +- .../LifecycleDependencyResolverTest.java | 61 +- .../LifecycleExecutionPlanCalculatorTest.java | 101 +- .../internal/LifecycleModuleBuilderTest.java | 100 +- ...ifecycleTaskSegmentCalculatorImplTest.java | 38 +- .../lifecycle/internal/PhaseRecorderTest.java | 59 +- .../internal/ProjectBuildListTest.java | 58 +- .../internal/builder/BuilderCommonTest.java | 116 +- .../ConcurrencyDependencyGraphTest.java | 86 +- .../multithreaded/ThreadOutputMuxerTest.java | 142 +- .../internal/stub/BuildPluginManagerStub.java | 56 +- .../internal/stub/CompletionServiceStub.java | 73 +- .../internal/stub/DefaultLifecyclesStub.java | 88 +- .../stub/ExecutionEventCatapultStub.java | 18 +- .../stub/LifeCyclePluginAnalyzerStub.java | 75 +- .../LifecycleExecutionPlanCalculatorStub.java | 275 +- .../LifecycleTaskSegmentCalculatorStub.java | 83 +- .../internal/stub/MojoExecutorStub.java | 79 +- .../stub/PluginPrefixResolverStub.java | 46 +- .../stub/PluginVersionResolverStub.java | 43 +- .../stub/ProjectDependenciesResolverStub.java | 102 +- .../stub/ProjectDependencyGraphStub.java | 198 +- .../stub/ProjectDependencyGraphStubTest.java | 74 +- .../lifecycle/mapping/LifecyclePhaseTest.java | 75 +- .../maven/plugin/PluginManagerTest.java | 221 +- .../plugin/PluginParameterExceptionTest.java | 184 +- ...luginParameterExpressionEvaluatorTest.java | 369 ++- .../internal/DefaultLegacySupportTest.java | 20 +- .../internal/MavenPluginValidatorTest.java | 110 +- .../project/AbstractMavenProjectTestCase.java | 144 +- .../DefaultMavenProjectBuilderTest.java | 415 ++- .../maven/project/EmptyLifecycleExecutor.java | 68 +- .../project/EmptyProjectBuildingHelper.java | 35 +- .../ExtensionDescriptorBuilderTest.java | 64 +- .../project/LegacyLocalRepositoryManager.java | 138 +- .../maven/project/MavenProjectTest.java | 219 +- .../maven/project/PomConstructionTest.java | 2257 ++++++++--------- .../maven/project/ProjectBuilderTest.java | 398 ++- ...jectBuildingResultWithLocationMatcher.java | 62 +- ...ildingResultWithProblemMessageMatcher.java | 56 +- .../project/ProjectModelResolverTest.java | 212 +- .../maven/project/ProjectSorterTest.java | 346 ++- .../maven/project/TestMetadataSource.java | 36 +- .../DefaultMavenMetadataCacheTest.java | 55 +- .../DefaultProjectArtifactsCacheTest.java | 57 +- .../artifact/MavenMetadataSourceTest.java | 24 +- .../CanonicalProjectBuilderTest.java | 58 +- .../maven/project/harness/PomTestWrapper.java | 70 +- .../harness/Xpp3DomAttributeIterator.java | 38 +- .../harness/Xpp3DomAttributePointer.java | 48 +- .../project/harness/Xpp3DomNodeIterator.java | 83 +- .../project/harness/Xpp3DomNodePointer.java | 89 +- .../harness/Xpp3DomPointerFactory.java | 40 +- .../maven/repository/TestArtifactHandler.java | 37 +- .../repository/TestRepositoryConnector.java | 126 +- .../TestRepositoryConnectorFactory.java | 21 +- .../repository/TestRepositorySystem.java | 305 +-- .../DefaultRuntimeInformationTest.java | 44 +- .../PomConstructionWithSettingsTest.java | 98 +- .../maven/settings/SettingsUtilsTest.java | 156 +- .../DefaultToolchainManagerPrivateTest.java | 104 +- .../DefaultToolchainManagerTest.java | 111 +- .../maven/toolchain/DefaultToolchainTest.java | 129 +- .../RequirementMatcherFactoryTest.java | 50 +- maven-embedder/pom.xml | 2 - .../java/org/apache/maven/embedder/App.java | 15 - .../org/apache/maven/embedder/AppTest.java | 15 - .../java/org/apache/maven/cli/CLIManager.java | 258 +- .../apache/maven/cli/CLIReportingUtils.java | 167 +- .../org/apache/maven/cli/CleanArgument.java | 80 +- .../java/org/apache/maven/cli/CliRequest.java | 50 +- .../java/org/apache/maven/cli/MavenCli.java | 1638 +++++------- .../org/apache/maven/cli/ResolveFile.java | 28 +- .../configuration/ConfigurationProcessor.java | 9 +- .../SettingsXmlConfigurationProcessor.java | 197 +- .../cli/event/DefaultEventSpyContext.java | 12 +- .../maven/cli/event/ExecutionEventLogger.java | 446 ++-- .../BootstrapCoreExtensionManager.java | 177 +- .../ExtensionResolutionException.java | 22 +- .../cli/logging/BaseSlf4jConfiguration.java | 19 +- .../maven/cli/logging/Slf4jConfiguration.java | 15 +- .../logging/Slf4jConfigurationFactory.java | 36 +- .../apache/maven/cli/logging/Slf4jLogger.java | 89 +- .../maven/cli/logging/Slf4jLoggerManager.java | 47 +- .../maven/cli/logging/Slf4jStdoutLogger.java | 253 +- .../cli/logging/impl/Log4j2Configuration.java | 18 +- .../logging/impl/LogbackConfiguration.java | 18 +- .../impl/Slf4jSimpleConfiguration.java | 18 +- .../UnsupportedSlf4jBindingConfiguration.java | 32 +- .../AbstractMavenTransferListener.java | 200 +- .../BatchModeMavenTransferListener.java | 15 +- .../ConsoleMavenTransferListener.java | 127 +- .../transfer/QuietMavenTransferListener.java | 11 +- .../transfer/Slf4jMavenTransferListener.java | 68 +- .../sisu/plexus/PlexusXmlBeanConverter.java | 359 +-- .../main/java/org/slf4j/MavenSlf4jFriend.java | 9 +- .../slf4j/impl/MavenSlf4jSimpleFriend.java | 14 +- .../cli/CLIManagerDocumentationTest.java | 93 +- .../maven/cli/CLIReportingUtilsTest.java | 31 +- .../apache/maven/cli/CleanArgumentTest.java | 44 +- .../org/apache/maven/cli/MavenCliTest.java | 504 ++-- .../cli/event/ExecutionEventLoggerTest.java | 294 ++- .../cli/transfer/FileSizeFormatTest.java | 338 ++- maven-model-builder/pom.xml | 2 - .../org/apache/maven/feature/Features.java | 33 +- .../AbstractModelBuildingListener.java | 11 +- .../AbstractModelSourceTransformer.java | 11 +- .../model/building/ArtifactModelSource.java | 44 +- .../building/BuildModelSourceTransformer.java | 18 +- .../DefaultBuildPomXMLFilterFactory.java | 61 +- .../model/building/DefaultModelBuilder.java | 2057 +++++++-------- .../building/DefaultModelBuilderFactory.java | 187 +- .../building/DefaultModelBuildingEvent.java | 20 +- .../building/DefaultModelBuildingRequest.java | 233 +- .../building/DefaultModelBuildingResult.java | 118 +- .../model/building/DefaultModelProblem.java | 108 +- .../DefaultModelProblemCollector.java | 129 +- .../model/building/DefaultModelProcessor.java | 40 +- .../DefaultModelSourceTransformer.java | 13 +- .../building/DefaultTransformerContext.java | 88 +- .../maven/model/building/FileModelSource.java | 55 +- .../model/building/FileToRawModelMerger.java | 200 +- .../building/FilterModelBuildingRequest.java | 165 +- .../maven/model/building/ModelBuilder.java | 16 +- .../model/building/ModelBuildingEvent.java | 7 +- .../building/ModelBuildingEventCatapult.java | 9 +- .../building/ModelBuildingException.java | 111 +- .../model/building/ModelBuildingListener.java | 9 +- .../model/building/ModelBuildingRequest.java | 46 +- .../model/building/ModelBuildingResult.java | 12 +- .../maven/model/building/ModelCache.java | 41 +- .../maven/model/building/ModelCacheTag.java | 57 +- .../maven/model/building/ModelData.java | 45 +- .../maven/model/building/ModelProblem.java | 17 +- .../model/building/ModelProblemCollector.java | 9 +- .../building/ModelProblemCollectorExt.java | 7 +- .../ModelProblemCollectorRequest.java | 38 +- .../model/building/ModelProblemUtils.java | 109 +- .../maven/model/building/ModelProcessor.java | 10 +- .../maven/model/building/ModelSource.java | 8 +- .../maven/model/building/ModelSource2.java | 9 +- .../building/ModelSourceTransformer.java | 11 +- .../apache/maven/model/building/Result.java | 146 +- .../model/building/StringModelSource.java | 17 +- .../model/building/TransformerContext.java | 13 +- .../building/TransformerContextBuilder.java | 8 +- .../model/building/TransformerException.java | 19 +- .../maven/model/building/UrlModelSource.java | 13 +- .../DefaultDependencyManagementImporter.java | 44 +- .../DependencyManagementImporter.java | 15 +- .../DefaultInheritanceAssembler.java | 309 +-- .../inheritance/InheritanceAssembler.java | 11 +- .../AbstractStringBasedModelInterpolator.java | 156 +- .../BuildTimestampValueSource.java | 23 +- .../DefaultModelVersionProcessor.java | 39 +- .../interpolation/MavenBuildTimestamp.java | 50 +- .../interpolation/ModelInterpolator.java | 22 +- .../interpolation/ModelVersionProcessor.java | 14 +- .../PathTranslatingPostProcessor.java | 38 +- .../StringVisitorModelInterpolator.java | 86 +- .../UrlNormalizingPostProcessor.java | 35 +- .../maven/model/io/DefaultModelReader.java | 128 +- .../maven/model/io/DefaultModelWriter.java | 67 +- .../maven/model/io/ModelParseException.java | 26 +- .../apache/maven/model/io/ModelReader.java | 17 +- .../apache/maven/model/io/ModelWriter.java | 26 +- .../model/locator/DefaultModelLocator.java | 14 +- .../maven/model/locator/ModelLocator.java | 9 +- .../DefaultDependencyManagementInjector.java | 95 +- .../DefaultPluginManagementInjector.java | 103 +- .../DependencyManagementInjector.java | 9 +- .../management/PluginManagementInjector.java | 9 +- .../maven/model/merge/MavenModelMerger.java | 665 +++-- .../normalization/DefaultModelNormalizer.java | 114 +- .../model/normalization/ModelNormalizer.java | 11 +- .../path/DefaultModelPathTranslator.java | 105 +- .../model/path/DefaultModelUrlNormalizer.java | 46 +- .../model/path/DefaultPathTranslator.java | 34 +- .../model/path/DefaultUrlNormalizer.java | 46 +- .../maven/model/path/ModelPathTranslator.java | 12 +- .../maven/model/path/ModelUrlNormalizer.java | 11 +- .../maven/model/path/PathTranslator.java | 11 +- ...ProfileActivationFilePathInterpolator.java | 54 +- .../maven/model/path/UrlNormalizer.java | 11 +- .../DefaultPluginConfigurationExpander.java | 41 +- .../DefaultReportConfigurationExpander.java | 30 +- .../plugin/DefaultReportingConverter.java | 218 +- .../plugin/LifecycleBindingsInjector.java | 9 +- .../plugin/PluginConfigurationExpander.java | 9 +- .../plugin/ReportConfigurationExpander.java | 9 +- .../model/plugin/ReportingConverter.java | 9 +- .../DefaultProfileActivationContext.java | 128 +- .../model/profile/DefaultProfileInjector.java | 238 +- .../model/profile/DefaultProfileSelector.java | 104 +- .../profile/ProfileActivationContext.java | 9 +- .../maven/model/profile/ProfileInjector.java | 9 +- .../maven/model/profile/ProfileSelector.java | 12 +- .../activation/FileProfileActivator.java | 68 +- .../JdkVersionProfileActivator.java | 170 +- .../OperatingSystemProfileActivator.java | 91 +- .../profile/activation/ProfileActivator.java | 11 +- .../activation/PropertyProfileActivator.java | 65 +- .../InvalidRepositoryException.java | 21 +- .../maven/model/resolution/ModelResolver.java | 62 +- .../UnresolvableModelException.java | 46 +- .../resolution/WorkspaceModelResolver.java | 19 +- .../superpom/DefaultSuperPomProvider.java | 53 +- .../model/superpom/SuperPomProvider.java | 9 +- .../validation/DefaultModelValidator.java | 1874 ++++++++------ .../model/validation/ModelValidator.java | 16 +- .../model/building/ComplexActivationTest.java | 47 +- .../DefaultModelBuilderFactoryTest.java | 90 +- .../building/DefaultModelBuilderTest.java | 174 +- .../model/building/FileModelSourceTest.java | 54 +- .../building/FileToRawModelMergerTest.java | 71 +- .../building/SimpleProblemCollector.java | 42 +- .../DefaultInheritanceAssemblerTest.java | 180 +- .../AbstractModelInterpolatorTest.java | 537 ++-- .../MavenBuildTimestampTest.java | 23 +- .../StringVisitorModelInterpolatorTest.java | 13 +- .../model/merge/MavenModelMergerTest.java | 103 +- .../model/path/DefaultUrlNormalizerTest.java | 69 +- .../AbstractProfileActivatorTest.java | 29 +- .../activation/FileProfileActivatorTest.java | 98 +- .../JdkVersionProfileActivatorTest.java | 190 +- .../PropertyProfileActivatorTest.java | 150 +- .../validation/DefaultModelValidatorTest.java | 939 ++++--- maven-model-transform/pom.xml | 4 +- .../BuildToRawPomXMLFilterFactory.java | 57 +- .../model/transform/CiFriendlyXMLFilter.java | 47 +- .../model/transform/FastForwardFilter.java | 58 +- .../model/transform/ModulesXMLFilter.java | 17 +- .../model/transform/ParentXMLFilter.java | 125 +- .../RawToConsumerPomXMLFilterFactory.java | 22 +- .../transform/ReactorDependencyXMLFilter.java | 79 +- .../transform/RelativePathXMLFilter.java | 40 +- .../model/transform/RelativeProject.java | 18 +- .../model/transform/pull/BufferingParser.java | 410 ++- .../transform/pull/NodeBufferingParser.java | 41 +- .../maven/model/transform/pull/XmlUtils.java | 97 +- .../transform/AbstractXMLFilterTests.java | 29 +- .../transform/CiFriendlyXMLFilterTest.java | 37 +- .../transform/ConsumerPomXMLFilterTest.java | 333 ++- .../model/transform/ModulesXMLFilterTest.java | 93 +- .../model/transform/ParentXMLFilterTest.java | 388 ++- .../ReactorDependencyXMLFilterTest.java | 164 +- .../transform/RelativePathXMLFilterTest.java | 155 +- maven-model/pom.xml | 6 +- .../org/apache/maven/model/BaseObject.java | 41 +- .../org/apache/maven/model/InputLocation.java | 357 ++- .../maven/model/InputLocationTracker.java | 26 +- .../org/apache/maven/model/InputSource.java | 112 +- .../org/apache/maven/model/WrapperList.java | 108 +- .../apache/maven/model/WrapperProperties.java | 309 +-- .../maven/model/io/xpp3/MavenXpp3Reader.java | 84 +- .../model/io/xpp3/MavenXpp3ReaderEx.java | 86 +- .../maven/model/io/xpp3/MavenXpp3Writer.java | 47 +- .../model/io/xpp3/MavenXpp3WriterEx.java | 70 +- .../maven/model/io/xpp3/package-info.java | 19 - .../maven/model/merge/package-info.java | 19 - .../maven/model/ActivationFileTest.java | 31 +- .../apache/maven/model/ActivationOSTest.java | 31 +- .../maven/model/ActivationPropertyTest.java | 31 +- .../apache/maven/model/ActivationTest.java | 31 +- .../org/apache/maven/model/BuildTest.java | 31 +- .../apache/maven/model/CiManagementTest.java | 31 +- .../apache/maven/model/ContributorTest.java | 31 +- .../maven/model/DependencyManagementTest.java | 31 +- .../apache/maven/model/DependencyTest.java | 31 +- .../maven/model/DeploymentRepositoryTest.java | 31 +- .../org/apache/maven/model/DeveloperTest.java | 31 +- .../model/DistributionManagementTest.java | 31 +- .../org/apache/maven/model/ExclusionTest.java | 31 +- .../org/apache/maven/model/ExtensionTest.java | 31 +- .../maven/model/IssueManagementTest.java | 31 +- .../org/apache/maven/model/LicenseTest.java | 31 +- .../apache/maven/model/MailingListTest.java | 31 +- .../org/apache/maven/model/ModelTest.java | 31 +- .../org/apache/maven/model/NotifierTest.java | 31 +- .../apache/maven/model/OrganizationTest.java | 31 +- .../org/apache/maven/model/ParentTest.java | 31 +- .../maven/model/PluginConfigurationTest.java | 31 +- .../maven/model/PluginContainerTest.java | 31 +- .../maven/model/PluginExecutionTest.java | 31 +- .../maven/model/PluginManagementTest.java | 31 +- .../org/apache/maven/model/PluginTest.java | 31 +- .../apache/maven/model/PrerequisitesTest.java | 31 +- .../org/apache/maven/model/ProfileTest.java | 31 +- .../apache/maven/model/RelocationTest.java | 31 +- .../apache/maven/model/ReportPluginTest.java | 31 +- .../org/apache/maven/model/ReportSetTest.java | 31 +- .../org/apache/maven/model/ReportingTest.java | 31 +- .../maven/model/RepositoryPolicyTest.java | 31 +- .../apache/maven/model/RepositoryTest.java | 31 +- .../org/apache/maven/model/ResourceTest.java | 31 +- .../java/org/apache/maven/model/ScmTest.java | 31 +- .../apache/maven/model/SerializationTest.java | 33 +- .../java/org/apache/maven/model/SiteTest.java | 31 +- .../maven/model/merge/MavenMergerTest.java | 65 +- .../apache/maven/model/v4/ModelXmlTest.java | 47 +- maven-plugin-api/pom.xml | 4 +- .../org/apache/maven/plugin/AbstractMojo.java | 25 +- .../AbstractMojoExecutionException.java | 30 +- .../apache/maven/plugin/ContextEnabled.java | 10 +- .../java/org/apache/maven/plugin/Mojo.java | 13 +- .../maven/plugin/MojoExecutionException.java | 35 +- .../maven/plugin/MojoFailureException.java | 30 +- .../maven/plugin/MojoNotFoundException.java | 50 +- .../DuplicateMojoDescriptorException.java | 21 +- .../DuplicateParameterException.java | 15 +- .../descriptor/InvalidParameterException.java | 21 +- .../InvalidPluginDescriptorException.java | 20 +- .../plugin/descriptor/MojoDescriptor.java | 253 +- .../maven/plugin/descriptor/Parameter.java | 105 +- .../plugin/descriptor/PluginDescriptor.java | 291 +-- .../descriptor/PluginDescriptorBuilder.java | 373 ++- .../maven/plugin/descriptor/Requirement.java | 34 +- .../lifecycle/ImmutableCollections.java | 488 ++-- .../org/apache/maven/plugin/logging/Log.java | 32 +- .../maven/plugin/logging/SystemStreamLog.java | 116 +- .../plugin/descriptor/MojoDescriptorTest.java | 45 +- .../PluginDescriptorBuilderTest.java | 170 +- maven-repository-metadata/pom.xml | 2 - .../repository/metadata/MetadataTest.java | 291 +-- maven-resolver-provider/pom.xml | 3 - .../ArtifactDescriptorReaderDelegate.java | 118 +- .../internal/ArtifactDescriptorUtils.java | 49 +- .../DefaultArtifactDescriptorReader.java | 285 +-- .../internal/DefaultModelCache.java | 147 +- .../internal/DefaultModelCacheFactory.java | 13 +- .../internal/DefaultModelResolver.java | 255 +- .../internal/DefaultVersionRangeResolver.java | 260 +- .../internal/DefaultVersionResolver.java | 510 ++-- .../DefaultVersionSchemeProvider.java | 18 +- .../internal/LocalSnapshotMetadata.java | 106 +- .../LocalSnapshotMetadataGenerator.java | 44 +- .../repository/internal/MavenMetadata.java | 93 +- .../internal/MavenRepositorySystemUtils.java | 64 +- .../internal/MavenResolverModule.java | 58 +- .../internal/MavenSnapshotMetadata.java | 53 +- .../internal/MavenWorkspaceReader.java | 12 +- .../internal/ModelCacheFactory.java | 9 +- .../repository/internal/PluginsMetadata.java | 64 +- .../internal/PluginsMetadataGenerator.java | 108 +- .../PluginsMetadataGeneratorFactory.java | 25 +- .../internal/RelocatedArtifact.java | 106 +- .../internal/RemoteSnapshotMetadata.java | 104 +- .../RemoteSnapshotMetadataGenerator.java | 64 +- .../SnapshotMetadataGeneratorFactory.java | 25 +- .../repository/internal/VersionsMetadata.java | 88 +- .../internal/VersionsMetadataGenerator.java | 58 +- .../VersionsMetadataGeneratorFactory.java | 25 +- .../repository/internal/package-info.java | 19 - .../internal/AbstractRepositoryTestCase.java | 40 +- .../DefaultArtifactDescriptorReaderTest.java | 58 +- .../internal/DefaultModelResolverTest.java | 204 +- .../internal/DefaultVersionResolverTest.java | 62 +- .../MavenRepositorySystemUtilsTest.java | 16 +- .../internal/RemoteSnapshotMetadataTest.java | 47 +- .../internal/RepositorySystemTest.java | 235 +- .../util/ConsoleRepositoryListener.java | 110 +- .../util/ConsoleTransferListener.java | 154 +- maven-settings-builder/pom.xml | 2 - .../building/DefaultSettingsBuilder.java | 233 +- .../DefaultSettingsBuilderFactory.java | 23 +- .../DefaultSettingsBuildingRequest.java | 72 +- .../DefaultSettingsBuildingResult.java | 20 +- .../building/DefaultSettingsProblem.java | 96 +- .../DefaultSettingsProblemCollector.java | 30 +- .../settings/building/FileSettingsSource.java | 16 +- .../settings/building/SettingsBuilder.java | 10 +- .../building/SettingsBuildingException.java | 52 +- .../building/SettingsBuildingRequest.java | 19 +- .../building/SettingsBuildingResult.java | 8 +- .../settings/building/SettingsProblem.java | 12 +- .../building/SettingsProblemCollector.java | 9 +- .../settings/building/SettingsSource.java | 8 +- .../building/StringSettingsSource.java | 21 +- .../settings/building/UrlSettingsSource.java | 17 +- .../crypto/DefaultSettingsDecrypter.java | 88 +- .../DefaultSettingsDecryptionRequest.java | 47 +- .../DefaultSettingsDecryptionResult.java | 37 +- .../crypto/MavenSecDispatcherProvider.java | 25 +- .../settings/crypto/SettingsDecrypter.java | 9 +- .../crypto/SettingsDecryptionRequest.java | 12 +- .../crypto/SettingsDecryptionResult.java | 8 +- .../settings/io/DefaultSettingsReader.java | 59 +- .../settings/io/DefaultSettingsWriter.java | 49 +- .../settings/io/SettingsParseException.java | 26 +- .../maven/settings/io/SettingsReader.java | 17 +- .../maven/settings/io/SettingsWriter.java | 17 +- .../settings/merge/MavenSettingsMerger.java | 84 +- .../validation/DefaultSettingsValidator.java | 262 +- .../validation/SettingsValidator.java | 11 +- .../DefaultSettingsBuilderFactoryTest.java | 35 +- .../DefaultSettingsValidatorTest.java | 261 +- maven-settings/pom.xml | 6 +- .../apache/maven/settings/WrapperList.java | 108 +- .../maven/settings/WrapperProperties.java | 307 +-- .../settings/io/xpp3/SettingsXpp3Reader.java | 85 +- .../settings/io/xpp3/SettingsXpp3Writer.java | 48 +- maven-slf4j-provider/pom.xml | 10 +- .../slf4j/impl/MavenFailOnSeverityLogger.java | 81 +- .../org/slf4j/impl/MavenLoggerFactory.java | 52 +- .../org/slf4j/impl/MavenSimpleLogger.java | 92 +- .../org/slf4j/impl/StaticLoggerBinder.java | 21 +- .../slf4j/impl/MavenLoggerFactoryTest.java | 86 +- maven-slf4j-wrapper/pom.xml | 8 +- .../maven/logwrapper/LogLevelRecorder.java | 46 +- .../logwrapper/MavenSlf4jWrapperFactory.java | 12 +- .../logwrapper/LogLevelRecorderTest.java | 54 +- maven-toolchain-builder/pom.xml | 6 +- .../building/DefaultToolchainsBuilder.java | 201 +- .../DefaultToolchainsBuildingRequest.java | 20 +- .../DefaultToolchainsBuildingResult.java | 20 +- .../toolchain/building/ToolchainsBuilder.java | 10 +- .../building/ToolchainsBuildingException.java | 52 +- .../building/ToolchainsBuildingRequest.java | 10 +- .../building/ToolchainsBuildingResult.java | 8 +- .../toolchain/io/DefaultToolchainsReader.java | 59 +- .../toolchain/io/DefaultToolchainsWriter.java | 29 +- .../io/ToolchainsParseException.java | 26 +- .../maven/toolchain/io/ToolchainsReader.java | 17 +- .../maven/toolchain/io/ToolchainsWriter.java | 14 +- .../toolchain/merge/MavenToolchainMerger.java | 71 +- .../DefaultToolchainsBuilderTest.java | 365 +-- .../ToolchainsBuildingExceptionTest.java | 69 +- .../merge/MavenToolchainMergerTest.java | 165 +- maven-toolchain-model/pom.xml | 178 +- .../maven/toolchain/model/WrapperList.java | 108 +- .../toolchain/model/WrapperProperties.java | 307 +-- maven-xml-impl/pom.xml | 52 +- .../apache/maven/internal/xml/DomBuilder.java | 67 +- .../maven/internal/xml/MavenXmlException.java | 32 +- .../internal/xml/XmlPlexusConfiguration.java | 59 +- .../apache/maven/internal/xml/Xpp3Dom.java | 311 +-- .../maven/internal/xml/Xpp3DomBuilder.java | 143 +- .../maven/internal/xml/Xpp3DomWriter.java | 52 +- .../maven/internal/xml/package-info.java | 19 - .../org/codehaus/plexus/util/xml/Xpp3Dom.java | 286 +-- .../plexus/util/xml/Xpp3DomBuilder.java | 74 +- .../plexus/util/xml/package-info.java | 19 - plexus-utils/pom.xml | 282 +- pom.xml | 183 +- 1278 files changed, 48062 insertions(+), 67004 deletions(-) diff --git a/apache-maven/pom.xml b/apache-maven/pom.xml index 7acd55dddb..a443d0b51e 100644 --- a/apache-maven/pom.xml +++ b/apache-maven/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -100,6 +98,19 @@ under the License. + + + + false + + + true + + apache.snapshots + https://repository.apache.org/snapshots/ + + + ${distributionFileName} @@ -179,10 +190,10 @@ under the License. create-distro-packages - package single + package src/assembly/bin.xml @@ -194,19 +205,6 @@ under the License. - - - apache.snapshots - https://repository.apache.org/snapshots/ - - true - - - false - - - - create-distribution-in-dir @@ -222,10 +220,10 @@ under the License. maven-clean-plugin + clean-target-dir clean - clean-target-dir prepare-package true @@ -243,10 +241,10 @@ under the License. create-distribution-dir - package single + package ./ false @@ -271,10 +269,10 @@ under the License. make-src-assembly - package single + package src/assembly/src.xml @@ -288,14 +286,6 @@ under the License. net.nicoulaj.maven.plugins checksum-maven-plugin - - - source-release-checksum - - files - - - @@ -310,6 +300,14 @@ under the License. true + + + source-release-checksum + + files + + + diff --git a/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java b/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java index 7d1853b7a7..fb7544ec14 100644 --- a/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java +++ b/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,39 +16,34 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; + +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; - import org.apache.maven.settings.v4.SettingsXpp3Reader; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Tests that the global settings.xml shipped with the distribution is in good state. * * @author Benjamin Bentmann */ -public class GlobalSettingsTest -{ +public class GlobalSettingsTest { @Test - public void testValidGlobalSettings() - throws Exception - { - String basedir = System.getProperty( "basedir", System.getProperty( "user.dir" ) ); + public void testValidGlobalSettings() throws Exception { + String basedir = System.getProperty("basedir", System.getProperty("user.dir")); - File globalSettingsFile = new File( basedir, "src/assembly/maven/conf/settings.xml" ); - assertTrue( globalSettingsFile.isFile(), globalSettingsFile.getAbsolutePath() ); + File globalSettingsFile = new File(basedir, "src/assembly/maven/conf/settings.xml"); + assertTrue(globalSettingsFile.isFile(), globalSettingsFile.getAbsolutePath()); - try ( Reader reader = new InputStreamReader( new FileInputStream( globalSettingsFile ), StandardCharsets.UTF_8) ) - { - new SettingsXpp3Reader().read( reader ); + try (Reader reader = new InputStreamReader(new FileInputStream(globalSettingsFile), StandardCharsets.UTF_8)) { + new SettingsXpp3Reader().read(reader); } } - } diff --git a/api/maven-api-core/pom.xml b/api/maven-api-core/pom.xml index fd78f534fe..bae7a9368e 100644 --- a/api/maven-api-core/pom.xml +++ b/api/maven-api-core/pom.xml @@ -1,4 +1,4 @@ - + - 4.0.0 diff --git a/api/maven-api-model/src/main/java/org/apache/maven/api/model/ImmutableCollections.java b/api/maven-api-model/src/main/java/org/apache/maven/api/model/ImmutableCollections.java index e47fa1a8bb..6c70c7400d 100644 --- a/api/maven-api-model/src/main/java/org/apache/maven/api/model/ImmutableCollections.java +++ b/api/maven-api-model/src/main/java/org/apache/maven/api/model/ImmutableCollections.java @@ -1,5 +1,3 @@ -package org.apache.maven.api.model; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.api.model; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.api.model; import java.io.Serializable; import java.util.AbstractList; @@ -38,541 +37,435 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; -class ImmutableCollections -{ +class ImmutableCollections { - private static final List EMPTY_LIST = new AbstractImmutableList() - { + private static final List EMPTY_LIST = new AbstractImmutableList() { @Override - public Object get( int index ) - { + public Object get(int index) { throw new IndexOutOfBoundsException(); } + @Override - public int size() - { + public int size() { return 0; } }; - private static final Map EMPTY_MAP = new AbstractImmutableMap() - { + private static final Map EMPTY_MAP = new AbstractImmutableMap() { @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { @Override - public boolean hasNext() - { + public boolean hasNext() { return false; } + @Override - public Entry next() - { + public Entry next() { throw new NoSuchElementException(); } }; } + @Override - public int size() - { + public int size() { return 0; } }; } }; - static List copy( Collection collection ) - { - if ( collection == null ) - { + static List copy(Collection collection) { + if (collection == null) { return emptyList(); - } - else if ( collection instanceof AbstractImmutableList ) - { - return ( List ) collection; - } - else - { - switch ( collection.size() ) - { + } else if (collection instanceof AbstractImmutableList) { + return (List) collection; + } else { + switch (collection.size()) { case 0: return emptyList(); case 1: - return singletonList( collection.iterator().next() ); + return singletonList(collection.iterator().next()); case 2: Iterator it = collection.iterator(); - return new List2<>( it.next(), it.next() ); + return new List2<>(it.next(), it.next()); default: - return new ListN<>( collection ); + return new ListN<>(collection); } } } - @SuppressWarnings( "unchecked" ) - static List emptyList() - { - return ( List ) EMPTY_LIST; + @SuppressWarnings("unchecked") + static List emptyList() { + return (List) EMPTY_LIST; } - static List singletonList( E element ) - { - return new List1<>( element ); + static List singletonList(E element) { + return new List1<>(element); } - static Map copy( Map map ) - { - if ( map == null ) - { + static Map copy(Map map) { + if (map == null) { return emptyMap(); - } - else if ( map instanceof AbstractImmutableMap ) - { + } else if (map instanceof AbstractImmutableMap) { return map; - } - else - { - switch ( map.size() ) - { + } else { + switch (map.size()) { case 0: return emptyMap(); case 1: Map.Entry entry = map.entrySet().iterator().next(); - return singletonMap( entry.getKey(), entry.getValue() ); + return singletonMap(entry.getKey(), entry.getValue()); default: - return new MapN<>( map ); + return new MapN<>(map); } } } - @SuppressWarnings( "unchecked" ) - static Map emptyMap() - { - return ( Map ) EMPTY_MAP; + @SuppressWarnings("unchecked") + static Map emptyMap() { + return (Map) EMPTY_MAP; } - static Map singletonMap( K key, V value ) - { - return new Map1<>( key, value ); + static Map singletonMap(K key, V value) { + return new Map1<>(key, value); } - static Properties copy( Properties properties ) - { - if ( properties instanceof ROProperties ) - { + static Properties copy(Properties properties) { + if (properties instanceof ROProperties) { return properties; } - return new ROProperties( properties ); + return new ROProperties(properties); } - private static class List1 extends AbstractImmutableList - { + private static class List1 extends AbstractImmutableList { private final E element; - private List1( E element ) - { + private List1(E element) { this.element = element; } @Override - public E get( int index ) - { - if ( index == 0 ) - { + public E get(int index) { + if (index == 0) { return element; } - throw outOfBounds( index ); + throw outOfBounds(index); } @Override - public int size() - { + public int size() { return 1; } } - private static class List2 extends AbstractImmutableList - { + private static class List2 extends AbstractImmutableList { private final E element1; private final E element2; - private List2( E element1, E element2 ) - { + private List2(E element1, E element2) { this.element1 = element1; this.element2 = element2; } @Override - public E get( int index ) - { - if ( index == 0 ) - { + public E get(int index) { + if (index == 0) { return element1; - } - else if ( index == 1 ) - { + } else if (index == 1) { return element2; } - throw outOfBounds( index ); + throw outOfBounds(index); } @Override - public int size() - { + public int size() { return 2; } } - private static class ListN extends AbstractImmutableList - { + private static class ListN extends AbstractImmutableList { private final Object[] elements; - private ListN( Collection elements ) - { + private ListN(Collection elements) { this.elements = elements.toArray(); } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - public E get( int index ) - { - return ( E ) elements[ index ]; + public E get(int index) { + return (E) elements[index]; } @Override - public int size() - { + public int size() { return elements.length; } } - private abstract static class AbstractImmutableList - extends AbstractList - implements RandomAccess, Serializable - { + private abstract static class AbstractImmutableList extends AbstractList + implements RandomAccess, Serializable { @Override - public boolean add( E e ) - { + public boolean add(E e) { throw uoe(); } @Override - public boolean remove( Object o ) - { + public boolean remove(Object o) { throw uoe(); } @Override - public boolean addAll( Collection c ) - { + public boolean addAll(Collection c) { throw uoe(); } @Override - public boolean removeAll( Collection c ) - { + public boolean removeAll(Collection c) { throw uoe(); } @Override - public boolean retainAll( Collection c ) - { + public boolean retainAll(Collection c) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public boolean removeIf( Predicate filter ) - { + public boolean removeIf(Predicate filter) { throw uoe(); } @Override - public void replaceAll( UnaryOperator operator ) - { + public void replaceAll(UnaryOperator operator) { throw uoe(); } @Override - public void sort( Comparator c ) - { + public void sort(Comparator c) { throw uoe(); } @Override - public Iterator iterator() - { - return new Itr( 0 ); + public Iterator iterator() { + return new Itr(0); } @Override - public ListIterator listIterator() - { - return new Itr( 0 ); + public ListIterator listIterator() { + return new Itr(0); } @Override - public ListIterator listIterator( int index ) - { - if ( index < 0 || index > size() ) - { - throw outOfBounds( index ); + public ListIterator listIterator(int index) { + if (index < 0 || index > size()) { + throw outOfBounds(index); } - return new Itr( index ); + return new Itr(index); } @Override - public List subList( int fromIndex, int toIndex ) - { - if ( fromIndex < 0 ) - { - throw new IndexOutOfBoundsException( "fromIndex = " + fromIndex ); + public List subList(int fromIndex, int toIndex) { + if (fromIndex < 0) { + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } - if ( toIndex > size() ) - { - throw new IndexOutOfBoundsException( "toIndex = " + toIndex ); + if (toIndex > size()) { + throw new IndexOutOfBoundsException("toIndex = " + toIndex); } - if ( fromIndex > toIndex ) - { - throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")" ); + if (fromIndex > toIndex) { + throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } - return new SubList( fromIndex, toIndex ); + return new SubList(fromIndex, toIndex); } - protected IndexOutOfBoundsException outOfBounds( int index ) - { - return new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size() ); + protected IndexOutOfBoundsException outOfBounds(int index) { + return new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } - private class SubList extends AbstractImmutableList - { + private class SubList extends AbstractImmutableList { private final int fromIndex; private final int toIndex; - private SubList( int fromIndex, int toIndex ) - { + private SubList(int fromIndex, int toIndex) { this.fromIndex = fromIndex; this.toIndex = toIndex; } @Override - public E get( int index ) - { - if ( index < 0 || index > size() ) - { - throw outOfBounds( index ); + public E get(int index) { + if (index < 0 || index > size()) { + throw outOfBounds(index); } - return AbstractImmutableList.this.get( fromIndex + index ); + return AbstractImmutableList.this.get(fromIndex + index); } @Override - public int size() - { + public int size() { return toIndex - fromIndex; } } - private class Itr implements ListIterator - { + private class Itr implements ListIterator { int index; - private Itr( int index ) - { + private Itr(int index) { this.index = index; } @Override - public boolean hasNext() - { + public boolean hasNext() { return index < size(); } @Override - public E next() - { - return get( index++ ); + public E next() { + return get(index++); } @Override - public boolean hasPrevious() - { + public boolean hasPrevious() { return index > 0; } @Override - public E previous() - { - return get( --index ); + public E previous() { + return get(--index); } @Override - public int nextIndex() - { + public int nextIndex() { return index; } @Override - public int previousIndex() - { + public int previousIndex() { return index - 1; } @Override - public void remove() - { + public void remove() { throw uoe(); } @Override - public void set( E e ) - { + public void set(E e) { throw uoe(); } @Override - public void add( E e ) - { + public void add(E e) { throw uoe(); } } } - private static class ROProperties extends Properties - { - private ROProperties( Properties props ) - { + private static class ROProperties extends Properties { + private ROProperties(Properties props) { super(); - if ( props != null ) - { + if (props != null) { // Do not use super.putAll, as it may delegate to put which throws an UnsupportedOperationException - for ( Map.Entry e : props.entrySet() ) - { - super.put( e.getKey(), e.getValue() ); + for (Map.Entry e : props.entrySet()) { + super.put(e.getKey(), e.getValue()); } } } @Override - public Object put( Object key, Object value ) - { + public Object put(Object key, Object value) { throw uoe(); } @Override - public Object remove( Object key ) - { + public Object remove(Object key) { throw uoe(); } @Override - public void putAll( Map t ) - { + public void putAll(Map t) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public void replaceAll( BiFunction function ) - { + public void replaceAll(BiFunction function) { throw uoe(); } @Override - public Object putIfAbsent( Object key, Object value ) - { + public Object putIfAbsent(Object key, Object value) { throw uoe(); } @Override - public boolean remove( Object key, Object value ) - { + public boolean remove(Object key, Object value) { throw uoe(); } @Override - public boolean replace( Object key, Object oldValue, Object newValue ) - { + public boolean replace(Object key, Object oldValue, Object newValue) { throw uoe(); } @Override - public Object replace( Object key, Object value ) - { + public Object replace(Object key, Object value) { throw uoe(); } @Override - public Object computeIfAbsent( Object key, Function mappingFunction ) - { + public Object computeIfAbsent(Object key, Function mappingFunction) { throw uoe(); } @Override - public Object computeIfPresent( Object key, BiFunction remappingFunction ) - { + public Object computeIfPresent(Object key, BiFunction remappingFunction) { throw uoe(); } @Override - public Object compute( Object key, BiFunction remappingFunction ) - { + public Object compute(Object key, BiFunction remappingFunction) { throw uoe(); } @Override - public Object merge( Object key, Object value, BiFunction remappingFunction ) - { + public Object merge(Object key, Object value, BiFunction remappingFunction) { throw uoe(); } } - private static class Map1 extends AbstractImmutableMap - { + private static class Map1 extends AbstractImmutableMap { private final Entry entry; - private Map1( K key, V value ) - { - this.entry = new SimpleImmutableEntry<>( key, value ); + private Map1(K key, V value) { + this.entry = new SimpleImmutableEntry<>(key, value); } @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { int index = 0; + @Override - public boolean hasNext() - { + public boolean hasNext() { return index == 0; } @Override - public Entry next() - { - if ( index++ == 0 ) - { + public Entry next() { + if (index++ == 0) { return entry; } throw new NoSuchElementException(); @@ -581,47 +474,38 @@ class ImmutableCollections } @Override - public int size() - { + public int size() { return 1; } }; } } - private static class MapN extends AbstractImmutableMap - { + private static class MapN extends AbstractImmutableMap { private final Object[] entries; - private MapN( Map map ) - { + private MapN(Map map) { entries = map != null ? map.entrySet().toArray() : new Object[0]; } @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { int index = 0; + @Override - public boolean hasNext() - { + public boolean hasNext() { return index < entries.length; } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - public Entry next() - { - if ( index < entries.length ) - { - return ( Entry ) entries[index++]; + public Entry next() { + if (index < entries.length) { + return (Entry) entries[index++]; } throw new NoSuchElementException(); } @@ -629,117 +513,93 @@ class ImmutableCollections } @Override - public int size() - { + public int size() { return entries.length; } }; } } - private abstract static class AbstractImmutableMap - extends AbstractMap - implements Serializable - { + private abstract static class AbstractImmutableMap extends AbstractMap implements Serializable { @Override - public void replaceAll( BiFunction function ) - { + public void replaceAll(BiFunction function) { throw uoe(); } @Override - public V putIfAbsent( K key, V value ) - { + public V putIfAbsent(K key, V value) { throw uoe(); } @Override - public boolean remove( Object key, Object value ) - { + public boolean remove(Object key, Object value) { throw uoe(); } @Override - public boolean replace( K key, V oldValue, V newValue ) - { + public boolean replace(K key, V oldValue, V newValue) { throw uoe(); } @Override - public V replace( K key, V value ) - { + public V replace(K key, V value) { throw uoe(); } @Override - public V computeIfAbsent( K key, Function mappingFunction ) - { + public V computeIfAbsent(K key, Function mappingFunction) { throw uoe(); } @Override - public V computeIfPresent( K key, BiFunction remappingFunction ) - { + public V computeIfPresent(K key, BiFunction remappingFunction) { throw uoe(); } @Override - public V compute( K key, BiFunction remappingFunction ) - { + public V compute(K key, BiFunction remappingFunction) { throw uoe(); } @Override - public V merge( K key, V value, BiFunction remappingFunction ) - { + public V merge(K key, V value, BiFunction remappingFunction) { throw uoe(); } } - private abstract static class AbstractImmutableSet - extends AbstractSet - implements Serializable - { + private abstract static class AbstractImmutableSet extends AbstractSet implements Serializable { @Override - public boolean removeAll( Collection c ) - { + public boolean removeAll(Collection c) { throw uoe(); } @Override - public boolean add( E e ) - { + public boolean add(E e) { throw uoe(); } @Override - public boolean remove( Object o ) - { + public boolean remove(Object o) { throw uoe(); } @Override - public boolean retainAll( Collection c ) - { + public boolean retainAll(Collection c) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public boolean removeIf( Predicate filter ) - { + public boolean removeIf(Predicate filter) { throw uoe(); } } - private static UnsupportedOperationException uoe() - { + private static UnsupportedOperationException uoe() { return new UnsupportedOperationException(); } - } diff --git a/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocation.java b/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocation.java index 8be05dbaa4..3e9e9e377a 100644 --- a/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocation.java +++ b/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocation.java @@ -1,5 +1,3 @@ -package org.apache.maven.api.model; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.api.model; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.api.model; import java.io.Serializable; import java.util.Collection; @@ -28,71 +27,59 @@ import java.util.Map; /** * Class InputLocation. */ -public class InputLocation - implements Serializable, InputLocationTracker -{ +public class InputLocation implements Serializable, InputLocationTracker { private final int lineNumber; private final int columnNumber; private final InputSource source; private final Map locations; - public InputLocation( InputSource source ) - { + public InputLocation(InputSource source) { this.lineNumber = -1; this.columnNumber = -1; this.source = source; - this.locations = Collections.singletonMap( 0, this ); + this.locations = Collections.singletonMap(0, this); } - public InputLocation( int lineNumber, int columnNumber ) - { - this( lineNumber, columnNumber, null, null ); + public InputLocation(int lineNumber, int columnNumber) { + this(lineNumber, columnNumber, null, null); } - public InputLocation( int lineNumber, int columnNumber, InputSource source ) - { - this( lineNumber, columnNumber, source, null ); + public InputLocation(int lineNumber, int columnNumber, InputSource source) { + this(lineNumber, columnNumber, source, null); } - public InputLocation( int lineNumber, int columnNumber, InputSource source, Object selfLocationKey ) - { + public InputLocation(int lineNumber, int columnNumber, InputSource source, Object selfLocationKey) { this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.source = source; - this.locations = selfLocationKey != null - ? Collections.singletonMap( selfLocationKey, this ) : Collections.emptyMap(); + this.locations = + selfLocationKey != null ? Collections.singletonMap(selfLocationKey, this) : Collections.emptyMap(); } - public InputLocation( int lineNumber, int columnNumber, InputSource source, Map locations ) - { + public InputLocation(int lineNumber, int columnNumber, InputSource source, Map locations) { this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.source = source; - this.locations = ImmutableCollections.copy( locations ); + this.locations = ImmutableCollections.copy(locations); } - public int getLineNumber() - { + public int getLineNumber() { return lineNumber; } - public int getColumnNumber() - { + public int getColumnNumber() { return columnNumber; } - public InputSource getSource() - { + public InputSource getSource() { return source; } - public InputLocation getLocation( Object key ) - { - return locations != null ? locations.get( key ) : null; + public InputLocation getLocation(Object key) { + return locations != null ? locations.get(key) : null; } - public Map getLocations() - { + public Map getLocations() { return locations; } @@ -104,37 +91,28 @@ public class InputLocation * @param sourceDominant the boolean indicating of {@code source} is dominant compared to {@code target} * @return the merged location */ - public static InputLocation merge( InputLocation target, InputLocation source, boolean sourceDominant ) - { - if ( source == null ) - { + public static InputLocation merge(InputLocation target, InputLocation source, boolean sourceDominant) { + if (source == null) { return target; - } - else if ( target == null ) - { + } else if (target == null) { return source; } Map locations; Map sourceLocations = source.locations; Map targetLocations = target.locations; - if ( sourceLocations == null ) - { + if (sourceLocations == null) { locations = targetLocations; - } - else if ( targetLocations == null ) - { + } else if (targetLocations == null) { locations = sourceLocations; - } - else - { + } else { locations = new LinkedHashMap<>(); - locations.putAll( sourceDominant ? targetLocations : sourceLocations ); - locations.putAll( sourceDominant ? sourceLocations : targetLocations ); + locations.putAll(sourceDominant ? targetLocations : sourceLocations); + locations.putAll(sourceDominant ? sourceLocations : targetLocations); } - return new InputLocation( target.getLineNumber(), target.getColumnNumber(), target.getSource(), locations ); - } //-- InputLocation merge( InputLocation, InputLocation, boolean ) + return new InputLocation(target.getLineNumber(), target.getColumnNumber(), target.getSource(), locations); + } // -- InputLocation merge( InputLocation, InputLocation, boolean ) /** * Merges the {@code source} location into the {@code target} location. @@ -145,66 +123,50 @@ public class InputLocation * @param indices the list of integers for the indices * @return the merged location */ - public static InputLocation merge( InputLocation target, InputLocation source, Collection indices ) - { - if ( source == null ) - { + public static InputLocation merge(InputLocation target, InputLocation source, Collection indices) { + if (source == null) { return target; - } - else if ( target == null ) - { + } else if (target == null) { return source; } Map locations; Map sourceLocations = source.locations; Map targetLocations = target.locations; - if ( sourceLocations == null ) - { + if (sourceLocations == null) { locations = targetLocations; - } - else if ( targetLocations == null ) - { + } else if (targetLocations == null) { locations = sourceLocations; - } - else - { + } else { locations = new LinkedHashMap<>(); - for ( int index : indices ) - { + for (int index : indices) { InputLocation location; - if ( index < 0 ) - { - location = sourceLocations.get( ~index ); + if (index < 0) { + location = sourceLocations.get(~index); + } else { + location = targetLocations.get(index); } - else - { - location = targetLocations.get( index ); - } - locations.put( locations.size(), location ); + locations.put(locations.size(), location); } } - return new InputLocation( target.getLineNumber(), target.getColumnNumber(), target.getSource(), locations ); - } //-- InputLocation merge( InputLocation, InputLocation, java.util.Collection ) + return new InputLocation(target.getLineNumber(), target.getColumnNumber(), target.getSource(), locations); + } // -- InputLocation merge( InputLocation, InputLocation, java.util.Collection ) /** * Class StringFormatter. * * @version $Revision$ $Date$ */ - public interface StringFormatter - { + public interface StringFormatter { - //-----------/ - //- Methods -/ - //-----------/ + // -----------/ + // - Methods -/ + // -----------/ /** * Method toString. */ - String toString( InputLocation location ); - + String toString(InputLocation location); } - } diff --git a/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocationTracker.java b/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocationTracker.java index e90934813a..ce4240e053 100644 --- a/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocationTracker.java +++ b/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocationTracker.java @@ -1,5 +1,3 @@ -package org.apache.maven.api.model; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,8 @@ package org.apache.maven.api.model; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.api.model; -public interface InputLocationTracker -{ - InputLocation getLocation( Object field ); +public interface InputLocationTracker { + InputLocation getLocation(Object field); } - diff --git a/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputSource.java b/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputSource.java index 37cb13c1fa..e192dcf8aa 100644 --- a/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputSource.java +++ b/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.api.model; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,21 +16,19 @@ package org.apache.maven.api.model; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.api.model; import java.io.Serializable; /** * Class InputSource. */ -public class InputSource - implements Serializable -{ +public class InputSource implements Serializable { private final String modelId; private final String location; - public InputSource( String modelId, String location ) - { + public InputSource(String modelId, String location) { this.modelId = modelId; this.location = location; } @@ -42,8 +38,7 @@ public class InputSource * * @return the location */ - public String getLocation() - { + public String getLocation() { return this.location; } @@ -52,14 +47,12 @@ public class InputSource * * @return the model id */ - public String getModelId() - { + public String getModelId() { return this.modelId; } @Override - public String toString() - { + public String toString() { return getModelId() + " " + getLocation(); } } diff --git a/api/maven-api-model/src/main/java/org/apache/maven/api/model/package-info.java b/api/maven-api-model/src/main/java/org/apache/maven/api/model/package-info.java index 0924cab90c..854562874e 100644 --- a/api/maven-api-model/src/main/java/org/apache/maven/api/model/package-info.java +++ b/api/maven-api-model/src/main/java/org/apache/maven/api/model/package-info.java @@ -4,22 +4,3 @@ * The root class is {@link org.apache.maven.api.model.Model}. */ package org.apache.maven.api.model; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ diff --git a/api/maven-api-settings/pom.xml b/api/maven-api-settings/pom.xml index c3db8c37c6..774fbd5b67 100644 --- a/api/maven-api-settings/pom.xml +++ b/api/maven-api-settings/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 diff --git a/api/maven-api-settings/src/main/java/org/apache/maven/api/settings/ImmutableCollections.java b/api/maven-api-settings/src/main/java/org/apache/maven/api/settings/ImmutableCollections.java index bdd5567b85..78d5f2de67 100644 --- a/api/maven-api-settings/src/main/java/org/apache/maven/api/settings/ImmutableCollections.java +++ b/api/maven-api-settings/src/main/java/org/apache/maven/api/settings/ImmutableCollections.java @@ -1,5 +1,3 @@ -package org.apache.maven.api.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.api.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.api.settings; import java.io.Serializable; import java.util.AbstractList; @@ -38,541 +37,435 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; -class ImmutableCollections -{ +class ImmutableCollections { - private static final List EMPTY_LIST = new AbstractImmutableList() - { + private static final List EMPTY_LIST = new AbstractImmutableList() { @Override - public Object get( int index ) - { + public Object get(int index) { throw new IndexOutOfBoundsException(); } + @Override - public int size() - { + public int size() { return 0; } }; - private static final Map EMPTY_MAP = new AbstractImmutableMap() - { + private static final Map EMPTY_MAP = new AbstractImmutableMap() { @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { @Override - public boolean hasNext() - { + public boolean hasNext() { return false; } + @Override - public Entry next() - { + public Entry next() { throw new NoSuchElementException(); } }; } + @Override - public int size() - { + public int size() { return 0; } }; } }; - static List copy( Collection collection ) - { - if ( collection == null ) - { + static List copy(Collection collection) { + if (collection == null) { return emptyList(); - } - else if ( collection instanceof AbstractImmutableList ) - { - return ( List ) collection; - } - else - { - switch ( collection.size() ) - { + } else if (collection instanceof AbstractImmutableList) { + return (List) collection; + } else { + switch (collection.size()) { case 0: return emptyList(); case 1: - return singletonList( collection.iterator().next() ); + return singletonList(collection.iterator().next()); case 2: Iterator it = collection.iterator(); - return new List2<>( it.next(), it.next() ); + return new List2<>(it.next(), it.next()); default: - return new ListN<>( collection ); + return new ListN<>(collection); } } } - @SuppressWarnings( "unchecked" ) - static List emptyList() - { - return ( List ) EMPTY_LIST; + @SuppressWarnings("unchecked") + static List emptyList() { + return (List) EMPTY_LIST; } - static List singletonList( E element ) - { - return new List1<>( element ); + static List singletonList(E element) { + return new List1<>(element); } - static Map copy( Map map ) - { - if ( map == null ) - { + static Map copy(Map map) { + if (map == null) { return emptyMap(); - } - else if ( map instanceof AbstractImmutableMap ) - { + } else if (map instanceof AbstractImmutableMap) { return map; - } - else - { - switch ( map.size() ) - { + } else { + switch (map.size()) { case 0: return emptyMap(); case 1: Map.Entry entry = map.entrySet().iterator().next(); - return singletonMap( entry.getKey(), entry.getValue() ); + return singletonMap(entry.getKey(), entry.getValue()); default: - return new MapN<>( map ); + return new MapN<>(map); } } } - @SuppressWarnings( "unchecked" ) - static Map emptyMap() - { - return ( Map ) EMPTY_MAP; + @SuppressWarnings("unchecked") + static Map emptyMap() { + return (Map) EMPTY_MAP; } - static Map singletonMap( K key, V value ) - { - return new Map1<>( key, value ); + static Map singletonMap(K key, V value) { + return new Map1<>(key, value); } - static Properties copy( Properties properties ) - { - if ( properties instanceof ROProperties ) - { + static Properties copy(Properties properties) { + if (properties instanceof ROProperties) { return properties; } - return new ROProperties( properties ); + return new ROProperties(properties); } - private static class List1 extends AbstractImmutableList - { + private static class List1 extends AbstractImmutableList { private final E element; - private List1( E element ) - { + private List1(E element) { this.element = element; } @Override - public E get( int index ) - { - if ( index == 0 ) - { + public E get(int index) { + if (index == 0) { return element; } - throw outOfBounds( index ); + throw outOfBounds(index); } @Override - public int size() - { + public int size() { return 1; } } - private static class List2 extends AbstractImmutableList - { + private static class List2 extends AbstractImmutableList { private final E element1; private final E element2; - private List2( E element1, E element2 ) - { + private List2(E element1, E element2) { this.element1 = element1; this.element2 = element2; } @Override - public E get( int index ) - { - if ( index == 0 ) - { + public E get(int index) { + if (index == 0) { return element1; - } - else if ( index == 1 ) - { + } else if (index == 1) { return element2; } - throw outOfBounds( index ); + throw outOfBounds(index); } @Override - public int size() - { + public int size() { return 2; } } - private static class ListN extends AbstractImmutableList - { + private static class ListN extends AbstractImmutableList { private final Object[] elements; - private ListN( Collection elements ) - { + private ListN(Collection elements) { this.elements = elements.toArray(); } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - public E get( int index ) - { - return ( E ) elements[ index ]; + public E get(int index) { + return (E) elements[index]; } @Override - public int size() - { + public int size() { return elements.length; } } - private abstract static class AbstractImmutableList - extends AbstractList - implements RandomAccess, Serializable - { + private abstract static class AbstractImmutableList extends AbstractList + implements RandomAccess, Serializable { @Override - public boolean add( E e ) - { + public boolean add(E e) { throw uoe(); } @Override - public boolean remove( Object o ) - { + public boolean remove(Object o) { throw uoe(); } @Override - public boolean addAll( Collection c ) - { + public boolean addAll(Collection c) { throw uoe(); } @Override - public boolean removeAll( Collection c ) - { + public boolean removeAll(Collection c) { throw uoe(); } @Override - public boolean retainAll( Collection c ) - { + public boolean retainAll(Collection c) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public boolean removeIf( Predicate filter ) - { + public boolean removeIf(Predicate filter) { throw uoe(); } @Override - public void replaceAll( UnaryOperator operator ) - { + public void replaceAll(UnaryOperator operator) { throw uoe(); } @Override - public void sort( Comparator c ) - { + public void sort(Comparator c) { throw uoe(); } @Override - public Iterator iterator() - { - return new Itr( 0 ); + public Iterator iterator() { + return new Itr(0); } @Override - public ListIterator listIterator() - { - return new Itr( 0 ); + public ListIterator listIterator() { + return new Itr(0); } @Override - public ListIterator listIterator( int index ) - { - if ( index < 0 || index > size() ) - { - throw outOfBounds( index ); + public ListIterator listIterator(int index) { + if (index < 0 || index > size()) { + throw outOfBounds(index); } - return new Itr( index ); + return new Itr(index); } @Override - public List subList( int fromIndex, int toIndex ) - { - if ( fromIndex < 0 ) - { - throw new IndexOutOfBoundsException( "fromIndex = " + fromIndex ); + public List subList(int fromIndex, int toIndex) { + if (fromIndex < 0) { + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } - if ( toIndex > size() ) - { - throw new IndexOutOfBoundsException( "toIndex = " + toIndex ); + if (toIndex > size()) { + throw new IndexOutOfBoundsException("toIndex = " + toIndex); } - if ( fromIndex > toIndex ) - { - throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")" ); + if (fromIndex > toIndex) { + throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } - return new SubList( fromIndex, toIndex ); + return new SubList(fromIndex, toIndex); } - protected IndexOutOfBoundsException outOfBounds( int index ) - { - return new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size() ); + protected IndexOutOfBoundsException outOfBounds(int index) { + return new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } - private class SubList extends AbstractImmutableList - { + private class SubList extends AbstractImmutableList { private final int fromIndex; private final int toIndex; - private SubList( int fromIndex, int toIndex ) - { + private SubList(int fromIndex, int toIndex) { this.fromIndex = fromIndex; this.toIndex = toIndex; } @Override - public E get( int index ) - { - if ( index < 0 || index > size() ) - { - throw outOfBounds( index ); + public E get(int index) { + if (index < 0 || index > size()) { + throw outOfBounds(index); } - return AbstractImmutableList.this.get( fromIndex + index ); + return AbstractImmutableList.this.get(fromIndex + index); } @Override - public int size() - { + public int size() { return toIndex - fromIndex; } } - private class Itr implements ListIterator - { + private class Itr implements ListIterator { int index; - private Itr( int index ) - { + private Itr(int index) { this.index = index; } @Override - public boolean hasNext() - { + public boolean hasNext() { return index < size(); } @Override - public E next() - { - return get( index++ ); + public E next() { + return get(index++); } @Override - public boolean hasPrevious() - { + public boolean hasPrevious() { return index > 0; } @Override - public E previous() - { - return get( --index ); + public E previous() { + return get(--index); } @Override - public int nextIndex() - { + public int nextIndex() { return index; } @Override - public int previousIndex() - { + public int previousIndex() { return index - 1; } @Override - public void remove() - { + public void remove() { throw uoe(); } @Override - public void set( E e ) - { + public void set(E e) { throw uoe(); } @Override - public void add( E e ) - { + public void add(E e) { throw uoe(); } } } - private static class ROProperties extends Properties - { - private ROProperties( Properties props ) - { + private static class ROProperties extends Properties { + private ROProperties(Properties props) { super(); - if ( props != null ) - { + if (props != null) { // Do not use super.putAll, as it may delegate to put which throws an UnsupportedOperationException - for ( Map.Entry e : props.entrySet() ) - { - super.put( e.getKey(), e.getValue() ); + for (Map.Entry e : props.entrySet()) { + super.put(e.getKey(), e.getValue()); } } } @Override - public Object put( Object key, Object value ) - { + public Object put(Object key, Object value) { throw uoe(); } @Override - public Object remove( Object key ) - { + public Object remove(Object key) { throw uoe(); } @Override - public void putAll( Map t ) - { + public void putAll(Map t) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public void replaceAll( BiFunction function ) - { + public void replaceAll(BiFunction function) { throw uoe(); } @Override - public Object putIfAbsent( Object key, Object value ) - { + public Object putIfAbsent(Object key, Object value) { throw uoe(); } @Override - public boolean remove( Object key, Object value ) - { + public boolean remove(Object key, Object value) { throw uoe(); } @Override - public boolean replace( Object key, Object oldValue, Object newValue ) - { + public boolean replace(Object key, Object oldValue, Object newValue) { throw uoe(); } @Override - public Object replace( Object key, Object value ) - { + public Object replace(Object key, Object value) { throw uoe(); } @Override - public Object computeIfAbsent( Object key, Function mappingFunction ) - { + public Object computeIfAbsent(Object key, Function mappingFunction) { throw uoe(); } @Override - public Object computeIfPresent( Object key, BiFunction remappingFunction ) - { + public Object computeIfPresent(Object key, BiFunction remappingFunction) { throw uoe(); } @Override - public Object compute( Object key, BiFunction remappingFunction ) - { + public Object compute(Object key, BiFunction remappingFunction) { throw uoe(); } @Override - public Object merge( Object key, Object value, BiFunction remappingFunction ) - { + public Object merge(Object key, Object value, BiFunction remappingFunction) { throw uoe(); } } - private static class Map1 extends AbstractImmutableMap - { + private static class Map1 extends AbstractImmutableMap { private final Entry entry; - private Map1( K key, V value ) - { - this.entry = new SimpleImmutableEntry<>( key, value ); + private Map1(K key, V value) { + this.entry = new SimpleImmutableEntry<>(key, value); } @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { int index = 0; + @Override - public boolean hasNext() - { + public boolean hasNext() { return index == 0; } @Override - public Entry next() - { - if ( index++ == 0 ) - { + public Entry next() { + if (index++ == 0) { return entry; } throw new NoSuchElementException(); @@ -581,47 +474,38 @@ class ImmutableCollections } @Override - public int size() - { + public int size() { return 1; } }; } } - private static class MapN extends AbstractImmutableMap - { + private static class MapN extends AbstractImmutableMap { private final Object[] entries; - private MapN( Map map ) - { + private MapN(Map map) { entries = map != null ? map.entrySet().toArray() : new Object[0]; } @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { int index = 0; + @Override - public boolean hasNext() - { + public boolean hasNext() { return index < entries.length; } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - public Entry next() - { - if ( index < entries.length ) - { - return ( Entry ) entries[index++]; + public Entry next() { + if (index < entries.length) { + return (Entry) entries[index++]; } throw new NoSuchElementException(); } @@ -629,117 +513,93 @@ class ImmutableCollections } @Override - public int size() - { + public int size() { return entries.length; } }; } } - private abstract static class AbstractImmutableMap - extends AbstractMap - implements Serializable - { + private abstract static class AbstractImmutableMap extends AbstractMap implements Serializable { @Override - public void replaceAll( BiFunction function ) - { + public void replaceAll(BiFunction function) { throw uoe(); } @Override - public V putIfAbsent( K key, V value ) - { + public V putIfAbsent(K key, V value) { throw uoe(); } @Override - public boolean remove( Object key, Object value ) - { + public boolean remove(Object key, Object value) { throw uoe(); } @Override - public boolean replace( K key, V oldValue, V newValue ) - { + public boolean replace(K key, V oldValue, V newValue) { throw uoe(); } @Override - public V replace( K key, V value ) - { + public V replace(K key, V value) { throw uoe(); } @Override - public V computeIfAbsent( K key, Function mappingFunction ) - { + public V computeIfAbsent(K key, Function mappingFunction) { throw uoe(); } @Override - public V computeIfPresent( K key, BiFunction remappingFunction ) - { + public V computeIfPresent(K key, BiFunction remappingFunction) { throw uoe(); } @Override - public V compute( K key, BiFunction remappingFunction ) - { + public V compute(K key, BiFunction remappingFunction) { throw uoe(); } @Override - public V merge( K key, V value, BiFunction remappingFunction ) - { + public V merge(K key, V value, BiFunction remappingFunction) { throw uoe(); } } - private abstract static class AbstractImmutableSet - extends AbstractSet - implements Serializable - { + private abstract static class AbstractImmutableSet extends AbstractSet implements Serializable { @Override - public boolean removeAll( Collection c ) - { + public boolean removeAll(Collection c) { throw uoe(); } @Override - public boolean add( E e ) - { + public boolean add(E e) { throw uoe(); } @Override - public boolean remove( Object o ) - { + public boolean remove(Object o) { throw uoe(); } @Override - public boolean retainAll( Collection c ) - { + public boolean retainAll(Collection c) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public boolean removeIf( Predicate filter ) - { + public boolean removeIf(Predicate filter) { throw uoe(); } } - private static UnsupportedOperationException uoe() - { + private static UnsupportedOperationException uoe() { return new UnsupportedOperationException(); } - } diff --git a/api/maven-api-toolchain/pom.xml b/api/maven-api-toolchain/pom.xml index 6b87b89cde..e0ea75a1d3 100644 --- a/api/maven-api-toolchain/pom.xml +++ b/api/maven-api-toolchain/pom.xml @@ -1,5 +1,4 @@ - - - - maven-api + 4.0.0 + + org.apache.maven + maven-api + 4.0.0-alpha-3-SNAPSHOT + + + maven-api-toolchain + + Maven API Toolchain + Maven API Toolchain model. + + + + org.apache.maven + maven-api-xml + 4.0.0-alpha-3-SNAPSHOT + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + attach-mdo + + attach-artifact + + + + + src/main/mdo/toolchains.mdo + mdo + + + + + + + org.apache.maven - 4.0.0-alpha-3-SNAPSHOT - - 4.0.0 - - maven-api-toolchain - - Maven API Toolchain - Maven API Toolchain model. - - - - org.apache.maven - maven-api-xml - 4.0.0-alpha-3-SNAPSHOT - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 3.2.0 - - - attach-mdo - - attach-artifact - - - - - src/main/mdo/toolchains.mdo - mdo - - - - - - - - org.apache.maven - modello-plugin-velocity - - 1.1.0 - - src/main/mdo/toolchains.mdo - - - - - - packageModelV4=org.apache.maven.api.toolchain - - - - - modello - - velocity - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/package-info.java - - - - - + modello-plugin-velocity + + 1.1.0 + + src/main/mdo/toolchains.mdo + + + + + + packageModelV4=org.apache.maven.api.toolchain + + + + + modello + + velocity + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/package-info.java + + + + + diff --git a/api/maven-api-toolchain/src/main/java/org/apache/maven/api/toolchain/ImmutableCollections.java b/api/maven-api-toolchain/src/main/java/org/apache/maven/api/toolchain/ImmutableCollections.java index 8e95ea98c9..3f53f5d677 100644 --- a/api/maven-api-toolchain/src/main/java/org/apache/maven/api/toolchain/ImmutableCollections.java +++ b/api/maven-api-toolchain/src/main/java/org/apache/maven/api/toolchain/ImmutableCollections.java @@ -1,5 +1,3 @@ -package org.apache.maven.api.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.api.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.api.toolchain; import java.io.Serializable; import java.util.AbstractList; @@ -38,541 +37,435 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; -class ImmutableCollections -{ +class ImmutableCollections { - private static final List EMPTY_LIST = new AbstractImmutableList() - { + private static final List EMPTY_LIST = new AbstractImmutableList() { @Override - public Object get( int index ) - { + public Object get(int index) { throw new IndexOutOfBoundsException(); } + @Override - public int size() - { + public int size() { return 0; } }; - private static final Map EMPTY_MAP = new AbstractImmutableMap() - { + private static final Map EMPTY_MAP = new AbstractImmutableMap() { @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { @Override - public boolean hasNext() - { + public boolean hasNext() { return false; } + @Override - public Entry next() - { + public Entry next() { throw new NoSuchElementException(); } }; } + @Override - public int size() - { + public int size() { return 0; } }; } }; - static List copy( Collection collection ) - { - if ( collection == null ) - { + static List copy(Collection collection) { + if (collection == null) { return emptyList(); - } - else if ( collection instanceof AbstractImmutableList ) - { - return ( List ) collection; - } - else - { - switch ( collection.size() ) - { + } else if (collection instanceof AbstractImmutableList) { + return (List) collection; + } else { + switch (collection.size()) { case 0: return emptyList(); case 1: - return singletonList( collection.iterator().next() ); + return singletonList(collection.iterator().next()); case 2: Iterator it = collection.iterator(); - return new List2<>( it.next(), it.next() ); + return new List2<>(it.next(), it.next()); default: - return new ListN<>( collection ); + return new ListN<>(collection); } } } - @SuppressWarnings( "unchecked" ) - static List emptyList() - { - return ( List ) EMPTY_LIST; + @SuppressWarnings("unchecked") + static List emptyList() { + return (List) EMPTY_LIST; } - static List singletonList( E element ) - { - return new List1<>( element ); + static List singletonList(E element) { + return new List1<>(element); } - static Map copy( Map map ) - { - if ( map == null ) - { + static Map copy(Map map) { + if (map == null) { return emptyMap(); - } - else if ( map instanceof AbstractImmutableMap ) - { + } else if (map instanceof AbstractImmutableMap) { return map; - } - else - { - switch ( map.size() ) - { + } else { + switch (map.size()) { case 0: return emptyMap(); case 1: Map.Entry entry = map.entrySet().iterator().next(); - return singletonMap( entry.getKey(), entry.getValue() ); + return singletonMap(entry.getKey(), entry.getValue()); default: - return new MapN<>( map ); + return new MapN<>(map); } } } - @SuppressWarnings( "unchecked" ) - static Map emptyMap() - { - return ( Map ) EMPTY_MAP; + @SuppressWarnings("unchecked") + static Map emptyMap() { + return (Map) EMPTY_MAP; } - static Map singletonMap( K key, V value ) - { - return new Map1<>( key, value ); + static Map singletonMap(K key, V value) { + return new Map1<>(key, value); } - static Properties copy( Properties properties ) - { - if ( properties instanceof ROProperties ) - { + static Properties copy(Properties properties) { + if (properties instanceof ROProperties) { return properties; } - return new ROProperties( properties ); + return new ROProperties(properties); } - private static class List1 extends AbstractImmutableList - { + private static class List1 extends AbstractImmutableList { private final E element; - private List1( E element ) - { + private List1(E element) { this.element = element; } @Override - public E get( int index ) - { - if ( index == 0 ) - { + public E get(int index) { + if (index == 0) { return element; } - throw outOfBounds( index ); + throw outOfBounds(index); } @Override - public int size() - { + public int size() { return 1; } } - private static class List2 extends AbstractImmutableList - { + private static class List2 extends AbstractImmutableList { private final E element1; private final E element2; - private List2( E element1, E element2 ) - { + private List2(E element1, E element2) { this.element1 = element1; this.element2 = element2; } @Override - public E get( int index ) - { - if ( index == 0 ) - { + public E get(int index) { + if (index == 0) { return element1; - } - else if ( index == 1 ) - { + } else if (index == 1) { return element2; } - throw outOfBounds( index ); + throw outOfBounds(index); } @Override - public int size() - { + public int size() { return 2; } } - private static class ListN extends AbstractImmutableList - { + private static class ListN extends AbstractImmutableList { private final Object[] elements; - private ListN( Collection elements ) - { + private ListN(Collection elements) { this.elements = elements.toArray(); } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - public E get( int index ) - { - return ( E ) elements[ index ]; + public E get(int index) { + return (E) elements[index]; } @Override - public int size() - { + public int size() { return elements.length; } } - private abstract static class AbstractImmutableList - extends AbstractList - implements RandomAccess, Serializable - { + private abstract static class AbstractImmutableList extends AbstractList + implements RandomAccess, Serializable { @Override - public boolean add( E e ) - { + public boolean add(E e) { throw uoe(); } @Override - public boolean remove( Object o ) - { + public boolean remove(Object o) { throw uoe(); } @Override - public boolean addAll( Collection c ) - { + public boolean addAll(Collection c) { throw uoe(); } @Override - public boolean removeAll( Collection c ) - { + public boolean removeAll(Collection c) { throw uoe(); } @Override - public boolean retainAll( Collection c ) - { + public boolean retainAll(Collection c) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public boolean removeIf( Predicate filter ) - { + public boolean removeIf(Predicate filter) { throw uoe(); } @Override - public void replaceAll( UnaryOperator operator ) - { + public void replaceAll(UnaryOperator operator) { throw uoe(); } @Override - public void sort( Comparator c ) - { + public void sort(Comparator c) { throw uoe(); } @Override - public Iterator iterator() - { - return new Itr( 0 ); + public Iterator iterator() { + return new Itr(0); } @Override - public ListIterator listIterator() - { - return new Itr( 0 ); + public ListIterator listIterator() { + return new Itr(0); } @Override - public ListIterator listIterator( int index ) - { - if ( index < 0 || index > size() ) - { - throw outOfBounds( index ); + public ListIterator listIterator(int index) { + if (index < 0 || index > size()) { + throw outOfBounds(index); } - return new Itr( index ); + return new Itr(index); } @Override - public List subList( int fromIndex, int toIndex ) - { - if ( fromIndex < 0 ) - { - throw new IndexOutOfBoundsException( "fromIndex = " + fromIndex ); + public List subList(int fromIndex, int toIndex) { + if (fromIndex < 0) { + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } - if ( toIndex > size() ) - { - throw new IndexOutOfBoundsException( "toIndex = " + toIndex ); + if (toIndex > size()) { + throw new IndexOutOfBoundsException("toIndex = " + toIndex); } - if ( fromIndex > toIndex ) - { - throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")" ); + if (fromIndex > toIndex) { + throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } - return new SubList( fromIndex, toIndex ); + return new SubList(fromIndex, toIndex); } - protected IndexOutOfBoundsException outOfBounds( int index ) - { - return new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size() ); + protected IndexOutOfBoundsException outOfBounds(int index) { + return new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } - private class SubList extends AbstractImmutableList - { + private class SubList extends AbstractImmutableList { private final int fromIndex; private final int toIndex; - private SubList( int fromIndex, int toIndex ) - { + private SubList(int fromIndex, int toIndex) { this.fromIndex = fromIndex; this.toIndex = toIndex; } @Override - public E get( int index ) - { - if ( index < 0 || index > size() ) - { - throw outOfBounds( index ); + public E get(int index) { + if (index < 0 || index > size()) { + throw outOfBounds(index); } - return AbstractImmutableList.this.get( fromIndex + index ); + return AbstractImmutableList.this.get(fromIndex + index); } @Override - public int size() - { + public int size() { return toIndex - fromIndex; } } - private class Itr implements ListIterator - { + private class Itr implements ListIterator { int index; - private Itr( int index ) - { + private Itr(int index) { this.index = index; } @Override - public boolean hasNext() - { + public boolean hasNext() { return index < size(); } @Override - public E next() - { - return get( index++ ); + public E next() { + return get(index++); } @Override - public boolean hasPrevious() - { + public boolean hasPrevious() { return index > 0; } @Override - public E previous() - { - return get( --index ); + public E previous() { + return get(--index); } @Override - public int nextIndex() - { + public int nextIndex() { return index; } @Override - public int previousIndex() - { + public int previousIndex() { return index - 1; } @Override - public void remove() - { + public void remove() { throw uoe(); } @Override - public void set( E e ) - { + public void set(E e) { throw uoe(); } @Override - public void add( E e ) - { + public void add(E e) { throw uoe(); } } } - private static class ROProperties extends Properties - { - private ROProperties( Properties props ) - { + private static class ROProperties extends Properties { + private ROProperties(Properties props) { super(); - if ( props != null ) - { + if (props != null) { // Do not use super.putAll, as it may delegate to put which throws an UnsupportedOperationException - for ( Map.Entry e : props.entrySet() ) - { - super.put( e.getKey(), e.getValue() ); + for (Map.Entry e : props.entrySet()) { + super.put(e.getKey(), e.getValue()); } } } @Override - public Object put( Object key, Object value ) - { + public Object put(Object key, Object value) { throw uoe(); } @Override - public Object remove( Object key ) - { + public Object remove(Object key) { throw uoe(); } @Override - public void putAll( Map t ) - { + public void putAll(Map t) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public void replaceAll( BiFunction function ) - { + public void replaceAll(BiFunction function) { throw uoe(); } @Override - public Object putIfAbsent( Object key, Object value ) - { + public Object putIfAbsent(Object key, Object value) { throw uoe(); } @Override - public boolean remove( Object key, Object value ) - { + public boolean remove(Object key, Object value) { throw uoe(); } @Override - public boolean replace( Object key, Object oldValue, Object newValue ) - { + public boolean replace(Object key, Object oldValue, Object newValue) { throw uoe(); } @Override - public Object replace( Object key, Object value ) - { + public Object replace(Object key, Object value) { throw uoe(); } @Override - public Object computeIfAbsent( Object key, Function mappingFunction ) - { + public Object computeIfAbsent(Object key, Function mappingFunction) { throw uoe(); } @Override - public Object computeIfPresent( Object key, BiFunction remappingFunction ) - { + public Object computeIfPresent(Object key, BiFunction remappingFunction) { throw uoe(); } @Override - public Object compute( Object key, BiFunction remappingFunction ) - { + public Object compute(Object key, BiFunction remappingFunction) { throw uoe(); } @Override - public Object merge( Object key, Object value, BiFunction remappingFunction ) - { + public Object merge(Object key, Object value, BiFunction remappingFunction) { throw uoe(); } } - private static class Map1 extends AbstractImmutableMap - { + private static class Map1 extends AbstractImmutableMap { private final Entry entry; - private Map1( K key, V value ) - { - this.entry = new SimpleImmutableEntry<>( key, value ); + private Map1(K key, V value) { + this.entry = new SimpleImmutableEntry<>(key, value); } @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { int index = 0; + @Override - public boolean hasNext() - { + public boolean hasNext() { return index == 0; } @Override - public Entry next() - { - if ( index++ == 0 ) - { + public Entry next() { + if (index++ == 0) { return entry; } throw new NoSuchElementException(); @@ -581,47 +474,38 @@ class ImmutableCollections } @Override - public int size() - { + public int size() { return 1; } }; } } - private static class MapN extends AbstractImmutableMap - { + private static class MapN extends AbstractImmutableMap { private final Object[] entries; - private MapN( Map map ) - { + private MapN(Map map) { entries = map != null ? map.entrySet().toArray() : new Object[0]; } @Override - public Set> entrySet() - { - return new AbstractImmutableSet>() - { + public Set> entrySet() { + return new AbstractImmutableSet>() { @Override - public Iterator> iterator() - { - return new Iterator>() - { + public Iterator> iterator() { + return new Iterator>() { int index = 0; + @Override - public boolean hasNext() - { + public boolean hasNext() { return index < entries.length; } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - public Entry next() - { - if ( index < entries.length ) - { - return ( Entry ) entries[index++]; + public Entry next() { + if (index < entries.length) { + return (Entry) entries[index++]; } throw new NoSuchElementException(); } @@ -629,117 +513,93 @@ class ImmutableCollections } @Override - public int size() - { + public int size() { return entries.length; } }; } } - private abstract static class AbstractImmutableMap - extends AbstractMap - implements Serializable - { + private abstract static class AbstractImmutableMap extends AbstractMap implements Serializable { @Override - public void replaceAll( BiFunction function ) - { + public void replaceAll(BiFunction function) { throw uoe(); } @Override - public V putIfAbsent( K key, V value ) - { + public V putIfAbsent(K key, V value) { throw uoe(); } @Override - public boolean remove( Object key, Object value ) - { + public boolean remove(Object key, Object value) { throw uoe(); } @Override - public boolean replace( K key, V oldValue, V newValue ) - { + public boolean replace(K key, V oldValue, V newValue) { throw uoe(); } @Override - public V replace( K key, V value ) - { + public V replace(K key, V value) { throw uoe(); } @Override - public V computeIfAbsent( K key, Function mappingFunction ) - { + public V computeIfAbsent(K key, Function mappingFunction) { throw uoe(); } @Override - public V computeIfPresent( K key, BiFunction remappingFunction ) - { + public V computeIfPresent(K key, BiFunction remappingFunction) { throw uoe(); } @Override - public V compute( K key, BiFunction remappingFunction ) - { + public V compute(K key, BiFunction remappingFunction) { throw uoe(); } @Override - public V merge( K key, V value, BiFunction remappingFunction ) - { + public V merge(K key, V value, BiFunction remappingFunction) { throw uoe(); } } - private abstract static class AbstractImmutableSet - extends AbstractSet - implements Serializable - { + private abstract static class AbstractImmutableSet extends AbstractSet implements Serializable { @Override - public boolean removeAll( Collection c ) - { + public boolean removeAll(Collection c) { throw uoe(); } @Override - public boolean add( E e ) - { + public boolean add(E e) { throw uoe(); } @Override - public boolean remove( Object o ) - { + public boolean remove(Object o) { throw uoe(); } @Override - public boolean retainAll( Collection c ) - { + public boolean retainAll(Collection c) { throw uoe(); } @Override - public void clear() - { + public void clear() { throw uoe(); } @Override - public boolean removeIf( Predicate filter ) - { + public boolean removeIf(Predicate filter) { throw uoe(); } } - private static UnsupportedOperationException uoe() - { + private static UnsupportedOperationException uoe() { return new UnsupportedOperationException(); } - } diff --git a/api/maven-api-xml/pom.xml b/api/maven-api-xml/pom.xml index b579eb3347..9c7ab20a9c 100644 --- a/api/maven-api-xml/pom.xml +++ b/api/maven-api-xml/pom.xml @@ -1,4 +1,4 @@ - + - 4.0.0 diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/Artifact.java b/maven-artifact/src/main/java/org/apache/maven/artifact/Artifact.java index 377935da03..e85b7fa005 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/Artifact.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/Artifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,12 +16,12 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; import java.io.File; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -36,9 +34,7 @@ import org.apache.maven.artifact.versioning.VersionRange; * Maven Artifact interface. Notice that it mixes artifact definition concepts (groupId, artifactId, version) * with dependency information (version range, scope). */ -public interface Artifact - extends Comparable -{ +public interface Artifact extends Comparable { String RELEASE_VERSION = "RELEASE"; @@ -46,7 +42,7 @@ public interface Artifact String SNAPSHOT_VERSION = "SNAPSHOT"; - Pattern VERSION_FILE_PATTERN = Pattern.compile( "^(.*)-([0-9]{8}\\.[0-9]{6})-([0-9]+)$" ); + Pattern VERSION_FILE_PATTERN = Pattern.compile("^(.*)-([0-9]{8}\\.[0-9]{6})-([0-9]+)$"); // TODO into artifactScope handler @@ -64,7 +60,7 @@ public interface Artifact String SCOPE_SYSTEM = "system"; - String SCOPE_IMPORT = "import"; // Used to import dependencyManagement dependencies + String SCOPE_IMPORT = "import"; // Used to import dependencyManagement dependencies String getGroupId(); @@ -72,7 +68,7 @@ public interface Artifact String getVersion(); - void setVersion( String version ); + void setVersion(String version); String getScope(); @@ -84,78 +80,75 @@ public interface Artifact File getFile(); - void setFile( File destination ); + void setFile(File destination); String getBaseVersion(); - void setBaseVersion( String baseVersion ); + void setBaseVersion(String baseVersion); String getId(); String getDependencyConflictId(); - void addMetadata( ArtifactMetadata metadata ); + void addMetadata(ArtifactMetadata metadata); Collection getMetadataList(); - void setRepository( ArtifactRepository remoteRepository ); + void setRepository(ArtifactRepository remoteRepository); ArtifactRepository getRepository(); - void updateVersion( String version, ArtifactRepository localRepository ); + void updateVersion(String version, ArtifactRepository localRepository); String getDownloadUrl(); - void setDownloadUrl( String downloadUrl ); + void setDownloadUrl(String downloadUrl); ArtifactFilter getDependencyFilter(); - void setDependencyFilter( ArtifactFilter artifactFilter ); + void setDependencyFilter(ArtifactFilter artifactFilter); ArtifactHandler getArtifactHandler(); List getDependencyTrail(); - void setDependencyTrail( List dependencyTrail ); + void setDependencyTrail(List dependencyTrail); - void setScope( String scope ); + void setScope(String scope); VersionRange getVersionRange(); - void setVersionRange( VersionRange newRange ); + void setVersionRange(VersionRange newRange); - void selectVersion( String version ); + void selectVersion(String version); - void setGroupId( String groupId ); + void setGroupId(String groupId); - void setArtifactId( String artifactId ); + void setArtifactId(String artifactId); boolean isSnapshot(); - void setResolved( boolean resolved ); + void setResolved(boolean resolved); boolean isResolved(); - void setResolvedVersion( String version ); + void setResolvedVersion(String version); - void setArtifactHandler( ArtifactHandler handler ); + void setArtifactHandler(ArtifactHandler handler); boolean isRelease(); - void setRelease( boolean release ); + void setRelease(boolean release); List getAvailableVersions(); - void setAvailableVersions( List versions ); + void setAvailableVersions(List versions); boolean isOptional(); - void setOptional( boolean optional ); + void setOptional(boolean optional); - ArtifactVersion getSelectedVersion() - throws OverConstrainedVersionException; - - boolean isSelectedVersionKnown() - throws OverConstrainedVersionException; + ArtifactVersion getSelectedVersion() throws OverConstrainedVersionException; + boolean isSelectedVersionKnown() throws OverConstrainedVersionException; } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/ArtifactUtils.java b/maven-artifact/src/main/java/org/apache/maven/artifact/ArtifactUtils.java index 800732134a..555375a921 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/ArtifactUtils.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/ArtifactUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; import java.util.ArrayList; import java.util.Collection; @@ -25,111 +24,93 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; - import org.apache.commons.lang3.Validate; import org.apache.maven.artifact.versioning.VersionRange; /** * ArtifactUtils */ -public final class ArtifactUtils -{ +public final class ArtifactUtils { - public static boolean isSnapshot( String version ) - { - if ( version != null ) - { - if ( version.regionMatches( true, version.length() - Artifact.SNAPSHOT_VERSION.length(), - Artifact.SNAPSHOT_VERSION, 0, Artifact.SNAPSHOT_VERSION.length() ) ) - { + public static boolean isSnapshot(String version) { + if (version != null) { + if (version.regionMatches( + true, + version.length() - Artifact.SNAPSHOT_VERSION.length(), + Artifact.SNAPSHOT_VERSION, + 0, + Artifact.SNAPSHOT_VERSION.length())) { return true; - } - else - { - return Artifact.VERSION_FILE_PATTERN.matcher( version ).matches(); + } else { + return Artifact.VERSION_FILE_PATTERN.matcher(version).matches(); } } return false; } - public static String toSnapshotVersion( String version ) - { - notBlank( version, "version can neither be null, empty nor blank" ); + public static String toSnapshotVersion(String version) { + notBlank(version, "version can neither be null, empty nor blank"); - int lastHyphen = version.lastIndexOf( '-' ); - if ( lastHyphen > 0 ) - { - int prevHyphen = version.lastIndexOf( '-', lastHyphen - 1 ); - if ( prevHyphen > 0 ) - { - Matcher m = Artifact.VERSION_FILE_PATTERN.matcher( version ); - if ( m.matches() ) - { - return m.group( 1 ) + "-" + Artifact.SNAPSHOT_VERSION; + int lastHyphen = version.lastIndexOf('-'); + if (lastHyphen > 0) { + int prevHyphen = version.lastIndexOf('-', lastHyphen - 1); + if (prevHyphen > 0) { + Matcher m = Artifact.VERSION_FILE_PATTERN.matcher(version); + if (m.matches()) { + return m.group(1) + "-" + Artifact.SNAPSHOT_VERSION; } } } return version; } - public static String versionlessKey( Artifact artifact ) - { - return versionlessKey( artifact.getGroupId(), artifact.getArtifactId() ); + public static String versionlessKey(Artifact artifact) { + return versionlessKey(artifact.getGroupId(), artifact.getArtifactId()); } - public static String versionlessKey( String groupId, String artifactId ) - { - notBlank( groupId, "groupId can neither be null, empty nor blank" ); - notBlank( artifactId, "artifactId can neither be null, empty nor blank" ); + public static String versionlessKey(String groupId, String artifactId) { + notBlank(groupId, "groupId can neither be null, empty nor blank"); + notBlank(artifactId, "artifactId can neither be null, empty nor blank"); return groupId + ":" + artifactId; } - public static String key( Artifact artifact ) - { - return key( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() ); + public static String key(Artifact artifact) { + return key(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); } - public static String key( String groupId, String artifactId, String version ) - { - notBlank( groupId, "groupId can neither be null, empty nor blank" ); - notBlank( artifactId, "artifactId can neither be null, empty nor blank" ); - notBlank( version, "version can neither be null, empty nor blank" ); + public static String key(String groupId, String artifactId, String version) { + notBlank(groupId, "groupId can neither be null, empty nor blank"); + notBlank(artifactId, "artifactId can neither be null, empty nor blank"); + notBlank(version, "version can neither be null, empty nor blank"); return groupId + ":" + artifactId + ":" + version; } - private static void notBlank( String str, String message ) - { - int c = str != null && str.length() > 0 ? str.charAt( 0 ) : 0; - if ( ( c < '0' || c > '9' ) && ( c < 'a' || c > 'z' ) ) - { - Validate.notBlank( str, message ); + private static void notBlank(String str, String message) { + int c = str != null && str.length() > 0 ? str.charAt(0) : 0; + if ((c < '0' || c > '9') && (c < 'a' || c > 'z')) { + Validate.notBlank(str, message); } } - public static Map artifactMapByVersionlessId( Collection artifacts ) - { + public static Map artifactMapByVersionlessId(Collection artifacts) { Map artifactMap = new LinkedHashMap<>(); - if ( artifacts != null ) - { - for ( Artifact artifact : artifacts ) - { - artifactMap.put( versionlessKey( artifact ), artifact ); + if (artifacts != null) { + for (Artifact artifact : artifacts) { + artifactMap.put(versionlessKey(artifact), artifact); } } return artifactMap; } - public static Artifact copyArtifactSafe( Artifact artifact ) - { - return ( artifact != null ) ? copyArtifact( artifact ) : null; + public static Artifact copyArtifactSafe(Artifact artifact) { + return (artifact != null) ? copyArtifact(artifact) : null; } - public static Artifact copyArtifact( Artifact artifact ) - { + public static Artifact copyArtifact(Artifact artifact) { VersionRange range = artifact.getVersionRange(); // For some reason with the introduction of MNG-1577 we have the case in Yoko where a depMan section has @@ -147,28 +128,32 @@ public final class ArtifactUtils // // And the range is not set so we'll check here and set it. jvz. - if ( range == null ) - { - range = VersionRange.createFromVersion( artifact.getVersion() ); + if (range == null) { + range = VersionRange.createFromVersion(artifact.getVersion()); } - DefaultArtifact clone = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), range, - artifact.getScope(), artifact.getType(), artifact.getClassifier(), - artifact.getArtifactHandler(), artifact.isOptional() ); - clone.setRelease( artifact.isRelease() ); - clone.setResolvedVersion( artifact.getVersion() ); - clone.setResolved( artifact.isResolved() ); - clone.setFile( artifact.getFile() ); + DefaultArtifact clone = new DefaultArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + range, + artifact.getScope(), + artifact.getType(), + artifact.getClassifier(), + artifact.getArtifactHandler(), + artifact.isOptional()); + clone.setRelease(artifact.isRelease()); + clone.setResolvedVersion(artifact.getVersion()); + clone.setResolved(artifact.isResolved()); + clone.setFile(artifact.getFile()); - clone.setAvailableVersions( copyList( artifact.getAvailableVersions() ) ); - if ( artifact.getVersion() != null ) - { - clone.setBaseVersion( artifact.getBaseVersion() ); + clone.setAvailableVersions(copyList(artifact.getAvailableVersions())); + if (artifact.getVersion() != null) { + clone.setBaseVersion(artifact.getBaseVersion()); } - clone.setDependencyFilter( artifact.getDependencyFilter() ); - clone.setDependencyTrail( copyList( artifact.getDependencyTrail() ) ); - clone.setDownloadUrl( artifact.getDownloadUrl() ); - clone.setRepository( artifact.getRepository() ); + clone.setDependencyFilter(artifact.getDependencyFilter()); + clone.setDependencyTrail(copyList(artifact.getDependencyTrail())); + clone.setDownloadUrl(artifact.getDownloadUrl()); + clone.setRepository(artifact.getRepository()); return clone; } @@ -181,43 +166,34 @@ public final class ArtifactUtils * @param to the target artifact collection * @return to collection */ - public static > T copyArtifacts( Collection from, T to ) - { - for ( Artifact artifact : from ) - { - to.add( ArtifactUtils.copyArtifact( artifact ) ); + public static > T copyArtifacts(Collection from, T to) { + for (Artifact artifact : from) { + to.add(ArtifactUtils.copyArtifact(artifact)); } return to; } - public static > T copyArtifacts( Map from, T to ) - { - if ( from != null ) - { - for ( Map.Entry entry : from.entrySet() ) - { - to.put( entry.getKey(), ArtifactUtils.copyArtifact( entry.getValue() ) ); + public static > T copyArtifacts(Map from, T to) { + if (from != null) { + for (Map.Entry entry : from.entrySet()) { + to.put(entry.getKey(), ArtifactUtils.copyArtifact(entry.getValue())); } } return to; } - private static List copyList( List original ) - { + private static List copyList(List original) { List copy = null; - if ( original != null ) - { + if (original != null) { copy = new ArrayList<>(); - if ( !original.isEmpty() ) - { - copy.addAll( original ); + if (!original.isEmpty()) { + copy.addAll(original); } } return copy; } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/DefaultArtifact.java b/maven-artifact/src/main/java/org/apache/maven/artifact/DefaultArtifact.java index 4aafcffc23..e7bf52b6e2 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/DefaultArtifact.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/DefaultArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; import java.io.File; import java.util.Collection; @@ -25,7 +24,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -39,9 +37,7 @@ import org.codehaus.plexus.util.StringUtils; /** * @author Jason van Zyl */ -public class DefaultArtifact - implements Artifact -{ +public class DefaultArtifact implements Artifact { private String groupId; private String artifactId; @@ -80,23 +76,46 @@ public class DefaultArtifact private boolean optional; - public DefaultArtifact( String groupId, String artifactId, String version, String scope, String type, - String classifier, ArtifactHandler artifactHandler ) - { - this( groupId, artifactId, VersionRange.createFromVersion( version ), scope, type, classifier, artifactHandler, - false ); + public DefaultArtifact( + String groupId, + String artifactId, + String version, + String scope, + String type, + String classifier, + ArtifactHandler artifactHandler) { + this( + groupId, + artifactId, + VersionRange.createFromVersion(version), + scope, + type, + classifier, + artifactHandler, + false); } - public DefaultArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, String type, - String classifier, ArtifactHandler artifactHandler ) - { - this( groupId, artifactId, versionRange, scope, type, classifier, artifactHandler, false ); + public DefaultArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String scope, + String type, + String classifier, + ArtifactHandler artifactHandler) { + this(groupId, artifactId, versionRange, scope, type, classifier, artifactHandler, false); } - @SuppressWarnings( "checkstyle:parameternumber" ) - public DefaultArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, String type, - String classifier, ArtifactHandler artifactHandler, boolean optional ) - { + @SuppressWarnings("checkstyle:parameternumber") + public DefaultArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String scope, + String type, + String classifier, + ArtifactHandler artifactHandler, + boolean optional) { this.groupId = groupId; this.artifactId = artifactId; @@ -111,8 +130,7 @@ public class DefaultArtifact this.type = type; - if ( classifier == null ) - { + if (classifier == null) { classifier = artifactHandler.getClassifier(); } @@ -123,97 +141,78 @@ public class DefaultArtifact validateIdentity(); } - private void validateIdentity() - { - if ( empty( groupId ) ) - { - throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type, - "The groupId cannot be empty." ); + private void validateIdentity() { + if (empty(groupId)) { + throw new InvalidArtifactRTException( + groupId, artifactId, getVersion(), type, "The groupId cannot be empty."); } - if ( artifactId == null ) - { - throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type, - "The artifactId cannot be empty." ); + if (artifactId == null) { + throw new InvalidArtifactRTException( + groupId, artifactId, getVersion(), type, "The artifactId cannot be empty."); } - if ( type == null ) - { - throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type, - "The type cannot be empty." ); + if (type == null) { + throw new InvalidArtifactRTException(groupId, artifactId, getVersion(), type, "The type cannot be empty."); } - if ( ( version == null ) && ( versionRange == null ) ) - { - throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type, - "The version cannot be empty." ); + if ((version == null) && (versionRange == null)) { + throw new InvalidArtifactRTException( + groupId, artifactId, getVersion(), type, "The version cannot be empty."); } } - private boolean empty( String value ) - { - return ( value == null ) || ( value.trim().length() < 1 ); + private boolean empty(String value) { + return (value == null) || (value.trim().length() < 1); } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public boolean hasClassifier() - { - return StringUtils.isNotEmpty( classifier ); + public boolean hasClassifier() { + return StringUtils.isNotEmpty(classifier); } - public String getScope() - { + public String getScope() { return scope; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; - setBaseVersionInternal( version ); + setBaseVersionInternal(version); versionRange = null; } - public String getType() - { + public String getType() { return type; } - public void setFile( File file ) - { + public void setFile(File file) { this.file = file; } - public File getFile() - { + public File getFile() { return file; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } - public void setRepository( ArtifactRepository repository ) - { + public void setRepository(ArtifactRepository repository) { this.repository = repository; } @@ -221,206 +220,159 @@ public class DefaultArtifact // // ---------------------------------------------------------------------- - public String getId() - { + public String getId() { return getDependencyConflictId() + ":" + getBaseVersion(); } - public String getDependencyConflictId() - { - StringBuilder sb = new StringBuilder( 128 ); - sb.append( getGroupId() ); - sb.append( ':' ); - appendArtifactTypeClassifierString( sb ); + public String getDependencyConflictId() { + StringBuilder sb = new StringBuilder(128); + sb.append(getGroupId()); + sb.append(':'); + appendArtifactTypeClassifierString(sb); return sb.toString(); } - private void appendArtifactTypeClassifierString( StringBuilder sb ) - { - sb.append( getArtifactId() ); - sb.append( ':' ); - sb.append( getType() ); - if ( hasClassifier() ) - { - sb.append( ':' ); - sb.append( getClassifier() ); + private void appendArtifactTypeClassifierString(StringBuilder sb) { + sb.append(getArtifactId()); + sb.append(':'); + sb.append(getType()); + if (hasClassifier()) { + sb.append(':'); + sb.append(getClassifier()); } } - public void addMetadata( ArtifactMetadata metadata ) - { - if ( metadataMap == null ) - { + public void addMetadata(ArtifactMetadata metadata) { + if (metadataMap == null) { metadataMap = new HashMap<>(); } - ArtifactMetadata m = metadataMap.get( metadata.getKey() ); - if ( m != null ) - { - m.merge( metadata ); - } - else - { - metadataMap.put( metadata.getKey(), metadata ); + ArtifactMetadata m = metadataMap.get(metadata.getKey()); + if (m != null) { + m.merge(metadata); + } else { + metadataMap.put(metadata.getKey(), metadata); } } - public Collection getMetadataList() - { - if ( metadataMap == null ) - { + public Collection getMetadataList() { + if (metadataMap == null) { return Collections.emptyList(); } - return Collections.unmodifiableCollection( metadataMap.values() ); + return Collections.unmodifiableCollection(metadataMap.values()); } // ---------------------------------------------------------------------- // Object overrides // ---------------------------------------------------------------------- - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - if ( getGroupId() != null ) - { - sb.append( getGroupId() ); - sb.append( ':' ); + if (getGroupId() != null) { + sb.append(getGroupId()); + sb.append(':'); } - appendArtifactTypeClassifierString( sb ); - sb.append( ':' ); - if ( getBaseVersionInternal() != null ) - { - sb.append( getBaseVersionInternal() ); + appendArtifactTypeClassifierString(sb); + sb.append(':'); + if (getBaseVersionInternal() != null) { + sb.append(getBaseVersionInternal()); + } else { + sb.append(versionRange.toString()); } - else - { - sb.append( versionRange.toString() ); - } - if ( scope != null ) - { - sb.append( ':' ); - sb.append( scope ); + if (scope != null) { + sb.append(':'); + sb.append(scope); } return sb.toString(); } - public int hashCode() - { + public int hashCode() { int result = 17; result = 37 * result + groupId.hashCode(); result = 37 * result + artifactId.hashCode(); result = 37 * result + type.hashCode(); - if ( version != null ) - { + if (version != null) { result = 37 * result + version.hashCode(); } - result = 37 * result + ( classifier != null ? classifier.hashCode() : 0 ); + result = 37 * result + (classifier != null ? classifier.hashCode() : 0); return result; } - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof Artifact ) ) - { + if (!(o instanceof Artifact)) { return false; } Artifact a = (Artifact) o; - if ( !a.getGroupId().equals( groupId ) ) - { + if (!a.getGroupId().equals(groupId)) { return false; - } - else if ( !a.getArtifactId().equals( artifactId ) ) - { + } else if (!a.getArtifactId().equals(artifactId)) { return false; - } - else if ( !a.getVersion().equals( version ) ) - { + } else if (!a.getVersion().equals(version)) { return false; - } - else if ( !a.getType().equals( type ) ) - { + } else if (!a.getType().equals(type)) { return false; - } - else - { - return a.getClassifier() == null ? classifier == null : a.getClassifier().equals( classifier ); + } else { + return a.getClassifier() == null + ? classifier == null + : a.getClassifier().equals(classifier); } // We don't consider the version range in the comparison, just the resolved version } - public String getBaseVersion() - { - if ( baseVersion == null && version != null ) - { - setBaseVersionInternal( version ); + public String getBaseVersion() { + if (baseVersion == null && version != null) { + setBaseVersionInternal(version); } return baseVersion; } - protected String getBaseVersionInternal() - { - if ( ( baseVersion == null ) && ( version != null ) ) - { - setBaseVersionInternal( version ); + protected String getBaseVersionInternal() { + if ((baseVersion == null) && (version != null)) { + setBaseVersionInternal(version); } return baseVersion; } - public void setBaseVersion( String baseVersion ) - { - setBaseVersionInternal( baseVersion ); + public void setBaseVersion(String baseVersion) { + setBaseVersionInternal(baseVersion); } - protected void setBaseVersionInternal( String baseVersion ) - { - this.baseVersion = ArtifactUtils.toSnapshotVersion( baseVersion ); + protected void setBaseVersionInternal(String baseVersion) { + this.baseVersion = ArtifactUtils.toSnapshotVersion(baseVersion); } - public int compareTo( Artifact a ) - { - int result = groupId.compareTo( a.getGroupId() ); - if ( result == 0 ) - { - result = artifactId.compareTo( a.getArtifactId() ); - if ( result == 0 ) - { - result = type.compareTo( a.getType() ); - if ( result == 0 ) - { - if ( classifier == null ) - { - if ( a.getClassifier() != null ) - { + public int compareTo(Artifact a) { + int result = groupId.compareTo(a.getGroupId()); + if (result == 0) { + result = artifactId.compareTo(a.getArtifactId()); + if (result == 0) { + result = type.compareTo(a.getType()); + if (result == 0) { + if (classifier == null) { + if (a.getClassifier() != null) { result = 1; } - } - else - { - if ( a.getClassifier() != null ) - { - result = classifier.compareTo( a.getClassifier() ); - } - else - { + } else { + if (a.getClassifier() != null) { + result = classifier.compareTo(a.getClassifier()); + } else { result = -1; } } - if ( result == 0 ) - { + if (result == 0) { // We don't consider the version range in the comparison, just the resolved version - result = new DefaultArtifactVersion( version ).compareTo( - new DefaultArtifactVersion( a.getVersion() ) ); + result = new DefaultArtifactVersion(version) + .compareTo(new DefaultArtifactVersion(a.getVersion())); } } } @@ -428,159 +380,126 @@ public class DefaultArtifact return result; } - public void updateVersion( String version, ArtifactRepository localRepository ) - { - setResolvedVersion( version ); - setFile( new File( localRepository.getBasedir(), localRepository.pathOf( this ) ) ); + public void updateVersion(String version, ArtifactRepository localRepository) { + setResolvedVersion(version); + setFile(new File(localRepository.getBasedir(), localRepository.pathOf(this))); } - public String getDownloadUrl() - { + public String getDownloadUrl() { return downloadUrl; } - public void setDownloadUrl( String downloadUrl ) - { + public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } - public ArtifactFilter getDependencyFilter() - { + public ArtifactFilter getDependencyFilter() { return dependencyFilter; } - public void setDependencyFilter( ArtifactFilter artifactFilter ) - { + public void setDependencyFilter(ArtifactFilter artifactFilter) { dependencyFilter = artifactFilter; } - public ArtifactHandler getArtifactHandler() - { + public ArtifactHandler getArtifactHandler() { return artifactHandler; } - public List getDependencyTrail() - { + public List getDependencyTrail() { return dependencyTrail; } - public void setDependencyTrail( List dependencyTrail ) - { + public void setDependencyTrail(List dependencyTrail) { this.dependencyTrail = dependencyTrail; } - public void setScope( String scope ) - { + public void setScope(String scope) { this.scope = scope; } - public VersionRange getVersionRange() - { + public VersionRange getVersionRange() { return versionRange; } - public void setVersionRange( VersionRange versionRange ) - { + public void setVersionRange(VersionRange versionRange) { this.versionRange = versionRange; selectVersionFromNewRangeIfAvailable(); } - private void selectVersionFromNewRangeIfAvailable() - { - if ( ( versionRange != null ) && ( versionRange.getRecommendedVersion() != null ) ) - { - selectVersion( versionRange.getRecommendedVersion().toString() ); - } - else - { + private void selectVersionFromNewRangeIfAvailable() { + if ((versionRange != null) && (versionRange.getRecommendedVersion() != null)) { + selectVersion(versionRange.getRecommendedVersion().toString()); + } else { version = null; baseVersion = null; } } - public void selectVersion( String version ) - { + public void selectVersion(String version) { this.version = version; - setBaseVersionInternal( version ); + setBaseVersionInternal(version); } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } - public boolean isSnapshot() - { + public boolean isSnapshot() { return getBaseVersion() != null - && ( getBaseVersion().endsWith( SNAPSHOT_VERSION ) || getBaseVersion().equals( LATEST_VERSION ) ); + && (getBaseVersion().endsWith(SNAPSHOT_VERSION) + || getBaseVersion().equals(LATEST_VERSION)); } - public void setResolved( boolean resolved ) - { + public void setResolved(boolean resolved) { this.resolved = resolved; } - public boolean isResolved() - { + public boolean isResolved() { return resolved; } - public void setResolvedVersion( String version ) - { + public void setResolvedVersion(String version) { this.version = version; // retain baseVersion } - public void setArtifactHandler( ArtifactHandler artifactHandler ) - { + public void setArtifactHandler(ArtifactHandler artifactHandler) { this.artifactHandler = artifactHandler; } - public void setRelease( boolean release ) - { + public void setRelease(boolean release) { this.release = release; } - public boolean isRelease() - { + public boolean isRelease() { return release; } - public List getAvailableVersions() - { + public List getAvailableVersions() { return availableVersions; } - public void setAvailableVersions( List availableVersions ) - { + public void setAvailableVersions(List availableVersions) { this.availableVersions = availableVersions; } - public boolean isOptional() - { + public boolean isOptional() { return optional; } - public ArtifactVersion getSelectedVersion() - throws OverConstrainedVersionException - { - return versionRange.getSelectedVersion( this ); + public ArtifactVersion getSelectedVersion() throws OverConstrainedVersionException { + return versionRange.getSelectedVersion(this); } - public boolean isSelectedVersionKnown() - throws OverConstrainedVersionException - { - return versionRange.isSelectedVersionKnown( this ); + public boolean isSelectedVersionKnown() throws OverConstrainedVersionException { + return versionRange.isSelectedVersionKnown(this); } - public void setOptional( boolean optional ) - { + public void setOptional(boolean optional) { this.optional = optional; } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/InvalidArtifactRTException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/InvalidArtifactRTException.java index 357ec71344..5582e98cd2 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/InvalidArtifactRTException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/InvalidArtifactRTException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; /** * Exception thrown when the identity of an artifact can not be established, * e.g. one of groupId, artifactId, version or type is null. */ -public class InvalidArtifactRTException - extends RuntimeException -{ +public class InvalidArtifactRTException extends RuntimeException { private final String groupId; private final String artifactId; @@ -33,12 +30,7 @@ public class InvalidArtifactRTException private final String type; private final String baseMessage; - public InvalidArtifactRTException( String groupId, - String artifactId, - String version, - String type, - String message ) - { + public InvalidArtifactRTException(String groupId, String artifactId, String version, String type, String message) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; @@ -46,14 +38,9 @@ public class InvalidArtifactRTException this.baseMessage = message; } - public InvalidArtifactRTException( String groupId, - String artifactId, - String version, - String type, - String message, - Throwable cause ) - { - super( cause ); + public InvalidArtifactRTException( + String groupId, String artifactId, String version, String type, String message, Throwable cause) { + super(cause); this.groupId = groupId; this.artifactId = artifactId; @@ -62,39 +49,31 @@ public class InvalidArtifactRTException this.baseMessage = message; } - public String getMessage() - { + public String getMessage() { return "For artifact {" + getArtifactKey() + "}: " + getBaseMessage(); } - public String getBaseMessage() - { + public String getBaseMessage() { return baseMessage; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getType() - { + public String getType() { return type; } - public String getVersion() - { + public String getVersion() { return version; } - public String getArtifactKey() - { + public String getArtifactKey() { return groupId + ":" + artifactId + ":" + version + ":" + type; } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/handler/ArtifactHandler.java b/maven-artifact/src/main/java/org/apache/maven/artifact/handler/ArtifactHandler.java index db101bf28a..51c7c51d2c 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/handler/ArtifactHandler.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/handler/ArtifactHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.handler; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler; /** * An artifact handler defines for a dependency type, defined as Plexus role:
    @@ -28,8 +27,7 @@ package org.apache.maven.artifact.handler; * * @author Jason van Zyl */ -public interface ArtifactHandler -{ +public interface ArtifactHandler { @Deprecated String ROLE = ArtifactHandler.class.getName(); diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadata.java b/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadata.java index 7bf8c6128b..fd079999a8 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadata.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.metadata; * "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 + * 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 @@ -18,13 +16,12 @@ package org.apache.maven.artifact.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.metadata; /** * Contains metadata about an artifact, and methods to retrieve/store it from an artifact repository. */ @Deprecated -public interface ArtifactMetadata - extends org.apache.maven.repository.legacy.metadata.ArtifactMetadata -{ - void merge( ArtifactMetadata metadata ); +public interface ArtifactMetadata extends org.apache.maven.repository.legacy.metadata.ArtifactMetadata { + void merge(ArtifactMetadata metadata); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepository.java b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepository.java index aecffb961f..0c0a02d4ac 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepository.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; @@ -30,17 +28,16 @@ import org.apache.maven.repository.Proxy; * Abstraction of an artifact repository. Artifact repositories can be remote, local, or even build reactor or * IDE workspace. */ -public interface ArtifactRepository -{ - String pathOf( Artifact artifact ); +public interface ArtifactRepository { + String pathOf(Artifact artifact); - String pathOfRemoteRepositoryMetadata( ArtifactMetadata artifactMetadata ); + String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata); - String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ); + String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository); String getUrl(); - void setUrl( String url ); + void setUrl(String url); String getBasedir(); @@ -48,19 +45,19 @@ public interface ArtifactRepository String getId(); - void setId( String id ); + void setId(String id); ArtifactRepositoryPolicy getSnapshots(); - void setSnapshotUpdatePolicy( ArtifactRepositoryPolicy policy ); + void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy policy); ArtifactRepositoryPolicy getReleases(); - void setReleaseUpdatePolicy( ArtifactRepositoryPolicy policy ); + void setReleaseUpdatePolicy(ArtifactRepositoryPolicy policy); ArtifactRepositoryLayout getLayout(); - void setLayout( ArtifactRepositoryLayout layout ); + void setLayout(ArtifactRepositoryLayout layout); String getKey(); @@ -71,7 +68,7 @@ public interface ArtifactRepository boolean isBlacklisted(); @Deprecated - void setBlacklisted( boolean blackListed ); + void setBlacklisted(boolean blackListed); /** * @return whether the repository is blocked @@ -83,7 +80,7 @@ public interface ArtifactRepository * @param blocked block the repository? * @since 3.8.1 **/ - void setBlocked( boolean blocked ); + void setBlocked(boolean blocked); // // New interface methods for the repository system. @@ -94,7 +91,7 @@ public interface ArtifactRepository * @return found artifact * @since 3.0-alpha-3 */ - Artifact find( Artifact artifact ); + Artifact find(Artifact artifact); /** * Finds the versions of the specified artifact that are available in this repository. @@ -103,7 +100,7 @@ public interface ArtifactRepository * @return The available versions of the artifact or an empty list if none, never {@code null}. * @since 3.0-alpha-3 */ - List findVersions( Artifact artifact ); + List findVersions(Artifact artifact); /** * Indicates whether this repository is backed by actual projects. For instance, the build reactor or IDE workspace @@ -118,7 +115,7 @@ public interface ArtifactRepository * @param authentication authentication * @since 3.0-alpha-3 */ - void setAuthentication( Authentication authentication ); + void setAuthentication(Authentication authentication); /** * @return repository authentication @@ -130,7 +127,7 @@ public interface ArtifactRepository * @param proxy proxy * @since 3.0-alpha-3 */ - void setProxy( Proxy proxy ); + void setProxy(Proxy proxy); /** * @since 3.0-alpha-3 @@ -148,6 +145,5 @@ public interface ArtifactRepository * @since 3.0.3 * @param mirroredRepositories the repositories that the actual one mirrors */ - void setMirroredRepositories( List mirroredRepositories ); - + void setMirroredRepositories(List mirroredRepositories); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java index 6ad2a26e47..a38f65e87a 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.util.Calendar; import java.util.Date; @@ -27,8 +26,7 @@ import java.util.Date; * * @author Brett Porter */ -public class ArtifactRepositoryPolicy -{ +public class ArtifactRepositoryPolicy { public static final String UPDATE_POLICY_NEVER = "never"; public static final String UPDATE_POLICY_ALWAYS = "always"; @@ -51,100 +49,79 @@ public class ArtifactRepositoryPolicy private String checksumPolicy; - public ArtifactRepositoryPolicy() - { - this( true, null, null ); + public ArtifactRepositoryPolicy() { + this(true, null, null); } - public ArtifactRepositoryPolicy( ArtifactRepositoryPolicy policy ) - { - this( policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy() ); + public ArtifactRepositoryPolicy(ArtifactRepositoryPolicy policy) { + this(policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy()); } - public ArtifactRepositoryPolicy( boolean enabled, String updatePolicy, String checksumPolicy ) - { + public ArtifactRepositoryPolicy(boolean enabled, String updatePolicy, String checksumPolicy) { this.enabled = enabled; - if ( updatePolicy == null ) - { + if (updatePolicy == null) { updatePolicy = UPDATE_POLICY_DAILY; } this.updatePolicy = updatePolicy; - if ( checksumPolicy == null ) - { + if (checksumPolicy == null) { checksumPolicy = DEFAULT_CHECKSUM_POLICY; } this.checksumPolicy = checksumPolicy; } - public void setEnabled( boolean enabled ) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public void setUpdatePolicy( String updatePolicy ) - { - if ( updatePolicy != null ) - { + public void setUpdatePolicy(String updatePolicy) { + if (updatePolicy != null) { this.updatePolicy = updatePolicy; } } - public void setChecksumPolicy( String checksumPolicy ) - { - if ( checksumPolicy != null ) - { + public void setChecksumPolicy(String checksumPolicy) { + if (checksumPolicy != null) { this.checksumPolicy = checksumPolicy; } } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public String getUpdatePolicy() - { + public String getUpdatePolicy() { return updatePolicy; } - public String getChecksumPolicy() - { + public String getChecksumPolicy() { return checksumPolicy; } - public boolean checkOutOfDate( Date lastModified ) - { + public boolean checkOutOfDate(Date lastModified) { boolean checkForUpdates = false; - if ( UPDATE_POLICY_ALWAYS.equals( updatePolicy ) ) - { + if (UPDATE_POLICY_ALWAYS.equals(updatePolicy)) { checkForUpdates = true; - } - else if ( UPDATE_POLICY_DAILY.equals( updatePolicy ) ) - { + } else if (UPDATE_POLICY_DAILY.equals(updatePolicy)) { // Get local midnight boundary Calendar cal = Calendar.getInstance(); - cal.set( Calendar.HOUR_OF_DAY, 0 ); - cal.set( Calendar.MINUTE, 0 ); - cal.set( Calendar.SECOND, 0 ); - cal.set( Calendar.MILLISECOND, 0 ); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); - if ( cal.getTime().after( lastModified ) ) - { + if (cal.getTime().after(lastModified)) { checkForUpdates = true; } - } - else if ( updatePolicy.startsWith( UPDATE_POLICY_INTERVAL ) ) - { - String s = updatePolicy.substring( UPDATE_POLICY_INTERVAL.length() + 1 ); - int minutes = Integer.parseInt( s ); + } else if (updatePolicy.startsWith(UPDATE_POLICY_INTERVAL)) { + String s = updatePolicy.substring(UPDATE_POLICY_INTERVAL.length() + 1); + int minutes = Integer.parseInt(s); Calendar cal = Calendar.getInstance(); - cal.add( Calendar.MINUTE, -minutes ); - if ( cal.getTime().after( lastModified ) ) - { + cal.add(Calendar.MINUTE, -minutes); + if (cal.getTime().after(lastModified)) { checkForUpdates = true; } } @@ -153,73 +130,53 @@ public class ArtifactRepositoryPolicy } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 64 ); - buffer.append( "{enabled=" ); - buffer.append( enabled ); - buffer.append( ", checksums=" ); - buffer.append( checksumPolicy ); - buffer.append( ", updates=" ); - buffer.append( updatePolicy ); - buffer.append( '}' ); + public String toString() { + StringBuilder buffer = new StringBuilder(64); + buffer.append("{enabled="); + buffer.append(enabled); + buffer.append(", checksums="); + buffer.append(checksumPolicy); + buffer.append(", updates="); + buffer.append(updatePolicy); + buffer.append('}'); return buffer.toString(); } - public void merge( ArtifactRepositoryPolicy policy ) - { - if ( policy != null && policy.isEnabled() ) - { - setEnabled( true ); + public void merge(ArtifactRepositoryPolicy policy) { + if (policy != null && policy.isEnabled()) { + setEnabled(true); - if ( ordinalOfCksumPolicy( policy.getChecksumPolicy() ) < ordinalOfCksumPolicy( getChecksumPolicy() ) ) - { - setChecksumPolicy( policy.getChecksumPolicy() ); + if (ordinalOfCksumPolicy(policy.getChecksumPolicy()) < ordinalOfCksumPolicy(getChecksumPolicy())) { + setChecksumPolicy(policy.getChecksumPolicy()); } - if ( ordinalOfUpdatePolicy( policy.getUpdatePolicy() ) < ordinalOfUpdatePolicy( getUpdatePolicy() ) ) - { - setUpdatePolicy( policy.getUpdatePolicy() ); + if (ordinalOfUpdatePolicy(policy.getUpdatePolicy()) < ordinalOfUpdatePolicy(getUpdatePolicy())) { + setUpdatePolicy(policy.getUpdatePolicy()); } } } - private int ordinalOfCksumPolicy( String policy ) - { - if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals( policy ) ) - { + private int ordinalOfCksumPolicy(String policy) { + if (ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals(policy)) { return 2; - } - else if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals( policy ) ) - { + } else if (ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals(policy)) { return 0; - } - else - { + } else { return 1; } } - @SuppressWarnings( "checkstyle:magicnumber" ) - private int ordinalOfUpdatePolicy( String policy ) - { - if ( ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) - { + @SuppressWarnings("checkstyle:magicnumber") + private int ordinalOfUpdatePolicy(String policy) { + if (ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY.equals(policy)) { return 1440; - } - else if ( ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) - { + } else if (ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(policy)) { return 0; - } - else if ( policy != null && policy.startsWith( ArtifactRepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) - { - String s = policy.substring( UPDATE_POLICY_INTERVAL.length() + 1 ); - return Integer.parseInt( s ); - } - else - { + } else if (policy != null && policy.startsWith(ArtifactRepositoryPolicy.UPDATE_POLICY_INTERVAL)) { + String s = policy.substring(UPDATE_POLICY_INTERVAL.length() + 1); + return Integer.parseInt(s); + } else { return Integer.MAX_VALUE; } } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/Authentication.java b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/Authentication.java index b6f1d93a6a..62d0165c54 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/Authentication.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/Authentication.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,18 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; /** * Authentication */ -public class Authentication -{ +public class Authentication { private String privateKey; private String passphrase; - public Authentication( String userName, String password ) - { + public Authentication(String userName, String password) { this.username = userName; this.password = password; } @@ -50,8 +47,7 @@ public class Authentication * * @return password of user */ - public String getPassword() - { + public String getPassword() { return password; } @@ -60,8 +56,7 @@ public class Authentication * * @param password password of the user */ - public void setPassword( String password ) - { + public void setPassword(String password) { this.password = password; } @@ -70,8 +65,7 @@ public class Authentication * * @return username at repository */ - public String getUsername() - { + public String getUsername() { return username; } @@ -80,8 +74,7 @@ public class Authentication * * @param userName the username used to access repository */ - public void setUsername( final String userName ) - { + public void setUsername(final String userName) { this.username = userName; } @@ -91,8 +84,7 @@ public class Authentication * * @return passphrase of the private key file */ - public String getPassphrase() - { + public String getPassphrase() { return passphrase; } @@ -101,8 +93,7 @@ public class Authentication * * @param passphrase passphrase of the private key file */ - public void setPassphrase( final String passphrase ) - { + public void setPassphrase(final String passphrase) { this.passphrase = passphrase; } @@ -111,8 +102,7 @@ public class Authentication * * @return absolute path to private key */ - public String getPrivateKey() - { + public String getPrivateKey() { return privateKey; } @@ -121,9 +111,7 @@ public class Authentication * * @param privateKey path to private key in local file system */ - public void setPrivateKey( final String privateKey ) - { + public void setPrivateKey(final String privateKey) { this.privateKey = privateKey; } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout.java b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout.java index 2a18c863df..a71c04429f 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.layout; * "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 + * 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 @@ -18,21 +16,21 @@ package org.apache.maven.artifact.repository.layout; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.layout; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; /** @author jdcasey */ -public interface ArtifactRepositoryLayout -{ +public interface ArtifactRepositoryLayout { String ROLE = ArtifactRepositoryLayout.class.getName(); String getId(); - String pathOf( Artifact artifact ); + String pathOf(Artifact artifact); - String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ); + String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository); - String pathOfRemoteRepositoryMetadata( ArtifactMetadata metadata ); + String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout2.java b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout2.java index f6bc573005..8cdc09d8a9 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout2.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout2.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.layout; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.layout; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.layout; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -25,10 +24,8 @@ import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; /** * ArtifactRepositoryLayout2 */ -public interface ArtifactRepositoryLayout2 - extends ArtifactRepositoryLayout -{ +public interface ArtifactRepositoryLayout2 extends ArtifactRepositoryLayout { - ArtifactRepository newMavenArtifactRepository( String id, String url, ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ); + ArtifactRepository newMavenArtifactRepository( + String id, String url, ArtifactRepositoryPolicy snapshots, ArtifactRepositoryPolicy releases); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataStoreException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataStoreException.java index 384885220a..3b369d134e 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataStoreException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataStoreException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; /** * Problem storing the repository metadata in the local repository. * * @author Brett Porter */ -public class RepositoryMetadataStoreException - extends Exception -{ - public RepositoryMetadataStoreException( String message ) - { - super( message ); +public class RepositoryMetadataStoreException extends Exception { + public RepositoryMetadataStoreException(String message) { + super(message); } - public RepositoryMetadataStoreException( String message, - Exception e ) - { - super( message, e ); + public RepositoryMetadataStoreException(String message, Exception e) { + super(message, e); } } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java index a2917b5cd8..baca0e1543 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.Iterator; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -31,9 +29,7 @@ import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; * * @author Brett Porter */ -public class AbstractArtifactResolutionException - extends Exception -{ +public class AbstractArtifactResolutionException extends Exception { private String groupId; private String artifactId; @@ -54,31 +50,31 @@ public class AbstractArtifactResolutionException static final String LS = System.lineSeparator(); - @SuppressWarnings( "checkstyle:parameternumber" ) - protected AbstractArtifactResolutionException( String message, - String groupId, - String artifactId, - String version, - String type, - String classifier, - List remoteRepositories, - List path ) - { - this( message, groupId, artifactId, version, type, classifier, remoteRepositories, path, null ); + @SuppressWarnings("checkstyle:parameternumber") + protected AbstractArtifactResolutionException( + String message, + String groupId, + String artifactId, + String version, + String type, + String classifier, + List remoteRepositories, + List path) { + this(message, groupId, artifactId, version, type, classifier, remoteRepositories, path, null); } - @SuppressWarnings( "checkstyle:parameternumber" ) - protected AbstractArtifactResolutionException( String message, - String groupId, - String artifactId, - String version, - String type, - String classifier, - List remoteRepositories, - List path, - Throwable t ) - { - super( constructMessageBase( message, groupId, artifactId, version, type, remoteRepositories, path ), t ); + @SuppressWarnings("checkstyle:parameternumber") + protected AbstractArtifactResolutionException( + String message, + String groupId, + String artifactId, + String version, + String type, + String classifier, + List remoteRepositories, + List path, + Throwable t) { + super(constructMessageBase(message, groupId, artifactId, version, type, remoteRepositories, path), t); this.originalMessage = message; this.groupId = groupId; @@ -87,261 +83,241 @@ public class AbstractArtifactResolutionException this.classifier = classifier; this.version = version; this.remoteRepositories = remoteRepositories; - this.path = constructArtifactPath( path, "" ); + this.path = constructArtifactPath(path, ""); } - protected AbstractArtifactResolutionException( String message, - Artifact artifact ) - { - this( message, artifact, null ); + protected AbstractArtifactResolutionException(String message, Artifact artifact) { + this(message, artifact, null); } - protected AbstractArtifactResolutionException( String message, - Artifact artifact, - List remoteRepositories ) - { - this( message, artifact, remoteRepositories, null ); + protected AbstractArtifactResolutionException( + String message, Artifact artifact, List remoteRepositories) { + this(message, artifact, remoteRepositories, null); } - protected AbstractArtifactResolutionException( String message, - Artifact artifact, - List remoteRepositories, - Throwable t ) - { - this( message, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), - artifact.getClassifier(), remoteRepositories, artifact.getDependencyTrail(), t ); + protected AbstractArtifactResolutionException( + String message, Artifact artifact, List remoteRepositories, Throwable t) { + this( + message, + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + artifact.getType(), + artifact.getClassifier(), + remoteRepositories, + artifact.getDependencyTrail(), + t); this.artifact = artifact; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getVersion() - { + public String getVersion() { return version; } - public String getType() - { + public String getType() { return type; } /** @return the classifier */ - public String getClassifier() - { + public String getClassifier() { return this.classifier; } /** @return the path */ - public String getPath() - { + public String getPath() { return this.path; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - public String getOriginalMessage() - { + public String getOriginalMessage() { return originalMessage; } - protected static String constructArtifactPath( List path, - String indentation ) - { + protected static String constructArtifactPath(List path, String indentation) { StringBuilder sb = new StringBuilder(); - if ( path != null ) - { - sb.append( LS ); - sb.append( indentation ); - sb.append( "Path to dependency: " ); - sb.append( LS ); + if (path != null) { + sb.append(LS); + sb.append(indentation); + sb.append("Path to dependency: "); + sb.append(LS); int num = 1; - for ( Iterator i = path.iterator(); i.hasNext(); num++ ) - { - sb.append( indentation ); - sb.append( '\t' ); - sb.append( num ); - sb.append( ") " ); - sb.append( i.next() ); - sb.append( LS ); + for (Iterator i = path.iterator(); i.hasNext(); num++) { + sb.append(indentation); + sb.append('\t'); + sb.append(num); + sb.append(") "); + sb.append(i.next()); + sb.append(LS); } } return sb.toString(); } - private static String constructMessageBase( String message, - String groupId, - String artifactId, - String version, - String type, - List remoteRepositories, - List path ) - { + private static String constructMessageBase( + String message, + String groupId, + String artifactId, + String version, + String type, + List remoteRepositories, + List path) { StringBuilder sb = new StringBuilder(); - sb.append( message ); + sb.append(message); - if ( message == null || !message.contains( "from the specified remote repositories:" ) ) - { - sb.append( LS ); - sb.append( " " ).append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( type ).append( - ':' ).append( version ); - sb.append( LS ); - if ( remoteRepositories != null ) - { - sb.append( LS ); - sb.append( "from the specified remote repositories:" ); - sb.append( LS ).append( " " ); + if (message == null || !message.contains("from the specified remote repositories:")) { + sb.append(LS); + sb.append(" ") + .append(groupId) + .append(':') + .append(artifactId) + .append(':') + .append(type) + .append(':') + .append(version); + sb.append(LS); + if (remoteRepositories != null) { + sb.append(LS); + sb.append("from the specified remote repositories:"); + sb.append(LS).append(" "); - if ( remoteRepositories.isEmpty() ) - { - sb.append( "(none)" ); + if (remoteRepositories.isEmpty()) { + sb.append("(none)"); } - for ( Iterator i = remoteRepositories.iterator(); i.hasNext(); ) - { + for (Iterator i = remoteRepositories.iterator(); i.hasNext(); ) { ArtifactRepository remoteRepository = i.next(); - sb.append( remoteRepository.getId() ); - sb.append( " (" ); - sb.append( remoteRepository.getUrl() ); + sb.append(remoteRepository.getId()); + sb.append(" ("); + sb.append(remoteRepository.getUrl()); ArtifactRepositoryPolicy releases = remoteRepository.getReleases(); - if ( releases != null ) - { - sb.append( ", releases=" ).append( releases.isEnabled() ); + if (releases != null) { + sb.append(", releases=").append(releases.isEnabled()); } ArtifactRepositoryPolicy snapshots = remoteRepository.getSnapshots(); - if ( snapshots != null ) - { - sb.append( ", snapshots=" ).append( snapshots.isEnabled() ); + if (snapshots != null) { + sb.append(", snapshots=").append(snapshots.isEnabled()); } - sb.append( ')' ); - if ( i.hasNext() ) - { - sb.append( ',' ).append( LS ).append( " " ); + sb.append(')'); + if (i.hasNext()) { + sb.append(',').append(LS).append(" "); } } } - sb.append( constructArtifactPath( path, "" ) ); - sb.append( LS ); + sb.append(constructArtifactPath(path, "")); + sb.append(LS); } return sb.toString(); } - @SuppressWarnings( "checkstyle:parameternumber" ) - protected static String constructMissingArtifactMessage( String message, - String indentation, - String groupId, - String artifactId, - String version, - String type, - String classifier, - String downloadUrl, - List path ) - { - StringBuilder sb = new StringBuilder( message ); + @SuppressWarnings("checkstyle:parameternumber") + protected static String constructMissingArtifactMessage( + String message, + String indentation, + String groupId, + String artifactId, + String version, + String type, + String classifier, + String downloadUrl, + List path) { + StringBuilder sb = new StringBuilder(message); - if ( !"pom".equals( type ) ) - { - if ( downloadUrl != null ) - { - sb.append( LS ); - sb.append( LS ); - sb.append( indentation ); - sb.append( "Try downloading the file manually from: " ); - sb.append( LS ); - sb.append( indentation ); - sb.append( " " ); - sb.append( downloadUrl ); - } - else - { - sb.append( LS ); - sb.append( LS ); - sb.append( indentation ); - sb.append( "Try downloading the file manually from the project website." ); + if (!"pom".equals(type)) { + if (downloadUrl != null) { + sb.append(LS); + sb.append(LS); + sb.append(indentation); + sb.append("Try downloading the file manually from: "); + sb.append(LS); + sb.append(indentation); + sb.append(" "); + sb.append(downloadUrl); + } else { + sb.append(LS); + sb.append(LS); + sb.append(indentation); + sb.append("Try downloading the file manually from the project website."); } - sb.append( LS ); - sb.append( LS ); - sb.append( indentation ); - sb.append( "Then, install it using the command: " ); - sb.append( LS ); - sb.append( indentation ); - sb.append( " mvn install:install-file -DgroupId=" ); - sb.append( groupId ); - sb.append( " -DartifactId=" ); - sb.append( artifactId ); - sb.append( " -Dversion=" ); - sb.append( version ); + sb.append(LS); + sb.append(LS); + sb.append(indentation); + sb.append("Then, install it using the command: "); + sb.append(LS); + sb.append(indentation); + sb.append(" mvn install:install-file -DgroupId="); + sb.append(groupId); + sb.append(" -DartifactId="); + sb.append(artifactId); + sb.append(" -Dversion="); + sb.append(version); - //insert classifier only if it was used in the artifact - if ( classifier != null && !classifier.equals( "" ) ) - { - sb.append( " -Dclassifier=" ); - sb.append( classifier ); + // insert classifier only if it was used in the artifact + if (classifier != null && !classifier.equals("")) { + sb.append(" -Dclassifier="); + sb.append(classifier); } - sb.append( " -Dpackaging=" ); - sb.append( type ); - sb.append( " -Dfile=/path/to/file" ); - sb.append( LS ); + sb.append(" -Dpackaging="); + sb.append(type); + sb.append(" -Dfile=/path/to/file"); + sb.append(LS); // If people want to deploy it - sb.append( LS ); - sb.append( indentation ); - sb.append( "Alternatively, if you host your own repository you can deploy the file there: " ); - sb.append( LS ); - sb.append( indentation ); - sb.append( " mvn deploy:deploy-file -DgroupId=" ); - sb.append( groupId ); - sb.append( " -DartifactId=" ); - sb.append( artifactId ); - sb.append( " -Dversion=" ); - sb.append( version ); + sb.append(LS); + sb.append(indentation); + sb.append("Alternatively, if you host your own repository you can deploy the file there: "); + sb.append(LS); + sb.append(indentation); + sb.append(" mvn deploy:deploy-file -DgroupId="); + sb.append(groupId); + sb.append(" -DartifactId="); + sb.append(artifactId); + sb.append(" -Dversion="); + sb.append(version); - //insert classifier only if it was used in the artifact - if ( classifier != null && !classifier.equals( "" ) ) - { - sb.append( " -Dclassifier=" ); - sb.append( classifier ); + // insert classifier only if it was used in the artifact + if (classifier != null && !classifier.equals("")) { + sb.append(" -Dclassifier="); + sb.append(classifier); } - sb.append( " -Dpackaging=" ); - sb.append( type ); - sb.append( " -Dfile=/path/to/file" ); - sb.append( " -Durl=[url] -DrepositoryId=[id]" ); - sb.append( LS ); + sb.append(" -Dpackaging="); + sb.append(type); + sb.append(" -Dfile=/path/to/file"); + sb.append(" -Durl=[url] -DrepositoryId=[id]"); + sb.append(LS); } - sb.append( constructArtifactPath( path, indentation ) ); - sb.append( LS ); + sb.append(constructArtifactPath(path, indentation)); + sb.append(LS); return sb.toString(); } - public String getArtifactPath() - { + public String getArtifactPath() { return path; } } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactNotFoundException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactNotFoundException.java index 76f7b584c5..8e4632e178 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactNotFoundException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,68 +16,104 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.artifact.resolver; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; /** * @author Jason van Zyl */ -public class ArtifactNotFoundException - extends AbstractArtifactResolutionException -{ +public class ArtifactNotFoundException extends AbstractArtifactResolutionException { private String downloadUrl; - protected ArtifactNotFoundException( String message, Artifact artifact, - List remoteRepositories ) - { - super( message, artifact, remoteRepositories ); + protected ArtifactNotFoundException( + String message, Artifact artifact, List remoteRepositories) { + super(message, artifact, remoteRepositories); } - public ArtifactNotFoundException( String message, Artifact artifact ) - { - this( message, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), - artifact.getClassifier(), null, artifact.getDownloadUrl(), artifact.getDependencyTrail() ); + public ArtifactNotFoundException(String message, Artifact artifact) { + this( + message, + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + artifact.getType(), + artifact.getClassifier(), + null, + artifact.getDownloadUrl(), + artifact.getDependencyTrail()); } - protected ArtifactNotFoundException( String message, Artifact artifact, - List remoteRepositories, Throwable cause ) - { - this( message, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), - artifact.getClassifier(), remoteRepositories, artifact.getDownloadUrl(), artifact.getDependencyTrail(), - cause ); + protected ArtifactNotFoundException( + String message, Artifact artifact, List remoteRepositories, Throwable cause) { + this( + message, + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + artifact.getType(), + artifact.getClassifier(), + remoteRepositories, + artifact.getDownloadUrl(), + artifact.getDependencyTrail(), + cause); } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactNotFoundException( String message, String groupId, String artifactId, String version, String type, - String classifier, List remoteRepositories, - String downloadUrl, List path, Throwable cause ) - { - super( constructMissingArtifactMessage( message, "", groupId, artifactId, version, type, classifier, - downloadUrl, path ), groupId, artifactId, version, type, classifier, - remoteRepositories, null, cause ); + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactNotFoundException( + String message, + String groupId, + String artifactId, + String version, + String type, + String classifier, + List remoteRepositories, + String downloadUrl, + List path, + Throwable cause) { + super( + constructMissingArtifactMessage( + message, "", groupId, artifactId, version, type, classifier, downloadUrl, path), + groupId, + artifactId, + version, + type, + classifier, + remoteRepositories, + null, + cause); this.downloadUrl = downloadUrl; } - @SuppressWarnings( "checkstyle:parameternumber" ) - private ArtifactNotFoundException( String message, String groupId, String artifactId, String version, String type, - String classifier, List remoteRepositories, - String downloadUrl, List path ) - { - super( constructMissingArtifactMessage( message, "", groupId, artifactId, version, type, classifier, - downloadUrl, path ), groupId, artifactId, version, type, classifier, - remoteRepositories, null ); + @SuppressWarnings("checkstyle:parameternumber") + private ArtifactNotFoundException( + String message, + String groupId, + String artifactId, + String version, + String type, + String classifier, + List remoteRepositories, + String downloadUrl, + List path) { + super( + constructMissingArtifactMessage( + message, "", groupId, artifactId, version, type, classifier, downloadUrl, path), + groupId, + artifactId, + version, + type, + classifier, + remoteRepositories, + null); this.downloadUrl = downloadUrl; } - public String getDownloadUrl() - { + public String getDownloadUrl() { return downloadUrl; } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionException.java index 074d812caa..c6fa723607 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,51 +16,55 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; /** * @author Jason van Zyl */ -public class ArtifactResolutionException - extends AbstractArtifactResolutionException -{ - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactResolutionException( String message, String groupId, String artifactId, String version, String type, - String classifier, List remoteRepositories, - List path, Throwable t ) - { - super( message, groupId, artifactId, version, type, classifier, remoteRepositories, path, t ); +public class ArtifactResolutionException extends AbstractArtifactResolutionException { + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactResolutionException( + String message, + String groupId, + String artifactId, + String version, + String type, + String classifier, + List remoteRepositories, + List path, + Throwable t) { + super(message, groupId, artifactId, version, type, classifier, remoteRepositories, path, t); } - public ArtifactResolutionException( String message, String groupId, String artifactId, String version, String type, - String classifier, Throwable t ) - { - super( message, groupId, artifactId, version, type, classifier, null, null, t ); + public ArtifactResolutionException( + String message, + String groupId, + String artifactId, + String version, + String type, + String classifier, + Throwable t) { + super(message, groupId, artifactId, version, type, classifier, null, null, t); } - public ArtifactResolutionException( String message, Artifact artifact ) - { - super( message, artifact ); + public ArtifactResolutionException(String message, Artifact artifact) { + super(message, artifact); } - public ArtifactResolutionException( String message, Artifact artifact, List remoteRepositories ) - { - super( message, artifact, remoteRepositories ); + public ArtifactResolutionException(String message, Artifact artifact, List remoteRepositories) { + super(message, artifact, remoteRepositories); } - public ArtifactResolutionException( String message, Artifact artifact, Throwable cause ) - { - super( message, artifact, null, cause ); + public ArtifactResolutionException(String message, Artifact artifact, Throwable cause) { + super(message, artifact, null, cause); } - public ArtifactResolutionException( String message, Artifact artifact, List remoteRepositories, - Throwable cause ) - { - super( message, artifact, remoteRepositories, cause ); + public ArtifactResolutionException( + String message, Artifact artifact, List remoteRepositories, Throwable cause) { + super(message, artifact, remoteRepositories, cause); } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/CyclicDependencyException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/CyclicDependencyException.java index bbc6733e90..e665201310 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/CyclicDependencyException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/CyclicDependencyException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import org.apache.maven.artifact.Artifact; @@ -26,20 +25,15 @@ import org.apache.maven.artifact.Artifact; * * @author Brett Porter */ -public class CyclicDependencyException - extends ArtifactResolutionException -{ +public class CyclicDependencyException extends ArtifactResolutionException { private Artifact artifact; - public CyclicDependencyException( String message, - Artifact artifact ) - { - super( message, artifact ); + public CyclicDependencyException(String message, Artifact artifact) { + super(message, artifact); this.artifact = artifact; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/MultipleArtifactsNotFoundException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/MultipleArtifactsNotFoundException.java index 24dcdb42fb..1186af807c 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/MultipleArtifactsNotFoundException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/MultipleArtifactsNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.ArrayList; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -29,9 +27,7 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * Exception caused when one or more artifacts can not be resolved because they are not found in the * local or remote repositories. */ -public class MultipleArtifactsNotFoundException - extends ArtifactResolutionException -{ +public class MultipleArtifactsNotFoundException extends ArtifactResolutionException { private static final String LS = System.lineSeparator(); private final List resolvedArtifacts; @@ -44,11 +40,11 @@ public class MultipleArtifactsNotFoundException * @deprecated use {@link #MultipleArtifactsNotFoundException(Artifact, List, List, List)} */ @Deprecated - public MultipleArtifactsNotFoundException( Artifact originatingArtifact, - List missingArtifacts, - List remoteRepositories ) - { - this( originatingArtifact, new ArrayList<>(), missingArtifacts, remoteRepositories ); + public MultipleArtifactsNotFoundException( + Artifact originatingArtifact, + List missingArtifacts, + List remoteRepositories) { + this(originatingArtifact, new ArrayList<>(), missingArtifacts, remoteRepositories); } /** @@ -59,12 +55,12 @@ public class MultipleArtifactsNotFoundException * @param missingArtifacts artifacts that could not be resolved * @param remoteRepositories remote repositories where the missing artifacts were not found */ - public MultipleArtifactsNotFoundException( Artifact originatingArtifact, - List resolvedArtifacts, - List missingArtifacts, - List remoteRepositories ) - { - super( constructMessage( missingArtifacts ), originatingArtifact, remoteRepositories ); + public MultipleArtifactsNotFoundException( + Artifact originatingArtifact, + List resolvedArtifacts, + List missingArtifacts, + List remoteRepositories) { + super(constructMessage(missingArtifacts), originatingArtifact, remoteRepositories); this.resolvedArtifacts = resolvedArtifacts; this.missingArtifacts = missingArtifacts; } @@ -74,8 +70,7 @@ public class MultipleArtifactsNotFoundException * * @return {@link List} of {@link Artifact} */ - public List getResolvedArtifacts() - { + public List getResolvedArtifacts() { return resolvedArtifacts; } @@ -84,47 +79,47 @@ public class MultipleArtifactsNotFoundException * * @return {@link List} of {@link Artifact} */ - public List getMissingArtifacts() - { + public List getMissingArtifacts() { return missingArtifacts; } - private static String constructMessage( List artifacts ) - { - StringBuilder buffer = new StringBuilder( 256 ); + private static String constructMessage(List artifacts) { + StringBuilder buffer = new StringBuilder(256); - buffer.append( "Missing:" ).append( LS ); - buffer.append( "----------" ).append( LS ); + buffer.append("Missing:").append(LS); + buffer.append("----------").append(LS); int counter = 0; - for ( Artifact artifact : artifacts ) - { - String message = ( ++counter ) + ") " + artifact.getId(); + for (Artifact artifact : artifacts) { + String message = (++counter) + ") " + artifact.getId(); - buffer.append( constructMissingArtifactMessage( message, " ", artifact.getGroupId(), - artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), artifact.getClassifier(), - artifact.getDownloadUrl(), artifact.getDependencyTrail() ) ); + buffer.append(constructMissingArtifactMessage( + message, + " ", + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + artifact.getType(), + artifact.getClassifier(), + artifact.getDownloadUrl(), + artifact.getDependencyTrail())); } - buffer.append( "----------" ).append( LS ); + buffer.append("----------").append(LS); int size = artifacts.size(); - buffer.append( size ).append( " required artifact" ); + buffer.append(size).append(" required artifact"); - if ( size > 1 ) - { - buffer.append( "s are" ); - } - else - { - buffer.append( " is" ); + if (size > 1) { + buffer.append("s are"); + } else { + buffer.append(" is"); } - buffer.append( " missing." ).append( LS ).append( LS ).append( "for artifact: " ); + buffer.append(" missing.").append(LS).append(LS).append("for artifact: "); return buffer.toString(); } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ArtifactFilter.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ArtifactFilter.java index 27b08a88c4..81c7fb4710 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ArtifactFilter.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import org.apache.maven.artifact.Artifact; /** * @author Jason van Zyl */ -public interface ArtifactFilter -{ - boolean include( Artifact artifact ); +public interface ArtifactFilter { + boolean include(Artifact artifact); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ArtifactVersion.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ArtifactVersion.java index 5b516a91d0..3afc57ec27 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ArtifactVersion.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ArtifactVersion.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; /** * Describes an artifact version in terms of its components, converts it to/from a string and @@ -25,9 +24,7 @@ package org.apache.maven.artifact.versioning; * * @author Brett Porter */ -public interface ArtifactVersion - extends Comparable -{ +public interface ArtifactVersion extends Comparable { int getMajorVersion(); int getMinorVersion(); @@ -38,5 +35,5 @@ public interface ArtifactVersion String getQualifier(); - void parseVersion( String version ); + void parseVersion(String version); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java index 24c7886007..d822471c8b 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; import java.math.BigInteger; import java.util.ArrayDeque; @@ -60,9 +59,7 @@ import java.util.Properties; * @author Kenney Westerhof * @author Hervé Boutemy */ -public class ComparableVersion - implements Comparable -{ +public class ComparableVersion implements Comparable { private static final int MAX_INTITEM_LENGTH = 9; private static final int MAX_LONGITEM_LENGTH = 18; @@ -73,15 +70,14 @@ public class ComparableVersion private ListItem items; - private interface Item - { + private interface Item { int INT_ITEM = 3; int LONG_ITEM = 4; int BIGINTEGER_ITEM = 0; int STRING_ITEM = 1; int LIST_ITEM = 2; - int compareTo( Item item ); + int compareTo(Item item); int getType(); @@ -91,48 +87,39 @@ public class ComparableVersion /** * Represents a numeric item in the version item list that can be represented with an int. */ - private static class IntItem - implements Item - { + private static class IntItem implements Item { private final int value; public static final IntItem ZERO = new IntItem(); - private IntItem() - { + private IntItem() { this.value = 0; } - IntItem( String str ) - { - this.value = Integer.parseInt( str ); + IntItem(String str) { + this.value = Integer.parseInt(str); } @Override - public int getType() - { + public int getType() { return INT_ITEM; } @Override - public boolean isNull() - { + public boolean isNull() { return value == 0; } @Override - public int compareTo( Item item ) - { - if ( item == null ) - { - return ( value == 0 ) ? 0 : 1; // 1.0 == 1, 1.1 > 1 + public int compareTo(Item item) { + if (item == null) { + return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 } - switch ( item.getType() ) - { + switch (item.getType()) { case INT_ITEM: - int itemValue = ( (IntItem) item ).value; - return Integer.compare( value, itemValue ); + int itemValue = ((IntItem) item).value; + return Integer.compare(value, itemValue); case LONG_ITEM: case BIGINTEGER_ITEM: return -1; @@ -144,81 +131,67 @@ public class ComparableVersion return 1; // 1.1 > 1-1 default: - throw new IllegalStateException( "invalid item: " + item.getClass() ); + throw new IllegalStateException("invalid item: " + item.getClass()); } } @Override - 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; } IntItem intItem = (IntItem) o; return value == intItem.value; - } @Override - public int hashCode() - { + public int hashCode() { return value; } @Override - public String toString() - { - return Integer.toString( value ); + public String toString() { + return Integer.toString(value); } } /** * Represents a numeric item in the version item list that can be represented with a long. */ - private static class LongItem - implements Item - { + private static class LongItem implements Item { private final long value; - LongItem( String str ) - { - this.value = Long.parseLong( str ); + LongItem(String str) { + this.value = Long.parseLong(str); } @Override - public int getType() - { + public int getType() { return LONG_ITEM; } @Override - public boolean isNull() - { + public boolean isNull() { return value == 0; } @Override - public int compareTo( Item item ) - { - if ( item == null ) - { - return ( value == 0 ) ? 0 : 1; // 1.0 == 1, 1.1 > 1 + public int compareTo(Item item) { + if (item == null) { + return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 } - switch ( item.getType() ) - { + switch (item.getType()) { case INT_ITEM: return 1; case LONG_ITEM: - long itemValue = ( (LongItem) item ).value; - return Long.compare( value, itemValue ); + long itemValue = ((LongItem) item).value; + return Long.compare(value, itemValue); case BIGINTEGER_ITEM: return -1; @@ -229,82 +202,68 @@ public class ComparableVersion return 1; // 1.1 > 1-1 default: - throw new IllegalStateException( "invalid item: " + item.getClass() ); + throw new IllegalStateException("invalid item: " + item.getClass()); } } @Override - 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; } LongItem longItem = (LongItem) o; return value == longItem.value; - } @Override - public int hashCode() - { - return (int) ( value ^ ( value >>> 32 ) ); + public int hashCode() { + return (int) (value ^ (value >>> 32)); } @Override - public String toString() - { - return Long.toString( value ); + public String toString() { + return Long.toString(value); } } /** * Represents a numeric item in the version item list. */ - private static class BigIntegerItem - implements Item - { + private static class BigIntegerItem implements Item { private final BigInteger value; - BigIntegerItem( String str ) - { - this.value = new BigInteger( str ); + BigIntegerItem(String str) { + this.value = new BigInteger(str); } @Override - public int getType() - { + public int getType() { return BIGINTEGER_ITEM; } @Override - public boolean isNull() - { - return BigInteger.ZERO.equals( value ); + public boolean isNull() { + return BigInteger.ZERO.equals(value); } @Override - public int compareTo( Item item ) - { - if ( item == null ) - { - return BigInteger.ZERO.equals( value ) ? 0 : 1; // 1.0 == 1, 1.1 > 1 + public int compareTo(Item item) { + if (item == null) { + return BigInteger.ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 } - switch ( item.getType() ) - { + switch (item.getType()) { case INT_ITEM: case LONG_ITEM: return 1; case BIGINTEGER_ITEM: - return value.compareTo( ( (BigIntegerItem) item ).value ); + return value.compareTo(((BigIntegerItem) item).value); case STRING_ITEM: return 1; // 1.1 > 1-sp @@ -313,36 +272,30 @@ public class ComparableVersion return 1; // 1.1 > 1-1 default: - throw new IllegalStateException( "invalid item: " + item.getClass() ); + throw new IllegalStateException("invalid item: " + item.getClass()); } } @Override - 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; } BigIntegerItem that = (BigIntegerItem) o; - return value.equals( that.value ); - + return value.equals(that.value); } @Override - public int hashCode() - { + public int hashCode() { return value.hashCode(); } - public String toString() - { + public String toString() { return value.toString(); } } @@ -350,36 +303,31 @@ public class ComparableVersion /** * Represents a string in the version item list, usually a qualifier. */ - private static class StringItem - implements Item - { + private static class StringItem implements Item { private static final List QUALIFIERS = - Arrays.asList( "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" ); + Arrays.asList("alpha", "beta", "milestone", "rc", "snapshot", "", "sp"); private static final Properties ALIASES = new Properties(); - static - { - ALIASES.put( "ga", "" ); - ALIASES.put( "final", "" ); - ALIASES.put( "release", "" ); - ALIASES.put( "cr", "rc" ); + + static { + ALIASES.put("ga", ""); + ALIASES.put("final", ""); + ALIASES.put("release", ""); + ALIASES.put("cr", "rc"); } /** * A comparable value 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 String RELEASE_VERSION_INDEX = String.valueOf( QUALIFIERS.indexOf( "" ) ); + private static final String RELEASE_VERSION_INDEX = String.valueOf(QUALIFIERS.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; @@ -392,19 +340,17 @@ public class ComparableVersion default: } } - this.value = ALIASES.getProperty( value , value ); + this.value = ALIASES.getProperty(value, value); } @Override - public int getType() - { + public int getType() { return STRING_ITEM; } @Override - public boolean isNull() - { - return ( comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX ) == 0 ); + public boolean isNull() { + return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); } /** @@ -420,65 +366,55 @@ public class ComparableVersion * @param qualifier * @return an equivalent value that can be used with lexical comparison */ - public static String comparableQualifier( String qualifier ) - { - int i = QUALIFIERS.indexOf( qualifier ); + public static String comparableQualifier(String qualifier) { + int i = QUALIFIERS.indexOf(qualifier); - return i == -1 ? ( QUALIFIERS.size() + "-" + qualifier ) : String.valueOf( i ); + return i == -1 ? (QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i); } @Override - 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 INT_ITEM: case LONG_ITEM: case BIGINTEGER_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 IllegalStateException( "invalid item: " + item.getClass() ); + throw new IllegalStateException("invalid item: " + item.getClass()); } } @Override - 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; } StringItem that = (StringItem) o; - return value.equals( that.value ); - + return value.equals(that.value); } @Override - public int hashCode() - { + public int hashCode() { return value.hashCode(); } - public String toString() - { + public String toString() { return value; } } @@ -487,62 +423,46 @@ public class ComparableVersion * 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 - { + private static class ListItem extends ArrayList implements Item { @Override - public int getType() - { + public int getType() { return LIST_ITEM; } @Override - public boolean isNull() - { - return ( size() == 0 ); + public boolean isNull() { + return (size() == 0); } - void normalize() - { - for ( int i = size() - 1; i >= 0; i-- ) - { - Item lastItem = get( i ); + void normalize() { + for (int i = size() - 1; i >= 0; i--) { + Item lastItem = get(i); - if ( lastItem.isNull() ) - { + if (lastItem.isNull()) { // remove null trailing items: 0, "", empty list - remove( i ); - } - else if ( !( lastItem instanceof ListItem ) ) - { + remove(i); + } else if (!(lastItem instanceof ListItem)) { break; } } } @Override - 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 } // Compare the entire list of items with null - not just the first one, MNG-6964 - for ( Item i : this ) - { - int result = i.compareTo( null ); - if ( result != 0 ) - { + for (Item i : this) { + int result = i.compareTo(null); + if (result != 0) { return result; } } return 0; } - switch ( item.getType() ) - { + switch (item.getType()) { case INT_ITEM: case LONG_ITEM: case BIGINTEGER_ITEM: @@ -553,18 +473,16 @@ public class ComparableVersion 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 ? ( r == null ? 0 : -1 * r.compareTo( l ) ) : l.compareTo( r ); + int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r); - if ( result != 0 ) - { + if (result != 0) { return result; } } @@ -572,21 +490,18 @@ public class ComparableVersion return 0; default: - throw new IllegalStateException( "invalid item: " + item.getClass() ); + throw new IllegalStateException("invalid item: " + item.getClass()); } } @Override - public String toString() - { + public String toString() { StringBuilder buffer = new StringBuilder(); - for ( Item item : this ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ( item instanceof ListItem ) ? '-' : '.' ); + for (Item item : this) { + if (buffer.length() > 0) { + buffer.append((item instanceof ListItem) ? '-' : '.'); } - buffer.append( item ); + buffer.append(item); } return buffer.toString(); } @@ -594,191 +509,150 @@ public class ComparableVersion /** * Return the contents in the same format that is used when you call toString() on a List. */ - private String toListString() - { + private String toListString() { StringBuilder buffer = new StringBuilder(); - buffer.append( "[" ); - for ( Item item : this ) - { - if ( buffer.length() > 1 ) - { - buffer.append( ", " ); + buffer.append("["); + for (Item item : this) { + if (buffer.length() > 1) { + buffer.append(", "); } - if ( item instanceof ListItem ) - { - buffer.append( ( (ListItem ) item ).toListString() ); - } - else - { - buffer.append( item ); + if (item instanceof ListItem) { + buffer.append(((ListItem) item).toListString()); + } else { + buffer.append(item); } } - buffer.append( "]" ); + buffer.append("]"); return buffer.toString(); } } - public ComparableVersion( String version ) - { - parseVersion( version ); + public ComparableVersion(String version) { + parseVersion(version); } - @SuppressWarnings( "checkstyle:innerassignment" ) - public final void parseVersion( String version ) - { + @SuppressWarnings("checkstyle:innerassignment") + 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; Deque stack = new ArrayDeque<>(); - 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( IntItem.ZERO ); - } - else - { - list.add( parseItem( isDigit, version.substring( startIndex, i ) ) ); + if (c == '.') { + if (i == startIndex) { + list.add(IntItem.ZERO); + } else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); } startIndex = i + 1; - } - else if ( c == '-' ) - { - if ( i == startIndex ) - { - list.add( IntItem.ZERO ); - } - else - { - list.add( parseItem( isDigit, version.substring( startIndex, i ) ) ); + } else if (c == '-') { + if (i == startIndex) { + list.add(IntItem.ZERO); + } else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); } startIndex = i + 1; - list.add( list = new ListItem() ); - stack.push( list ); - } - else if ( Character.isDigit( c ) ) - { - if ( !isDigit && i > startIndex ) - { - list.add( new StringItem( version.substring( startIndex, i ), true ) ); + list.add(list = new ListItem()); + stack.push(list); + } else if (Character.isDigit(c)) { + if (!isDigit && i > startIndex) { + list.add(new StringItem(version.substring(startIndex, i), true)); startIndex = i; - list.add( list = new ListItem() ); - stack.push( list ); + list.add(list = new ListItem()); + stack.push(list); } 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; - list.add( list = new ListItem() ); - stack.push( list ); + list.add(list = new ListItem()); + stack.push(list); } isDigit = false; } } - 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 = (ListItem) stack.pop(); list.normalize(); } } - private static Item parseItem( boolean isDigit, String buf ) - { - if ( isDigit ) - { - buf = stripLeadingZeroes( buf ); - if ( buf.length() <= MAX_INTITEM_LENGTH ) - { + private static Item parseItem(boolean isDigit, String buf) { + if (isDigit) { + buf = stripLeadingZeroes(buf); + if (buf.length() <= MAX_INTITEM_LENGTH) { // lower than 2^31 - return new IntItem( buf ); - } - else if ( buf.length() <= MAX_LONGITEM_LENGTH ) - { + return new IntItem(buf); + } else if (buf.length() <= MAX_LONGITEM_LENGTH) { // lower than 2^63 - return new LongItem( buf ); + return new LongItem(buf); } - return new BigIntegerItem( buf ); + return new BigIntegerItem(buf); } - return new StringItem( buf, false ); + return new StringItem(buf, false); } - private static String stripLeadingZeroes( String buf ) - { - if ( buf == null || buf.isEmpty() ) - { + private static String stripLeadingZeroes(String buf) { + if (buf == null || buf.isEmpty()) { return "0"; } - for ( int i = 0; i < buf.length(); ++i ) - { - char c = buf.charAt( i ); - if ( c != '0' ) - { - return buf.substring( i ); + for (int i = 0; i < buf.length(); ++i) { + char c = buf.charAt(i); + if (c != '0') { + return buf.substring(i); } } return buf; } @Override - public int compareTo( ComparableVersion o ) - { - return items.compareTo( o.items ); + public int compareTo(ComparableVersion o) { + return items.compareTo(o.items); } @Override - public String toString() - { + public String toString() { return value; } - public String getCanonical() - { - if ( canonical == null ) - { + public String getCanonical() { + if (canonical == null) { canonical = items.toString(); } return canonical; } @Override - public boolean equals( Object o ) - { - return ( o instanceof ComparableVersion ) && items.equals( ( (ComparableVersion) o ).items ); + public boolean equals(Object o) { + return (o instanceof ComparableVersion) && items.equals(((ComparableVersion) o).items); } @Override - public int hashCode() - { + public int hashCode() { return items.hashCode(); } @@ -800,30 +674,26 @@ public class ComparableVersion * two adjacent will be compared */ // CHECKSTYLE_ON: LineLength - public static void main( String... args ) - { - System.out.println( "Display parameters as parsed by Maven (in canonical form and as a list of tokens) and" - + " comparison result:" ); - if ( args.length == 0 ) - { + public static void main(String... args) { + System.out.println("Display parameters as parsed by Maven (in canonical form and as a list of tokens) and" + + " comparison result:"); + if (args.length == 0) { return; } ComparableVersion prev = null; int i = 1; - for ( String version : args ) - { - ComparableVersion c = new ComparableVersion( version ); + for (String version : args) { + ComparableVersion c = new ComparableVersion(version); - if ( prev != null ) - { - int compare = prev.compareTo( c ); - System.out.println( " " + prev.toString() + ' ' - + ( ( compare == 0 ) ? "==" : ( ( compare < 0 ) ? "<" : ">" ) ) + ' ' + version ); + if (prev != null) { + int compare = prev.compareTo(c); + System.out.println(" " + prev.toString() + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) + + ' ' + version); } - System.out.println( ( i++ ) + ". " + version + " -> " + c.getCanonical() - + "; tokens: " + c.items.toListString() ); + System.out.println( + (i++) + ". " + version + " -> " + c.getCanonical() + "; tokens: " + c.items.toListString()); prev = c; } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java index cf81eb30ff..d4d6aebc39 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,19 +16,18 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ - -import java.util.StringTokenizer; +package org.apache.maven.artifact.versioning; import static org.apache.commons.lang3.math.NumberUtils.isDigits; +import java.util.StringTokenizer; + /** * Default implementation of artifact versioning. * * @author Brett Porter */ -public class DefaultArtifactVersion - implements ArtifactVersion -{ +public class DefaultArtifactVersion implements ArtifactVersion { private Integer majorVersion; private Integer minorVersion; @@ -43,162 +40,124 @@ public class DefaultArtifactVersion private ComparableVersion comparable; - public DefaultArtifactVersion( String version ) - { - parseVersion( version ); + public DefaultArtifactVersion(String version) { + parseVersion(version); } @Override - public int hashCode() - { + public int hashCode() { return 11 + comparable.hashCode(); } @Override - public boolean equals( Object other ) - { - if ( this == other ) - { + public boolean equals(Object other) { + if (this == other) { return true; } - if ( !( other instanceof ArtifactVersion ) ) - { + if (!(other instanceof ArtifactVersion)) { return false; } - return compareTo( (ArtifactVersion) other ) == 0; + return compareTo((ArtifactVersion) other) == 0; } - public int compareTo( ArtifactVersion otherVersion ) - { - if ( otherVersion instanceof DefaultArtifactVersion ) - { - return this.comparable.compareTo( ( (DefaultArtifactVersion) otherVersion ).comparable ); - } - else - { - return compareTo( new DefaultArtifactVersion( otherVersion.toString() ) ); + public int compareTo(ArtifactVersion otherVersion) { + if (otherVersion instanceof DefaultArtifactVersion) { + return this.comparable.compareTo(((DefaultArtifactVersion) otherVersion).comparable); + } else { + return compareTo(new DefaultArtifactVersion(otherVersion.toString())); } } - public int getMajorVersion() - { + public int getMajorVersion() { return majorVersion != null ? majorVersion : 0; } - public int getMinorVersion() - { + public int getMinorVersion() { return minorVersion != null ? minorVersion : 0; } - public int getIncrementalVersion() - { + public int getIncrementalVersion() { return incrementalVersion != null ? incrementalVersion : 0; } - public int getBuildNumber() - { + public int getBuildNumber() { return buildNumber != null ? buildNumber : 0; } - public String getQualifier() - { + public String getQualifier() { return qualifier; } - public final void parseVersion( String version ) - { - comparable = new ComparableVersion( version ); + public final void parseVersion(String version) { + comparable = new ComparableVersion(version); - int index = version.indexOf( '-' ); + int index = version.indexOf('-'); String part1; String part2 = null; - if ( index < 0 ) - { + if (index < 0) { part1 = version; - } - else - { - part1 = version.substring( 0, index ); - part2 = version.substring( index + 1 ); + } else { + part1 = version.substring(0, index); + part2 = version.substring(index + 1); } - if ( part2 != null ) - { - if ( part2.length() == 1 || !part2.startsWith( "0" ) ) - { - buildNumber = tryParseInt( part2 ); - if ( buildNumber == null ) - { + if (part2 != null) { + if (part2.length() == 1 || !part2.startsWith("0")) { + buildNumber = tryParseInt(part2); + if (buildNumber == null) { qualifier = part2; } - } - else - { + } else { qualifier = part2; } } - if ( ( !part1.contains( "." ) ) && !part1.startsWith( "0" ) ) - { - majorVersion = tryParseInt( part1 ); - if ( majorVersion == null ) - { + if ((!part1.contains(".")) && !part1.startsWith("0")) { + majorVersion = tryParseInt(part1); + if (majorVersion == null) { // qualifier is the whole version, including "-" qualifier = version; buildNumber = null; } - } - else - { + } else { boolean fallback = false; - StringTokenizer tok = new StringTokenizer( part1, "." ); - if ( tok.hasMoreTokens() ) - { - majorVersion = getNextIntegerToken( tok ); - if ( majorVersion == null ) - { + StringTokenizer tok = new StringTokenizer(part1, "."); + if (tok.hasMoreTokens()) { + majorVersion = getNextIntegerToken(tok); + if (majorVersion == null) { fallback = true; } - } - else - { + } else { fallback = true; } - if ( tok.hasMoreTokens() ) - { - minorVersion = getNextIntegerToken( tok ); - if ( minorVersion == null ) - { + if (tok.hasMoreTokens()) { + minorVersion = getNextIntegerToken(tok); + if (minorVersion == null) { fallback = true; } } - if ( tok.hasMoreTokens() ) - { - incrementalVersion = getNextIntegerToken( tok ); - if ( incrementalVersion == null ) - { + if (tok.hasMoreTokens()) { + incrementalVersion = getNextIntegerToken(tok); + if (incrementalVersion == null) { fallback = true; } } - if ( tok.hasMoreTokens() ) - { + if (tok.hasMoreTokens()) { qualifier = tok.nextToken(); - fallback = isDigits( qualifier ); + fallback = isDigits(qualifier); } // string tokenizer won't detect these and ignores them - if ( part1.contains( ".." ) || part1.startsWith( "." ) || part1.endsWith( "." ) ) - { + if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) { fallback = true; } - if ( fallback ) - { + if (fallback) { // qualifier is the whole version, including "-" qualifier = version; majorVersion = null; @@ -209,43 +168,34 @@ public class DefaultArtifactVersion } } - private static Integer getNextIntegerToken( StringTokenizer tok ) - { + private static Integer getNextIntegerToken(StringTokenizer tok) { String s = tok.nextToken(); - if ( ( s.length() > 1 ) && s.startsWith( "0" ) ) - { + if ((s.length() > 1) && s.startsWith("0")) { return null; } - return tryParseInt( s ); + return tryParseInt(s); } - private static Integer tryParseInt( String s ) - { + private static Integer tryParseInt(String s) { // for performance, check digits instead of relying later on catching NumberFormatException - if ( !isDigits( s ) ) - { + if (!isDigits(s)) { return null; } - try - { - long longValue = Long.parseLong( s ); - if ( longValue > Integer.MAX_VALUE ) - { + try { + long longValue = Long.parseLong(s); + if (longValue > Integer.MAX_VALUE) { return null; } return (int) longValue; - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { // should never happen since checked isDigits(s) before return null; } } @Override - public String toString() - { + public String toString() { return comparable.toString(); } } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/InvalidVersionSpecificationException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/InvalidVersionSpecificationException.java index adc48b93d5..02a4a42e51 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/InvalidVersionSpecificationException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/InvalidVersionSpecificationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,17 +16,15 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; /** * Occurs when a version is invalid. * * @author Brett Porter */ -public class InvalidVersionSpecificationException - extends Exception -{ - public InvalidVersionSpecificationException( String message ) - { - super( message ); +public class InvalidVersionSpecificationException extends Exception { + public InvalidVersionSpecificationException(String message) { + super(message); } } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/OverConstrainedVersionException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/OverConstrainedVersionException.java index bd8f3830be..52afaad0ce 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/OverConstrainedVersionException.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/OverConstrainedVersionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionException; @@ -30,20 +28,12 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionException; * * @author Brett Porter */ -public class OverConstrainedVersionException - extends ArtifactResolutionException -{ - public OverConstrainedVersionException( String msg, - Artifact artifact ) - { - super( msg, artifact ); +public class OverConstrainedVersionException extends ArtifactResolutionException { + public OverConstrainedVersionException(String msg, Artifact artifact) { + super(msg, artifact); } - public OverConstrainedVersionException( String msg, - Artifact artifact, - List remoteRepositories ) - { - super( msg, artifact, remoteRepositories ); + public OverConstrainedVersionException(String msg, Artifact artifact, List remoteRepositories) { + super(msg, artifact, remoteRepositories); } - } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java index 2b37793d2d..6bcfdc9fbe 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,14 +16,14 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; /** * Describes a restriction in versioning. * * @author Brett Porter */ -public class Restriction -{ +public class Restriction { private final ArtifactVersion lowerBound; private final boolean lowerBoundInclusive; @@ -34,58 +32,50 @@ public class Restriction private final boolean upperBoundInclusive; - public static final Restriction EVERYTHING = new Restriction( null, false, null, false ); + public static final Restriction EVERYTHING = new Restriction(null, false, null, false); - public Restriction( ArtifactVersion lowerBound, boolean lowerBoundInclusive, ArtifactVersion upperBound, - boolean upperBoundInclusive ) - { + public Restriction( + ArtifactVersion lowerBound, + boolean lowerBoundInclusive, + ArtifactVersion upperBound, + boolean upperBoundInclusive) { this.lowerBound = lowerBound; this.lowerBoundInclusive = lowerBoundInclusive; this.upperBound = upperBound; this.upperBoundInclusive = upperBoundInclusive; } - public ArtifactVersion getLowerBound() - { + public ArtifactVersion getLowerBound() { return lowerBound; } - public boolean isLowerBoundInclusive() - { + public boolean isLowerBoundInclusive() { return lowerBoundInclusive; } - public ArtifactVersion getUpperBound() - { + public ArtifactVersion getUpperBound() { return upperBound; } - public boolean isUpperBoundInclusive() - { + public boolean isUpperBoundInclusive() { return upperBoundInclusive; } - public boolean containsVersion( ArtifactVersion version ) - { - if ( lowerBound != null ) - { - int comparison = lowerBound.compareTo( version ); + public boolean containsVersion(ArtifactVersion version) { + if (lowerBound != null) { + int comparison = lowerBound.compareTo(version); - if ( ( comparison == 0 ) && !lowerBoundInclusive ) - { + if ((comparison == 0) && !lowerBoundInclusive) { return false; } - if ( comparison > 0 ) - { + if (comparison > 0) { return false; } } - if ( upperBound != null ) - { - int comparison = upperBound.compareTo( version ); + if (upperBound != null) { + int comparison = upperBound.compareTo(version); - if ( ( comparison == 0 ) && !upperBoundInclusive ) - { + if ((comparison == 0) && !upperBoundInclusive) { return false; } return comparison >= 0; @@ -95,27 +85,20 @@ public class Restriction } @Override - public int hashCode() - { + public int hashCode() { int result = 13; - if ( lowerBound == null ) - { + if (lowerBound == null) { result += 1; - } - else - { + } else { result += lowerBound.hashCode(); } result *= lowerBoundInclusive ? 1 : 2; - if ( upperBound == null ) - { + if (upperBound == null) { result -= 3; - } - else - { + } else { result -= upperBound.hashCode(); } @@ -125,67 +108,51 @@ public class Restriction } @Override - public boolean equals( Object other ) - { - if ( this == other ) - { + public boolean equals(Object other) { + if (this == other) { return true; } - if ( !( other instanceof Restriction ) ) - { + if (!(other instanceof Restriction)) { return false; } Restriction restriction = (Restriction) other; - if ( lowerBound != null ) - { - if ( !lowerBound.equals( restriction.lowerBound ) ) - { + if (lowerBound != null) { + if (!lowerBound.equals(restriction.lowerBound)) { return false; } - } - else if ( restriction.lowerBound != null ) - { + } else if (restriction.lowerBound != null) { return false; } - if ( lowerBoundInclusive != restriction.lowerBoundInclusive ) - { + if (lowerBoundInclusive != restriction.lowerBoundInclusive) { return false; } - if ( upperBound != null ) - { - if ( !upperBound.equals( restriction.upperBound ) ) - { + if (upperBound != null) { + if (!upperBound.equals(restriction.upperBound)) { return false; } - } - else if ( restriction.upperBound != null ) - { + } else if (restriction.upperBound != null) { return false; } return upperBoundInclusive == restriction.upperBoundInclusive; - } - public String toString() - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( isLowerBoundInclusive() ? '[' : '(' ); - if ( getLowerBound() != null ) - { - buf.append( getLowerBound().toString() ); + buf.append(isLowerBoundInclusive() ? '[' : '('); + if (getLowerBound() != null) { + buf.append(getLowerBound().toString()); } - buf.append( ',' ); - if ( getUpperBound() != null ) - { - buf.append( getUpperBound().toString() ); + buf.append(','); + if (getUpperBound() != null) { + buf.append(getUpperBound().toString()); } - buf.append( isUpperBoundInclusive() ? ']' : ')' ); + buf.append(isUpperBoundInclusive() ? ']' : ')'); return buf.toString(); } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/VersionRange.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/VersionRange.java index c4fbf9b431..20c06f3deb 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/VersionRange.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/VersionRange.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,15 +16,15 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.WeakHashMap; import java.util.Objects; - +import java.util.WeakHashMap; import org.apache.maven.artifact.Artifact; /** @@ -34,32 +32,25 @@ import org.apache.maven.artifact.Artifact; * * @author Brett Porter */ -public class VersionRange -{ - private static final Map CACHE_SPEC = - Collections.synchronizedMap( new WeakHashMap<>() ); +public class VersionRange { + private static final Map CACHE_SPEC = Collections.synchronizedMap(new WeakHashMap<>()); - private static final Map CACHE_VERSION = - Collections.synchronizedMap( new WeakHashMap<>() ); + private static final Map CACHE_VERSION = Collections.synchronizedMap(new WeakHashMap<>()); private final ArtifactVersion recommendedVersion; private final List restrictions; - private VersionRange( ArtifactVersion recommendedVersion, - List restrictions ) - { + private VersionRange(ArtifactVersion recommendedVersion, List restrictions) { this.recommendedVersion = recommendedVersion; this.restrictions = restrictions; } - public ArtifactVersion getRecommendedVersion() - { + public ArtifactVersion getRecommendedVersion() { return recommendedVersion; } - public List getRestrictions() - { + public List getRestrictions() { return restrictions; } @@ -68,21 +59,18 @@ public class VersionRange * @return a clone */ @Deprecated - public VersionRange cloneOf() - { + public VersionRange cloneOf() { List copiedRestrictions = null; - if ( restrictions != null ) - { + if (restrictions != null) { copiedRestrictions = new ArrayList<>(); - if ( !restrictions.isEmpty() ) - { - copiedRestrictions.addAll( restrictions ); + if (!restrictions.isEmpty()) { + copiedRestrictions.addAll(restrictions); } } - return new VersionRange( recommendedVersion, copiedRestrictions ); + return new VersionRange(recommendedVersion, copiedRestrictions); } /** @@ -103,17 +91,13 @@ public class VersionRange * @return a new {@link VersionRange} object that represents the spec * @throws InvalidVersionSpecificationException if invalid version specification */ - public static VersionRange createFromVersionSpec( String spec ) - throws InvalidVersionSpecificationException - { - if ( spec == null ) - { + public static VersionRange createFromVersionSpec(String spec) throws InvalidVersionSpecificationException { + if (spec == null) { return null; } - VersionRange cached = CACHE_SPEC.get( spec ); - if ( cached != null ) - { + VersionRange cached = CACHE_SPEC.get(spec); + if (cached != null) { return cached; } @@ -123,129 +107,106 @@ public class VersionRange ArtifactVersion upperBound = null; ArtifactVersion lowerBound = null; - while ( process.startsWith( "[" ) || process.startsWith( "(" ) ) - { - int index1 = process.indexOf( ')' ); - int index2 = process.indexOf( ']' ); + while (process.startsWith("[") || process.startsWith("(")) { + int index1 = process.indexOf(')'); + int index2 = process.indexOf(']'); int index = index2; - if ( index2 < 0 || index1 < index2 ) - { - if ( index1 >= 0 ) - { + if (index2 < 0 || index1 < index2) { + if (index1 >= 0) { index = index1; } } - if ( index < 0 ) - { - throw new InvalidVersionSpecificationException( "Unbounded range: " + spec ); + if (index < 0) { + throw new InvalidVersionSpecificationException("Unbounded range: " + spec); } - Restriction restriction = parseRestriction( process.substring( 0, index + 1 ) ); - if ( lowerBound == null ) - { + Restriction restriction = parseRestriction(process.substring(0, index + 1)); + if (lowerBound == null) { lowerBound = restriction.getLowerBound(); } - if ( upperBound != null ) - { - if ( restriction.getLowerBound() == null || restriction.getLowerBound().compareTo( upperBound ) < 0 ) - { - throw new InvalidVersionSpecificationException( "Ranges overlap: " + spec ); + if (upperBound != null) { + if (restriction.getLowerBound() == null + || restriction.getLowerBound().compareTo(upperBound) < 0) { + throw new InvalidVersionSpecificationException("Ranges overlap: " + spec); } } - restrictions.add( restriction ); + restrictions.add(restriction); upperBound = restriction.getUpperBound(); - process = process.substring( index + 1 ).trim(); + process = process.substring(index + 1).trim(); - if ( process.startsWith( "," ) ) - { - process = process.substring( 1 ).trim(); + if (process.startsWith(",")) { + process = process.substring(1).trim(); } } - if ( process.length() > 0 ) - { - if ( restrictions.size() > 0 ) - { + if (process.length() > 0) { + if (restrictions.size() > 0) { throw new InvalidVersionSpecificationException( - "Only fully-qualified sets allowed in multiple set scenario: " + spec ); - } - else - { - version = new DefaultArtifactVersion( process ); - restrictions.add( Restriction.EVERYTHING ); + "Only fully-qualified sets allowed in multiple set scenario: " + spec); + } else { + version = new DefaultArtifactVersion(process); + restrictions.add(Restriction.EVERYTHING); } } - cached = new VersionRange( version, restrictions ); - CACHE_SPEC.put( spec, cached ); + cached = new VersionRange(version, restrictions); + CACHE_SPEC.put(spec, cached); return cached; } - private static Restriction parseRestriction( String spec ) - throws InvalidVersionSpecificationException - { - boolean lowerBoundInclusive = spec.startsWith( "[" ); - boolean upperBoundInclusive = spec.endsWith( "]" ); + private static Restriction parseRestriction(String spec) throws InvalidVersionSpecificationException { + boolean lowerBoundInclusive = spec.startsWith("["); + boolean upperBoundInclusive = spec.endsWith("]"); - String process = spec.substring( 1, spec.length() - 1 ).trim(); + String process = spec.substring(1, spec.length() - 1).trim(); Restriction restriction; - int index = process.indexOf( ',' ); + int index = process.indexOf(','); - if ( index < 0 ) - { - if ( !lowerBoundInclusive || !upperBoundInclusive ) - { - throw new InvalidVersionSpecificationException( "Single version must be surrounded by []: " + spec ); + if (index < 0) { + if (!lowerBoundInclusive || !upperBoundInclusive) { + throw new InvalidVersionSpecificationException("Single version must be surrounded by []: " + spec); } - ArtifactVersion version = new DefaultArtifactVersion( process ); + ArtifactVersion version = new DefaultArtifactVersion(process); - restriction = new Restriction( version, lowerBoundInclusive, version, upperBoundInclusive ); - } - else - { - String lowerBound = process.substring( 0, index ).trim(); - String upperBound = process.substring( index + 1 ).trim(); + restriction = new Restriction(version, lowerBoundInclusive, version, upperBoundInclusive); + } else { + String lowerBound = process.substring(0, index).trim(); + String upperBound = process.substring(index + 1).trim(); ArtifactVersion lowerVersion = null; - if ( lowerBound.length() > 0 ) - { - lowerVersion = new DefaultArtifactVersion( lowerBound ); + if (lowerBound.length() > 0) { + lowerVersion = new DefaultArtifactVersion(lowerBound); } ArtifactVersion upperVersion = null; - if ( upperBound.length() > 0 ) - { - upperVersion = new DefaultArtifactVersion( upperBound ); + if (upperBound.length() > 0) { + upperVersion = new DefaultArtifactVersion(upperBound); } - if ( upperVersion != null && lowerVersion != null ) - { - int result = upperVersion.compareTo( lowerVersion ); - if ( result < 0 || ( result == 0 && ( !lowerBoundInclusive || !upperBoundInclusive ) ) ) - { - throw new InvalidVersionSpecificationException( "Range defies version ordering: " + spec ); + if (upperVersion != null && lowerVersion != null) { + int result = upperVersion.compareTo(lowerVersion); + if (result < 0 || (result == 0 && (!lowerBoundInclusive || !upperBoundInclusive))) { + throw new InvalidVersionSpecificationException("Range defies version ordering: " + spec); } } - restriction = new Restriction( lowerVersion, lowerBoundInclusive, upperVersion, upperBoundInclusive ); + restriction = new Restriction(lowerVersion, lowerBoundInclusive, upperVersion, upperBoundInclusive); } return restriction; } - public static VersionRange createFromVersion( String version ) - { - VersionRange cached = CACHE_VERSION.get( version ); - if ( cached == null ) - { + public static VersionRange createFromVersion(String version) { + VersionRange cached = CACHE_VERSION.get(version); + if (cached == null) { List restrictions = Collections.emptyList(); - cached = new VersionRange( new DefaultArtifactVersion( version ), restrictions ); - CACHE_VERSION.put( version, cached ); + cached = new VersionRange(new DefaultArtifactVersion(version), restrictions); + CACHE_VERSION.put(version, cached); } return cached; } @@ -278,203 +239,148 @@ public class VersionRange * @throws NullPointerException if the specified VersionRange is * null. */ - public VersionRange restrict( VersionRange restriction ) - { + public VersionRange restrict(VersionRange restriction) { List r1 = this.restrictions; List r2 = restriction.restrictions; List restrictions; - if ( r1.isEmpty() || r2.isEmpty() ) - { + if (r1.isEmpty() || r2.isEmpty()) { restrictions = Collections.emptyList(); - } - else - { - restrictions = Collections.unmodifiableList( intersection( r1, r2 ) ); + } else { + restrictions = Collections.unmodifiableList(intersection(r1, r2)); } ArtifactVersion version = null; - if ( restrictions.size() > 0 ) - { - for ( Restriction r : restrictions ) - { - if ( recommendedVersion != null && r.containsVersion( recommendedVersion ) ) - { + if (restrictions.size() > 0) { + for (Restriction r : restrictions) { + if (recommendedVersion != null && r.containsVersion(recommendedVersion)) { // if we find the original, use that version = recommendedVersion; break; - } - else if ( version == null && restriction.getRecommendedVersion() != null - && r.containsVersion( restriction.getRecommendedVersion() ) ) - { + } else if (version == null + && restriction.getRecommendedVersion() != null + && r.containsVersion(restriction.getRecommendedVersion())) { // use this if we can, but prefer the original if possible version = restriction.getRecommendedVersion(); } } } // Either the original or the specified version ranges have no restrictions - else if ( recommendedVersion != null ) - { + else if (recommendedVersion != null) { // Use the original recommended version since it exists version = recommendedVersion; - } - else if ( restriction.recommendedVersion != null ) - { + } else if (restriction.recommendedVersion != null) { // Use the recommended version from the specified VersionRange since there is no // original recommended version version = restriction.recommendedVersion; } -/* TODO should throw this immediately, but need artifact - else - { - throw new OverConstrainedVersionException( "Restricting incompatible version ranges" ); - } -*/ + /* TODO should throw this immediately, but need artifact + else + { + throw new OverConstrainedVersionException( "Restricting incompatible version ranges" ); + } + */ - return new VersionRange( version, restrictions ); + return new VersionRange(version, restrictions); } - private List intersection( List r1, List r2 ) - { - List restrictions = new ArrayList<>( r1.size() + r2.size() ); + private List intersection(List r1, List r2) { + List restrictions = new ArrayList<>(r1.size() + r2.size()); Iterator i1 = r1.iterator(); Iterator i2 = r2.iterator(); Restriction res1 = i1.next(); Restriction res2 = i2.next(); boolean done = false; - while ( !done ) - { - if ( res1.getLowerBound() == null || res2.getUpperBound() == null - || res1.getLowerBound().compareTo( res2.getUpperBound() ) <= 0 ) - { - if ( res1.getUpperBound() == null || res2.getLowerBound() == null - || res1.getUpperBound().compareTo( res2.getLowerBound() ) >= 0 ) - { + while (!done) { + if (res1.getLowerBound() == null + || res2.getUpperBound() == null + || res1.getLowerBound().compareTo(res2.getUpperBound()) <= 0) { + if (res1.getUpperBound() == null + || res2.getLowerBound() == null + || res1.getUpperBound().compareTo(res2.getLowerBound()) >= 0) { ArtifactVersion lower; ArtifactVersion upper; boolean lowerInclusive; boolean upperInclusive; // overlaps - if ( res1.getLowerBound() == null ) - { + if (res1.getLowerBound() == null) { lower = res2.getLowerBound(); lowerInclusive = res2.isLowerBoundInclusive(); - } - else if ( res2.getLowerBound() == null ) - { + } else if (res2.getLowerBound() == null) { lower = res1.getLowerBound(); lowerInclusive = res1.isLowerBoundInclusive(); - } - else - { - int comparison = res1.getLowerBound().compareTo( res2.getLowerBound() ); - if ( comparison < 0 ) - { + } else { + int comparison = res1.getLowerBound().compareTo(res2.getLowerBound()); + if (comparison < 0) { lower = res2.getLowerBound(); lowerInclusive = res2.isLowerBoundInclusive(); - } - else if ( comparison == 0 ) - { + } else if (comparison == 0) { lower = res1.getLowerBound(); lowerInclusive = res1.isLowerBoundInclusive() && res2.isLowerBoundInclusive(); - } - else - { + } else { lower = res1.getLowerBound(); lowerInclusive = res1.isLowerBoundInclusive(); } } - if ( res1.getUpperBound() == null ) - { + if (res1.getUpperBound() == null) { upper = res2.getUpperBound(); upperInclusive = res2.isUpperBoundInclusive(); - } - else if ( res2.getUpperBound() == null ) - { + } else if (res2.getUpperBound() == null) { upper = res1.getUpperBound(); upperInclusive = res1.isUpperBoundInclusive(); - } - else - { - int comparison = res1.getUpperBound().compareTo( res2.getUpperBound() ); - if ( comparison < 0 ) - { + } else { + int comparison = res1.getUpperBound().compareTo(res2.getUpperBound()); + if (comparison < 0) { upper = res1.getUpperBound(); upperInclusive = res1.isUpperBoundInclusive(); - } - else if ( comparison == 0 ) - { + } else if (comparison == 0) { upper = res1.getUpperBound(); upperInclusive = res1.isUpperBoundInclusive() && res2.isUpperBoundInclusive(); - } - else - { + } else { upper = res2.getUpperBound(); upperInclusive = res2.isUpperBoundInclusive(); } } // don't add if they are equal and one is not inclusive - if ( lower == null || upper == null || lower.compareTo( upper ) != 0 ) - { - restrictions.add( new Restriction( lower, lowerInclusive, upper, upperInclusive ) ); - } - else if ( lowerInclusive && upperInclusive ) - { - restrictions.add( new Restriction( lower, lowerInclusive, upper, upperInclusive ) ); + if (lower == null || upper == null || lower.compareTo(upper) != 0) { + restrictions.add(new Restriction(lower, lowerInclusive, upper, upperInclusive)); + } else if (lowerInclusive && upperInclusive) { + restrictions.add(new Restriction(lower, lowerInclusive, upper, upperInclusive)); } //noinspection ObjectEquality - if ( upper == res2.getUpperBound() ) - { + if (upper == res2.getUpperBound()) { // advance res2 - if ( i2.hasNext() ) - { + if (i2.hasNext()) { res2 = i2.next(); - } - else - { + } else { done = true; } - } - else - { + } else { // advance res1 - if ( i1.hasNext() ) - { + if (i1.hasNext()) { res1 = i1.next(); - } - else - { + } else { done = true; } } - } - else - { + } else { // move on to next in r1 - if ( i1.hasNext() ) - { + if (i1.hasNext()) { res1 = i1.next(); - } - else - { + } else { done = true; } } - } - else - { + } else { // move on to next in r2 - if ( i2.hasNext() ) - { + if (i2.hasNext()) { res2 = i2.next(); - } - else - { + } else { done = true; } } @@ -483,19 +389,13 @@ public class VersionRange return restrictions; } - public ArtifactVersion getSelectedVersion( Artifact artifact ) - throws OverConstrainedVersionException - { + public ArtifactVersion getSelectedVersion(Artifact artifact) throws OverConstrainedVersionException { ArtifactVersion version; - if ( recommendedVersion != null ) - { + if (recommendedVersion != null) { version = recommendedVersion; - } - else - { - if ( restrictions.size() == 0 ) - { - throw new OverConstrainedVersionException( "The artifact has no valid ranges", artifact ); + } else { + if (restrictions.size() == 0) { + throw new OverConstrainedVersionException("The artifact has no valid ranges", artifact); } version = null; @@ -503,60 +403,44 @@ public class VersionRange return version; } - public boolean isSelectedVersionKnown( Artifact artifact ) - throws OverConstrainedVersionException - { + public boolean isSelectedVersionKnown(Artifact artifact) throws OverConstrainedVersionException { boolean value = false; - if ( recommendedVersion != null ) - { + if (recommendedVersion != null) { value = true; - } - else - { - if ( restrictions.size() == 0 ) - { - throw new OverConstrainedVersionException( "The artifact has no valid ranges", artifact ); + } else { + if (restrictions.size() == 0) { + throw new OverConstrainedVersionException("The artifact has no valid ranges", artifact); } } return value; } - public String toString() - { - if ( recommendedVersion != null ) - { + public String toString() { + if (recommendedVersion != null) { return recommendedVersion.toString(); - } - else - { + } else { StringBuilder buf = new StringBuilder(); - for ( Iterator i = restrictions.iterator(); i.hasNext(); ) - { + for (Iterator i = restrictions.iterator(); i.hasNext(); ) { Restriction r = i.next(); - buf.append( r.toString() ); + buf.append(r.toString()); - if ( i.hasNext() ) - { - buf.append( ',' ); + if (i.hasNext()) { + buf.append(','); } } return buf.toString(); } } - public ArtifactVersion matchVersion( List versions ) - { + public ArtifactVersion matchVersion(List versions) { // TODO could be more efficient by sorting the list and then moving along the restrictions in order? ArtifactVersion matched = null; - for ( ArtifactVersion version : versions ) - { - if ( containsVersion( version ) ) - { + for (ArtifactVersion version : versions) { + if (containsVersion(version)) { // valid - check if it is greater than the currently matched version - if ( matched == null || version.compareTo( matched ) > 0 ) - { + if (matched == null || version.compareTo(matched) > 0) { matched = version; } } @@ -564,44 +448,36 @@ public class VersionRange return matched; } - public boolean containsVersion( ArtifactVersion version ) - { - for ( Restriction restriction : restrictions ) - { - if ( restriction.containsVersion( version ) ) - { + public boolean containsVersion(ArtifactVersion version) { + for (Restriction restriction : restrictions) { + if (restriction.containsVersion(version)) { return true; } } return false; } - public boolean hasRestrictions() - { + public boolean hasRestrictions() { return !restrictions.isEmpty() && recommendedVersion == null; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof VersionRange ) ) - { + if (!(obj instanceof VersionRange)) { return false; } VersionRange other = (VersionRange) obj; - return Objects.equals( recommendedVersion, other.recommendedVersion ) - && Objects.equals( restrictions, other.restrictions ); + return Objects.equals(recommendedVersion, other.recommendedVersion) + && Objects.equals(restrictions, other.restrictions); } - public int hashCode() - { + public int hashCode() { int hash = 7; - hash = 31 * hash + ( recommendedVersion == null ? 0 : recommendedVersion.hashCode() ); - hash = 31 * hash + ( restrictions == null ? 0 : restrictions.hashCode() ); + hash = 31 * hash + (recommendedVersion == null ? 0 : recommendedVersion.hashCode()); + hash = 31 * hash + (restrictions == null ? 0 : restrictions.hashCode()); return hash; } } diff --git a/maven-artifact/src/main/java/org/apache/maven/repository/Proxy.java b/maven-artifact/src/main/java/org/apache/maven/repository/Proxy.java index 4669276eab..aa27e6286d 100644 --- a/maven-artifact/src/main/java/org/apache/maven/repository/Proxy.java +++ b/maven-artifact/src/main/java/org/apache/maven/repository/Proxy.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; /** * Proxy */ -public class Proxy -{ +public class Proxy { public static final String PROXY_SOCKS5 = "SOCKS_5"; public static final String PROXY_SOCKS4 = "SOCKS4"; @@ -75,8 +73,7 @@ public class Proxy * * @return proxy server host name */ - public String getHost() - { + public String getHost() { return host; } @@ -85,8 +82,7 @@ public class Proxy * * @param host proxy server host name */ - public void setHost( String host ) - { + public void setHost(String host) { this.host = host; } @@ -95,8 +91,7 @@ public class Proxy * * @return user's password at proxy host */ - public String getPassword() - { + public String getPassword() { return password; } @@ -105,8 +100,7 @@ public class Proxy * * @param password password to use to log in to a proxy server */ - public void setPassword( String password ) - { + public void setPassword(String password) { this.password = password; } @@ -115,8 +109,7 @@ public class Proxy * * @return proxy server port */ - public int getPort() - { + public int getPort() { return port; } @@ -125,8 +118,7 @@ public class Proxy * * @param port proxy server port */ - public void setPort( int port ) - { + public void setPort(int port) { this.port = port; } @@ -135,8 +127,7 @@ public class Proxy * * @return username for the proxy server */ - public String getUserName() - { + public String getUserName() { return userName; } @@ -145,8 +136,7 @@ public class Proxy * * @param userName username for the proxy server */ - public void setUserName( String userName ) - { + public void setUserName(String userName) { this.userName = userName; } @@ -155,46 +145,38 @@ public class Proxy * * @return the protocol of the proxy server */ - public String getProtocol() - { + public String getProtocol() { return protocol; } /** * @param protocol the protocol of the proxy server like SOCKSv4 */ - public void setProtocol( String protocol ) - { + public void setProtocol(String protocol) { this.protocol = protocol; } - public String getNonProxyHosts() - { + public String getNonProxyHosts() { return nonProxyHosts; } - public void setNonProxyHosts( String nonProxyHosts ) - { + public void setNonProxyHosts(String nonProxyHosts) { this.nonProxyHosts = nonProxyHosts; } - public String getNtlmHost() - { + public String getNtlmHost() { return ntlmHost; } - public void setNtlmHost( String ntlmHost ) - { + public void setNtlmHost(String ntlmHost) { this.ntlmHost = ntlmHost; } - public void setNtlmDomain( String ntlmDomain ) - { + public void setNtlmDomain(String ntlmDomain) { this.ntlmDomain = ntlmDomain; } - public String getNtlmDomain() - { + public String getNtlmDomain() { return ntlmDomain; } } diff --git a/maven-artifact/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadata.java b/maven-artifact/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadata.java index 136ab44d54..57b377fcdf 100644 --- a/maven-artifact/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadata.java +++ b/maven-artifact/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.metadata.RepositoryMetadataStoreException; @@ -29,8 +28,7 @@ import org.apache.maven.artifact.repository.metadata.RepositoryMetadataStoreExce * * @author Brett Porter */ -public interface ArtifactMetadata -{ +public interface ArtifactMetadata { /** * Whether this metadata should be stored alongside the artifact. * @@ -59,7 +57,7 @@ public interface ArtifactMetadata * @param repository the remote repository it came from * @return the filename */ - String getLocalFilename( ArtifactRepository repository ); + String getLocalFilename(ArtifactRepository repository); /** * Get the filename of this metadata on the remote repository. @@ -74,7 +72,7 @@ public interface ArtifactMetadata * * @param metadata the new metadata */ - void merge( ArtifactMetadata metadata ); + void merge(ArtifactMetadata metadata); /** * Store the metadata in the local repository. @@ -84,9 +82,8 @@ public interface ArtifactMetadata * @param remoteRepository the remote repository it came from * @throws RepositoryMetadataStoreException in case of issue */ - void storeInLocalRepository( ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws RepositoryMetadataStoreException; + void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataStoreException; String extendedToString(); } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/ArtifactUtilsTest.java b/maven-artifact/src/test/java/org/apache/maven/artifact/ArtifactUtilsTest.java index 485b3f66a2..98ccb948e8 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/ArtifactUtilsTest.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/ArtifactUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,70 +16,63 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.maven.artifact.versioning.VersionRange; -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.apache.maven.artifact.versioning.VersionRange; +import org.junit.jupiter.api.Test; + /** * Tests {@link ArtifactUtils}. * * @author Benjamin Bentmann */ -public class ArtifactUtilsTest -{ +public class ArtifactUtilsTest { - private Artifact newArtifact( String aid ) - { - return new DefaultArtifact( "group", aid, VersionRange.createFromVersion( "1.0" ), "test", "jar", "tests", null ); + private Artifact newArtifact(String aid) { + return new DefaultArtifact("group", aid, VersionRange.createFromVersion("1.0"), "test", "jar", "tests", null); } @Test - public void testIsSnapshot() - { - assertFalse( ArtifactUtils.isSnapshot( null ) ); - assertFalse( ArtifactUtils.isSnapshot( "" ) ); - assertFalse( ArtifactUtils.isSnapshot( "1.2.3" ) ); - assertTrue( ArtifactUtils.isSnapshot( "1.2.3-SNAPSHOT" ) ); - assertTrue( ArtifactUtils.isSnapshot( "1.2.3-snapshot" ) ); - assertTrue( ArtifactUtils.isSnapshot( "1.2.3-20090413.094722-2" ) ); - assertFalse( ArtifactUtils.isSnapshot( "1.2.3-20090413X094722-2" ) ); + public void testIsSnapshot() { + assertFalse(ArtifactUtils.isSnapshot(null)); + assertFalse(ArtifactUtils.isSnapshot("")); + assertFalse(ArtifactUtils.isSnapshot("1.2.3")); + assertTrue(ArtifactUtils.isSnapshot("1.2.3-SNAPSHOT")); + assertTrue(ArtifactUtils.isSnapshot("1.2.3-snapshot")); + assertTrue(ArtifactUtils.isSnapshot("1.2.3-20090413.094722-2")); + assertFalse(ArtifactUtils.isSnapshot("1.2.3-20090413X094722-2")); } @Test - public void testToSnapshotVersion() - { - assertEquals( "1.2.3", ArtifactUtils.toSnapshotVersion( "1.2.3" ) ); - assertEquals( "1.2.3-SNAPSHOT", ArtifactUtils.toSnapshotVersion( "1.2.3-SNAPSHOT" ) ); - assertEquals( "1.2.3-SNAPSHOT", ArtifactUtils.toSnapshotVersion( "1.2.3-20090413.094722-2" ) ); - assertEquals( "1.2.3-20090413X094722-2", ArtifactUtils.toSnapshotVersion( "1.2.3-20090413X094722-2" ) ); + public void testToSnapshotVersion() { + assertEquals("1.2.3", ArtifactUtils.toSnapshotVersion("1.2.3")); + assertEquals("1.2.3-SNAPSHOT", ArtifactUtils.toSnapshotVersion("1.2.3-SNAPSHOT")); + assertEquals("1.2.3-SNAPSHOT", ArtifactUtils.toSnapshotVersion("1.2.3-20090413.094722-2")); + assertEquals("1.2.3-20090413X094722-2", ArtifactUtils.toSnapshotVersion("1.2.3-20090413X094722-2")); } /** * Tests that the ordering of the map resembles the ordering of the input collection of artifacts. */ @Test - public void testArtifactMapByVersionlessIdOrdering() - throws Exception - { + public void testArtifactMapByVersionlessIdOrdering() throws Exception { List list = new ArrayList<>(); - list.add( newArtifact( "b" ) ); - list.add( newArtifact( "a" ) ); - list.add( newArtifact( "c" ) ); - list.add( newArtifact( "e" ) ); - list.add( newArtifact( "d" ) ); + list.add(newArtifact("b")); + list.add(newArtifact("a")); + list.add(newArtifact("c")); + list.add(newArtifact("e")); + list.add(newArtifact("d")); - Map map = ArtifactUtils.artifactMapByVersionlessId( list ); - assertNotNull( map ); - assertEquals( list, new ArrayList<>( map.values() ) ); + Map map = ArtifactUtils.artifactMapByVersionlessId(list); + assertNotNull(map); + assertEquals(list, new ArrayList<>(map.values())); } - } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/DefaultArtifactTest.java b/maven-artifact/src/test/java/org/apache/maven/artifact/DefaultArtifactTest.java index 4f919628a1..1c068d4042 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/DefaultArtifactTest.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/DefaultArtifactTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,25 +16,29 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.maven.artifact.handler.ArtifactHandlerMock; import org.apache.maven.artifact.versioning.VersionRange; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class DefaultArtifactTest -{ +public class DefaultArtifactTest { private DefaultArtifact artifact; private DefaultArtifact snapshotArtifact; - private String groupId = "groupid", artifactId = "artifactId", version = "1.0", scope = "artifactScope", type = "type", - classifier = "classifier"; + private String groupId = "groupid", + artifactId = "artifactId", + version = "1.0", + scope = "artifactScope", + type = "type", + classifier = "classifier"; private String snapshotSpecVersion = "1.0-SNAPSHOT"; private String snapshotResolvedVersion = "1.0-20070606.010101-1"; @@ -47,108 +49,95 @@ public class DefaultArtifactTest private ArtifactHandlerMock artifactHandler; @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { artifactHandler = new ArtifactHandlerMock(); - versionRange = VersionRange.createFromVersion( version ); - artifact = new DefaultArtifact( groupId, artifactId, versionRange, scope, type, classifier, artifactHandler ); + versionRange = VersionRange.createFromVersion(version); + artifact = new DefaultArtifact(groupId, artifactId, versionRange, scope, type, classifier, artifactHandler); - snapshotVersionRange = VersionRange.createFromVersion( snapshotResolvedVersion ); - snapshotArtifact = new DefaultArtifact( groupId, artifactId, snapshotVersionRange, scope, type, classifier, artifactHandler ); + snapshotVersionRange = VersionRange.createFromVersion(snapshotResolvedVersion); + snapshotArtifact = new DefaultArtifact( + groupId, artifactId, snapshotVersionRange, scope, type, classifier, artifactHandler); } @Test - public void testGetVersionReturnsResolvedVersionOnSnapshot() - { - assertEquals( snapshotResolvedVersion, snapshotArtifact.getVersion() ); + public void testGetVersionReturnsResolvedVersionOnSnapshot() { + assertEquals(snapshotResolvedVersion, snapshotArtifact.getVersion()); // this is FOUL! -// snapshotArtifact.isSnapshot(); + // snapshotArtifact.isSnapshot(); - assertEquals( snapshotSpecVersion, snapshotArtifact.getBaseVersion() ); + assertEquals(snapshotSpecVersion, snapshotArtifact.getBaseVersion()); } @Test - public void testGetDependencyConflictId() - { - assertEquals( groupId + ":" + artifactId + ":" + type + ":" + classifier, artifact.getDependencyConflictId() ); + public void testGetDependencyConflictId() { + assertEquals(groupId + ":" + artifactId + ":" + type + ":" + classifier, artifact.getDependencyConflictId()); } @Test - public void testGetDependencyConflictIdNullGroupId() - { - artifact.setGroupId( null ); - assertEquals( null + ":" + artifactId + ":" + type + ":" + classifier, artifact.getDependencyConflictId() ); + public void testGetDependencyConflictIdNullGroupId() { + artifact.setGroupId(null); + assertEquals(null + ":" + artifactId + ":" + type + ":" + classifier, artifact.getDependencyConflictId()); } @Test - public void testGetDependencyConflictIdNullClassifier() - { - artifact = new DefaultArtifact( groupId, artifactId, versionRange, scope, type, null, artifactHandler ); - assertEquals( groupId + ":" + artifactId + ":" + type, artifact.getDependencyConflictId() ); + public void testGetDependencyConflictIdNullClassifier() { + artifact = new DefaultArtifact(groupId, artifactId, versionRange, scope, type, null, artifactHandler); + assertEquals(groupId + ":" + artifactId + ":" + type, artifact.getDependencyConflictId()); } @Test - public void testGetDependencyConflictIdNullScope() - { - artifact.setScope( null ); - assertEquals( groupId + ":" + artifactId + ":" + type + ":" + classifier, artifact.getDependencyConflictId() ); + public void testGetDependencyConflictIdNullScope() { + artifact.setScope(null); + assertEquals(groupId + ":" + artifactId + ":" + type + ":" + classifier, artifact.getDependencyConflictId()); } @Test - public void testToString() - { - assertEquals( groupId + ":" + artifactId + ":" + type + ":" + classifier + ":" + version + ":" + scope, - artifact.toString() ); + public void testToString() { + assertEquals( + groupId + ":" + artifactId + ":" + type + ":" + classifier + ":" + version + ":" + scope, + artifact.toString()); } @Test - public void testToStringNullGroupId() - { - artifact.setGroupId( null ); - assertEquals( artifactId + ":" + type + ":" + classifier + ":" + version + ":" + scope, artifact.toString() ); + public void testToStringNullGroupId() { + artifact.setGroupId(null); + assertEquals(artifactId + ":" + type + ":" + classifier + ":" + version + ":" + scope, artifact.toString()); } @Test - public void testToStringNullClassifier() - { - artifact = new DefaultArtifact( groupId, artifactId, versionRange, scope, type, null, artifactHandler ); - assertEquals( groupId + ":" + artifactId + ":" + type + ":" + version + ":" + scope, artifact.toString() ); + public void testToStringNullClassifier() { + artifact = new DefaultArtifact(groupId, artifactId, versionRange, scope, type, null, artifactHandler); + assertEquals(groupId + ":" + artifactId + ":" + type + ":" + version + ":" + scope, artifact.toString()); } @Test - public void testToStringNullScope() - { - artifact.setScope( null ); - assertEquals( groupId + ":" + artifactId + ":" + type + ":" + classifier + ":" + version, artifact.toString() ); + public void testToStringNullScope() { + artifact.setScope(null); + assertEquals(groupId + ":" + artifactId + ":" + type + ":" + classifier + ":" + version, artifact.toString()); } @Test - public void testComparisonByVersion() - { - Artifact artifact1 = new DefaultArtifact( groupId, artifactId, VersionRange.createFromVersion( "5.0" ), scope, - type, classifier, artifactHandler ); - Artifact artifact2 = new DefaultArtifact( groupId, artifactId, VersionRange.createFromVersion( "12.0" ), scope, - type, classifier, artifactHandler ); + public void testComparisonByVersion() { + Artifact artifact1 = new DefaultArtifact( + groupId, artifactId, VersionRange.createFromVersion("5.0"), scope, type, classifier, artifactHandler); + Artifact artifact2 = new DefaultArtifact( + groupId, artifactId, VersionRange.createFromVersion("12.0"), scope, type, classifier, artifactHandler); - assertTrue( artifact1.compareTo( artifact2 ) < 0 ); - assertTrue( artifact2.compareTo( artifact1 ) > 0 ); + assertTrue(artifact1.compareTo(artifact2) < 0); + assertTrue(artifact2.compareTo(artifact1) > 0); - Artifact artifact = new DefaultArtifact( groupId, artifactId, VersionRange.createFromVersion( "5.0" ), scope, - type, classifier, artifactHandler ); - assertTrue( artifact.compareTo( artifact1 ) == 0 ); - assertTrue( artifact1.compareTo( artifact ) == 0 ); + Artifact artifact = new DefaultArtifact( + groupId, artifactId, VersionRange.createFromVersion("5.0"), scope, type, classifier, artifactHandler); + assertTrue(artifact.compareTo(artifact1) == 0); + assertTrue(artifact1.compareTo(artifact) == 0); } @Test - public void testNonResolvedVersionRangeConsistentlyYieldsNullVersions() - throws Exception - { - VersionRange vr = VersionRange.createFromVersionSpec( "[1.0,2.0)" ); - artifact = new DefaultArtifact( groupId, artifactId, vr, scope, type, null, artifactHandler ); - assertNull( artifact.getVersion() ); - assertNull( artifact.getBaseVersion() ); + public void testNonResolvedVersionRangeConsistentlyYieldsNullVersions() throws Exception { + VersionRange vr = VersionRange.createFromVersionSpec("[1.0,2.0)"); + artifact = new DefaultArtifact(groupId, artifactId, vr, scope, type, null, artifactHandler); + assertNull(artifact.getVersion()); + assertNull(artifact.getBaseVersion()); } - } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerMock.java b/maven-artifact/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerMock.java index a9f335e696..deb3e77c54 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerMock.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerMock.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler; * "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 + * 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 @@ -18,83 +16,66 @@ package org.apache.maven.artifact.handler; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler; -public class ArtifactHandlerMock - implements ArtifactHandler -{ +public class ArtifactHandlerMock implements ArtifactHandler { private String extension, directory, classifier, packaging, language; - private boolean includesDependencies, addedToClasspath; - public void setExtension( String extension ) - { + public void setExtension(String extension) { this.extension = extension; } - public String getExtension() - { + public String getExtension() { return extension; } - public void setDirectory( String directory ) - { + public void setDirectory(String directory) { this.directory = directory; } - public String getDirectory() - { + public String getDirectory() { return directory; } - public void setClassifier( String classifier ) - { + public void setClassifier(String classifier) { this.classifier = classifier; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public void setPackaging( String packaging ) - { + public void setPackaging(String packaging) { this.packaging = packaging; } - public String getPackaging() - { + public String getPackaging() { return packaging; } - public void setIncludesDependencies( boolean includesDependencies ) - { + public void setIncludesDependencies(boolean includesDependencies) { this.includesDependencies = includesDependencies; } - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return includesDependencies; } - public void setLanguage( String language ) - { + public void setLanguage(String language) { this.language = language; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setAddedToClasspath( boolean addedToClasspath ) - { + public void setAddedToClasspath(boolean addedToClasspath) { this.addedToClasspath = addedToClasspath; } - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return addedToClasspath; } - } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionIT.java b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionIT.java index cd63b4db3c..dd31f5bee7 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionIT.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionIT.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,6 +16,9 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InterruptedIOException; @@ -28,66 +29,46 @@ import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.regex.Pattern; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class ComparableVersionIT -{ +public class ComparableVersionIT { @Test - public void test() - throws Exception - { - Files.walkFileTree( Paths.get( "target" ), new SimpleFileVisitor() - { - Pattern mavenArtifactJar = Pattern.compile( "maven-artifact-[\\d.]+(-SNAPSHOT)?\\.jar" ); + public void test() throws Exception { + Files.walkFileTree(Paths.get("target"), new SimpleFileVisitor() { + Pattern mavenArtifactJar = Pattern.compile("maven-artifact-[\\d.]+(-SNAPSHOT)?\\.jar"); @Override - public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) - throws IOException - { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String filename = file.getFileName().toString(); - if ( mavenArtifactJar.matcher( filename ).matches() ) - { - Process p = Runtime.getRuntime().exec( new String[] { - Paths.get( System.getProperty( "java.home" ), "bin/java" ).toString(), + if (mavenArtifactJar.matcher(filename).matches()) { + Process p = Runtime.getRuntime().exec(new String[] { + Paths.get(System.getProperty("java.home"), "bin/java").toString(), "-jar", file.toAbsolutePath().toString(), "5.32", - "5.27" } ); + "5.27" + }); - try - { - assertEquals( 0, p.waitFor(), "Unexpected exit code" ); - } - catch ( InterruptedException e ) - { - throw new InterruptedIOException( e.toString() ); + try { + assertEquals(0, p.waitFor(), "Unexpected exit code"); + } catch (InterruptedException e) { + throw new InterruptedIOException(e.toString()); } return FileVisitResult.TERMINATE; - } - else - { + } else { return FileVisitResult.CONTINUE; } } @Override - public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) - throws IOException - { - if ( Paths.get( "target" ).equals( dir ) ) - { + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + if (Paths.get("target").equals(dir)) { return FileVisitResult.CONTINUE; - } - else - { + } else { return FileVisitResult.SKIP_SUBTREE; } } - } ); + }); } - } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionTest.java b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionTest.java index a36f605545..4105569fb2 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionTest.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/ComparableVersionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,187 +16,196 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ - -import java.util.Locale; - -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.versioning; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Locale; +import org.junit.jupiter.api.Test; + /** * Test ComparableVersion. * * @author Hervé Boutemy */ -@SuppressWarnings( "unchecked" ) -public class ComparableVersionTest -{ - private Comparable newComparable( String version ) - { - ComparableVersion ret = new ComparableVersion( version ); +@SuppressWarnings("unchecked") +public class ComparableVersionTest { + private Comparable newComparable(String version) { + ComparableVersion ret = new ComparableVersion(version); String canonical = ret.getCanonical(); - String parsedCanonical = new ComparableVersion( canonical ).getCanonical(); + String parsedCanonical = new ComparableVersion(canonical).getCanonical(); - System.out.println( "canonical( " + version + " ) = " + canonical ); - assertEquals( canonical, parsedCanonical, - "canonical( " + version + " ) = " + canonical + " -> canonical: " + parsedCanonical ); + System.out.println("canonical( " + version + " ) = " + canonical); + assertEquals( + canonical, + parsedCanonical, + "canonical( " + version + " ) = " + canonical + " -> canonical: " + parsedCanonical); return ret; } - private static final String[] VERSIONS_QUALIFIER = - { "1-alpha2snapshot", "1-alpha2", "1-alpha-123", "1-beta-2", "1-beta123", "1-m2", "1-m11", "1-rc", "1-cr2", - "1-rc123", "1-SNAPSHOT", "1", "1-sp", "1-sp2", "1-sp123", "1-abc", "1-def", "1-pom-1", "1-1-snapshot", - "1-1", "1-2", "1-123" }; + private static final String[] VERSIONS_QUALIFIER = { + "1-alpha2snapshot", + "1-alpha2", + "1-alpha-123", + "1-beta-2", + "1-beta123", + "1-m2", + "1-m11", + "1-rc", + "1-cr2", + "1-rc123", + "1-SNAPSHOT", + "1", + "1-sp", + "1-sp2", + "1-sp123", + "1-abc", + "1-def", + "1-pom-1", + "1-1-snapshot", + "1-1", + "1-2", + "1-123" + }; - private static final String[] VERSIONS_NUMBER = - { "2.0", "2-1", "2.0.a", "2.0.0.a", "2.0.2", "2.0.123", "2.1.0", "2.1-a", "2.1b", "2.1-c", "2.1-1", "2.1.0.1", - "2.2", "2.123", "11.a2", "11.a11", "11.b2", "11.b11", "11.m2", "11.m11", "11", "11.a", "11b", "11c", "11m" }; + private static final String[] VERSIONS_NUMBER = { + "2.0", "2-1", "2.0.a", "2.0.0.a", "2.0.2", "2.0.123", "2.1.0", "2.1-a", "2.1b", "2.1-c", "2.1-1", "2.1.0.1", + "2.2", "2.123", "11.a2", "11.a11", "11.b2", "11.b11", "11.m2", "11.m11", "11", "11.a", "11b", "11c", "11m" + }; - private void checkVersionsOrder( String[] versions ) - { + private void checkVersionsOrder(String[] versions) { Comparable[] c = new Comparable[versions.length]; - for ( int i = 0; i < versions.length; i++ ) - { - c[i] = newComparable( versions[i] ); + for (int i = 0; i < versions.length; i++) { + c[i] = newComparable(versions[i]); } - for ( int i = 1; i < versions.length; i++ ) - { + for (int i = 1; i < versions.length; i++) { Comparable low = c[i - 1]; - for ( int j = i; j < versions.length; j++ ) - { + for (int j = i; j < versions.length; j++) { Comparable high = c[j]; - assertTrue( low.compareTo( high ) < 0, "expected " + low + " < " + high ); - assertTrue( high.compareTo( low ) > 0, "expected " + high + " > " + low ); + assertTrue(low.compareTo(high) < 0, "expected " + low + " < " + high); + assertTrue(high.compareTo(low) > 0, "expected " + high + " > " + low); } } } - private void checkVersionsEqual( String v1, String v2 ) - { - Comparable c1 = newComparable( v1 ); - Comparable c2 = newComparable( v2 ); - assertTrue( c1.compareTo( c2 ) == 0, "expected " + v1 + " == " + v2 ); - assertTrue( c2.compareTo( c1 ) == 0, "expected " + v2 + " == " + v1 ); - assertTrue( c1.hashCode() == c2.hashCode(), "expected same hashcode for " + v1 + " and " + v2 ); - assertTrue( c1.equals( c2 ), "expected " + v1 + ".equals( " + v2 + " )" ); - assertTrue( c2.equals( c1 ), "expected " + v2 + ".equals( " + v1 + " )" ); + private void checkVersionsEqual(String v1, String v2) { + Comparable c1 = newComparable(v1); + Comparable c2 = newComparable(v2); + assertTrue(c1.compareTo(c2) == 0, "expected " + v1 + " == " + v2); + assertTrue(c2.compareTo(c1) == 0, "expected " + v2 + " == " + v1); + assertTrue(c1.hashCode() == c2.hashCode(), "expected same hashcode for " + v1 + " and " + v2); + assertTrue(c1.equals(c2), "expected " + v1 + ".equals( " + v2 + " )"); + assertTrue(c2.equals(c1), "expected " + v2 + ".equals( " + v1 + " )"); } - private void checkVersionsArrayEqual( String[] array ) - { + private void checkVersionsArrayEqual(String[] array) { // compare against each other (including itself) - for ( int i = 0; i < array.length; ++i ) - for ( int j = i; j < array.length; ++j ) - checkVersionsEqual( array[i], array[j] ); + for (int i = 0; i < array.length; ++i) + for (int j = i; j < array.length; ++j) checkVersionsEqual(array[i], array[j]); } - private void checkVersionsOrder( String v1, String v2 ) - { - Comparable c1 = newComparable( v1 ); - Comparable c2 = newComparable( v2 ); - assertTrue( c1.compareTo( c2 ) < 0, "expected " + v1 + " < " + v2 ); - assertTrue( c2.compareTo( c1 ) > 0, "expected " + v2 + " > " + v1 ); + private void checkVersionsOrder(String v1, String v2) { + Comparable c1 = newComparable(v1); + Comparable c2 = newComparable(v2); + assertTrue(c1.compareTo(c2) < 0, "expected " + v1 + " < " + v2); + assertTrue(c2.compareTo(c1) > 0, "expected " + v2 + " > " + v1); } @Test - public void testVersionsQualifier() - { - checkVersionsOrder( VERSIONS_QUALIFIER ); + public void testVersionsQualifier() { + checkVersionsOrder(VERSIONS_QUALIFIER); } @Test - public void testVersionsNumber() - { - checkVersionsOrder( VERSIONS_NUMBER ); + public void testVersionsNumber() { + checkVersionsOrder(VERSIONS_NUMBER); } @Test - public void testVersionsEqual() - { - newComparable( "1.0-alpha" ); - checkVersionsEqual( "1", "1" ); - checkVersionsEqual( "1", "1.0" ); - checkVersionsEqual( "1", "1.0.0" ); - checkVersionsEqual( "1.0", "1.0.0" ); - checkVersionsEqual( "1", "1-0" ); - checkVersionsEqual( "1", "1.0-0" ); - checkVersionsEqual( "1.0", "1.0-0" ); + public void testVersionsEqual() { + newComparable("1.0-alpha"); + checkVersionsEqual("1", "1"); + checkVersionsEqual("1", "1.0"); + checkVersionsEqual("1", "1.0.0"); + checkVersionsEqual("1.0", "1.0.0"); + checkVersionsEqual("1", "1-0"); + checkVersionsEqual("1", "1.0-0"); + checkVersionsEqual("1.0", "1.0-0"); // no separator between number and character - checkVersionsEqual( "1a", "1-a" ); - checkVersionsEqual( "1a", "1.0-a" ); - checkVersionsEqual( "1a", "1.0.0-a" ); - checkVersionsEqual( "1.0a", "1-a" ); - checkVersionsEqual( "1.0.0a", "1-a" ); - checkVersionsEqual( "1x", "1-x" ); - checkVersionsEqual( "1x", "1.0-x" ); - checkVersionsEqual( "1x", "1.0.0-x" ); - checkVersionsEqual( "1.0x", "1-x" ); - checkVersionsEqual( "1.0.0x", "1-x" ); + checkVersionsEqual("1a", "1-a"); + checkVersionsEqual("1a", "1.0-a"); + checkVersionsEqual("1a", "1.0.0-a"); + checkVersionsEqual("1.0a", "1-a"); + checkVersionsEqual("1.0.0a", "1-a"); + checkVersionsEqual("1x", "1-x"); + checkVersionsEqual("1x", "1.0-x"); + checkVersionsEqual("1x", "1.0.0-x"); + checkVersionsEqual("1.0x", "1-x"); + checkVersionsEqual("1.0.0x", "1-x"); // aliases - checkVersionsEqual( "1ga", "1" ); - checkVersionsEqual( "1release", "1" ); - checkVersionsEqual( "1final", "1" ); - checkVersionsEqual( "1cr", "1rc" ); + checkVersionsEqual("1ga", "1"); + checkVersionsEqual("1release", "1"); + checkVersionsEqual("1final", "1"); + checkVersionsEqual("1cr", "1rc"); // special "aliases" a, b and m for alpha, beta and milestone - checkVersionsEqual( "1a1", "1-alpha-1" ); - checkVersionsEqual( "1b2", "1-beta-2" ); - checkVersionsEqual( "1m3", "1-milestone-3" ); + checkVersionsEqual("1a1", "1-alpha-1"); + checkVersionsEqual("1b2", "1-beta-2"); + checkVersionsEqual("1m3", "1-milestone-3"); // case insensitive - checkVersionsEqual( "1X", "1x" ); - checkVersionsEqual( "1A", "1a" ); - checkVersionsEqual( "1B", "1b" ); - checkVersionsEqual( "1M", "1m" ); - checkVersionsEqual( "1Ga", "1" ); - checkVersionsEqual( "1GA", "1" ); - checkVersionsEqual( "1RELEASE", "1" ); - checkVersionsEqual( "1release", "1" ); - checkVersionsEqual( "1RELeaSE", "1" ); - checkVersionsEqual( "1Final", "1" ); - checkVersionsEqual( "1FinaL", "1" ); - checkVersionsEqual( "1FINAL", "1" ); - checkVersionsEqual( "1Cr", "1Rc" ); - checkVersionsEqual( "1cR", "1rC" ); - checkVersionsEqual( "1m3", "1Milestone3" ); - checkVersionsEqual( "1m3", "1MileStone3" ); - checkVersionsEqual( "1m3", "1MILESTONE3" ); + checkVersionsEqual("1X", "1x"); + checkVersionsEqual("1A", "1a"); + checkVersionsEqual("1B", "1b"); + checkVersionsEqual("1M", "1m"); + checkVersionsEqual("1Ga", "1"); + checkVersionsEqual("1GA", "1"); + checkVersionsEqual("1RELEASE", "1"); + checkVersionsEqual("1release", "1"); + checkVersionsEqual("1RELeaSE", "1"); + checkVersionsEqual("1Final", "1"); + checkVersionsEqual("1FinaL", "1"); + checkVersionsEqual("1FINAL", "1"); + checkVersionsEqual("1Cr", "1Rc"); + checkVersionsEqual("1cR", "1rC"); + checkVersionsEqual("1m3", "1Milestone3"); + checkVersionsEqual("1m3", "1MileStone3"); + checkVersionsEqual("1m3", "1MILESTONE3"); } @Test - public void testVersionComparing() - { - checkVersionsOrder( "1", "2" ); - checkVersionsOrder( "1.5", "2" ); - checkVersionsOrder( "1", "2.5" ); - checkVersionsOrder( "1.0", "1.1" ); - checkVersionsOrder( "1.1", "1.2" ); - checkVersionsOrder( "1.0.0", "1.1" ); - checkVersionsOrder( "1.0.1", "1.1" ); - checkVersionsOrder( "1.1", "1.2.0" ); + public void testVersionComparing() { + checkVersionsOrder("1", "2"); + checkVersionsOrder("1.5", "2"); + checkVersionsOrder("1", "2.5"); + checkVersionsOrder("1.0", "1.1"); + checkVersionsOrder("1.1", "1.2"); + checkVersionsOrder("1.0.0", "1.1"); + checkVersionsOrder("1.0.1", "1.1"); + checkVersionsOrder("1.1", "1.2.0"); - checkVersionsOrder( "1.0-alpha-1", "1.0" ); - checkVersionsOrder( "1.0-alpha-1", "1.0-alpha-2" ); - checkVersionsOrder( "1.0-alpha-1", "1.0-beta-1" ); + checkVersionsOrder("1.0-alpha-1", "1.0"); + checkVersionsOrder("1.0-alpha-1", "1.0-alpha-2"); + checkVersionsOrder("1.0-alpha-1", "1.0-beta-1"); - checkVersionsOrder( "1.0-beta-1", "1.0-SNAPSHOT" ); - checkVersionsOrder( "1.0-SNAPSHOT", "1.0" ); - checkVersionsOrder( "1.0-alpha-1-SNAPSHOT", "1.0-alpha-1" ); + checkVersionsOrder("1.0-beta-1", "1.0-SNAPSHOT"); + checkVersionsOrder("1.0-SNAPSHOT", "1.0"); + checkVersionsOrder("1.0-alpha-1-SNAPSHOT", "1.0-alpha-1"); - checkVersionsOrder( "1.0", "1.0-1" ); - checkVersionsOrder( "1.0-1", "1.0-2" ); - checkVersionsOrder( "1.0.0", "1.0-1" ); + checkVersionsOrder("1.0", "1.0-1"); + checkVersionsOrder("1.0-1", "1.0-2"); + checkVersionsOrder("1.0.0", "1.0-1"); - checkVersionsOrder( "2.0-1", "2.0.1" ); - checkVersionsOrder( "2.0.1-klm", "2.0.1-lmn" ); - checkVersionsOrder( "2.0.1", "2.0.1-xyz" ); + checkVersionsOrder("2.0-1", "2.0.1"); + checkVersionsOrder("2.0.1-klm", "2.0.1-lmn"); + checkVersionsOrder("2.0.1", "2.0.1-xyz"); - checkVersionsOrder( "2.0.1", "2.0.1-123" ); - checkVersionsOrder( "2.0.1-xyz", "2.0.1-123" ); + checkVersionsOrder("2.0.1", "2.0.1-123"); + checkVersionsOrder("2.0.1-xyz", "2.0.1-123"); } /** @@ -209,34 +216,32 @@ public class ComparableVersionTest * 226100 */ @Test - public void testMng5568() - { + public void testMng5568() { String a = "6.1.0"; String b = "6.1.0rc3"; String c = "6.1H.5-beta"; // this is the unusual version string, with 'H' in the middle - checkVersionsOrder( b, a ); // classical - checkVersionsOrder( b, c ); // now b < c, but before MNG-5568, we had b > c - checkVersionsOrder( a, c ); + checkVersionsOrder(b, a); // classical + checkVersionsOrder(b, c); // now b < c, but before MNG-5568, we had b > c + checkVersionsOrder(a, c); } /** * Test MNG-6572 optimization. */ @Test - public void testMng6572() - { + public void testMng6572() { String a = "20190126.230843"; // resembles a SNAPSHOT String b = "1234567890.12345"; // 10 digit number String c = "123456789012345.1H.5-beta"; // 15 digit number String d = "12345678901234567890.1H.5-beta"; // 20 digit number - checkVersionsOrder( a, b ); - checkVersionsOrder( b, c ); - checkVersionsOrder( a, c ); - checkVersionsOrder( c, d ); - checkVersionsOrder( b, d ); - checkVersionsOrder( a, d ); + checkVersionsOrder(a, b); + checkVersionsOrder(b, c); + checkVersionsOrder(a, c); + checkVersionsOrder(c, d); + checkVersionsOrder(b, d); + checkVersionsOrder(a, d); } /** @@ -244,8 +249,7 @@ public class ComparableVersionTest * (related to MNG-6572 optimization) */ @Test - public void testVersionEqualWithLeadingZeroes() - { + public void testVersionEqualWithLeadingZeroes() { // versions with string lengths from 1 to 19 String[] arr = new String[] { "0000000000000000001", @@ -269,7 +273,7 @@ public class ComparableVersionTest "1" }; - checkVersionsArrayEqual( arr ); + checkVersionsArrayEqual(arr); } /** @@ -277,8 +281,7 @@ public class ComparableVersionTest * (related to MNG-6572 optimization) */ @Test - public void testVersionZeroEqualWithLeadingZeroes() - { + public void testVersionZeroEqualWithLeadingZeroes() { // versions with string lengths from 1 to 19 String[] arr = new String[] { "0000000000000000000", @@ -302,7 +305,7 @@ public class ComparableVersionTest "0" }; - checkVersionsArrayEqual( arr ); + checkVersionsArrayEqual(arr); } /** @@ -310,44 +313,37 @@ public class ComparableVersionTest * for qualifiers that start with "-0.", which was showing A == C and B == C but A < B. */ @Test - public void testMng6964() - { + public void testMng6964() { String a = "1-0.alpha"; String b = "1-0.beta"; String c = "1"; - checkVersionsOrder( a, c ); // Now a < c, but before MNG-6964 they were equal - checkVersionsOrder( b, c ); // Now b < c, but before MNG-6964 they were equal - checkVersionsOrder( a, b ); // Should still be true + checkVersionsOrder(a, c); // Now a < c, but before MNG-6964 they were equal + checkVersionsOrder(b, c); // Now b < c, but before MNG-6964 they were equal + checkVersionsOrder(a, b); // Should still be true } @Test - public void testLocaleIndependent() - { + public void testLocaleIndependent() { Locale orig = Locale.getDefault(); - Locale[] locales = { Locale.ENGLISH, new Locale( "tr" ), Locale.getDefault() }; - try - { - for ( Locale locale : locales ) - { - Locale.setDefault( locale ); - checkVersionsEqual( "1-abcdefghijklmnopqrstuvwxyz", "1-ABCDEFGHIJKLMNOPQRSTUVWXYZ" ); + Locale[] locales = {Locale.ENGLISH, new Locale("tr"), Locale.getDefault()}; + try { + for (Locale locale : locales) { + Locale.setDefault(locale); + checkVersionsEqual("1-abcdefghijklmnopqrstuvwxyz", "1-ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } - } - finally - { - Locale.setDefault( orig ); + } finally { + Locale.setDefault(orig); } } @Test - public void testReuse() - { - ComparableVersion c1 = new ComparableVersion( "1" ); - c1.parseVersion( "2" ); + public void testReuse() { + ComparableVersion c1 = new ComparableVersion("1"); + c1.parseVersion("2"); - Comparable c2 = newComparable( "2" ); + Comparable c2 = newComparable("2"); - assertEquals( c1, c2, "reused instance should be equivalent to new instance" ); + assertEquals(c1, c2, "reused instance should be equivalent to new instance"); } } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/DefaultArtifactVersionTest.java b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/DefaultArtifactVersionTest.java index 13f3ffa438..b1de43b33b 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/DefaultArtifactVersionTest.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/DefaultArtifactVersionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,208 +16,196 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ - -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.versioning; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Test DefaultArtifactVersion. * * @author Brett Porter */ -public class DefaultArtifactVersionTest -{ - private ArtifactVersion newArtifactVersion( String version ) - { - return new DefaultArtifactVersion( version ); +public class DefaultArtifactVersionTest { + private ArtifactVersion newArtifactVersion(String version) { + return new DefaultArtifactVersion(version); } - private void checkVersionParsing( String version, int major, int minor, int incremental, int buildnumber, - String qualifier ) - { - ArtifactVersion artifactVersion = newArtifactVersion( version ); - String parsed = - "'" + version + "' parsed as ('" + artifactVersion.getMajorVersion() + "', '" + private void checkVersionParsing( + String version, int major, int minor, int incremental, int buildnumber, String qualifier) { + ArtifactVersion artifactVersion = newArtifactVersion(version); + String parsed = "'" + version + "' parsed as ('" + artifactVersion.getMajorVersion() + "', '" + artifactVersion.getMinorVersion() + "', '" + artifactVersion.getIncrementalVersion() + "', '" + artifactVersion.getBuildNumber() + "', '" + artifactVersion.getQualifier() + "'), "; - assertEquals( major, artifactVersion.getMajorVersion(), parsed + "check major version" ); - assertEquals( minor, artifactVersion.getMinorVersion(), parsed + "check minor version" ); - assertEquals( incremental, artifactVersion.getIncrementalVersion(), parsed + "check incremental version" ); - assertEquals( buildnumber, artifactVersion.getBuildNumber(), parsed + "check build number" ); - assertEquals( qualifier, artifactVersion.getQualifier(), parsed + "check qualifier" ); - assertEquals( version, artifactVersion.toString(), "check " + version + " string value" ); + assertEquals(major, artifactVersion.getMajorVersion(), parsed + "check major version"); + assertEquals(minor, artifactVersion.getMinorVersion(), parsed + "check minor version"); + assertEquals(incremental, artifactVersion.getIncrementalVersion(), parsed + "check incremental version"); + assertEquals(buildnumber, artifactVersion.getBuildNumber(), parsed + "check build number"); + assertEquals(qualifier, artifactVersion.getQualifier(), parsed + "check qualifier"); + assertEquals(version, artifactVersion.toString(), "check " + version + " string value"); } @Test - public void testVersionParsing() - { - checkVersionParsing( "1", 1, 0, 0, 0, null ); - checkVersionParsing( "1.2", 1, 2, 0, 0, null ); - checkVersionParsing( "1.2.3", 1, 2, 3, 0, null ); - checkVersionParsing( "1.2.3-1", 1, 2, 3, 1, null ); - checkVersionParsing( "1.2.3-alpha-1", 1, 2, 3, 0, "alpha-1" ); - checkVersionParsing( "1.2-alpha-1", 1, 2, 0, 0, "alpha-1" ); - checkVersionParsing( "1.2-alpha-1-20050205.060708-1", 1, 2, 0, 0, "alpha-1-20050205.060708-1" ); - checkVersionParsing( "RELEASE", 0, 0, 0, 0, "RELEASE" ); - checkVersionParsing( "2.0-1", 2, 0, 0, 1, null ); + public void testVersionParsing() { + checkVersionParsing("1", 1, 0, 0, 0, null); + checkVersionParsing("1.2", 1, 2, 0, 0, null); + checkVersionParsing("1.2.3", 1, 2, 3, 0, null); + checkVersionParsing("1.2.3-1", 1, 2, 3, 1, null); + checkVersionParsing("1.2.3-alpha-1", 1, 2, 3, 0, "alpha-1"); + checkVersionParsing("1.2-alpha-1", 1, 2, 0, 0, "alpha-1"); + checkVersionParsing("1.2-alpha-1-20050205.060708-1", 1, 2, 0, 0, "alpha-1-20050205.060708-1"); + checkVersionParsing("RELEASE", 0, 0, 0, 0, "RELEASE"); + checkVersionParsing("2.0-1", 2, 0, 0, 1, null); // 0 at the beginning of a number has a special handling - checkVersionParsing( "02", 0, 0, 0, 0, "02" ); - checkVersionParsing( "0.09", 0, 0, 0, 0, "0.09" ); - checkVersionParsing( "0.2.09", 0, 0, 0, 0, "0.2.09" ); - checkVersionParsing( "2.0-01", 2, 0, 0, 0, "01" ); + checkVersionParsing("02", 0, 0, 0, 0, "02"); + checkVersionParsing("0.09", 0, 0, 0, 0, "0.09"); + checkVersionParsing("0.2.09", 0, 0, 0, 0, "0.2.09"); + checkVersionParsing("2.0-01", 2, 0, 0, 0, "01"); // version schemes not really supported: fully transformed as qualifier - checkVersionParsing( "1.0.1b", 0, 0, 0, 0, "1.0.1b" ); - checkVersionParsing( "1.0M2", 0, 0, 0, 0, "1.0M2" ); - checkVersionParsing( "1.0RC2", 0, 0, 0, 0, "1.0RC2" ); - checkVersionParsing( "1.1.2.beta1", 1, 1, 2, 0, "beta1" ); - checkVersionParsing( "1.7.3.beta1", 1, 7, 3, 0, "beta1" ); - checkVersionParsing( "1.7.3.0", 0, 0, 0, 0, "1.7.3.0" ); - checkVersionParsing( "1.7.3.0-1", 0, 0, 0, 0, "1.7.3.0-1" ); - checkVersionParsing( "PATCH-1193602", 0, 0, 0, 0, "PATCH-1193602" ); - checkVersionParsing( "5.0.0alpha-2006020117", 0, 0, 0, 0, "5.0.0alpha-2006020117" ); - checkVersionParsing( "1.0.0.-SNAPSHOT", 0, 0, 0, 0, "1.0.0.-SNAPSHOT" ); - checkVersionParsing( "1..0-SNAPSHOT", 0, 0, 0, 0, "1..0-SNAPSHOT" ); - checkVersionParsing( "1.0.-SNAPSHOT", 0, 0, 0, 0, "1.0.-SNAPSHOT" ); - checkVersionParsing( ".1.0-SNAPSHOT", 0, 0, 0, 0, ".1.0-SNAPSHOT" ); + checkVersionParsing("1.0.1b", 0, 0, 0, 0, "1.0.1b"); + checkVersionParsing("1.0M2", 0, 0, 0, 0, "1.0M2"); + checkVersionParsing("1.0RC2", 0, 0, 0, 0, "1.0RC2"); + checkVersionParsing("1.1.2.beta1", 1, 1, 2, 0, "beta1"); + checkVersionParsing("1.7.3.beta1", 1, 7, 3, 0, "beta1"); + checkVersionParsing("1.7.3.0", 0, 0, 0, 0, "1.7.3.0"); + checkVersionParsing("1.7.3.0-1", 0, 0, 0, 0, "1.7.3.0-1"); + checkVersionParsing("PATCH-1193602", 0, 0, 0, 0, "PATCH-1193602"); + checkVersionParsing("5.0.0alpha-2006020117", 0, 0, 0, 0, "5.0.0alpha-2006020117"); + checkVersionParsing("1.0.0.-SNAPSHOT", 0, 0, 0, 0, "1.0.0.-SNAPSHOT"); + checkVersionParsing("1..0-SNAPSHOT", 0, 0, 0, 0, "1..0-SNAPSHOT"); + checkVersionParsing("1.0.-SNAPSHOT", 0, 0, 0, 0, "1.0.-SNAPSHOT"); + checkVersionParsing(".1.0-SNAPSHOT", 0, 0, 0, 0, ".1.0-SNAPSHOT"); - checkVersionParsing( "1.2.3.200705301630", 0, 0, 0, 0, "1.2.3.200705301630" ); - checkVersionParsing( "1.2.3-200705301630", 1, 2, 3, 0, "200705301630" ); + checkVersionParsing("1.2.3.200705301630", 0, 0, 0, 0, "1.2.3.200705301630"); + checkVersionParsing("1.2.3-200705301630", 1, 2, 3, 0, "200705301630"); } @Test - public void testVersionComparing() - { - assertVersionEqual( "1", "1" ); - assertVersionOlder( "1", "2" ); - assertVersionOlder( "1.5", "2" ); - assertVersionOlder( "1", "2.5" ); - assertVersionEqual( "1", "1.0" ); - assertVersionEqual( "1", "1.0.0" ); - assertVersionOlder( "1.0", "1.1" ); - assertVersionOlder( "1.1", "1.2" ); - assertVersionOlder( "1.0.0", "1.1" ); - assertVersionOlder( "1.1", "1.2.0" ); + public void testVersionComparing() { + assertVersionEqual("1", "1"); + assertVersionOlder("1", "2"); + assertVersionOlder("1.5", "2"); + assertVersionOlder("1", "2.5"); + assertVersionEqual("1", "1.0"); + assertVersionEqual("1", "1.0.0"); + assertVersionOlder("1.0", "1.1"); + assertVersionOlder("1.1", "1.2"); + assertVersionOlder("1.0.0", "1.1"); + assertVersionOlder("1.1", "1.2.0"); - assertVersionOlder( "1.1.2.alpha1", "1.1.2" ); - assertVersionOlder( "1.1.2.alpha1", "1.1.2.beta1" ); - assertVersionOlder( "1.1.2.beta1", "1.2" ); + assertVersionOlder("1.1.2.alpha1", "1.1.2"); + assertVersionOlder("1.1.2.alpha1", "1.1.2.beta1"); + assertVersionOlder("1.1.2.beta1", "1.2"); - assertVersionOlder( "1.0-alpha-1", "1.0" ); - assertVersionOlder( "1.0-alpha-1", "1.0-alpha-2" ); - assertVersionOlder( "1.0-alpha-2", "1.0-alpha-15" ); - assertVersionOlder( "1.0-alpha-1", "1.0-beta-1" ); + assertVersionOlder("1.0-alpha-1", "1.0"); + assertVersionOlder("1.0-alpha-1", "1.0-alpha-2"); + assertVersionOlder("1.0-alpha-2", "1.0-alpha-15"); + assertVersionOlder("1.0-alpha-1", "1.0-beta-1"); - assertVersionOlder( "1.0-beta-1", "1.0-SNAPSHOT" ); - assertVersionOlder( "1.0-SNAPSHOT", "1.0" ); - assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-alpha-1" ); + assertVersionOlder("1.0-beta-1", "1.0-SNAPSHOT"); + assertVersionOlder("1.0-SNAPSHOT", "1.0"); + assertVersionOlder("1.0-alpha-1-SNAPSHOT", "1.0-alpha-1"); - assertVersionOlder( "1.0", "1.0-1" ); - assertVersionOlder( "1.0-1", "1.0-2" ); - assertVersionEqual( "2.0-0", "2.0" ); - assertVersionOlder( "2.0", "2.0-1" ); - assertVersionOlder( "2.0.0", "2.0-1" ); - assertVersionOlder( "2.0-1", "2.0.1" ); + assertVersionOlder("1.0", "1.0-1"); + assertVersionOlder("1.0-1", "1.0-2"); + assertVersionEqual("2.0-0", "2.0"); + assertVersionOlder("2.0", "2.0-1"); + assertVersionOlder("2.0.0", "2.0-1"); + assertVersionOlder("2.0-1", "2.0.1"); - assertVersionOlder( "2.0.1-klm", "2.0.1-lmn" ); - assertVersionOlder( "2.0.1", "2.0.1-xyz" ); - assertVersionOlder( "2.0.1-xyz-1", "2.0.1-1-xyz" ); + assertVersionOlder("2.0.1-klm", "2.0.1-lmn"); + assertVersionOlder("2.0.1", "2.0.1-xyz"); + assertVersionOlder("2.0.1-xyz-1", "2.0.1-1-xyz"); - assertVersionOlder( "2.0.1", "2.0.1-123" ); - assertVersionOlder( "2.0.1-xyz", "2.0.1-123" ); + assertVersionOlder("2.0.1", "2.0.1-123"); + assertVersionOlder("2.0.1-xyz", "2.0.1-123"); - assertVersionOlder( "1.2.3-10000000000", "1.2.3-10000000001" ); - assertVersionOlder( "1.2.3-1", "1.2.3-10000000001" ); - assertVersionOlder( "2.3.0-v200706262000", "2.3.0-v200706262130" ); // org.eclipse:emf:2.3.0-v200706262000 + assertVersionOlder("1.2.3-10000000000", "1.2.3-10000000001"); + assertVersionOlder("1.2.3-1", "1.2.3-10000000001"); + assertVersionOlder("2.3.0-v200706262000", "2.3.0-v200706262130"); // org.eclipse:emf:2.3.0-v200706262000 // org.eclipse.wst.common_core.feature_2.0.0.v200706041905-7C78EK9E_EkMNfNOd2d8qq - assertVersionOlder( "2.0.0.v200706041905-7C78EK9E_EkMNfNOd2d8qq", "2.0.0.v200706041906-7C78EK9E_EkMNfNOd2d8qq" ); + assertVersionOlder("2.0.0.v200706041905-7C78EK9E_EkMNfNOd2d8qq", "2.0.0.v200706041906-7C78EK9E_EkMNfNOd2d8qq"); } @Test - public void testVersionSnapshotComparing() - { - assertVersionEqual( "1-SNAPSHOT", "1-SNAPSHOT" ); - assertVersionOlder( "1-SNAPSHOT", "2-SNAPSHOT" ); - assertVersionOlder( "1.5-SNAPSHOT", "2-SNAPSHOT" ); - assertVersionOlder( "1-SNAPSHOT", "2.5-SNAPSHOT" ); - assertVersionEqual( "1-SNAPSHOT", "1.0-SNAPSHOT" ); - assertVersionEqual( "1-SNAPSHOT", "1.0.0-SNAPSHOT" ); - assertVersionOlder( "1.0-SNAPSHOT", "1.1-SNAPSHOT" ); - assertVersionOlder( "1.1-SNAPSHOT", "1.2-SNAPSHOT" ); - assertVersionOlder( "1.0.0-SNAPSHOT", "1.1-SNAPSHOT" ); - assertVersionOlder( "1.1-SNAPSHOT", "1.2.0-SNAPSHOT" ); + public void testVersionSnapshotComparing() { + assertVersionEqual("1-SNAPSHOT", "1-SNAPSHOT"); + assertVersionOlder("1-SNAPSHOT", "2-SNAPSHOT"); + assertVersionOlder("1.5-SNAPSHOT", "2-SNAPSHOT"); + assertVersionOlder("1-SNAPSHOT", "2.5-SNAPSHOT"); + assertVersionEqual("1-SNAPSHOT", "1.0-SNAPSHOT"); + assertVersionEqual("1-SNAPSHOT", "1.0.0-SNAPSHOT"); + assertVersionOlder("1.0-SNAPSHOT", "1.1-SNAPSHOT"); + assertVersionOlder("1.1-SNAPSHOT", "1.2-SNAPSHOT"); + assertVersionOlder("1.0.0-SNAPSHOT", "1.1-SNAPSHOT"); + assertVersionOlder("1.1-SNAPSHOT", "1.2.0-SNAPSHOT"); // assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-SNAPSHOT" ); - assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-alpha-2-SNAPSHOT" ); - assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-beta-1-SNAPSHOT" ); + assertVersionOlder("1.0-alpha-1-SNAPSHOT", "1.0-alpha-2-SNAPSHOT"); + assertVersionOlder("1.0-alpha-1-SNAPSHOT", "1.0-beta-1-SNAPSHOT"); - assertVersionOlder( "1.0-beta-1-SNAPSHOT", "1.0-SNAPSHOT-SNAPSHOT" ); - assertVersionOlder( "1.0-SNAPSHOT-SNAPSHOT", "1.0-SNAPSHOT" ); - assertVersionOlder( "1.0-alpha-1-SNAPSHOT-SNAPSHOT", "1.0-alpha-1-SNAPSHOT" ); + assertVersionOlder("1.0-beta-1-SNAPSHOT", "1.0-SNAPSHOT-SNAPSHOT"); + assertVersionOlder("1.0-SNAPSHOT-SNAPSHOT", "1.0-SNAPSHOT"); + assertVersionOlder("1.0-alpha-1-SNAPSHOT-SNAPSHOT", "1.0-alpha-1-SNAPSHOT"); - assertVersionOlder( "1.0-SNAPSHOT", "1.0-1-SNAPSHOT" ); - assertVersionOlder( "1.0-1-SNAPSHOT", "1.0-2-SNAPSHOT" ); + assertVersionOlder("1.0-SNAPSHOT", "1.0-1-SNAPSHOT"); + assertVersionOlder("1.0-1-SNAPSHOT", "1.0-2-SNAPSHOT"); // assertVersionEqual( "2.0-0-SNAPSHOT", "2.0-SNAPSHOT" ); - assertVersionOlder( "2.0-SNAPSHOT", "2.0-1-SNAPSHOT" ); - assertVersionOlder( "2.0.0-SNAPSHOT", "2.0-1-SNAPSHOT" ); - assertVersionOlder( "2.0-1-SNAPSHOT", "2.0.1-SNAPSHOT" ); + assertVersionOlder("2.0-SNAPSHOT", "2.0-1-SNAPSHOT"); + assertVersionOlder("2.0.0-SNAPSHOT", "2.0-1-SNAPSHOT"); + assertVersionOlder("2.0-1-SNAPSHOT", "2.0.1-SNAPSHOT"); - assertVersionOlder( "2.0.1-klm-SNAPSHOT", "2.0.1-lmn-SNAPSHOT" ); + assertVersionOlder("2.0.1-klm-SNAPSHOT", "2.0.1-lmn-SNAPSHOT"); // assertVersionOlder( "2.0.1-xyz-SNAPSHOT", "2.0.1-SNAPSHOT" ); - assertVersionOlder( "2.0.1-SNAPSHOT", "2.0.1-123-SNAPSHOT" ); - assertVersionOlder( "2.0.1-xyz-SNAPSHOT", "2.0.1-123-SNAPSHOT" ); + assertVersionOlder("2.0.1-SNAPSHOT", "2.0.1-123-SNAPSHOT"); + assertVersionOlder("2.0.1-xyz-SNAPSHOT", "2.0.1-123-SNAPSHOT"); } @Test - public void testSnapshotVsReleases() - { - assertVersionOlder( "1.0-RC1", "1.0-SNAPSHOT" ); - assertVersionOlder( "1.0-rc1", "1.0-SNAPSHOT" ); - assertVersionOlder( "1.0-rc-1", "1.0-SNAPSHOT" ); + public void testSnapshotVsReleases() { + assertVersionOlder("1.0-RC1", "1.0-SNAPSHOT"); + assertVersionOlder("1.0-rc1", "1.0-SNAPSHOT"); + assertVersionOlder("1.0-rc-1", "1.0-SNAPSHOT"); } @Test - public void testHashCode() - { - ArtifactVersion v1 = newArtifactVersion( "1" ); - ArtifactVersion v2 = newArtifactVersion( "1.0" ); - assertTrue( v1.equals( v2 ) ); - assertEquals( v1.hashCode(), v2.hashCode() ); + public void testHashCode() { + ArtifactVersion v1 = newArtifactVersion("1"); + ArtifactVersion v2 = newArtifactVersion("1.0"); + assertTrue(v1.equals(v2)); + assertEquals(v1.hashCode(), v2.hashCode()); } @Test - public void testEqualsNullSafe() - { - assertFalse( newArtifactVersion( "1" ).equals( null ) ); + public void testEqualsNullSafe() { + assertFalse(newArtifactVersion("1").equals(null)); } @Test - public void testEqualsTypeSafe() - { - assertFalse( newArtifactVersion( "1" ).equals( "non-an-artifact-version-instance" ) ); + public void testEqualsTypeSafe() { + assertFalse(newArtifactVersion("1").equals("non-an-artifact-version-instance")); } - private void assertVersionOlder( String left, String right ) - { + private void assertVersionOlder(String left, String right) { assertTrue( - newArtifactVersion( left ).compareTo( newArtifactVersion( right ) ) < 0, - left + " should be older than " + right ); + newArtifactVersion(left).compareTo(newArtifactVersion(right)) < 0, + left + " should be older than " + right); assertTrue( - newArtifactVersion( right ).compareTo( newArtifactVersion( left ) ) > 0, - right + " should be newer than " + left ); + newArtifactVersion(right).compareTo(newArtifactVersion(left)) > 0, + right + " should be newer than " + left); } - private void assertVersionEqual( String left, String right ) - { + private void assertVersionEqual(String left, String right) { assertTrue( - newArtifactVersion( left ).compareTo( newArtifactVersion( right ) ) == 0, - left + " should be equal to " + right ); + newArtifactVersion(left).compareTo(newArtifactVersion(right)) == 0, + left + " should be equal to " + right); assertTrue( - newArtifactVersion( right ).compareTo( newArtifactVersion( left ) ) == 0, - right + " should be equal to " + left ); + newArtifactVersion(right).compareTo(newArtifactVersion(left)) == 0, + right + " should be equal to " + left); } } diff --git a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/VersionRangeTest.java b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/VersionRangeTest.java index 7c05940c05..6a11998cc7 100644 --- a/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/VersionRangeTest.java +++ b/maven-artifact/src/test/java/org/apache/maven/artifact/versioning/VersionRangeTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,11 +16,7 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ - -import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.versioning; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -31,13 +25,16 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; +import org.apache.maven.artifact.Artifact; +import org.junit.jupiter.api.Test; + /** * Tests version range construction. * * @author Brett Porter */ -public class VersionRangeTest -{ +public class VersionRangeTest { private static final String CHECK_NUM_RESTRICTIONS = "check number of restrictions"; private static final String CHECK_UPPER_BOUND = "check upper bound"; @@ -55,712 +52,698 @@ public class VersionRangeTest private static final String CHECK_SELECTED_VERSION = "check selected version"; @Test - public void testRange() - throws InvalidVersionSpecificationException, OverConstrainedVersionException - { + public void testRange() throws InvalidVersionSpecificationException, OverConstrainedVersionException { Artifact artifact = null; - VersionRange range = VersionRange.createFromVersionSpec( "(,1.0]" ); + VersionRange range = VersionRange.createFromVersionSpec("(,1.0]"); List restrictions = range.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - Restriction restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - assertFalse( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertNull( range.getSelectedVersion( artifact ), CHECK_SELECTED_VERSION ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + Restriction restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + assertFalse(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertNull(range.getSelectedVersion(artifact), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "1.0" ); - assertEquals( "1.0", range.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range = VersionRange.createFromVersionSpec("1.0"); + assertEquals("1.0", range.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = range.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertTrue( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertEquals( "1.0", range.getSelectedVersion( artifact ).toString(), CHECK_SELECTED_VERSION ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertTrue(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertEquals("1.0", range.getSelectedVersion(artifact).toString(), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "[1.0]" ); + range = VersionRange.createFromVersionSpec("[1.0]"); restrictions = range.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.0", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - assertFalse( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertNull( range.getSelectedVersion( artifact ), CHECK_SELECTED_VERSION ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.0", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + assertFalse(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertNull(range.getSelectedVersion(artifact), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "[1.2,1.3]" ); + range = VersionRange.createFromVersionSpec("[1.2,1.3]"); restrictions = range.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - assertFalse( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertNull( range.getSelectedVersion( artifact ), CHECK_SELECTED_VERSION ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + assertFalse(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertNull(range.getSelectedVersion(artifact), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "[1.0,2.0)" ); + range = VersionRange.createFromVersionSpec("[1.0,2.0)"); restrictions = range.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.0", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "2.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - assertFalse( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertNull( range.getSelectedVersion( artifact ), CHECK_SELECTED_VERSION ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.0", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("2.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + assertFalse(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertNull(range.getSelectedVersion(artifact), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "[1.5,)" ); + range = VersionRange.createFromVersionSpec("[1.5,)"); restrictions = range.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.5", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - assertFalse( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertNull( range.getSelectedVersion( artifact ), CHECK_SELECTED_VERSION ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.5", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + assertFalse(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertNull(range.getSelectedVersion(artifact), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "(,1.0],[1.2,)" ); + range = VersionRange.createFromVersionSpec("(,1.0],[1.2,)"); restrictions = range.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - restriction = restrictions.get( 1 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - assertNull( range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); - assertFalse( range.isSelectedVersionKnown( artifact ), CHECK_SELECTED_VERSION_KNOWN ); - assertNull( range.getSelectedVersion( artifact ), CHECK_SELECTED_VERSION ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + restriction = restrictions.get(1); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + assertNull(range.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); + assertFalse(range.isSelectedVersionKnown(artifact), CHECK_SELECTED_VERSION_KNOWN); + assertNull(range.getSelectedVersion(artifact), CHECK_SELECTED_VERSION); - range = VersionRange.createFromVersionSpec( "[1.0,)" ); - assertFalse( range.containsVersion( new DefaultArtifactVersion( "1.0-SNAPSHOT" ) ) ); + range = VersionRange.createFromVersionSpec("[1.0,)"); + assertFalse(range.containsVersion(new DefaultArtifactVersion("1.0-SNAPSHOT"))); - range = VersionRange.createFromVersionSpec( "[1.0,1.1-SNAPSHOT]" ); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.1-SNAPSHOT" ) ) ); + range = VersionRange.createFromVersionSpec("[1.0,1.1-SNAPSHOT]"); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.1-SNAPSHOT"))); - range = VersionRange.createFromVersionSpec( "[5.0.9.0,5.0.10.0)" ); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "5.0.9.0" ) ) ); + range = VersionRange.createFromVersionSpec("[5.0.9.0,5.0.10.0)"); + assertTrue(range.containsVersion(new DefaultArtifactVersion("5.0.9.0"))); } @Test - public void testSameUpperAndLowerBoundRoundtrip() throws InvalidVersionSpecificationException - { - VersionRange range = VersionRange.createFromVersionSpec( "[1.0]" ); - VersionRange range2 = VersionRange.createFromVersionSpec( range.toString() ); - assertEquals( range, range2 ); + public void testSameUpperAndLowerBoundRoundtrip() throws InvalidVersionSpecificationException { + VersionRange range = VersionRange.createFromVersionSpec("[1.0]"); + VersionRange range2 = VersionRange.createFromVersionSpec(range.toString()); + assertEquals(range, range2); } @Test - public void testInvalidRanges() - { - checkInvalidRange( "(1.0)" ); - checkInvalidRange( "[1.0)" ); - checkInvalidRange( "(1.0]" ); - checkInvalidRange( "(1.0,1.0]" ); - checkInvalidRange( "[1.0,1.0)" ); - checkInvalidRange( "(1.0,1.0)" ); - checkInvalidRange( "[1.1,1.0]" ); - checkInvalidRange( "[1.0,1.2),1.3" ); + public void testInvalidRanges() { + checkInvalidRange("(1.0)"); + checkInvalidRange("[1.0)"); + checkInvalidRange("(1.0]"); + checkInvalidRange("(1.0,1.0]"); + checkInvalidRange("[1.0,1.0)"); + checkInvalidRange("(1.0,1.0)"); + checkInvalidRange("[1.1,1.0]"); + checkInvalidRange("[1.0,1.2),1.3"); // overlap - checkInvalidRange( "[1.0,1.2),(1.1,1.3]" ); + checkInvalidRange("[1.0,1.2),(1.1,1.3]"); // overlap - checkInvalidRange( "[1.1,1.3),(1.0,1.2]" ); + checkInvalidRange("[1.1,1.3),(1.0,1.2]"); // ordering - checkInvalidRange( "(1.1,1.2],[1.0,1.1)" ); + checkInvalidRange("(1.1,1.2],[1.0,1.1)"); } @Test - public void testIntersections() - throws InvalidVersionSpecificationException - { - VersionRange range1 = VersionRange.createFromVersionSpec( "1.0" ); - VersionRange range2 = VersionRange.createFromVersionSpec( "1.1" ); - VersionRange mergedRange = range1.restrict( range2 ); - // TODO current policy is to retain the original version - is this correct, do we need strategies or is that handled elsewhere? -// assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); - assertEquals( "1.0", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + public void testIntersections() throws InvalidVersionSpecificationException { + VersionRange range1 = VersionRange.createFromVersionSpec("1.0"); + VersionRange range2 = VersionRange.createFromVersionSpec("1.1"); + VersionRange mergedRange = range1.restrict(range2); + // TODO current policy is to retain the original version - is this correct, do we need strategies or is that + // handled elsewhere? + // assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + assertEquals("1.0", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); List restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - Restriction restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + Restriction restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - mergedRange = range2.restrict( range1 ); - assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + mergedRange = range2.restrict(range1); + assertEquals("1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); // TODO test reversed restrictions on all below - range1 = VersionRange.createFromVersionSpec( "[1.0,)" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,)"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertEquals("1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.0", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.0", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.1,)" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.1,)"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertEquals("1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.1]" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.1]"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertEquals("1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(1.1,)" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(1.1,)"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.2,)" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.2,)"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.2]" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.2]"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertEquals("1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.1]" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertEquals( "1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.1]"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertEquals("1.1", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.1)" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.1)"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.0]" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.0]"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.0], [1.1,)" ); - range2 = VersionRange.createFromVersionSpec( "1.2" ); - mergedRange = range1.restrict( range2 ); - assertEquals( "1.2", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.0], [1.1,)"); + range2 = VersionRange.createFromVersionSpec("1.2"); + mergedRange = range1.restrict(range2); + assertEquals("1.2", mergedRange.getRecommendedVersion().toString(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.0], [1.1,)" ); - range2 = VersionRange.createFromVersionSpec( "1.0.5" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.0], [1.1,)"); + range2 = VersionRange.createFromVersionSpec("1.0.5"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.0", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.1), (1.1,)" ); - range2 = VersionRange.createFromVersionSpec( "1.1" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.1), (1.1,)"); + range2 = VersionRange.createFromVersionSpec("1.1"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertNull( restriction.getLowerBound(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertNull( restriction.getUpperBound(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertNull(restriction.getLowerBound(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertNull(restriction.getUpperBound(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.1,1.3]" ); - range2 = VersionRange.createFromVersionSpec( "(1.1,)" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.1,1.3]"); + range2 = VersionRange.createFromVersionSpec("(1.1,)"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.3)" ); - range2 = VersionRange.createFromVersionSpec( "[1.2,1.3]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.3)"); + range2 = VersionRange.createFromVersionSpec("[1.2,1.3]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.1,1.3]" ); - range2 = VersionRange.createFromVersionSpec( "[1.2,)" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.1,1.3]"); + range2 = VersionRange.createFromVersionSpec("[1.2,)"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.3]" ); - range2 = VersionRange.createFromVersionSpec( "[1.2,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.3]"); + range2 = VersionRange.createFromVersionSpec("[1.2,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(1.2,1.3]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(1.2,1.3]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(1.2,1.3)" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(1.2,1.3)"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.2,1.3)" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.2,1.3)"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.2", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.3", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.1]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.1]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.1)" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.1)"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("[1.1]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.1", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "[1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("[1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.4", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.4", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2),(1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2),(1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "(1.1,1.4)" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("(1.1,1.4)"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2),(1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "(1.1,1.4)" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2),(1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("(1.1,1.4)"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertFalse( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertFalse( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertFalse(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertFalse(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "(,1.1),(1.4,)" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.1),(1.4,)"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); - range1 = VersionRange.createFromVersionSpec( "(,1.1],[1.4,)" ); - range2 = VersionRange.createFromVersionSpec( "(1.1,1.4)" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("(,1.1],[1.4,)"); + range2 = VersionRange.createFromVersionSpec("(1.1,1.4)"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); - range1 = VersionRange.createFromVersionSpec( "[,1.1],[1.4,]" ); - range2 = VersionRange.createFromVersionSpec( "[1.2,1.3]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[,1.1],[1.4,]"); + range2 = VersionRange.createFromVersionSpec("[1.2,1.3]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4],[1.6,]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4],[1.6,]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 2, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(2, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.5]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4],[1.5,]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.5]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4],[1.5,]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 3, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 2 ); - assertEquals( "1.5", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.5", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(3, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(2); + assertEquals("1.5", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.5", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); - range1 = VersionRange.createFromVersionSpec( "[1.0,1.2],[1.3,1.7]" ); - range2 = VersionRange.createFromVersionSpec( "[1.1,1.4],[1.5,1.6]" ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[1.0,1.2],[1.3,1.7]"); + range2 = VersionRange.createFromVersionSpec("[1.1,1.4],[1.5,1.6]"); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 3, restrictions.size(), CHECK_NUM_RESTRICTIONS ); - restriction = restrictions.get( 0 ); - assertEquals( "1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 1 ); - assertEquals( "1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); - restriction = restrictions.get( 2 ); - assertEquals( "1.5", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND ); - assertTrue( restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE ); - assertEquals( "1.6", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND ); - assertTrue( restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE ); + assertEquals(3, restrictions.size(), CHECK_NUM_RESTRICTIONS); + restriction = restrictions.get(0); + assertEquals("1.1", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.2", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(1); + assertEquals("1.3", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.4", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); + restriction = restrictions.get(2); + assertEquals("1.5", restriction.getLowerBound().toString(), CHECK_LOWER_BOUND); + assertTrue(restriction.isLowerBoundInclusive(), CHECK_LOWER_BOUND_INCLUSIVE); + assertEquals("1.6", restriction.getUpperBound().toString(), CHECK_UPPER_BOUND); + assertTrue(restriction.isUpperBoundInclusive(), CHECK_UPPER_BOUND_INCLUSIVE); // test restricting empty sets - range1 = VersionRange.createFromVersionSpec( "[,1.1],[1.4,]" ); - range2 = VersionRange.createFromVersionSpec( "[1.2,1.3]" ); - range1 = range1.restrict( range2 ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[,1.1],[1.4,]"); + range2 = VersionRange.createFromVersionSpec("[1.2,1.3]"); + range1 = range1.restrict(range2); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); - range1 = VersionRange.createFromVersionSpec( "[,1.1],[1.4,]" ); - range2 = VersionRange.createFromVersionSpec( "[1.2,1.3]" ); - range2 = range1.restrict( range2 ); - mergedRange = range1.restrict( range2 ); - assertNull( mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION ); + range1 = VersionRange.createFromVersionSpec("[,1.1],[1.4,]"); + range2 = VersionRange.createFromVersionSpec("[1.2,1.3]"); + range2 = range1.restrict(range2); + mergedRange = range1.restrict(range2); + assertNull(mergedRange.getRecommendedVersion(), CHECK_VERSION_RECOMMENDATION); restrictions = mergedRange.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); } @Test - public void testReleaseRangeBoundsContainsSnapshots() - throws InvalidVersionSpecificationException - { - VersionRange range = VersionRange.createFromVersionSpec( "[1.0,1.2]" ); + public void testReleaseRangeBoundsContainsSnapshots() throws InvalidVersionSpecificationException { + VersionRange range = VersionRange.createFromVersionSpec("[1.0,1.2]"); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.1-SNAPSHOT" ) ) ); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.2-SNAPSHOT" ) ) ); - assertFalse( range.containsVersion( new DefaultArtifactVersion( "1.0-SNAPSHOT" ) ) ); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.1-SNAPSHOT"))); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.2-SNAPSHOT"))); + assertFalse(range.containsVersion(new DefaultArtifactVersion("1.0-SNAPSHOT"))); } @Test - public void testSnapshotRangeBoundsCanContainSnapshots() - throws InvalidVersionSpecificationException - { - VersionRange range = VersionRange.createFromVersionSpec( "[1.0,1.2-SNAPSHOT]" ); + public void testSnapshotRangeBoundsCanContainSnapshots() throws InvalidVersionSpecificationException { + VersionRange range = VersionRange.createFromVersionSpec("[1.0,1.2-SNAPSHOT]"); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.1-SNAPSHOT" ) ) ); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.2-SNAPSHOT" ) ) ); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.1-SNAPSHOT"))); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.2-SNAPSHOT"))); - range = VersionRange.createFromVersionSpec( "[1.0-SNAPSHOT,1.2]" ); + range = VersionRange.createFromVersionSpec("[1.0-SNAPSHOT,1.2]"); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.0-SNAPSHOT" ) ) ); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.1-SNAPSHOT" ) ) ); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.0-SNAPSHOT"))); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.1-SNAPSHOT"))); } @Test - public void testSnapshotSoftVersionCanContainSnapshot() - throws InvalidVersionSpecificationException - { - VersionRange range = VersionRange.createFromVersionSpec( "1.0-SNAPSHOT" ); + public void testSnapshotSoftVersionCanContainSnapshot() throws InvalidVersionSpecificationException { + VersionRange range = VersionRange.createFromVersionSpec("1.0-SNAPSHOT"); - assertTrue( range.containsVersion( new DefaultArtifactVersion( "1.0-SNAPSHOT" ) ) ); + assertTrue(range.containsVersion(new DefaultArtifactVersion("1.0-SNAPSHOT"))); } - private void checkInvalidRange( String version ) - { + private void checkInvalidRange(String version) { assertThrows( InvalidVersionSpecificationException.class, - () -> VersionRange.createFromVersionSpec( version ), - "Version " + version + " should have failed to construct" ); + () -> VersionRange.createFromVersionSpec(version), + "Version " + version + " should have failed to construct"); } @Test - public void testContains() throws InvalidVersionSpecificationException - { - ArtifactVersion actualVersion = new DefaultArtifactVersion( "2.0.5" ); - assertTrue( enforceVersion( "2.0.5", actualVersion ) ); - assertTrue( enforceVersion( "2.0.4", actualVersion ) ); - assertTrue( enforceVersion( "[2.0.5]", actualVersion ) ); - assertFalse( enforceVersion( "[2.0.6,)", actualVersion ) ); - assertFalse( enforceVersion( "[2.0.6]", actualVersion ) ); - assertTrue( enforceVersion( "[2.0,2.1]", actualVersion ) ); - assertFalse( enforceVersion( "[2.0,2.0.3]", actualVersion ) ); - assertTrue( enforceVersion( "[2.0,2.0.5]", actualVersion ) ); - assertFalse( enforceVersion( "[2.0,2.0.5)", actualVersion ) ); + public void testContains() throws InvalidVersionSpecificationException { + ArtifactVersion actualVersion = new DefaultArtifactVersion("2.0.5"); + assertTrue(enforceVersion("2.0.5", actualVersion)); + assertTrue(enforceVersion("2.0.4", actualVersion)); + assertTrue(enforceVersion("[2.0.5]", actualVersion)); + assertFalse(enforceVersion("[2.0.6,)", actualVersion)); + assertFalse(enforceVersion("[2.0.6]", actualVersion)); + assertTrue(enforceVersion("[2.0,2.1]", actualVersion)); + assertFalse(enforceVersion("[2.0,2.0.3]", actualVersion)); + assertTrue(enforceVersion("[2.0,2.0.5]", actualVersion)); + assertFalse(enforceVersion("[2.0,2.0.5)", actualVersion)); } - public boolean enforceVersion( String requiredVersionRange, ArtifactVersion actualVersion ) - throws InvalidVersionSpecificationException - { + public boolean enforceVersion(String requiredVersionRange, ArtifactVersion actualVersion) + throws InvalidVersionSpecificationException { VersionRange vr = null; - vr = VersionRange.createFromVersionSpec( requiredVersionRange ); + vr = VersionRange.createFromVersionSpec(requiredVersionRange); - return vr.containsVersion( actualVersion ); + return vr.containsVersion(actualVersion); } @Test - public void testOrder0() - { - // assertTrue( new DefaultArtifactVersion( "1.0-alpha10" ).compareTo( new DefaultArtifactVersion( "1.0-alpha1" ) ) > 0 ); + public void testOrder0() { + // assertTrue( new DefaultArtifactVersion( "1.0-alpha10" ).compareTo( new DefaultArtifactVersion( "1.0-alpha1" ) + // ) > 0 ); } @Test - public void testCache() - throws InvalidVersionSpecificationException - { - VersionRange range = VersionRange.createFromVersionSpec( "[1.0,1.2]" ); - assertSame( range, VersionRange.createFromVersionSpec( "[1.0,1.2]" ) ); // same instance from spec cache + public void testCache() throws InvalidVersionSpecificationException { + VersionRange range = VersionRange.createFromVersionSpec("[1.0,1.2]"); + assertSame(range, VersionRange.createFromVersionSpec("[1.0,1.2]")); // same instance from spec cache - VersionRange spec = VersionRange.createFromVersionSpec( "1.0" ); - assertSame( spec, VersionRange.createFromVersionSpec( "1.0" ) ); // same instance from spec cache + VersionRange spec = VersionRange.createFromVersionSpec("1.0"); + assertSame(spec, VersionRange.createFromVersionSpec("1.0")); // same instance from spec cache List restrictions = spec.getRestrictions(); - assertEquals( 1, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(1, restrictions.size(), CHECK_NUM_RESTRICTIONS); - VersionRange version = VersionRange.createFromVersion( "1.0" ); - assertSame( version, VersionRange.createFromVersion( "1.0" ) ); // same instance from version cache + VersionRange version = VersionRange.createFromVersion("1.0"); + assertSame(version, VersionRange.createFromVersion("1.0")); // same instance from version cache restrictions = version.getRestrictions(); - assertEquals( 0, restrictions.size(), CHECK_NUM_RESTRICTIONS ); + assertEquals(0, restrictions.size(), CHECK_NUM_RESTRICTIONS); - assertFalse( spec.equals( version ), "check !VersionRange.createFromVersionSpec(x).equals(VersionRange.createFromVersion(x))" ); + assertFalse( + spec.equals(version), + "check !VersionRange.createFromVersionSpec(x).equals(VersionRange.createFromVersion(x))"); } } diff --git a/maven-builder-support/pom.xml b/maven-builder-support/pom.xml index 807451e526..345f0c91da 100644 --- a/maven-builder-support/pom.xml +++ b/maven-builder-support/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblem.java b/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblem.java index 212eaa1725..9c18c8a63a 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblem.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblem.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; /** * Describes a problem that was encountered during settings building. A problem can either be an exception that was @@ -27,9 +26,7 @@ package org.apache.maven.building; * @author Benjamin Bentmann * @author Robert Scholte */ -class DefaultProblem - implements Problem -{ +class DefaultProblem implements Problem { private final String source; @@ -55,85 +52,68 @@ class DefaultProblem * @param columnNumber The one-based index of the column containing the problem or {@code -1} if unknown. * @param exception The exception that caused this problem, may be {@code null}. */ - DefaultProblem( String message, Severity severity, String source, int lineNumber, int columnNumber, - Exception exception ) - { + DefaultProblem( + String message, Severity severity, String source, int lineNumber, int columnNumber, Exception exception) { this.message = message; - this.severity = ( severity != null ) ? severity : Severity.ERROR; - this.source = ( source != null ) ? source : ""; + this.severity = (severity != null) ? severity : Severity.ERROR; + this.source = (source != null) ? source : ""; this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.exception = exception; } - public String getSource() - { + public String getSource() { return source; } - public int getLineNumber() - { + public int getLineNumber() { return lineNumber; } - public int getColumnNumber() - { + public int getColumnNumber() { return columnNumber; } - public String getLocation() - { - StringBuilder buffer = new StringBuilder( 256 ); + public String getLocation() { + StringBuilder buffer = new StringBuilder(256); - if ( getSource().length() > 0 ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + if (getSource().length() > 0) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( getSource() ); + buffer.append(getSource()); } - if ( getLineNumber() > 0 ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + if (getLineNumber() > 0) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( "line " ).append( getLineNumber() ); + buffer.append("line ").append(getLineNumber()); } - if ( getColumnNumber() > 0 ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + if (getColumnNumber() > 0) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( "column " ).append( getColumnNumber() ); + buffer.append("column ").append(getColumnNumber()); } return buffer.toString(); } - public Exception getException() - { + public Exception getException() { return exception; } - public String getMessage() - { + public String getMessage() { String msg; - if ( message != null && message.length() > 0 ) - { + if (message != null && message.length() > 0) { msg = message; - } - else - { + } else { msg = exception.getMessage(); - if ( msg == null ) - { + if (msg == null) { msg = ""; } } @@ -141,27 +121,22 @@ class DefaultProblem return msg; } - public Severity getSeverity() - { + public Severity getSeverity() { return severity; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 128 ); + public String toString() { + StringBuilder buffer = new StringBuilder(128); - buffer.append( '[' ).append( getSeverity() ).append( "] " ); - buffer.append( getMessage() ); + buffer.append('[').append(getSeverity()).append("] "); + buffer.append(getMessage()); String location = getLocation(); - if ( !location.isEmpty() ) - { - buffer.append( " @ " ); - buffer.append( location ); + if (!location.isEmpty()) { + buffer.append(" @ "); + buffer.append(location); } - return buffer.toString(); } - } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblemCollector.java b/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblemCollector.java index 2c09df6b3e..2007c6d83f 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblemCollector.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblemCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.util.ArrayList; import java.util.List; @@ -28,37 +27,30 @@ import java.util.List; * @author Benjamin Bentmann * @author Robert Scholte */ -class DefaultProblemCollector - implements ProblemCollector -{ +class DefaultProblemCollector implements ProblemCollector { private List problems; private String source; - DefaultProblemCollector( List problems ) - { - this.problems = ( problems != null ) ? problems : new ArrayList<>(); + DefaultProblemCollector(List problems) { + this.problems = (problems != null) ? problems : new ArrayList<>(); } @Override - public List getProblems() - { + public List getProblems() { return problems; } @Override - public void setSource( String source ) - { + public void setSource(String source) { this.source = source; } @Override - public void add( Problem.Severity severity, String message, int line, int column, Exception cause ) - { - Problem problem = new DefaultProblem( message, severity, source, line, column, cause ); + public void add(Problem.Severity severity, String message, int line, int column, Exception cause) { + Problem problem = new DefaultProblem(message, severity, source, line, column, cause); - problems.add( problem ); + problems.add(problem); } - } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/FileSource.java b/maven-builder-support/src/main/java/org/apache/maven/building/FileSource.java index db1b2b2df7..37020a825a 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/FileSource.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/FileSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.io.File; import java.io.FileInputStream; @@ -30,9 +29,7 @@ import java.util.Objects; * * @author Benjamin Bentmann */ -public class FileSource - implements Source -{ +public class FileSource implements Source { private final File file; private final int hashCode; @@ -42,22 +39,18 @@ public class FileSource * * @param file The file, must not be {@code null}. */ - public FileSource( File file ) - { - this.file = Objects.requireNonNull( file, "file cannot be null" ).getAbsoluteFile(); - this.hashCode = Objects.hash( file ); + public FileSource(File file) { + this.file = Objects.requireNonNull(file, "file cannot be null").getAbsoluteFile(); + this.hashCode = Objects.hash(file); } @Override - public InputStream getInputStream() - throws IOException - { - return new FileInputStream( file ); + public InputStream getInputStream() throws IOException { + return new FileInputStream(file); } @Override - public String getLocation() - { + public String getLocation() { return file.getPath(); } @@ -66,42 +59,35 @@ public class FileSource * * @return The underlying file, never {@code null}. */ - public File getFile() - { + public File getFile() { return file; } @Override - public String toString() - { + public String toString() { return getLocation(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( !FileSource.class.equals( obj.getClass() ) ) - { + if (!FileSource.class.equals(obj.getClass())) { return false; } FileSource other = (FileSource) obj; - return this.file.equals( other.file ); + return this.file.equals(other.file); } } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/Problem.java b/maven-builder-support/src/main/java/org/apache/maven/building/Problem.java index 9ab9b3a85c..a69efacf57 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/Problem.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/Problem.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; /** * Describes a problem that was encountered during settings building. A problem can either be an exception that was @@ -27,19 +26,15 @@ package org.apache.maven.building; * @author Benjamin Bentmann * @author Robert Scholte */ -public interface Problem -{ +public interface Problem { /** * The different severity levels for a problem, in decreasing order. */ - enum Severity - { - + enum Severity { FATAL, // ERROR, // WARNING // - } /** @@ -97,5 +92,4 @@ public interface Problem * @return The severity level of this problem, never {@code null}. */ Severity getSeverity(); - } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollector.java b/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollector.java index 6e61256063..b2f32c9e60 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollector.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.util.List; @@ -27,8 +26,7 @@ import java.util.List; * @author Benjamin Bentmann * @author Robert Scholte */ -public interface ProblemCollector -{ +public interface ProblemCollector { /** * Adds the specified problem. @@ -40,7 +38,7 @@ public interface ProblemCollector * @param column The one-based index of the column containing the problem or {@code -1} if unknown. * @param cause The cause of the problem, may be {@code null}. */ - void add( Problem.Severity severity, String message, int line, int column, Exception cause ); + void add(Problem.Severity severity, String message, int line, int column, Exception cause); /** * The next messages will be bound to this source. When calling this method again, previous messages keep @@ -48,12 +46,11 @@ public interface ProblemCollector * * @param source a source */ - void setSource( String source ); + void setSource(String source); /** * * @return the collected Problems, never {@code null} */ List getProblems(); - } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollectorFactory.java b/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollectorFactory.java index 43c9bd3838..e9ae66c858 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollectorFactory.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/ProblemCollectorFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.util.List; @@ -26,8 +25,7 @@ import java.util.List; * @author Robert Scholte * @since 3.3.0 */ -public class ProblemCollectorFactory -{ +public class ProblemCollectorFactory { /** * The default implementation is not visible, create it with this factory @@ -35,9 +33,7 @@ public class ProblemCollectorFactory * @param problems starting set of problems, may be {@code null} * @return a new instance of a ProblemCollector */ - public static ProblemCollector newInstance( List problems ) - { - return new DefaultProblemCollector( problems ); + public static ProblemCollector newInstance(List problems) { + return new DefaultProblemCollector(problems); } - } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/Source.java b/maven-builder-support/src/main/java/org/apache/maven/building/Source.java index 948a557ce9..061871e4c3 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/Source.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/Source.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.io.IOException; import java.io.InputStream; @@ -27,8 +26,7 @@ import java.io.InputStream; * * @author Benjamin Bentmann */ -public interface Source -{ +public interface Source { /** * Gets a byte stream to the source contents. Closing the returned stream is the responsibility of the caller. @@ -36,8 +34,7 @@ public interface Source * @return A byte stream to the source contents, never {@code null}. * @throws IOException in case of IO issue */ - InputStream getInputStream() - throws IOException; + InputStream getInputStream() throws IOException; /** * Provides a user-friendly hint about the location of the source. This could be a local file path, a URI or just an @@ -46,5 +43,4 @@ public interface Source * @return A user-friendly hint about the location of the source, never {@code null}. */ String getLocation(); - } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/StringSource.java b/maven-builder-support/src/main/java/org/apache/maven/building/StringSource.java index d305899578..10590d43ff 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/StringSource.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/StringSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -29,9 +28,7 @@ import java.nio.charset.StandardCharsets; * * @author Benjamin Bentmann */ -public class StringSource - implements Source -{ +public class StringSource implements Source { private final String content; private final String location; @@ -43,9 +40,8 @@ public class StringSource * * @param content The String representation, may be empty or {@code null}. */ - public StringSource( CharSequence content ) - { - this( content, null ); + public StringSource(CharSequence content) { + this(content, null); } /** @@ -54,23 +50,19 @@ public class StringSource * @param content The String representation, may be empty or {@code null}. * @param location The location to report for this use, may be {@code null}. */ - public StringSource( CharSequence content, String location ) - { - this.content = ( content != null ) ? content.toString() : ""; - this.location = ( location != null ) ? location : "(memory)"; + public StringSource(CharSequence content, String location) { + this.content = (content != null) ? content.toString() : ""; + this.location = (location != null) ? location : "(memory)"; this.hashCode = this.content.hashCode(); } @Override - public InputStream getInputStream() - throws IOException - { - return new ByteArrayInputStream( content.getBytes( StandardCharsets.UTF_8 ) ); + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); } @Override - public String getLocation() - { + public String getLocation() { return location; } @@ -79,42 +71,35 @@ public class StringSource * * @return The underlying character stream, never {@code null}. */ - public String getContent() - { + public String getContent() { return content; } @Override - public String toString() - { + public String toString() { return getLocation(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( !StringSource.class.equals( obj.getClass() ) ) - { + if (!StringSource.class.equals(obj.getClass())) { return false; } StringSource other = (StringSource) obj; - return this.content.equals( other.content ); + return this.content.equals(other.content); } } diff --git a/maven-builder-support/src/main/java/org/apache/maven/building/UrlSource.java b/maven-builder-support/src/main/java/org/apache/maven/building/UrlSource.java index 72262934ab..7de90bfecc 100644 --- a/maven-builder-support/src/main/java/org/apache/maven/building/UrlSource.java +++ b/maven-builder-support/src/main/java/org/apache/maven/building/UrlSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; import java.io.IOException; import java.io.InputStream; @@ -29,9 +28,7 @@ import java.util.Objects; * * @author Benjamin Bentmann */ -public class UrlSource - implements Source -{ +public class UrlSource implements Source { private final URL url; @@ -42,22 +39,18 @@ public class UrlSource * * @param url The file, must not be {@code null}. */ - public UrlSource( URL url ) - { - this.url = Objects.requireNonNull( url, "url cannot be null" ); - this.hashCode = Objects.hashCode( url ); + public UrlSource(URL url) { + this.url = Objects.requireNonNull(url, "url cannot be null"); + this.hashCode = Objects.hashCode(url); } @Override - public InputStream getInputStream() - throws IOException - { + public InputStream getInputStream() throws IOException { return url.openStream(); } @Override - public String getLocation() - { + public String getLocation() { return url.toString(); } @@ -66,42 +59,35 @@ public class UrlSource * * @return The underlying URL, never {@code null}. */ - public URL getUrl() - { + public URL getUrl() { return url; } @Override - public String toString() - { + public String toString() { return getLocation(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( !UrlSource.class.equals( obj.getClass() ) ) - { + if (!UrlSource.class.equals(obj.getClass())) { return false; } UrlSource other = (UrlSource) obj; - return this.url.equals( other.url ); + return this.url.equals(other.url); } } diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemCollectorTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemCollectorTest.java index a8b85d896f..632ab6a317 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemCollectorTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemCollectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,61 +16,59 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.building.Problem.Severity; -import org.junit.jupiter.api.Test; +package org.apache.maven.building; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -public class DefaultProblemCollectorTest -{ +import org.apache.maven.building.Problem.Severity; +import org.junit.jupiter.api.Test; + +public class DefaultProblemCollectorTest { @Test - public void testGetProblems() - { - DefaultProblemCollector collector = new DefaultProblemCollector( null ); - assertNotNull( collector.getProblems() ); - assertEquals( 0, collector.getProblems().size() ); + public void testGetProblems() { + DefaultProblemCollector collector = new DefaultProblemCollector(null); + assertNotNull(collector.getProblems()); + assertEquals(0, collector.getProblems().size()); - collector.add( null, "MESSAGE1", -1, -1, null ); + collector.add(null, "MESSAGE1", -1, -1, null); Exception e2 = new Exception(); - collector.add( Severity.WARNING, null, 42, 127, e2 ); + collector.add(Severity.WARNING, null, 42, 127, e2); - assertEquals( 2, collector.getProblems().size() ); + assertEquals(2, collector.getProblems().size()); Problem p1 = collector.getProblems().get(0); - assertEquals( Severity.ERROR, p1.getSeverity() ); - assertEquals( "MESSAGE1",p1.getMessage() ); - assertEquals( -1, p1.getLineNumber() ); - assertEquals( -1, p1.getColumnNumber() ); - assertNull( p1.getException() ); + assertEquals(Severity.ERROR, p1.getSeverity()); + assertEquals("MESSAGE1", p1.getMessage()); + assertEquals(-1, p1.getLineNumber()); + assertEquals(-1, p1.getColumnNumber()); + assertNull(p1.getException()); Problem p2 = collector.getProblems().get(1); - assertEquals( Severity.WARNING, p2.getSeverity() ); - assertEquals( "",p2.getMessage() ); - assertEquals( 42, p2.getLineNumber() ); - assertEquals( 127, p2.getColumnNumber() ); - assertEquals( e2, p2.getException() ); + assertEquals(Severity.WARNING, p2.getSeverity()); + assertEquals("", p2.getMessage()); + assertEquals(42, p2.getLineNumber()); + assertEquals(127, p2.getColumnNumber()); + assertEquals(e2, p2.getException()); } @Test - public void testSetSource() - { - DefaultProblemCollector collector = new DefaultProblemCollector( null ); + public void testSetSource() { + DefaultProblemCollector collector = new DefaultProblemCollector(null); - collector.add( null, "PROBLEM1", -1, -1, null ); + collector.add(null, "PROBLEM1", -1, -1, null); - collector.setSource( "SOURCE_PROBLEM2" ); - collector.add( null, "PROBLEM2", -1, -1, null ); + collector.setSource("SOURCE_PROBLEM2"); + collector.add(null, "PROBLEM2", -1, -1, null); - collector.setSource( "SOURCE_PROBLEM3" ); - collector.add( null, "PROBLEM3", -1, -1, null ); + collector.setSource("SOURCE_PROBLEM3"); + collector.add(null, "PROBLEM3", -1, -1, null); - assertEquals( "", collector.getProblems().get( 0 ).getSource() ); - assertEquals( "SOURCE_PROBLEM2", collector.getProblems().get( 1 ).getSource() ); - assertEquals( "SOURCE_PROBLEM3", collector.getProblems().get( 2 ).getSource() ); + assertEquals("", collector.getProblems().get(0).getSource()); + assertEquals("SOURCE_PROBLEM2", collector.getProblems().get(1).getSource()); + assertEquals("SOURCE_PROBLEM3", collector.getProblems().get(2).getSource()); } } diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemTest.java index 6182f99166..857c222eb4 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,120 +16,113 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.building.Problem.Severity; -import org.junit.jupiter.api.Test; +package org.apache.maven.building; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; -public class DefaultProblemTest -{ +import org.apache.maven.building.Problem.Severity; +import org.junit.jupiter.api.Test; + +public class DefaultProblemTest { @Test - public void testGetSeverity() - { - DefaultProblem problem = new DefaultProblem( null, null, null, -1, -1, null ); - assertEquals( Severity.ERROR, problem.getSeverity() ); + public void testGetSeverity() { + DefaultProblem problem = new DefaultProblem(null, null, null, -1, -1, null); + assertEquals(Severity.ERROR, problem.getSeverity()); - problem = new DefaultProblem( null, Severity.FATAL, null, -1, -1, null ); - assertEquals( Severity.FATAL, problem.getSeverity() ); + problem = new DefaultProblem(null, Severity.FATAL, null, -1, -1, null); + assertEquals(Severity.FATAL, problem.getSeverity()); - problem = new DefaultProblem( null, Severity.ERROR, null, -1, -1, null ); - assertEquals( Severity.ERROR, problem.getSeverity() ); + problem = new DefaultProblem(null, Severity.ERROR, null, -1, -1, null); + assertEquals(Severity.ERROR, problem.getSeverity()); - problem = new DefaultProblem( null, Severity.WARNING, null, -1, -1, null ); - assertEquals( Severity.WARNING, problem.getSeverity() ); + problem = new DefaultProblem(null, Severity.WARNING, null, -1, -1, null); + assertEquals(Severity.WARNING, problem.getSeverity()); } @Test - public void testGetLineNumber() - { - DefaultProblem problem = new DefaultProblem( null, null, null, -1, -1, null ); - assertEquals( -1, problem.getLineNumber() ); + public void testGetLineNumber() { + DefaultProblem problem = new DefaultProblem(null, null, null, -1, -1, null); + assertEquals(-1, problem.getLineNumber()); - problem = new DefaultProblem( null, null, null, 42, -1, null ); - assertEquals( 42, problem.getLineNumber() ); + problem = new DefaultProblem(null, null, null, 42, -1, null); + assertEquals(42, problem.getLineNumber()); - problem = new DefaultProblem( null, null, null, Integer.MAX_VALUE, -1, null ); - assertEquals( Integer.MAX_VALUE, problem.getLineNumber() ); + problem = new DefaultProblem(null, null, null, Integer.MAX_VALUE, -1, null); + assertEquals(Integer.MAX_VALUE, problem.getLineNumber()); // this case is not specified, might also return -1 - problem = new DefaultProblem( null, null, null, Integer.MIN_VALUE, -1, null ); - assertEquals( Integer.MIN_VALUE, problem.getLineNumber() ); + problem = new DefaultProblem(null, null, null, Integer.MIN_VALUE, -1, null); + assertEquals(Integer.MIN_VALUE, problem.getLineNumber()); } @Test - public void testGetColumnNumber() - { - DefaultProblem problem = new DefaultProblem( null, null, null, -1, -1, null ); - assertEquals( -1, problem.getColumnNumber() ); + public void testGetColumnNumber() { + DefaultProblem problem = new DefaultProblem(null, null, null, -1, -1, null); + assertEquals(-1, problem.getColumnNumber()); - problem = new DefaultProblem( null, null, null, -1, 42, null ); - assertEquals( 42, problem.getColumnNumber() ); + problem = new DefaultProblem(null, null, null, -1, 42, null); + assertEquals(42, problem.getColumnNumber()); - problem = new DefaultProblem( null, null, null, -1, Integer.MAX_VALUE, null ); - assertEquals( Integer.MAX_VALUE, problem.getColumnNumber() ); + problem = new DefaultProblem(null, null, null, -1, Integer.MAX_VALUE, null); + assertEquals(Integer.MAX_VALUE, problem.getColumnNumber()); // this case is not specified, might also return -1 - problem = new DefaultProblem( null, null, null, -1, Integer.MIN_VALUE, null ); - assertEquals( Integer.MIN_VALUE, problem.getColumnNumber() ); + problem = new DefaultProblem(null, null, null, -1, Integer.MIN_VALUE, null); + assertEquals(Integer.MIN_VALUE, problem.getColumnNumber()); } @Test - public void testGetException() - { - DefaultProblem problem = new DefaultProblem( null, null, null, -1, -1, null ); - assertNull( problem.getException() ); + public void testGetException() { + DefaultProblem problem = new DefaultProblem(null, null, null, -1, -1, null); + assertNull(problem.getException()); Exception e = new Exception(); - problem = new DefaultProblem( null, null, null, -1, -1, e ); - assertSame( e, problem.getException() ); + problem = new DefaultProblem(null, null, null, -1, -1, e); + assertSame(e, problem.getException()); } @Test - public void testGetSource() - { - DefaultProblem problem = new DefaultProblem( null, null, null, -1, -1, null ); - assertEquals( "", problem.getSource() ); + public void testGetSource() { + DefaultProblem problem = new DefaultProblem(null, null, null, -1, -1, null); + assertEquals("", problem.getSource()); - problem = new DefaultProblem( null, null, "", -1, -1, null ); - assertEquals( "", problem.getSource() ); + problem = new DefaultProblem(null, null, "", -1, -1, null); + assertEquals("", problem.getSource()); - problem = new DefaultProblem( null, null, "SOURCE", -1, -1, null ); - assertEquals( "SOURCE", problem.getSource() ); + problem = new DefaultProblem(null, null, "SOURCE", -1, -1, null); + assertEquals("SOURCE", problem.getSource()); } @Test - public void testGetLocation() - { - DefaultProblem problem = new DefaultProblem( null, null, null, -1, -1, null ); - assertEquals( "", problem.getLocation() ); + public void testGetLocation() { + DefaultProblem problem = new DefaultProblem(null, null, null, -1, -1, null); + assertEquals("", problem.getLocation()); - problem = new DefaultProblem( null, null, "SOURCE", -1, -1, null ); - assertEquals( "SOURCE", problem.getLocation() ); + problem = new DefaultProblem(null, null, "SOURCE", -1, -1, null); + assertEquals("SOURCE", problem.getLocation()); - problem = new DefaultProblem( null, null, null, 42, -1, null ); - assertEquals( "line 42", problem.getLocation() ); + problem = new DefaultProblem(null, null, null, 42, -1, null); + assertEquals("line 42", problem.getLocation()); - problem = new DefaultProblem( null, null, null, -1, 127, null ); - assertEquals( "column 127", problem.getLocation() ); + problem = new DefaultProblem(null, null, null, -1, 127, null); + assertEquals("column 127", problem.getLocation()); - problem = new DefaultProblem( null, null, "SOURCE", 42, 127, null ); - assertEquals( "SOURCE, line 42, column 127", problem.getLocation() ); + problem = new DefaultProblem(null, null, "SOURCE", 42, 127, null); + assertEquals("SOURCE, line 42, column 127", problem.getLocation()); } @Test - public void testGetMessage() - { - DefaultProblem problem = new DefaultProblem( "MESSAGE", null, null, -1, -1, null ); - assertEquals( "MESSAGE", problem.getMessage() ); + public void testGetMessage() { + DefaultProblem problem = new DefaultProblem("MESSAGE", null, null, -1, -1, null); + assertEquals("MESSAGE", problem.getMessage()); - problem = new DefaultProblem( null, null, null, -1, -1, new Exception() ); - assertEquals( "", problem.getMessage() ); + problem = new DefaultProblem(null, null, null, -1, -1, new Exception()); + assertEquals("", problem.getMessage()); - problem = new DefaultProblem( null, null, null, -1, -1, new Exception( "EXCEPTION MESSAGE" ) ); - assertEquals( "EXCEPTION MESSAGE", problem.getMessage() ); + problem = new DefaultProblem(null, null, null, -1, -1, new Exception("EXCEPTION MESSAGE")); + assertEquals("EXCEPTION MESSAGE", problem.getMessage()); } } diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java index 9373c01e8d..320a2cd867 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,58 +16,48 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.io.InputStream; -import java.util.Scanner; - -import org.junit.jupiter.api.Test; +package org.apache.maven.building; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -public class FileSourceTest -{ +import java.io.File; +import java.io.InputStream; +import java.util.Scanner; +import org.junit.jupiter.api.Test; + +public class FileSourceTest { @Test - public void testFileSource() - { + public void testFileSource() { NullPointerException e = assertThrows( - NullPointerException.class, - () -> new FileSource( null ), - "Should fail, since you must specify a file" ); - assertEquals( "file cannot be null", e.getMessage() ); + NullPointerException.class, () -> new FileSource(null), "Should fail, since you must specify a file"); + assertEquals("file cannot be null", e.getMessage()); } @Test - public void testGetInputStream() - throws Exception - { - File txtFile = new File( "target/test-classes/source.txt" ); - FileSource source = new FileSource( txtFile ); + public void testGetInputStream() throws Exception { + File txtFile = new File("target/test-classes/source.txt"); + FileSource source = new FileSource(txtFile); - try ( InputStream is = source.getInputStream(); - Scanner scanner = new Scanner( is ) ) - { + try (InputStream is = source.getInputStream(); + Scanner scanner = new Scanner(is)) { - assertEquals( "Hello World!", scanner.nextLine() ); + assertEquals("Hello World!", scanner.nextLine()); } } @Test - public void testGetLocation() - { - File txtFile = new File( "target/test-classes/source.txt" ); - FileSource source = new FileSource( txtFile ); - assertEquals( txtFile.getAbsolutePath(), source.getLocation() ); + public void testGetLocation() { + File txtFile = new File("target/test-classes/source.txt"); + FileSource source = new FileSource(txtFile); + assertEquals(txtFile.getAbsolutePath(), source.getLocation()); } @Test - public void testGetFile() - { - File txtFile = new File( "target/test-classes/source.txt" ); - FileSource source = new FileSource( txtFile ); - assertEquals( txtFile.getAbsoluteFile(), source.getFile() ); + public void testGetFile() { + File txtFile = new File("target/test-classes/source.txt"); + FileSource source = new FileSource(txtFile); + assertEquals(txtFile.getAbsoluteFile(), source.getFile()); } - } diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/ProblemCollectorFactoryTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/ProblemCollectorFactoryTest.java index ee2575b9f1..6bab9e6c6f 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/ProblemCollectorFactoryTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/ProblemCollectorFactoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,28 +16,25 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ - -import java.util.Collections; - -import org.junit.jupiter.api.Test; +package org.apache.maven.building; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; -public class ProblemCollectorFactoryTest -{ +import java.util.Collections; +import org.junit.jupiter.api.Test; + +public class ProblemCollectorFactoryTest { @Test - public void testNewInstance() - { - ProblemCollector collector1 = ProblemCollectorFactory.newInstance( null ); + public void testNewInstance() { + ProblemCollector collector1 = ProblemCollectorFactory.newInstance(null); - Problem problem = new DefaultProblem( "MESSAGE1", null, null, -1, -1, null ); - ProblemCollector collector2 = ProblemCollectorFactory.newInstance( Collections.singletonList( problem ) ); + Problem problem = new DefaultProblem("MESSAGE1", null, null, -1, -1, null); + ProblemCollector collector2 = ProblemCollectorFactory.newInstance(Collections.singletonList(problem)); - assertNotSame( collector1, collector2 ); - assertEquals( 0, collector1.getProblems().size() ); - assertEquals( 1, collector2.getProblems().size() ); + assertNotSame(collector1, collector2); + assertEquals(0, collector1.getProblems().size()); + assertEquals(1, collector2.getProblems().size()); } - } diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java index 85309aa86b..2c47169779 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,47 +16,40 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ - -import java.io.InputStream; -import java.util.Scanner; - -import org.junit.jupiter.api.Test; +package org.apache.maven.building; import static org.junit.jupiter.api.Assertions.assertEquals; -public class StringSourceTest -{ - @Test - public void testGetInputStream() - throws Exception - { - StringSource source = new StringSource( "Hello World!" ); +import java.io.InputStream; +import java.util.Scanner; +import org.junit.jupiter.api.Test; - try ( InputStream is = source.getInputStream(); - Scanner scanner = new Scanner( is ) ) - { - assertEquals( "Hello World!", scanner.nextLine() ); +public class StringSourceTest { + @Test + public void testGetInputStream() throws Exception { + StringSource source = new StringSource("Hello World!"); + + try (InputStream is = source.getInputStream(); + Scanner scanner = new Scanner(is)) { + assertEquals("Hello World!", scanner.nextLine()); } } @Test - public void testGetLocation() - { - StringSource source = new StringSource( "Hello World!" ); - assertEquals( "(memory)", source.getLocation() ); + public void testGetLocation() { + StringSource source = new StringSource("Hello World!"); + assertEquals("(memory)", source.getLocation()); - source = new StringSource( "Hello World!", "LOCATION" ); - assertEquals( "LOCATION", source.getLocation() ); + source = new StringSource("Hello World!", "LOCATION"); + assertEquals("LOCATION", source.getLocation()); } @Test - public void testGetContent() - { - StringSource source = new StringSource( null ); - assertEquals( "", source.getContent() ); + public void testGetContent() { + StringSource source = new StringSource(null); + assertEquals("", source.getContent()); - source = new StringSource( "Hello World!", "LOCATION" ); - assertEquals( "Hello World!", source.getContent() ); + source = new StringSource("Hello World!", "LOCATION"); + assertEquals("Hello World!", source.getContent()); } - } diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java index efdb9bb684..7ba2a647e2 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.building; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,50 +16,40 @@ package org.apache.maven.building; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.building; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.Scanner; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class UrlSourceTest -{ +public class UrlSourceTest { @Test - public void testUrlSource() - { + public void testUrlSource() { NullPointerException e = assertThrows( - NullPointerException.class, - () -> new UrlSource( null ), - "Should fail, since you must specify a url" ); - assertEquals( "url cannot be null", e.getMessage() ); + NullPointerException.class, () -> new UrlSource(null), "Should fail, since you must specify a url"); + assertEquals("url cannot be null", e.getMessage()); } @Test - public void testGetInputStream() - throws Exception - { - URL txtFile = new File( "target/test-classes/source.txt" ).toURI().toURL(); - UrlSource source = new UrlSource( txtFile ); - try ( InputStream is = source.getInputStream(); - Scanner scanner = new Scanner( is ) ) - { - assertEquals( "Hello World!", scanner.nextLine() ); + public void testGetInputStream() throws Exception { + URL txtFile = new File("target/test-classes/source.txt").toURI().toURL(); + UrlSource source = new UrlSource(txtFile); + try (InputStream is = source.getInputStream(); + Scanner scanner = new Scanner(is)) { + assertEquals("Hello World!", scanner.nextLine()); } } @Test - public void testGetLocation() - throws Exception - { - URL txtFile = new File( "target/test-classes/source.txt" ).toURI().toURL(); - UrlSource source = new UrlSource( txtFile ); - assertEquals( txtFile.toExternalForm(), source.getLocation() ); + public void testGetLocation() throws Exception { + URL txtFile = new File("target/test-classes/source.txt").toURI().toURL(); + UrlSource source = new UrlSource(txtFile); + assertEquals(txtFile.toExternalForm(), source.getLocation()); } - } diff --git a/maven-compat/pom.xml b/maven-compat/pom.xml index 298207f750..367c91ffa4 100644 --- a/maven-compat/pom.xml +++ b/maven-compat/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactScopeEnum.java b/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactScopeEnum.java index 4745467524..c0862a1664 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactScopeEnum.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactScopeEnum.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; /** * Type safe reincarnation of Artifact scope. Also supplies the {@code DEFAULT_SCOPE} as well @@ -26,35 +25,34 @@ package org.apache.maven.artifact; * @author Oleg Gusakov * */ - -public enum ArtifactScopeEnum -{ - compile( 1 ), test( 2 ), runtime( 3 ), provided( 4 ), system( 5 ), runtime_plus_system( 6 ); +public enum ArtifactScopeEnum { + compile(1), + test(2), + runtime(3), + provided(4), + system(5), + runtime_plus_system(6); public static final ArtifactScopeEnum DEFAULT_SCOPE = compile; private int id; // Constructor - ArtifactScopeEnum( int id ) - { + ArtifactScopeEnum(int id) { this.id = id; } - int getId() - { + int getId() { return id; } - /** * Helper method to simplify null processing * * @param scope a scope or {@code null} * @return the provided scope or DEFAULT_SCOPE */ - public static ArtifactScopeEnum checkScope( ArtifactScopeEnum scope ) - { + public static ArtifactScopeEnum checkScope(ArtifactScopeEnum scope) { return scope == null ? DEFAULT_SCOPE : scope; } @@ -62,41 +60,29 @@ public enum ArtifactScopeEnum * * @return unsafe String representation of this scope. */ - public String getScope() - { - if ( id == 1 ) - { + public String getScope() { + if (id == 1) { return Artifact.SCOPE_COMPILE; - } - else if ( id == 2 ) - { + } else if (id == 2) { return Artifact.SCOPE_TEST; - } - else if ( id == 3 ) - { + } else if (id == 3) { return Artifact.SCOPE_RUNTIME; - } - else if ( id == 4 ) - { + } else if (id == 4) { return Artifact.SCOPE_PROVIDED; - } - else if ( id == 5 ) - { + } else if (id == 5) { return Artifact.SCOPE_SYSTEM; - } - else - { + } else { return Artifact.SCOPE_RUNTIME_PLUS_SYSTEM; } } - private static final ArtifactScopeEnum [][][] COMPLIANCY_SETS = { - { { compile }, { compile, provided, system } } - , { { test }, { compile, test, provided, system } } - , { { runtime }, { compile, runtime, system } } - , { { provided }, { compile, test, provided } } + private static final ArtifactScopeEnum[][][] COMPLIANCY_SETS = { + {{compile}, {compile, provided, system}}, + {{test}, {compile, test, provided, system}}, + {{runtime}, {compile, runtime, system}}, + {{provided}, {compile, test, provided}} }; /** @@ -105,24 +91,18 @@ public enum ArtifactScopeEnum * @param scope a scope * @return true is supplied scope is an inclusive sub-scope of current one. */ - public boolean encloses( ArtifactScopeEnum scope ) - { - final ArtifactScopeEnum s = checkScope( scope ); + public boolean encloses(ArtifactScopeEnum scope) { + final ArtifactScopeEnum s = checkScope(scope); // system scope is historic only - and simple - if ( id == system.id ) - { + if (id == system.id) { return scope.id == system.id; } - for ( ArtifactScopeEnum[][] set : COMPLIANCY_SETS ) - { - if ( id == set[0][0].id ) - { - for ( ArtifactScopeEnum ase : set[1] ) - { - if ( s.id == ase.id ) - { + for (ArtifactScopeEnum[][] set : COMPLIANCY_SETS) { + if (id == set[0][0].id) { + for (ArtifactScopeEnum ase : set[1]) { + if (s.id == ase.id) { return true; } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactStatus.java b/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactStatus.java index 1705d6654a..6875ad2c16 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactStatus.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactStatus.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; import java.util.HashMap; import java.util.Map; @@ -27,38 +26,36 @@ import java.util.Map; * * @author Brett Porter */ -public final class ArtifactStatus - implements Comparable -{ +public final class ArtifactStatus implements Comparable { /** * No trust - no information about status. */ - public static final ArtifactStatus NONE = new ArtifactStatus( "none", 0 ); + public static final ArtifactStatus NONE = new ArtifactStatus("none", 0); /** * No trust - information was generated with defaults. */ - public static final ArtifactStatus GENERATED = new ArtifactStatus( "generated", 1 ); + public static final ArtifactStatus GENERATED = new ArtifactStatus("generated", 1); /** * Low trust - was converted from the Maven 1.x repository. */ - public static final ArtifactStatus CONVERTED = new ArtifactStatus( "converted", 2 ); + public static final ArtifactStatus CONVERTED = new ArtifactStatus("converted", 2); /** * Moderate trust - it was deployed directly from a partner. */ - public static final ArtifactStatus PARTNER = new ArtifactStatus( "partner", 3 ); + public static final ArtifactStatus PARTNER = new ArtifactStatus("partner", 3); /** * Moderate trust - it was deployed directly by a user. */ - public static final ArtifactStatus DEPLOYED = new ArtifactStatus( "deployed", 4 ); + public static final ArtifactStatus DEPLOYED = new ArtifactStatus("deployed", 4); /** * Trusted, as it has had its data verified by hand. */ - public static final ArtifactStatus VERIFIED = new ArtifactStatus( "verified", 5 ); + public static final ArtifactStatus VERIFIED = new ArtifactStatus("verified", 5); private final int rank; @@ -66,59 +63,48 @@ public final class ArtifactStatus private static Map map; - private ArtifactStatus( String key, int rank ) - { + private ArtifactStatus(String key, int rank) { this.rank = rank; this.key = key; - if ( map == null ) - { + if (map == null) { map = new HashMap<>(); } - map.put( key, this ); + map.put(key, this); } - public static ArtifactStatus valueOf( String status ) - { + public static ArtifactStatus valueOf(String status) { ArtifactStatus retVal = null; - if ( status != null ) - { - retVal = map.get( status ); + if (status != null) { + retVal = map.get(status); } return retVal != null ? retVal : NONE; } - 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; } final ArtifactStatus that = (ArtifactStatus) o; return rank == that.rank; - } - public int hashCode() - { + public int hashCode() { return rank; } - public String toString() - { + public String toString() { return key; } - public int compareTo( ArtifactStatus s ) - { + public int compareTo(ArtifactStatus s) { return rank - s.rank; } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/UnknownRepositoryLayoutException.java b/maven-compat/src/main/java/org/apache/maven/artifact/UnknownRepositoryLayoutException.java index e23bea9a89..835b3771aa 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/UnknownRepositoryLayoutException.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/UnknownRepositoryLayoutException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; @@ -28,27 +27,21 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti * * @author jdcasey */ -public class UnknownRepositoryLayoutException - extends InvalidRepositoryException -{ +public class UnknownRepositoryLayoutException extends InvalidRepositoryException { private final String layoutId; - public UnknownRepositoryLayoutException( String repositoryId, String layoutId ) - { - super( "Cannot find ArtifactRepositoryLayout instance for: " + layoutId, repositoryId ); + public UnknownRepositoryLayoutException(String repositoryId, String layoutId) { + super("Cannot find ArtifactRepositoryLayout instance for: " + layoutId, repositoryId); this.layoutId = layoutId; } - public UnknownRepositoryLayoutException( String repositoryId, String layoutId, ComponentLookupException e ) - { - super( "Cannot find ArtifactRepositoryLayout instance for: " + layoutId, repositoryId, e ); + public UnknownRepositoryLayoutException(String repositoryId, String layoutId, ComponentLookupException e) { + super("Cannot find ArtifactRepositoryLayout instance for: " + layoutId, repositoryId, e); this.layoutId = layoutId; } - public String getLayoutId() - { + public String getLayoutId() { return layoutId; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeployer.java b/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeployer.java index bf15206958..739a742fec 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeployer.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeployer.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.deployer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.deployer; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.artifact.deployer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.deployer; import java.io.File; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; /** * ArtifactDeployer */ -public interface ArtifactDeployer -{ +public interface ArtifactDeployer { String ROLE = ArtifactDeployer.class.getName(); /** @@ -45,9 +42,13 @@ public interface ArtifactDeployer * method */ @Deprecated - void deploy( String basedir, String finalName, Artifact artifact, ArtifactRepository deploymentRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException; + void deploy( + String basedir, + String finalName, + Artifact artifact, + ArtifactRepository deploymentRepository, + ArtifactRepository localRepository) + throws ArtifactDeploymentException; /** * Deploy an artifact from a particular file. @@ -58,7 +59,7 @@ public interface ArtifactDeployer * @param localRepository the local repository to install into * @throws ArtifactDeploymentException if an error occurred deploying the artifact */ - void deploy( File source, Artifact artifact, ArtifactRepository deploymentRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException; + void deploy( + File source, Artifact artifact, ArtifactRepository deploymentRepository, ArtifactRepository localRepository) + throws ArtifactDeploymentException; } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeploymentException.java b/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeploymentException.java index 6e44ed3c45..14f09ac385 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeploymentException.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/deployer/ArtifactDeploymentException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.deployer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.deployer; * "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 + * 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 @@ -18,26 +16,21 @@ package org.apache.maven.artifact.deployer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.deployer; /** * @author Jason van Zyl */ -public class ArtifactDeploymentException - extends Exception -{ - public ArtifactDeploymentException( String message ) - { - super( message ); +public class ArtifactDeploymentException extends Exception { + public ArtifactDeploymentException(String message) { + super(message); } - public ArtifactDeploymentException( Throwable cause ) - { - super( cause ); + public ArtifactDeploymentException(Throwable cause) { + super(cause); } - public ArtifactDeploymentException( String message, - Throwable cause ) - { - super( message, cause ); + public ArtifactDeploymentException(String message, Throwable cause) { + super(message, cause); } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/deployer/DefaultArtifactDeployer.java b/maven-compat/src/main/java/org/apache/maven/artifact/deployer/DefaultArtifactDeployer.java index 87d9c46df2..2be72f8afe 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/deployer/DefaultArtifactDeployer.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/deployer/DefaultArtifactDeployer.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.deployer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.deployer; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.artifact.deployer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.deployer; import java.io.File; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -50,11 +48,8 @@ import org.eclipse.aether.util.artifact.SubArtifact; /** * DefaultArtifactDeployer */ -@Component( role = ArtifactDeployer.class, instantiationStrategy = "per-lookup" ) -public class DefaultArtifactDeployer - extends AbstractLogEnabled - implements ArtifactDeployer -{ +@Component(role = ArtifactDeployer.class, instantiationStrategy = "per-lookup") +public class DefaultArtifactDeployer extends AbstractLogEnabled implements ArtifactDeployer { @Requirement private RepositorySystem repoSystem; @@ -69,96 +64,83 @@ public class DefaultArtifactDeployer * correctly. */ @Deprecated - public void deploy( String basedir, String finalName, Artifact artifact, ArtifactRepository deploymentRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException - { + public void deploy( + String basedir, + String finalName, + Artifact artifact, + ArtifactRepository deploymentRepository, + ArtifactRepository localRepository) + throws ArtifactDeploymentException { String extension = artifact.getArtifactHandler().getExtension(); - File source = new File( basedir, finalName + "." + extension ); - deploy( source, artifact, deploymentRepository, localRepository ); + File source = new File(basedir, finalName + "." + extension); + deploy(source, artifact, deploymentRepository, localRepository); } - public void deploy( File source, Artifact artifact, ArtifactRepository deploymentRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException - { + public void deploy( + File source, Artifact artifact, ArtifactRepository deploymentRepository, ArtifactRepository localRepository) + throws ArtifactDeploymentException { RepositorySystemSession session = - LegacyLocalRepositoryManager.overlay( localRepository, legacySupport.getRepositorySession(), repoSystem ); + LegacyLocalRepositoryManager.overlay(localRepository, legacySupport.getRepositorySession(), repoSystem); DeployRequest request = new DeployRequest(); - request.setTrace( RequestTrace.newChild( null, legacySupport.getSession().getCurrentProject() ) ); + request.setTrace(RequestTrace.newChild(null, legacySupport.getSession().getCurrentProject())); - org.eclipse.aether.artifact.Artifact mainArtifact = RepositoryUtils.toArtifact( artifact ); - mainArtifact = mainArtifact.setFile( source ); - request.addArtifact( mainArtifact ); + org.eclipse.aether.artifact.Artifact mainArtifact = RepositoryUtils.toArtifact(artifact); + mainArtifact = mainArtifact.setFile(source); + request.addArtifact(mainArtifact); String versionKey = artifact.getGroupId() + ':' + artifact.getArtifactId(); String snapshotKey = null; - if ( artifact.isSnapshot() ) - { + if (artifact.isSnapshot()) { snapshotKey = versionKey + ':' + artifact.getBaseVersion(); - request.addMetadata( relatedMetadata.get( snapshotKey ) ); + request.addMetadata(relatedMetadata.get(snapshotKey)); } - request.addMetadata( relatedMetadata.get( versionKey ) ); + request.addMetadata(relatedMetadata.get(versionKey)); - for ( ArtifactMetadata metadata : artifact.getMetadataList() ) - { - if ( metadata instanceof ProjectArtifactMetadata ) - { - org.eclipse.aether.artifact.Artifact pomArtifact = new SubArtifact( mainArtifact, "", "pom" ); - pomArtifact = pomArtifact.setFile( ( (ProjectArtifactMetadata) metadata ).getFile() ); - request.addArtifact( pomArtifact ); - } - else if ( metadata instanceof SnapshotArtifactRepositoryMetadata - || metadata instanceof ArtifactRepositoryMetadata ) - { + for (ArtifactMetadata metadata : artifact.getMetadataList()) { + if (metadata instanceof ProjectArtifactMetadata) { + org.eclipse.aether.artifact.Artifact pomArtifact = new SubArtifact(mainArtifact, "", "pom"); + pomArtifact = pomArtifact.setFile(((ProjectArtifactMetadata) metadata).getFile()); + request.addArtifact(pomArtifact); + } else if (metadata instanceof SnapshotArtifactRepositoryMetadata + || metadata instanceof ArtifactRepositoryMetadata) { // eaten, handled by repo system - } - else - { - request.addMetadata( new MetadataBridge( metadata ) ); + } else { + request.addMetadata(new MetadataBridge(metadata)); } } - RemoteRepository remoteRepo = RepositoryUtils.toRepo( deploymentRepository ); + RemoteRepository remoteRepo = RepositoryUtils.toRepo(deploymentRepository); /* * NOTE: This provides backward-compat with maven-deploy-plugin:2.4 which bypasses the repository factory when * using an alternative deployment location. */ - if ( deploymentRepository instanceof DefaultArtifactRepository - && deploymentRepository.getAuthentication() == null ) - { - RemoteRepository.Builder builder = new RemoteRepository.Builder( remoteRepo ); - builder.setAuthentication( session.getAuthenticationSelector().getAuthentication( remoteRepo ) ); - builder.setProxy( session.getProxySelector().getProxy( remoteRepo ) ); + if (deploymentRepository instanceof DefaultArtifactRepository + && deploymentRepository.getAuthentication() == null) { + RemoteRepository.Builder builder = new RemoteRepository.Builder(remoteRepo); + builder.setAuthentication(session.getAuthenticationSelector().getAuthentication(remoteRepo)); + builder.setProxy(session.getProxySelector().getProxy(remoteRepo)); remoteRepo = builder.build(); } - request.setRepository( remoteRepo ); + request.setRepository(remoteRepo); DeployResult result; - try - { - result = repoSystem.deploy( session, request ); - } - catch ( DeploymentException e ) - { - throw new ArtifactDeploymentException( e.getMessage(), e ); + try { + result = repoSystem.deploy(session, request); + } catch (DeploymentException e) { + throw new ArtifactDeploymentException(e.getMessage(), e); } - for ( Object metadata : result.getMetadata() ) - { - if ( metadata.getClass().getName().endsWith( ".internal.VersionsMetadata" ) ) - { - relatedMetadata.put( versionKey, (MergeableMetadata) metadata ); + for (Object metadata : result.getMetadata()) { + if (metadata.getClass().getName().endsWith(".internal.VersionsMetadata")) { + relatedMetadata.put(versionKey, (MergeableMetadata) metadata); } - if ( snapshotKey != null && metadata.getClass().getName().endsWith( ".internal.RemoteSnapshotMetadata" ) ) - { - relatedMetadata.put( snapshotKey, (MergeableMetadata) metadata ); + if (snapshotKey != null && metadata.getClass().getName().endsWith(".internal.RemoteSnapshotMetadata")) { + relatedMetadata.put(snapshotKey, (MergeableMetadata) metadata); } } - artifact.setResolvedVersion( result.getArtifacts().iterator().next().getVersion() ); + artifact.setResolvedVersion(result.getArtifacts().iterator().next().getVersion()); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstallationException.java b/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstallationException.java index 9f1e45b9ae..4179f81f1e 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstallationException.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstallationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.installer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.installer; * "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 + * 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 @@ -18,26 +16,21 @@ package org.apache.maven.artifact.installer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.installer; /** * @author Jason van Zyl */ -public class ArtifactInstallationException - extends Exception -{ - public ArtifactInstallationException( String message ) - { - super( message ); +public class ArtifactInstallationException extends Exception { + public ArtifactInstallationException(String message) { + super(message); } - public ArtifactInstallationException( Throwable cause ) - { - super( cause ); + public ArtifactInstallationException(Throwable cause) { + super(cause); } - public ArtifactInstallationException( String message, - Throwable cause ) - { - super( message, cause ); + public ArtifactInstallationException(String message, Throwable cause) { + super(message, cause); } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstaller.java b/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstaller.java index ca6bb206a2..40e43a4338 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstaller.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/installer/ArtifactInstaller.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.installer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.installer; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.artifact.installer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.installer; import java.io.File; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; /** * @author Michal Maczka */ -public interface ArtifactInstaller -{ +public interface ArtifactInstaller { String ROLE = ArtifactInstaller.class.getName(); /** @@ -44,8 +41,8 @@ public interface ArtifactInstaller * method */ @Deprecated - void install( String basedir, String finalName, Artifact artifact, ArtifactRepository localRepository ) - throws ArtifactInstallationException; + void install(String basedir, String finalName, Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException; /** * Install an artifact from a particular file. @@ -55,6 +52,6 @@ public interface ArtifactInstaller * @param localRepository the local repository to install into * @throws ArtifactInstallationException if an error occurred installing the artifact */ - void install( File source, Artifact artifact, ArtifactRepository localRepository ) - throws ArtifactInstallationException; + void install(File source, Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException; } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/installer/DefaultArtifactInstaller.java b/maven-compat/src/main/java/org/apache/maven/artifact/installer/DefaultArtifactInstaller.java index 5deee382f9..2fd26e5f2d 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/installer/DefaultArtifactInstaller.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/installer/DefaultArtifactInstaller.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.installer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.installer; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.installer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.installer; import java.io.File; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -46,11 +44,8 @@ import org.eclipse.aether.util.artifact.SubArtifact; /** * @author Jason van Zyl */ -@Component( role = ArtifactInstaller.class ) -public class DefaultArtifactInstaller - extends AbstractLogEnabled - implements ArtifactInstaller -{ +@Component(role = ArtifactInstaller.class) +public class DefaultArtifactInstaller extends AbstractLogEnabled implements ArtifactInstaller { @Requirement private RepositorySystem repoSystem; @@ -60,77 +55,63 @@ public class DefaultArtifactInstaller /** @deprecated we want to use the artifact method only, and ensure artifact.file is set correctly. */ @Deprecated - public void install( String basedir, String finalName, Artifact artifact, ArtifactRepository localRepository ) - throws ArtifactInstallationException - { + public void install(String basedir, String finalName, Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException { String extension = artifact.getArtifactHandler().getExtension(); - File source = new File( basedir, finalName + "." + extension ); + File source = new File(basedir, finalName + "." + extension); - install( source, artifact, localRepository ); + install(source, artifact, localRepository); } - public void install( File source, Artifact artifact, ArtifactRepository localRepository ) - throws ArtifactInstallationException - { + public void install(File source, Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException { RepositorySystemSession session = - LegacyLocalRepositoryManager.overlay( localRepository, legacySupport.getRepositorySession(), repoSystem ); + LegacyLocalRepositoryManager.overlay(localRepository, legacySupport.getRepositorySession(), repoSystem); InstallRequest request = new InstallRequest(); - request.setTrace( RequestTrace.newChild( null, legacySupport.getSession().getCurrentProject() ) ); + request.setTrace(RequestTrace.newChild(null, legacySupport.getSession().getCurrentProject())); - org.eclipse.aether.artifact.Artifact mainArtifact = RepositoryUtils.toArtifact( artifact ); - mainArtifact = mainArtifact.setFile( source ); - request.addArtifact( mainArtifact ); + org.eclipse.aether.artifact.Artifact mainArtifact = RepositoryUtils.toArtifact(artifact); + mainArtifact = mainArtifact.setFile(source); + request.addArtifact(mainArtifact); - for ( ArtifactMetadata metadata : artifact.getMetadataList() ) - { - if ( metadata instanceof ProjectArtifactMetadata ) - { - org.eclipse.aether.artifact.Artifact pomArtifact = new SubArtifact( mainArtifact, "", "pom" ); - pomArtifact = pomArtifact.setFile( ( (ProjectArtifactMetadata) metadata ).getFile() ); - request.addArtifact( pomArtifact ); - } - else if ( metadata instanceof SnapshotArtifactRepositoryMetadata - || metadata instanceof ArtifactRepositoryMetadata ) - { + for (ArtifactMetadata metadata : artifact.getMetadataList()) { + if (metadata instanceof ProjectArtifactMetadata) { + org.eclipse.aether.artifact.Artifact pomArtifact = new SubArtifact(mainArtifact, "", "pom"); + pomArtifact = pomArtifact.setFile(((ProjectArtifactMetadata) metadata).getFile()); + request.addArtifact(pomArtifact); + } else if (metadata instanceof SnapshotArtifactRepositoryMetadata + || metadata instanceof ArtifactRepositoryMetadata) { // eaten, handled by repo system - } - else - { - request.addMetadata( new MetadataBridge( metadata ) ); + } else { + request.addMetadata(new MetadataBridge(metadata)); } } - try - { - repoSystem.install( session, request ); - } - catch ( InstallationException e ) - { - throw new ArtifactInstallationException( e.getMessage(), e ); + try { + repoSystem.install(session, request); + } catch (InstallationException e) { + throw new ArtifactInstallationException(e.getMessage(), e); } /* * NOTE: Not used by Maven core, only here to provide backward-compat with plugins like the Install Plugin. */ - if ( artifact.isSnapshot() ) - { + if (artifact.isSnapshot()) { Snapshot snapshot = new Snapshot(); - snapshot.setLocalCopy( true ); - artifact.addMetadata( new SnapshotArtifactRepositoryMetadata( artifact, snapshot ) ); + snapshot.setLocalCopy(true); + artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot)); } Versioning versioning = new Versioning(); // TODO Should this be changed for MNG-6754 too? versioning.updateTimestamp(); - versioning.addVersion( artifact.getBaseVersion() ); - if ( artifact.isRelease() ) - { - versioning.setRelease( artifact.getBaseVersion() ); + versioning.addVersion(artifact.getBaseVersion()); + if (artifact.isRelease()) { + versioning.setRelease(artifact.getBaseVersion()); } - artifact.addMetadata( new ArtifactRepositoryMetadata( artifact, versioning ) ); + artifact.addMetadata(new ArtifactRepositoryMetadata(artifact, versioning)); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/manager/DefaultWagonManager.java b/maven-compat/src/main/java/org/apache/maven/artifact/manager/DefaultWagonManager.java index 2724b1f55c..cc3ad612f5 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/manager/DefaultWagonManager.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/manager/DefaultWagonManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.artifact.manager; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.manager; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; @@ -45,11 +43,9 @@ import org.codehaus.plexus.logging.Logger; /** * Manages Wagon related operations in Maven. */ -@Component( role = WagonManager.class ) -public class DefaultWagonManager - extends org.apache.maven.repository.legacy.DefaultWagonManager - implements WagonManager -{ +@Component(role = WagonManager.class) +public class DefaultWagonManager extends org.apache.maven.repository.legacy.DefaultWagonManager + implements WagonManager { // NOTE: This must use a different field name than in the super class or IoC has no chance to inject the loggers @Requirement @@ -67,33 +63,27 @@ public class DefaultWagonManager @Requirement private ArtifactRepositoryFactory artifactRepositoryFactory; - public AuthenticationInfo getAuthenticationInfo( String id ) - { + public AuthenticationInfo getAuthenticationInfo(String id) { MavenSession session = legacySupport.getSession(); - if ( session != null && id != null ) - { + if (session != null && id != null) { MavenExecutionRequest request = session.getRequest(); - if ( request != null ) - { + if (request != null) { List servers = request.getServers(); - if ( servers != null ) - { - for ( Server server : servers ) - { - if ( id.equalsIgnoreCase( server.getId() ) ) - { - SettingsDecryptionResult result = settingsDecrypter.decrypt( - new DefaultSettingsDecryptionRequest( server ) ); + if (servers != null) { + for (Server server : servers) { + if (id.equalsIgnoreCase(server.getId())) { + SettingsDecryptionResult result = + settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(server)); server = result.getServer(); AuthenticationInfo authInfo = new AuthenticationInfo(); - authInfo.setUserName( server.getUsername() ); - authInfo.setPassword( server.getPassword() ); - authInfo.setPrivateKey( server.getPrivateKey() ); - authInfo.setPassphrase( server.getPassphrase() ); + authInfo.setUserName(server.getUsername()); + authInfo.setPassword(server.getPassword()); + authInfo.setPrivateKey(server.getPrivateKey()); + authInfo.setPassphrase(server.getPassphrase()); return authInfo; } @@ -103,38 +93,32 @@ public class DefaultWagonManager } // empty one to prevent NPE - return new AuthenticationInfo(); + return new AuthenticationInfo(); } - public ProxyInfo getProxy( String protocol ) - { + public ProxyInfo getProxy(String protocol) { MavenSession session = legacySupport.getSession(); - if ( session != null && protocol != null ) - { + if (session != null && protocol != null) { MavenExecutionRequest request = session.getRequest(); - if ( request != null ) - { + if (request != null) { List proxies = request.getProxies(); - if ( proxies != null ) - { - for ( Proxy proxy : proxies ) - { - if ( proxy.isActive() && protocol.equalsIgnoreCase( proxy.getProtocol() ) ) - { - SettingsDecryptionResult result = settingsDecrypter.decrypt( - new DefaultSettingsDecryptionRequest( proxy ) ); + if (proxies != null) { + for (Proxy proxy : proxies) { + if (proxy.isActive() && protocol.equalsIgnoreCase(proxy.getProtocol())) { + SettingsDecryptionResult result = + settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(proxy)); proxy = result.getProxy(); ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setHost( proxy.getHost() ); - proxyInfo.setType( proxy.getProtocol() ); - proxyInfo.setPort( proxy.getPort() ); - proxyInfo.setNonProxyHosts( proxy.getNonProxyHosts() ); - proxyInfo.setUserName( proxy.getUsername() ); - proxyInfo.setPassword( proxy.getPassword() ); + proxyInfo.setHost(proxy.getHost()); + proxyInfo.setType(proxy.getProtocol()); + proxyInfo.setPort(proxy.getPort()); + proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts()); + proxyInfo.setUserName(proxy.getUsername()); + proxyInfo.setPassword(proxy.getPassword()); return proxyInfo; } @@ -146,40 +130,34 @@ public class DefaultWagonManager return null; } - public void getArtifact( Artifact artifact, ArtifactRepository repository ) - throws TransferFailedException, ResourceDoesNotExistException - { - getArtifact( artifact, repository, null, false ); + public void getArtifact(Artifact artifact, ArtifactRepository repository) + throws TransferFailedException, ResourceDoesNotExistException { + getArtifact(artifact, repository, null, false); } - public void getArtifact( Artifact artifact, List remoteRepositories ) - throws TransferFailedException, ResourceDoesNotExistException - { - getArtifact( artifact, remoteRepositories, null, false ); + public void getArtifact(Artifact artifact, List remoteRepositories) + throws TransferFailedException, ResourceDoesNotExistException { + getArtifact(artifact, remoteRepositories, null, false); } @Deprecated - public ArtifactRepository getMirrorRepository( ArtifactRepository repository ) - { + public ArtifactRepository getMirrorRepository(ArtifactRepository repository) { - Mirror mirror = mirrorSelector.getMirror( repository, legacySupport.getSession().getSettings().getMirrors() ); + Mirror mirror = mirrorSelector.getMirror( + repository, legacySupport.getSession().getSettings().getMirrors()); - if ( mirror != null ) - { + if (mirror != null) { String id = mirror.getId(); - if ( id == null ) - { + if (id == null) { // TODO this should be illegal in settings.xml id = repository.getId(); } - log.debug( "Using mirror: " + mirror.getUrl() + " (id: " + id + ")" ); + log.debug("Using mirror: " + mirror.getUrl() + " (id: " + id + ")"); - repository = artifactRepositoryFactory.createArtifactRepository( id, mirror.getUrl(), - repository.getLayout(), repository.getSnapshots(), - repository.getReleases() ); + repository = artifactRepositoryFactory.createArtifactRepository( + id, mirror.getUrl(), repository.getLayout(), repository.getSnapshots(), repository.getReleases()); } return repository; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonConfigurationException.java b/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonConfigurationException.java index 8065116f7b..28b446682a 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonConfigurationException.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonConfigurationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,21 +16,18 @@ package org.apache.maven.artifact.manager; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.manager; /** * @author Olivier Lamy */ @Deprecated -public class WagonConfigurationException - extends org.apache.maven.repository.legacy.WagonConfigurationException -{ - public WagonConfigurationException( String repositoryId, String message, Throwable cause ) - { - super( repositoryId, message, cause ); +public class WagonConfigurationException extends org.apache.maven.repository.legacy.WagonConfigurationException { + public WagonConfigurationException(String repositoryId, String message, Throwable cause) { + super(repositoryId, message, cause); } - public WagonConfigurationException( String repositoryId, String message ) - { - super( repositoryId, message ); + public WagonConfigurationException(String repositoryId, String message) { + super(repositoryId, message); } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonManager.java b/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonManager.java index 3f9c0bdbdd..ef7aa85fc9 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonManager.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.manager; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.manager; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.manager; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.wagon.ResourceDoesNotExistException; @@ -34,9 +32,7 @@ import org.apache.maven.wagon.proxy.ProxyInfo; * @author Michal Maczka */ @Deprecated -public interface WagonManager - extends org.apache.maven.repository.legacy.WagonManager -{ +public interface WagonManager extends org.apache.maven.repository.legacy.WagonManager { /** * this method is only here for backward compat (project-info-reports:dependencies) * the default implementation will return an empty AuthenticationInfo @@ -44,16 +40,15 @@ public interface WagonManager * @param id an id * @return corresponding authentication info */ - AuthenticationInfo getAuthenticationInfo( String id ); + AuthenticationInfo getAuthenticationInfo(String id); - ProxyInfo getProxy( String protocol ); + ProxyInfo getProxy(String protocol); - void getArtifact( Artifact artifact, ArtifactRepository repository ) - throws TransferFailedException, ResourceDoesNotExistException; + void getArtifact(Artifact artifact, ArtifactRepository repository) + throws TransferFailedException, ResourceDoesNotExistException; - void getArtifact( Artifact artifact, List remoteRepositories ) - throws TransferFailedException, ResourceDoesNotExistException; - - ArtifactRepository getMirrorRepository( ArtifactRepository repository ); + void getArtifact(Artifact artifact, List remoteRepositories) + throws TransferFailedException, ResourceDoesNotExistException; + ArtifactRepository getMirrorRepository(ArtifactRepository repository); } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryFactory.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryFactory.java index 446ec49561..0503c5f784 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryFactory.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import org.apache.maven.artifact.UnknownRepositoryLayoutException; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; @@ -25,8 +24,7 @@ import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; /** * @author jdcasey */ -public interface ArtifactRepositoryFactory -{ +public interface ArtifactRepositoryFactory { String ROLE = ArtifactRepositoryFactory.class.getName(); String DEFAULT_LAYOUT_ID = "default"; @@ -34,26 +32,31 @@ public interface ArtifactRepositoryFactory String LOCAL_REPOSITORY_ID = "local"; @Deprecated - ArtifactRepositoryLayout getLayout( String layoutId ) - throws UnknownRepositoryLayoutException; + ArtifactRepositoryLayout getLayout(String layoutId) throws UnknownRepositoryLayoutException; @Deprecated - ArtifactRepository createDeploymentArtifactRepository( String id, String url, String layoutId, - boolean uniqueVersion ) - throws UnknownRepositoryLayoutException; + ArtifactRepository createDeploymentArtifactRepository(String id, String url, String layoutId, boolean uniqueVersion) + throws UnknownRepositoryLayoutException; - ArtifactRepository createDeploymentArtifactRepository( String id, String url, ArtifactRepositoryLayout layout, - boolean uniqueVersion ); + ArtifactRepository createDeploymentArtifactRepository( + String id, String url, ArtifactRepositoryLayout layout, boolean uniqueVersion); - ArtifactRepository createArtifactRepository( String id, String url, String layoutId, - ArtifactRepositoryPolicy snapshots, ArtifactRepositoryPolicy releases ) - throws UnknownRepositoryLayoutException; + ArtifactRepository createArtifactRepository( + String id, + String url, + String layoutId, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) + throws UnknownRepositoryLayoutException; - ArtifactRepository createArtifactRepository( String id, String url, ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ); + ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases); - void setGlobalUpdatePolicy( String snapshotPolicy ); + void setGlobalUpdatePolicy(String snapshotPolicy); - void setGlobalChecksumPolicy( String checksumPolicy ); + void setGlobalChecksumPolicy(String checksumPolicy); } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepository.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepository.java index 4c9da38312..c0e19f4de2 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepository.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.io.File; import java.util.Collections; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; @@ -36,10 +34,7 @@ import org.apache.maven.wagon.repository.Repository; * @author Michal Maczka */ @Deprecated -public class DefaultArtifactRepository - extends Repository - implements ArtifactRepository -{ +public class DefaultArtifactRepository extends Repository implements ArtifactRepository { private ArtifactRepositoryLayout layout; private ArtifactRepositoryPolicy snapshots; @@ -63,9 +58,8 @@ public class DefaultArtifactRepository * @param url the URL of the repository * @param layout the layout of the repository */ - public DefaultArtifactRepository( String id, String url, ArtifactRepositoryLayout layout ) - { - this( id, url, layout, null, null ); + public DefaultArtifactRepository(String id, String url, ArtifactRepositoryLayout layout) { + this(id, url, layout, null, null); } /** @@ -76,9 +70,8 @@ public class DefaultArtifactRepository * @param layout the layout of the repository * @param uniqueVersion whether to assign each snapshot a unique version */ - public DefaultArtifactRepository( String id, String url, ArtifactRepositoryLayout layout, boolean uniqueVersion ) - { - super( id, url ); + public DefaultArtifactRepository(String id, String url, ArtifactRepositoryLayout layout, boolean uniqueVersion) { + super(id, url); this.layout = layout; } @@ -91,189 +84,162 @@ public class DefaultArtifactRepository * @param snapshots the policies to use for snapshots * @param releases the policies to use for releases */ - public DefaultArtifactRepository( String id, String url, ArtifactRepositoryLayout layout, - ArtifactRepositoryPolicy snapshots, ArtifactRepositoryPolicy releases ) - { - super( id, url ); + public DefaultArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout layout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + super(id, url); this.layout = layout; - if ( snapshots == null ) - { - snapshots = new ArtifactRepositoryPolicy( true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE ); + if (snapshots == null) { + snapshots = new ArtifactRepositoryPolicy( + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, + ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE); } this.snapshots = snapshots; - if ( releases == null ) - { - releases = new ArtifactRepositoryPolicy( true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE ); + if (releases == null) { + releases = new ArtifactRepositoryPolicy( + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, + ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE); } this.releases = releases; } - public String pathOf( Artifact artifact ) - { - return layout.pathOf( artifact ); + public String pathOf(Artifact artifact) { + return layout.pathOf(artifact); } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata artifactMetadata ) - { - return layout.pathOfRemoteRepositoryMetadata( artifactMetadata ); + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata) { + return layout.pathOfRemoteRepositoryMetadata(artifactMetadata); } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return layout.pathOfLocalRepositoryMetadata( metadata, repository ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return layout.pathOfLocalRepositoryMetadata(metadata, repository); } - public void setLayout( ArtifactRepositoryLayout layout ) - { + public void setLayout(ArtifactRepositoryLayout layout) { this.layout = layout; } - public ArtifactRepositoryLayout getLayout() - { + public ArtifactRepositoryLayout getLayout() { return layout; } - public void setSnapshotUpdatePolicy( ArtifactRepositoryPolicy snapshots ) - { + public void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy snapshots) { this.snapshots = snapshots; } - public ArtifactRepositoryPolicy getSnapshots() - { + public ArtifactRepositoryPolicy getSnapshots() { return snapshots; } - public void setReleaseUpdatePolicy( ArtifactRepositoryPolicy releases ) - { + public void setReleaseUpdatePolicy(ArtifactRepositoryPolicy releases) { this.releases = releases; } - public ArtifactRepositoryPolicy getReleases() - { + public ArtifactRepositoryPolicy getReleases() { return releases; } - public String getKey() - { + public String getKey() { return getId(); } - public boolean isBlacklisted() - { + public boolean isBlacklisted() { return blacklisted; } - public void setBlacklisted( boolean blacklisted ) - { + public void setBlacklisted(boolean blacklisted) { this.blacklisted = blacklisted; } - public String toString() - { - StringBuilder sb = new StringBuilder( 256 ); + public String toString() { + StringBuilder sb = new StringBuilder(256); - sb.append( " id: " ).append( getId() ).append( '\n' ); - sb.append( " url: " ).append( getUrl() ).append( '\n' ); - sb.append( " layout: " ).append( layout != null ? layout : "none" ).append( '\n' ); + sb.append(" id: ").append(getId()).append('\n'); + sb.append(" url: ").append(getUrl()).append('\n'); + sb.append(" layout: ").append(layout != null ? layout : "none").append('\n'); - if ( snapshots != null ) - { - sb.append( "snapshots: [enabled => " ).append( snapshots.isEnabled() ); - sb.append( ", update => " ).append( snapshots.getUpdatePolicy() ).append( "]\n" ); + if (snapshots != null) { + sb.append("snapshots: [enabled => ").append(snapshots.isEnabled()); + sb.append(", update => ").append(snapshots.getUpdatePolicy()).append("]\n"); } - if ( releases != null ) - { - sb.append( " releases: [enabled => " ).append( releases.isEnabled() ); - sb.append( ", update => " ).append( releases.getUpdatePolicy() ).append( "]\n" ); + if (releases != null) { + sb.append(" releases: [enabled => ").append(releases.isEnabled()); + sb.append(", update => ").append(releases.getUpdatePolicy()).append("]\n"); } return sb.toString(); } - public Artifact find( Artifact artifact ) - { - File artifactFile = new File( getBasedir(), pathOf( artifact ) ); + public Artifact find(Artifact artifact) { + File artifactFile = new File(getBasedir(), pathOf(artifact)); // We need to set the file here or the resolver will fail with an NPE, not fully equipped to deal // with multiple local repository implementations yet. - artifact.setFile( artifactFile ); + artifact.setFile(artifactFile); - if ( artifactFile.exists() ) - { - artifact.setResolved( true ); + if (artifactFile.exists()) { + artifact.setResolved(true); } return artifact; } - public List findVersions( Artifact artifact ) - { + public List findVersions(Artifact artifact) { return Collections.emptyList(); } - public boolean isProjectAware() - { + public boolean isProjectAware() { return false; } - public Authentication getAuthentication() - { + public Authentication getAuthentication() { return authentication; } - public void setAuthentication( Authentication authentication ) - { + public void setAuthentication(Authentication authentication) { this.authentication = authentication; } - public Proxy getProxy() - { + public Proxy getProxy() { return proxy; } - public void setProxy( Proxy proxy ) - { + public void setProxy(Proxy proxy) { this.proxy = proxy; } - public boolean isUniqueVersion() - { + public boolean isUniqueVersion() { return true; } - public List getMirroredRepositories() - { + public List getMirroredRepositories() { return mirroredRepositories; } - public void setMirroredRepositories( List mirroredRepositories ) - { - if ( mirroredRepositories != null ) - { - this.mirroredRepositories = Collections.unmodifiableList( mirroredRepositories ); - } - else - { + public void setMirroredRepositories(List mirroredRepositories) { + if (mirroredRepositories != null) { + this.mirroredRepositories = Collections.unmodifiableList(mirroredRepositories); + } else { this.mirroredRepositories = Collections.emptyList(); } } - public boolean isBlocked() - { + public boolean isBlocked() { return blocked; } - public void setBlocked( boolean blocked ) - { + public void setBlocked(boolean blocked) { this.blocked = blocked; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepositoryFactory.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepositoryFactory.java index 0f69835c45..ddc789c224 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepositoryFactory.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepositoryFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.util.Arrays; import java.util.List; - import org.apache.maven.artifact.UnknownRepositoryLayoutException; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.plugin.LegacySupport; @@ -33,10 +31,8 @@ import org.eclipse.aether.RepositorySystemSession; /** * @author jdcasey */ -@Component( role = ArtifactRepositoryFactory.class ) -public class DefaultArtifactRepositoryFactory - implements ArtifactRepositoryFactory -{ +@Component(role = ArtifactRepositoryFactory.class) +public class DefaultArtifactRepositoryFactory implements ArtifactRepositoryFactory { @Requirement private org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory factory; @@ -47,80 +43,68 @@ public class DefaultArtifactRepositoryFactory @Requirement private RepositorySystem repositorySystem; - public ArtifactRepositoryLayout getLayout( String layoutId ) - throws UnknownRepositoryLayoutException - { - return factory.getLayout( layoutId ); + public ArtifactRepositoryLayout getLayout(String layoutId) throws UnknownRepositoryLayoutException { + return factory.getLayout(layoutId); } - public ArtifactRepository createDeploymentArtifactRepository( String id, String url, String layoutId, - boolean uniqueVersion ) - throws UnknownRepositoryLayoutException - { - return injectSession( factory.createDeploymentArtifactRepository( id, url, layoutId, uniqueVersion ), false ); + public ArtifactRepository createDeploymentArtifactRepository( + String id, String url, String layoutId, boolean uniqueVersion) throws UnknownRepositoryLayoutException { + return injectSession(factory.createDeploymentArtifactRepository(id, url, layoutId, uniqueVersion), false); } - public ArtifactRepository createDeploymentArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - boolean uniqueVersion ) - { - return injectSession( factory.createDeploymentArtifactRepository( id, url, repositoryLayout, uniqueVersion ), - false ); + public ArtifactRepository createDeploymentArtifactRepository( + String id, String url, ArtifactRepositoryLayout repositoryLayout, boolean uniqueVersion) { + return injectSession( + factory.createDeploymentArtifactRepository(id, url, repositoryLayout, uniqueVersion), false); } - public ArtifactRepository createArtifactRepository( String id, String url, String layoutId, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - throws UnknownRepositoryLayoutException - { - return injectSession( factory.createArtifactRepository( id, url, layoutId, snapshots, releases ), true ); + public ArtifactRepository createArtifactRepository( + String id, + String url, + String layoutId, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) + throws UnknownRepositoryLayoutException { + return injectSession(factory.createArtifactRepository(id, url, layoutId, snapshots, releases), true); } - public ArtifactRepository createArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - { - return injectSession( factory.createArtifactRepository( id, url, repositoryLayout, snapshots, releases ), - true ); - + public ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + return injectSession(factory.createArtifactRepository(id, url, repositoryLayout, snapshots, releases), true); } - public void setGlobalUpdatePolicy( String updatePolicy ) - { - factory.setGlobalUpdatePolicy( updatePolicy ); + public void setGlobalUpdatePolicy(String updatePolicy) { + factory.setGlobalUpdatePolicy(updatePolicy); } - public void setGlobalChecksumPolicy( String checksumPolicy ) - { - factory.setGlobalChecksumPolicy( checksumPolicy ); + public void setGlobalChecksumPolicy(String checksumPolicy) { + factory.setGlobalChecksumPolicy(checksumPolicy); } - private ArtifactRepository injectSession( ArtifactRepository repository, boolean mirrors ) - { + private ArtifactRepository injectSession(ArtifactRepository repository, boolean mirrors) { RepositorySystemSession session = legacySupport.getRepositorySession(); - if ( session != null && repository != null && !isLocalRepository( repository ) ) - { - List repositories = Arrays.asList( repository ); + if (session != null && repository != null && !isLocalRepository(repository)) { + List repositories = Arrays.asList(repository); - if ( mirrors ) - { - repositorySystem.injectMirror( session, repositories ); + if (mirrors) { + repositorySystem.injectMirror(session, repositories); } - repositorySystem.injectProxy( session, repositories ); + repositorySystem.injectProxy(session, repositories); - repositorySystem.injectAuthentication( session, repositories ); + repositorySystem.injectAuthentication(session, repositories); } return repository; } - private boolean isLocalRepository( ArtifactRepository repository ) - { + private boolean isLocalRepository(ArtifactRepository repository) { // unfortunately, the API doesn't allow to tell a remote repo and the local repo apart... - return "local".equals( repository.getId() ); + return "local".equals(repository.getId()); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/layout/FlatRepositoryLayout.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/layout/FlatRepositoryLayout.java index 4426611570..6960d1a948 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/layout/FlatRepositoryLayout.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/layout/FlatRepositoryLayout.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.layout; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.layout; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.layout; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; @@ -28,64 +27,54 @@ import org.codehaus.plexus.component.annotations.Component; /** * FlatRepositoryLayout */ -@Component( role = ArtifactRepositoryLayout.class, hint = "flat" ) -public class FlatRepositoryLayout - implements ArtifactRepositoryLayout -{ +@Component(role = ArtifactRepositoryLayout.class, hint = "flat") +public class FlatRepositoryLayout implements ArtifactRepositoryLayout { private static final char ARTIFACT_SEPARATOR = '-'; private static final char GROUP_SEPARATOR = '.'; - public String getId() - { + public String getId() { return "flat"; } - public String pathOf( Artifact artifact ) - { + public String pathOf(Artifact artifact) { ArtifactHandler artifactHandler = artifact.getArtifactHandler(); - StringBuilder path = new StringBuilder( 128 ); + StringBuilder path = new StringBuilder(128); - path.append( artifact.getArtifactId() ).append( ARTIFACT_SEPARATOR ).append( artifact.getVersion() ); + path.append(artifact.getArtifactId()).append(ARTIFACT_SEPARATOR).append(artifact.getVersion()); - if ( artifact.hasClassifier() ) - { - path.append( ARTIFACT_SEPARATOR ).append( artifact.getClassifier() ); + if (artifact.hasClassifier()) { + path.append(ARTIFACT_SEPARATOR).append(artifact.getClassifier()); } - if ( artifactHandler.getExtension() != null && artifactHandler.getExtension().length() > 0 ) - { - path.append( GROUP_SEPARATOR ).append( artifactHandler.getExtension() ); + if (artifactHandler.getExtension() != null + && artifactHandler.getExtension().length() > 0) { + path.append(GROUP_SEPARATOR).append(artifactHandler.getExtension()); } return path.toString(); } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return pathOfRepositoryMetadata( metadata.getLocalFilename( repository ) ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return pathOfRepositoryMetadata(metadata.getLocalFilename(repository)); } - private String pathOfRepositoryMetadata( String filename ) - { - StringBuilder path = new StringBuilder( 128 ); + private String pathOfRepositoryMetadata(String filename) { + StringBuilder path = new StringBuilder(128); - path.append( filename ); + path.append(filename); return path.toString(); } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata metadata ) - { - return pathOfRepositoryMetadata( metadata.getRemoteFilename() ); + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) { + return pathOfRepositoryMetadata(metadata.getRemoteFilename()); } @Override - public String toString() - { + public String toString() { return getId(); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java index 8ade23f4c5..dc7c115c4c 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,7 +16,17 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -37,165 +45,126 @@ import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.WriterFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * @author Jason van Zyl */ -@Component( role = RepositoryMetadataManager.class ) -public class DefaultRepositoryMetadataManager - extends AbstractLogEnabled - implements RepositoryMetadataManager -{ +@Component(role = RepositoryMetadataManager.class) +public class DefaultRepositoryMetadataManager extends AbstractLogEnabled implements RepositoryMetadataManager { @Requirement private WagonManager wagonManager; @Requirement private UpdateCheckManager updateCheckManager; - public void resolve( RepositoryMetadata metadata, List remoteRepositories, - ArtifactRepository localRepository ) - throws RepositoryMetadataResolutionException - { + public void resolve( + RepositoryMetadata metadata, + List remoteRepositories, + ArtifactRepository localRepository) + throws RepositoryMetadataResolutionException { RepositoryRequest request = new DefaultRepositoryRequest(); - request.setLocalRepository( localRepository ); - request.setRemoteRepositories( remoteRepositories ); - resolve( metadata, request ); + request.setLocalRepository(localRepository); + request.setRemoteRepositories(remoteRepositories); + resolve(metadata, request); } - public void resolve( RepositoryMetadata metadata, RepositoryRequest request ) - throws RepositoryMetadataResolutionException - { + public void resolve(RepositoryMetadata metadata, RepositoryRequest request) + throws RepositoryMetadataResolutionException { ArtifactRepository localRepo = request.getLocalRepository(); List remoteRepositories = request.getRemoteRepositories(); - if ( !request.isOffline() ) - { + if (!request.isOffline()) { Date localCopyLastModified = null; - if ( metadata.getBaseVersion() != null ) - { - localCopyLastModified = getLocalCopyLastModified( localRepo, metadata ); + if (metadata.getBaseVersion() != null) { + localCopyLastModified = getLocalCopyLastModified(localRepo, metadata); } - for ( ArtifactRepository repository : remoteRepositories ) - { - ArtifactRepositoryPolicy policy = metadata.getPolicy( repository ); + for (ArtifactRepository repository : remoteRepositories) { + ArtifactRepositoryPolicy policy = metadata.getPolicy(repository); File file = - new File( localRepo.getBasedir(), localRepo.pathOfLocalRepositoryMetadata( metadata, repository ) ); + new File(localRepo.getBasedir(), localRepo.pathOfLocalRepositoryMetadata(metadata, repository)); boolean update; - if ( !policy.isEnabled() ) - { + if (!policy.isEnabled()) { update = false; - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( "Skipping update check for " + metadata.getKey() + " (" + file - + ") from disabled repository " + repository.getId() + " (" - + repository.getUrl() + ")" ); + if (getLogger().isDebugEnabled()) { + getLogger() + .debug("Skipping update check for " + metadata.getKey() + " (" + file + + ") from disabled repository " + repository.getId() + " (" + + repository.getUrl() + ")"); } - } - else if ( request.isForceUpdate() ) - { + } else if (request.isForceUpdate()) { update = true; - } - else if ( localCopyLastModified != null && !policy.checkOutOfDate( localCopyLastModified ) ) - { + } else if (localCopyLastModified != null && !policy.checkOutOfDate(localCopyLastModified)) { update = false; - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( - "Skipping update check for " + metadata.getKey() + " (" + file + ") from repository " - + repository.getId() + " (" + repository.getUrl() + ") in favor of local copy" ); + if (getLogger().isDebugEnabled()) { + getLogger() + .debug("Skipping update check for " + metadata.getKey() + " (" + file + + ") from repository " + repository.getId() + " (" + repository.getUrl() + + ") in favor of local copy"); } - } - else - { - update = updateCheckManager.isUpdateRequired( metadata, repository, file ); + } else { + update = updateCheckManager.isUpdateRequired(metadata, repository, file); } - if ( update ) - { - getLogger().info( metadata.getKey() + ": checking for updates from " + repository.getId() ); - try - { - wagonManager.getArtifactMetadata( metadata, repository, file, policy.getChecksumPolicy() ); - } - catch ( ResourceDoesNotExistException e ) - { - getLogger().debug( metadata + " could not be found on repository: " + repository.getId() ); + if (update) { + getLogger().info(metadata.getKey() + ": checking for updates from " + repository.getId()); + try { + wagonManager.getArtifactMetadata(metadata, repository, file, policy.getChecksumPolicy()); + } catch (ResourceDoesNotExistException e) { + getLogger().debug(metadata + " could not be found on repository: " + repository.getId()); // delete the local copy so the old details aren't used. - if ( file.exists() ) - { - if ( !file.delete() ) - { + if (file.exists()) { + if (!file.delete()) { // sleep for 10ms just in case this is windows holding a file lock - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException ie ) - { + try { + Thread.sleep(10); + } catch (InterruptedException ie) { // ignore } file.delete(); // if this fails, forget about it } } - } - catch ( TransferFailedException e ) - { - getLogger().warn( metadata + " could not be retrieved from repository: " + repository.getId() - + " due to an error: " + e.getMessage() ); - getLogger().debug( "Exception", e ); - } - finally - { - updateCheckManager.touch( metadata, repository, file ); + } catch (TransferFailedException e) { + getLogger() + .warn(metadata + " could not be retrieved from repository: " + repository.getId() + + " due to an error: " + e.getMessage()); + getLogger().debug("Exception", e); + } finally { + updateCheckManager.touch(metadata, repository, file); } } // TODO should this be inside the above check? // touch file so that this is not checked again until interval has passed - if ( file.exists() ) - { - file.setLastModified( System.currentTimeMillis() ); + if (file.exists()) { + file.setLastModified(System.currentTimeMillis()); } } } - try - { - mergeMetadata( metadata, remoteRepositories, localRepo ); - } - catch ( RepositoryMetadataStoreException e ) - { + try { + mergeMetadata(metadata, remoteRepositories, localRepo); + } catch (RepositoryMetadataStoreException e) { throw new RepositoryMetadataResolutionException( - "Unable to store local copy of metadata: " + e.getMessage(), e ); + "Unable to store local copy of metadata: " + e.getMessage(), e); } } - private Date getLocalCopyLastModified( ArtifactRepository localRepository, RepositoryMetadata metadata ) - { - String metadataPath = localRepository.pathOfLocalRepositoryMetadata( metadata, localRepository ); - File metadataFile = new File( localRepository.getBasedir(), metadataPath ); - return metadataFile.isFile() ? new Date( metadataFile.lastModified() ) : null; + private Date getLocalCopyLastModified(ArtifactRepository localRepository, RepositoryMetadata metadata) { + String metadataPath = localRepository.pathOfLocalRepositoryMetadata(metadata, localRepository); + File metadataFile = new File(localRepository.getBasedir(), metadataPath); + return metadataFile.isFile() ? new Date(metadataFile.lastModified()) : null; } - private void mergeMetadata( RepositoryMetadata metadata, List remoteRepositories, - ArtifactRepository localRepository ) - throws RepositoryMetadataStoreException - { + private void mergeMetadata( + RepositoryMetadata metadata, + List remoteRepositories, + ArtifactRepository localRepository) + throws RepositoryMetadataStoreException { // TODO currently this is first wins, but really we should take the latest by comparing either the // snapshot timestamp, or some other timestamp later encoded into the metadata. // TODO this needs to be repeated here so the merging doesn't interfere with the written metadata @@ -203,108 +172,90 @@ public class DefaultRepositoryMetadataManager Map previousMetadata = new HashMap<>(); ArtifactRepository selected = null; - for ( ArtifactRepository repository : remoteRepositories ) - { - ArtifactRepositoryPolicy policy = metadata.getPolicy( repository ); + for (ArtifactRepository repository : remoteRepositories) { + ArtifactRepositoryPolicy policy = metadata.getPolicy(repository); - if ( policy.isEnabled() && loadMetadata( metadata, repository, localRepository, previousMetadata ) ) - { - metadata.setRepository( repository ); + if (policy.isEnabled() && loadMetadata(metadata, repository, localRepository, previousMetadata)) { + metadata.setRepository(repository); selected = repository; } } - if ( loadMetadata( metadata, localRepository, localRepository, previousMetadata ) ) - { - metadata.setRepository( null ); + if (loadMetadata(metadata, localRepository, localRepository, previousMetadata)) { + metadata.setRepository(null); selected = localRepository; } - updateSnapshotMetadata( metadata, previousMetadata, selected, localRepository ); + updateSnapshotMetadata(metadata, previousMetadata, selected, localRepository); } - private void updateSnapshotMetadata( RepositoryMetadata metadata, - Map previousMetadata, - ArtifactRepository selected, ArtifactRepository localRepository ) - throws RepositoryMetadataStoreException - { + private void updateSnapshotMetadata( + RepositoryMetadata metadata, + Map previousMetadata, + ArtifactRepository selected, + ArtifactRepository localRepository) + throws RepositoryMetadataStoreException { // TODO this could be a lot nicer... should really be in the snapshot transformation? - if ( metadata.isSnapshot() ) - { + if (metadata.isSnapshot()) { Metadata prevMetadata = metadata.getMetadata(); - for ( ArtifactRepository repository : previousMetadata.keySet() ) - { - Metadata m = previousMetadata.get( repository ); - if ( repository.equals( selected ) ) - { - if ( m.getVersioning() == null ) - { - m.setVersioning( new Versioning() ); + for (ArtifactRepository repository : previousMetadata.keySet()) { + Metadata m = previousMetadata.get(repository); + if (repository.equals(selected)) { + if (m.getVersioning() == null) { + m.setVersioning(new Versioning()); } - if ( m.getVersioning().getSnapshot() == null ) - { - m.getVersioning().setSnapshot( new Snapshot() ); + if (m.getVersioning().getSnapshot() == null) { + m.getVersioning().setSnapshot(new Snapshot()); } - } - else - { - if ( ( m.getVersioning() != null ) && ( m.getVersioning().getSnapshot() != null ) - && m.getVersioning().getSnapshot().isLocalCopy() ) - { - m.getVersioning().getSnapshot().setLocalCopy( false ); - metadata.setMetadata( m ); - metadata.storeInLocalRepository( localRepository, repository ); + } else { + if ((m.getVersioning() != null) + && (m.getVersioning().getSnapshot() != null) + && m.getVersioning().getSnapshot().isLocalCopy()) { + m.getVersioning().getSnapshot().setLocalCopy(false); + metadata.setMetadata(m); + metadata.storeInLocalRepository(localRepository, repository); } } } - metadata.setMetadata( prevMetadata ); + metadata.setMetadata(prevMetadata); } } - private boolean loadMetadata( RepositoryMetadata repoMetadata, ArtifactRepository remoteRepository, - ArtifactRepository localRepository, - Map previousMetadata ) - { + private boolean loadMetadata( + RepositoryMetadata repoMetadata, + ArtifactRepository remoteRepository, + ArtifactRepository localRepository, + Map previousMetadata) { boolean setRepository = false; - File metadataFile = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( repoMetadata, remoteRepository ) ); + File metadataFile = new File( + localRepository.getBasedir(), + localRepository.pathOfLocalRepositoryMetadata(repoMetadata, remoteRepository)); - if ( metadataFile.exists() ) - { + if (metadataFile.exists()) { Metadata metadata; - try - { - metadata = readMetadata( metadataFile ); - } - catch ( RepositoryMetadataReadException e ) - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().warn( e.getMessage(), e ); - } - else - { - getLogger().warn( e.getMessage() ); + try { + metadata = readMetadata(metadataFile); + } catch (RepositoryMetadataReadException e) { + if (getLogger().isDebugEnabled()) { + getLogger().warn(e.getMessage(), e); + } else { + getLogger().warn(e.getMessage()); } return setRepository; } - if ( repoMetadata.isSnapshot() && ( previousMetadata != null ) ) - { - previousMetadata.put( remoteRepository, metadata ); + if (repoMetadata.isSnapshot() && (previousMetadata != null)) { + previousMetadata.put(remoteRepository, metadata); } - if ( repoMetadata.getMetadata() != null ) - { - setRepository = repoMetadata.getMetadata().merge( metadata ); - } - else - { - repoMetadata.setMetadata( metadata ); + if (repoMetadata.getMetadata() != null) { + setRepository = repoMetadata.getMetadata().merge(metadata); + } else { + repoMetadata.setMetadata(metadata); setRepository = true; } } @@ -314,25 +265,18 @@ public class DefaultRepositoryMetadataManager /* * TODO share with DefaultPluginMappingManager. */ - protected Metadata readMetadata( File mappingFile ) - throws RepositoryMetadataReadException - { + protected Metadata readMetadata(File mappingFile) throws RepositoryMetadataReadException { Metadata result; - try ( Reader reader = ReaderFactory.newXmlReader( mappingFile ) ) - { + try (Reader reader = ReaderFactory.newXmlReader(mappingFile)) { MetadataXpp3Reader mappingReader = new MetadataXpp3Reader(); - result = mappingReader.read( reader, false ); - } - catch ( FileNotFoundException e ) - { - throw new RepositoryMetadataReadException( "Cannot read metadata from '" + mappingFile + "'", e ); - } - catch ( IOException | XmlPullParserException e ) - { + result = mappingReader.read(reader, false); + } catch (FileNotFoundException e) { + throw new RepositoryMetadataReadException("Cannot read metadata from '" + mappingFile + "'", e); + } catch (IOException | XmlPullParserException e) { throw new RepositoryMetadataReadException( - "Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e ); + "Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e); } return result; } @@ -341,196 +285,148 @@ public class DefaultRepositoryMetadataManager * Ensures the last updated timestamp of the specified metadata does not refer to the future and fixes the local * metadata if necessary to allow proper merging/updating of metadata during deployment. */ - private void fixTimestamp( File metadataFile, Metadata metadata, Metadata reference ) - { + private void fixTimestamp(File metadataFile, Metadata metadata, Metadata reference) { boolean changed = false; - if ( metadata != null && reference != null ) - { + if (metadata != null && reference != null) { Versioning versioning = metadata.getVersioning(); Versioning versioningRef = reference.getVersioning(); - if ( versioning != null && versioningRef != null ) - { + if (versioning != null && versioningRef != null) { String lastUpdated = versioning.getLastUpdated(); String now = versioningRef.getLastUpdated(); - if ( lastUpdated != null && now != null && now.compareTo( lastUpdated ) < 0 ) - { - getLogger().warn( - "The last updated timestamp in " + metadataFile + " refers to the future (now = " + now - + ", lastUpdated = " + lastUpdated + "). Please verify that the clocks of all" - + " deploying machines are reasonably synchronized." ); - versioning.setLastUpdated( now ); + if (lastUpdated != null && now != null && now.compareTo(lastUpdated) < 0) { + getLogger() + .warn("The last updated timestamp in " + metadataFile + " refers to the future (now = " + + now + + ", lastUpdated = " + lastUpdated + "). Please verify that the clocks of all" + + " deploying machines are reasonably synchronized."); + versioning.setLastUpdated(now); changed = true; } } } - if ( changed ) - { - getLogger().debug( "Repairing metadata in " + metadataFile ); + if (changed) { + getLogger().debug("Repairing metadata in " + metadataFile); - try ( Writer writer = WriterFactory.newXmlWriter( metadataFile ) ) - { - new MetadataXpp3Writer().write( writer, metadata ); - } - catch ( IOException e ) - { + try (Writer writer = WriterFactory.newXmlWriter(metadataFile)) { + new MetadataXpp3Writer().write(writer, metadata); + } catch (IOException e) { String msg = "Could not write fixed metadata to " + metadataFile + ": " + e.getMessage(); - if ( getLogger().isDebugEnabled() ) - { - getLogger().warn( msg, e ); - } - else - { - getLogger().warn( msg ); + if (getLogger().isDebugEnabled()) { + getLogger().warn(msg, e); + } else { + getLogger().warn(msg); } } } } - public void resolveAlways( RepositoryMetadata metadata, ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws RepositoryMetadataResolutionException - { + public void resolveAlways( + RepositoryMetadata metadata, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataResolutionException { File file; - try - { - file = getArtifactMetadataFromDeploymentRepository( metadata, localRepository, remoteRepository ); - } - catch ( TransferFailedException e ) - { + try { + file = getArtifactMetadataFromDeploymentRepository(metadata, localRepository, remoteRepository); + } catch (TransferFailedException e) { throw new RepositoryMetadataResolutionException( - metadata + " could not be retrieved from repository: " + remoteRepository.getId() + " due to an error: " - + e.getMessage(), e ); + metadata + " could not be retrieved from repository: " + remoteRepository.getId() + + " due to an error: " + e.getMessage(), + e); } - try - { - if ( file.exists() ) - { - Metadata prevMetadata = readMetadata( file ); - metadata.setMetadata( prevMetadata ); + try { + if (file.exists()) { + Metadata prevMetadata = readMetadata(file); + metadata.setMetadata(prevMetadata); } - } - catch ( RepositoryMetadataReadException e ) - { - throw new RepositoryMetadataResolutionException( e.getMessage(), e ); + } catch (RepositoryMetadataReadException e) { + throw new RepositoryMetadataResolutionException(e.getMessage(), e); } } - private File getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository localRepo, - ArtifactRepository remoteRepository ) - throws TransferFailedException - { + private File getArtifactMetadataFromDeploymentRepository( + ArtifactMetadata metadata, ArtifactRepository localRepo, ArtifactRepository remoteRepository) + throws TransferFailedException { File file = - new File( localRepo.getBasedir(), localRepo.pathOfLocalRepositoryMetadata( metadata, remoteRepository ) ); + new File(localRepo.getBasedir(), localRepo.pathOfLocalRepositoryMetadata(metadata, remoteRepository)); - try - { - wagonManager.getArtifactMetadataFromDeploymentRepository( metadata, remoteRepository, file, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN ); - } - catch ( ResourceDoesNotExistException e ) - { - getLogger().info( - metadata + " could not be found on repository: " + remoteRepository.getId() + ", so will be created" ); + try { + wagonManager.getArtifactMetadataFromDeploymentRepository( + metadata, remoteRepository, file, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); + } catch (ResourceDoesNotExistException e) { + getLogger() + .info(metadata + " could not be found on repository: " + remoteRepository.getId() + + ", so will be created"); // delete the local copy so the old details aren't used. - if ( file.exists() ) - { - if ( !file.delete() ) - { + if (file.exists()) { + if (!file.delete()) { // sleep for 10ms just in case this is windows holding a file lock - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException ie ) - { + try { + Thread.sleep(10); + } catch (InterruptedException ie) { // ignore } file.delete(); // if this fails, forget about it } } - } - finally - { - if ( metadata instanceof RepositoryMetadata ) - { - updateCheckManager.touch( (RepositoryMetadata) metadata, remoteRepository, file ); + } finally { + if (metadata instanceof RepositoryMetadata) { + updateCheckManager.touch((RepositoryMetadata) metadata, remoteRepository, file); } } return file; } - public void deploy( ArtifactMetadata metadata, ArtifactRepository localRepository, - ArtifactRepository deploymentRepository ) - throws RepositoryMetadataDeploymentException - { + public void deploy( + ArtifactMetadata metadata, ArtifactRepository localRepository, ArtifactRepository deploymentRepository) + throws RepositoryMetadataDeploymentException { File file; - if ( metadata instanceof RepositoryMetadata ) - { - getLogger().info( "Retrieving previous metadata from " + deploymentRepository.getId() ); - try - { - file = getArtifactMetadataFromDeploymentRepository( metadata, localRepository, deploymentRepository ); - } - catch ( TransferFailedException e ) - { + if (metadata instanceof RepositoryMetadata) { + getLogger().info("Retrieving previous metadata from " + deploymentRepository.getId()); + try { + file = getArtifactMetadataFromDeploymentRepository(metadata, localRepository, deploymentRepository); + } catch (TransferFailedException e) { throw new RepositoryMetadataDeploymentException( - metadata + " could not be retrieved from repository: " + deploymentRepository.getId() - + " due to an error: " + e.getMessage(), e ); + metadata + " could not be retrieved from repository: " + deploymentRepository.getId() + + " due to an error: " + e.getMessage(), + e); } - if ( file.isFile() ) - { - try - { - fixTimestamp( file, readMetadata( file ), ( (RepositoryMetadata) metadata ).getMetadata() ); - } - catch ( RepositoryMetadataReadException e ) - { + if (file.isFile()) { + try { + fixTimestamp(file, readMetadata(file), ((RepositoryMetadata) metadata).getMetadata()); + } catch (RepositoryMetadataReadException e) { // will be reported via storeInlocalRepository } } - } - else - { + } else { // It's a POM - we don't need to retrieve it first - file = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( metadata, deploymentRepository ) ); + file = new File( + localRepository.getBasedir(), + localRepository.pathOfLocalRepositoryMetadata(metadata, deploymentRepository)); } - try - { - metadata.storeInLocalRepository( localRepository, deploymentRepository ); - } - catch ( RepositoryMetadataStoreException e ) - { - throw new RepositoryMetadataDeploymentException( "Error installing metadata: " + e.getMessage(), e ); + try { + metadata.storeInLocalRepository(localRepository, deploymentRepository); + } catch (RepositoryMetadataStoreException e) { + throw new RepositoryMetadataDeploymentException("Error installing metadata: " + e.getMessage(), e); } - try - { - wagonManager.putArtifactMetadata( file, metadata, deploymentRepository ); - } - catch ( TransferFailedException e ) - { - throw new RepositoryMetadataDeploymentException( "Error while deploying metadata: " + e.getMessage(), e ); + try { + wagonManager.putArtifactMetadata(file, metadata, deploymentRepository); + } catch (TransferFailedException e) { + throw new RepositoryMetadataDeploymentException("Error while deploying metadata: " + e.getMessage(), e); } } - public void install( ArtifactMetadata metadata, ArtifactRepository localRepository ) - throws RepositoryMetadataInstallationException - { - try - { - metadata.storeInLocalRepository( localRepository, localRepository ); - } - catch ( RepositoryMetadataStoreException e ) - { - throw new RepositoryMetadataInstallationException( "Error installing metadata: " + e.getMessage(), e ); + public void install(ArtifactMetadata metadata, ArtifactRepository localRepository) + throws RepositoryMetadataInstallationException { + try { + metadata.storeInLocalRepository(localRepository, localRepository); + } catch (RepositoryMetadataStoreException e) { + throw new RepositoryMetadataInstallationException("Error installing metadata: " + e.getMessage(), e); } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/GroupRepositoryMetadata.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/GroupRepositoryMetadata.java index fd88ddcb97..ff8683410c 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/GroupRepositoryMetadata.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/GroupRepositoryMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,102 +16,81 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.repository.ArtifactRepository; +package org.apache.maven.artifact.repository.metadata; import java.util.Iterator; import java.util.List; +import org.apache.maven.artifact.repository.ArtifactRepository; /** * Metadata for the group directory of the repository. * * @author Brett Porter */ -public class GroupRepositoryMetadata - extends AbstractRepositoryMetadata -{ +public class GroupRepositoryMetadata extends AbstractRepositoryMetadata { private final String groupId; - public GroupRepositoryMetadata( String groupId ) - { - super( new Metadata() ); + public GroupRepositoryMetadata(String groupId) { + super(new Metadata()); this.groupId = groupId; } - public boolean storedInGroupDirectory() - { + public boolean storedInGroupDirectory() { return true; } - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return false; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return null; } - public String getBaseVersion() - { + public String getBaseVersion() { return null; } - public void addPluginMapping( String goalPrefix, - String artifactId ) - { - addPluginMapping( goalPrefix, artifactId, artifactId ); + public void addPluginMapping(String goalPrefix, String artifactId) { + addPluginMapping(goalPrefix, artifactId, artifactId); } - public void addPluginMapping( String goalPrefix, - String artifactId, - String name ) - { + public void addPluginMapping(String goalPrefix, String artifactId, String name) { List plugins = getMetadata().getPlugins(); boolean found = false; - for ( Iterator i = plugins.iterator(); i.hasNext() && !found; ) - { + for (Iterator i = plugins.iterator(); i.hasNext() && !found; ) { Plugin plugin = i.next(); - if ( plugin.getPrefix().equals( goalPrefix ) ) - { + if (plugin.getPrefix().equals(goalPrefix)) { found = true; } } - if ( !found ) - { + if (!found) { Plugin plugin = new Plugin(); - plugin.setPrefix( goalPrefix ); - plugin.setArtifactId( artifactId ); - plugin.setName( name ); + plugin.setPrefix(goalPrefix); + plugin.setArtifactId(artifactId); + plugin.setName(name); - - getMetadata().addPlugin( plugin ); + getMetadata().addPlugin(plugin); } } - public Object getKey() - { + public Object getKey() { return groupId; } - public boolean isSnapshot() - { + public boolean isSnapshot() { return false; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return null; } - public void setRepository( ArtifactRepository remoteRepository ) - { + public void setRepository(ArtifactRepository remoteRepository) { // intentionally blank } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataBridge.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataBridge.java index 0fd49dd344..179273a207 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataBridge.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataBridge.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; import java.io.File; import java.util.Collections; import java.util.Map; - import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.DefaultArtifactRepository; @@ -38,85 +36,64 @@ import org.eclipse.aether.metadata.Metadata; * * @author Benjamin Bentmann */ -public final class MetadataBridge - extends AbstractMetadata - implements MergeableMetadata -{ +public final class MetadataBridge extends AbstractMetadata implements MergeableMetadata { private ArtifactMetadata metadata; private boolean merged; - public MetadataBridge( ArtifactMetadata metadata ) - { + public MetadataBridge(ArtifactMetadata metadata) { this.metadata = metadata; } - public void merge( File current, File result ) - throws RepositoryException - { - try - { - if ( current.exists() ) - { - FileUtils.copyFile( current, result ); + public void merge(File current, File result) throws RepositoryException { + try { + if (current.exists()) { + FileUtils.copyFile(current, result); } - ArtifactRepository localRepo = new MetadataRepository( result ); - metadata.storeInLocalRepository( localRepo, localRepo ); + ArtifactRepository localRepo = new MetadataRepository(result); + metadata.storeInLocalRepository(localRepo, localRepo); merged = true; - } - catch ( Exception e ) - { - throw new RepositoryException( e.getMessage(), e ); + } catch (Exception e) { + throw new RepositoryException(e.getMessage(), e); } } - public boolean isMerged() - { + public boolean isMerged() { return merged; } - public String getGroupId() - { - return emptify( metadata.getGroupId() ); + public String getGroupId() { + return emptify(metadata.getGroupId()); } - public String getArtifactId() - { - return metadata.storedInGroupDirectory() ? "" : emptify( metadata.getArtifactId() ); + public String getArtifactId() { + return metadata.storedInGroupDirectory() ? "" : emptify(metadata.getArtifactId()); } - public String getVersion() - { - return metadata.storedInArtifactVersionDirectory() ? emptify( metadata.getBaseVersion() ) : ""; + public String getVersion() { + return metadata.storedInArtifactVersionDirectory() ? emptify(metadata.getBaseVersion()) : ""; } - public String getType() - { + public String getType() { return metadata.getRemoteFilename(); } - private String emptify( String string ) - { - return ( string != null ) ? string : ""; + private String emptify(String string) { + return (string != null) ? string : ""; } - public File getFile() - { + public File getFile() { return null; } - public MetadataBridge setFile( File file ) - { + public MetadataBridge setFile(File file) { return this; } - public Nature getNature() - { - if ( metadata instanceof RepositoryMetadata ) - { - switch ( ( (RepositoryMetadata) metadata ).getNature() ) - { + public Nature getNature() { + if (metadata instanceof RepositoryMetadata) { + switch (((RepositoryMetadata) metadata).getNature()) { case RepositoryMetadata.RELEASE_OR_SNAPSHOT: return Nature.RELEASE_OR_SNAPSHOT; case RepositoryMetadata.SNAPSHOT: @@ -124,49 +101,38 @@ public final class MetadataBridge default: return Nature.RELEASE; } - } - else - { + } else { return Nature.RELEASE; } } - public Map getProperties() - { + public Map getProperties() { return Collections.emptyMap(); } @Override - public Metadata setProperties( Map properties ) - { + public Metadata setProperties(Map properties) { return this; } - @SuppressWarnings( "deprecation" ) - static class MetadataRepository - extends DefaultArtifactRepository - { + @SuppressWarnings("deprecation") + static class MetadataRepository extends DefaultArtifactRepository { private File metadataFile; - MetadataRepository( File metadataFile ) - { - super( "local", "", null ); + MetadataRepository(File metadataFile) { + super("local", "", null); this.metadataFile = metadataFile; } @Override - public String getBasedir() - { + public String getBasedir() { return metadataFile.getParent(); } @Override - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { return metadataFile.getName(); } - } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataUtils.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataUtils.java index bdc4a795ad..a60a44ae87 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataUtils.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,22 +16,19 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; /** * Assists in handling repository metadata. * * @author Benjamin Bentmann */ -class MetadataUtils -{ +class MetadataUtils { - public static Metadata cloneMetadata( Metadata src ) - { - if ( src == null ) - { + public static Metadata cloneMetadata(Metadata src) { + if (src == null) { return null; } return src.clone(); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataReadException.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataReadException.java index 23e598410f..043857bf62 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataReadException.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataReadException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; /** * Problem storing the repository metadata in the local repository. * * @author Brett Porter */ -public class RepositoryMetadataReadException - extends Exception -{ - public RepositoryMetadataReadException( String message ) - { - super( message ); +public class RepositoryMetadataReadException extends Exception { + public RepositoryMetadataReadException(String message) { + super(message); } - public RepositoryMetadataReadException( String message, - Exception e ) - { - super( message, e ); + public RepositoryMetadataReadException(String message, Exception e) { + super(message, e); } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/SnapshotArtifactRepositoryMetadata.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/SnapshotArtifactRepositoryMetadata.java index 5120199276..eb933b6e7f 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/SnapshotArtifactRepositoryMetadata.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/SnapshotArtifactRepositoryMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -28,71 +27,56 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * @author Brett Porter * TODO split instantiation (versioning, plugin mappings) from definition */ -public class SnapshotArtifactRepositoryMetadata - extends AbstractRepositoryMetadata -{ +public class SnapshotArtifactRepositoryMetadata extends AbstractRepositoryMetadata { private Artifact artifact; - public SnapshotArtifactRepositoryMetadata( Artifact artifact ) - { - super( createMetadata( artifact, null ) ); + public SnapshotArtifactRepositoryMetadata(Artifact artifact) { + super(createMetadata(artifact, null)); this.artifact = artifact; } - public SnapshotArtifactRepositoryMetadata( Artifact artifact, - Snapshot snapshot ) - { - super( createMetadata( artifact, createVersioning( snapshot ) ) ); + public SnapshotArtifactRepositoryMetadata(Artifact artifact, Snapshot snapshot) { + super(createMetadata(artifact, createVersioning(snapshot))); this.artifact = artifact; } - public boolean storedInGroupDirectory() - { + public boolean storedInGroupDirectory() { return false; } - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return true; } - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } - public String getBaseVersion() - { + public String getBaseVersion() { return artifact.getBaseVersion(); } - public Object getKey() - { + public Object getKey() { return "snapshot " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion(); } - public boolean isSnapshot() - { + public boolean isSnapshot() { return artifact.isSnapshot(); } - public int getNature() - { + public int getNature() { return isSnapshot() ? SNAPSHOT : RELEASE; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return artifact.getRepository(); } - public void setRepository( ArtifactRepository remoteRepository ) - { - artifact.setRepository( remoteRepository ); + public void setRepository(ArtifactRepository remoteRepository) { + artifact.setRepository(remoteRepository); } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactCollector.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactCollector.java index 3526be4081..28d9438e0f 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactCollector.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -32,15 +30,16 @@ import org.apache.maven.artifact.resolver.filter.ArtifactFilter; * along with their metadata. No artifacts are downloaded. */ @Deprecated -public interface ArtifactCollector - extends org.apache.maven.repository.legacy.resolver.LegacyArtifactCollector -{ +public interface ArtifactCollector extends org.apache.maven.repository.legacy.resolver.LegacyArtifactCollector { @Deprecated - ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - ArtifactRepository localRepository, List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners ) - throws ArtifactResolutionException; - + ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners) + throws ArtifactResolutionException; } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolver.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolver.java index 45204f8479..259535943e 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -33,10 +31,9 @@ import org.apache.maven.wagon.events.TransferListener; * @author Jason van Zyl */ // Just hide the one method we want behind the RepositorySystem interface. -public interface ArtifactResolver -{ +public interface ArtifactResolver { - ArtifactResolutionResult resolve( ArtifactResolutionRequest request ); + ArtifactResolutionResult resolve(ArtifactResolutionRequest request); // The rest is deprecated // USED BY MAVEN ASSEMBLY PLUGIN 2.2-beta-2 @@ -46,71 +43,87 @@ public interface ArtifactResolver // USED BY SUREFIRE, DEPENDENCY PLUGIN @Deprecated ArtifactResolutionResult resolveTransitively( - Set artifacts, Artifact originatingArtifact, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set artifacts, + Artifact originatingArtifact, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter) + throws ArtifactResolutionException, ArtifactNotFoundException; // USED BY MAVEN ASSEMBLY PLUGIN @Deprecated ArtifactResolutionResult resolveTransitively( - Set artifacts, Artifact originatingArtifact, - Map managedVersions, ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source) + throws ArtifactResolutionException, ArtifactNotFoundException; // USED BY MAVEN ASSEMBLY PLUGIN @Deprecated ArtifactResolutionResult resolveTransitively( - Set artifacts, Artifact originatingArtifact, - Map managedVersions, ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter) + throws ArtifactResolutionException, ArtifactNotFoundException; // USED BY INVOKER PLUGIN @Deprecated ArtifactResolutionResult resolveTransitively( - Set artifacts, Artifact originatingArtifact, - List remoteRepositories, - ArtifactRepository localRepository, ArtifactMetadataSource source ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set artifacts, + Artifact originatingArtifact, + List remoteRepositories, + ArtifactRepository localRepository, + ArtifactMetadataSource source) + throws ArtifactResolutionException, ArtifactNotFoundException; @Deprecated - @SuppressWarnings( "checkstyle:parameternumber" ) + @SuppressWarnings("checkstyle:parameternumber") ArtifactResolutionResult resolveTransitively( - Set artifacts, Artifact originatingArtifact, - Map managedVersions, ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners) + throws ArtifactResolutionException, ArtifactNotFoundException; @Deprecated ArtifactResolutionResult resolveTransitively( - Set artifacts, Artifact originatingArtifact, - List remoteRepositories, - ArtifactRepository localRepository, ArtifactMetadataSource source, - List listeners ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set artifacts, + Artifact originatingArtifact, + List remoteRepositories, + ArtifactRepository localRepository, + ArtifactMetadataSource source, + List listeners) + throws ArtifactResolutionException, ArtifactNotFoundException; // USED BY REMOTE RESOURCES PLUGIN, DEPENDENCY PLUGIN, SHADE PLUGIN @Deprecated - void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException; + void resolve(Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException; // USED BY REMOTE RESOURCES PLUGIN @Deprecated - void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository, - TransferListener downloadMonitor ) - throws ArtifactResolutionException, ArtifactNotFoundException; + void resolve( + Artifact artifact, + List remoteRepositories, + ArtifactRepository localRepository, + TransferListener downloadMonitor) + throws ArtifactResolutionException, ArtifactNotFoundException; // USED BY DEPENDENCY PLUGIN, ARCHETYPE DOWNLOADER @Deprecated - void resolveAlways( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException; - + void resolveAlways( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException; } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DebugResolutionListener.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DebugResolutionListener.java index 56c1805cd2..8e14e56d2f 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DebugResolutionListener.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DebugResolutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.HashSet; import java.util.Objects; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; import org.codehaus.plexus.logging.Logger; @@ -32,85 +30,69 @@ import org.codehaus.plexus.logging.Logger; * * @author Brett Porter */ -public class DebugResolutionListener - implements ResolutionListener, ResolutionListenerForDepMgmt -{ +public class DebugResolutionListener implements ResolutionListener, ResolutionListenerForDepMgmt { private Logger logger; private String indent = ""; private static Set ignoredArtifacts = new HashSet<>(); - public DebugResolutionListener( Logger logger ) - { + public DebugResolutionListener(Logger logger) { this.logger = logger; } - public void testArtifact( Artifact node ) - { - } + public void testArtifact(Artifact node) {} - public void startProcessChildren( Artifact artifact ) - { + public void startProcessChildren(Artifact artifact) { indent += " "; } - public void endProcessChildren( Artifact artifact ) - { - indent = indent.substring( 2 ); + public void endProcessChildren(Artifact artifact) { + indent = indent.substring(2); } - public void includeArtifact( Artifact artifact ) - { - logger.debug( indent + artifact + " (selected for " + artifact.getScope() + ")" ); + public void includeArtifact(Artifact artifact) { + logger.debug(indent + artifact + " (selected for " + artifact.getScope() + ")"); } - public void omitForNearer( Artifact omitted, Artifact kept ) - { + public void omitForNearer(Artifact omitted, Artifact kept) { String omittedVersion = omitted.getVersion(); String keptVersion = kept.getVersion(); - if ( !Objects.equals( omittedVersion, keptVersion ) ) - { - logger.debug( indent + omitted + " (removed - nearer found: " + keptVersion + ")" ); + if (!Objects.equals(omittedVersion, keptVersion)) { + logger.debug(indent + omitted + " (removed - nearer found: " + keptVersion + ")"); } } - public void omitForCycle( Artifact omitted ) - { - logger.debug( indent + omitted + " (removed - causes a cycle in the graph)" ); + public void omitForCycle(Artifact omitted) { + logger.debug(indent + omitted + " (removed - causes a cycle in the graph)"); } - public void updateScopeCurrentPom( Artifact artifact, String ignoredScope ) - { - logger.debug( indent + artifact + " (not setting artifactScope to: " + ignoredScope + "; local artifactScope " - + artifact.getScope() + " wins)" ); + public void updateScopeCurrentPom(Artifact artifact, String ignoredScope) { + logger.debug(indent + artifact + " (not setting artifactScope to: " + ignoredScope + "; local artifactScope " + + artifact.getScope() + " wins)"); // TODO better way than static? this might hide messages in a reactor - if ( !ignoredArtifacts.contains( artifact ) ) - { - logger.warn( "\n\tArtifact " + artifact + " retains local artifactScope '" + artifact.getScope() - + "' overriding broader artifactScope '" + ignoredScope + "'\n" - + "\tgiven by a dependency. If this is not intended, modify or remove the local artifactScope.\n" ); - ignoredArtifacts.add( artifact ); + if (!ignoredArtifacts.contains(artifact)) { + logger.warn("\n\tArtifact " + artifact + " retains local artifactScope '" + artifact.getScope() + + "' overriding broader artifactScope '" + ignoredScope + "'\n" + + "\tgiven by a dependency. If this is not intended, modify or remove the local artifactScope.\n"); + ignoredArtifacts.add(artifact); } } - public void updateScope( Artifact artifact, String scope ) - { - logger.debug( indent + artifact + " (setting artifactScope to: " + scope + ")" ); + public void updateScope(Artifact artifact, String scope) { + logger.debug(indent + artifact + " (setting artifactScope to: " + scope + ")"); } - public void selectVersionFromRange( Artifact artifact ) - { - logger.debug( indent + artifact + " (setting version to: " + artifact.getVersion() + " from range: " - + artifact.getVersionRange() + ")" ); + public void selectVersionFromRange(Artifact artifact) { + logger.debug(indent + artifact + " (setting version to: " + artifact.getVersion() + " from range: " + + artifact.getVersionRange() + ")"); } - public void restrictRange( Artifact artifact, Artifact replacement, VersionRange newRange ) - { - logger.debug( indent + artifact + " (range restricted from: " + artifact.getVersionRange() + " and: " - + replacement.getVersionRange() + " to: " + newRange + " )" ); + public void restrictRange(Artifact artifact, Artifact replacement, VersionRange newRange) { + logger.debug(indent + artifact + " (range restricted from: " + artifact.getVersionRange() + " and: " + + replacement.getVersionRange() + " to: " + newRange + " )"); } /** @@ -119,50 +101,40 @@ public class DebugResolutionListener * (and more information) is needed to be able to determine when and if the version and/or artifactScope changes. * See the two added methods, manageArtifactVersion and manageArtifactScope. */ - public void manageArtifact( Artifact artifact, Artifact replacement ) - { + public void manageArtifact(Artifact artifact, Artifact replacement) { String msg = indent + artifact; msg += " ("; - if ( replacement.getVersion() != null ) - { + if (replacement.getVersion() != null) { msg += "applying version: " + replacement.getVersion() + ";"; } - if ( replacement.getScope() != null ) - { + if (replacement.getScope() != null) { msg += "applying artifactScope: " + replacement.getScope(); } msg += ")"; - logger.debug( msg ); + logger.debug(msg); } - public void manageArtifactVersion( Artifact artifact, Artifact replacement ) - { + public void manageArtifactVersion(Artifact artifact, Artifact replacement) { // only show msg if a change is actually taking place - if ( !replacement.getVersion().equals( artifact.getVersion() ) ) - { + if (!replacement.getVersion().equals(artifact.getVersion())) { String msg = indent + artifact + " (applying version: " + replacement.getVersion() + ")"; - logger.debug( msg ); + logger.debug(msg); } } - public void manageArtifactScope( Artifact artifact, Artifact replacement ) - { + public void manageArtifactScope(Artifact artifact, Artifact replacement) { // only show msg if a change is actually taking place - if ( !replacement.getScope().equals( artifact.getScope() ) ) - { + if (!replacement.getScope().equals(artifact.getScope())) { String msg = indent + artifact + " (applying artifactScope: " + replacement.getScope() + ")"; - logger.debug( msg ); + logger.debug(msg); } } - public void manageArtifactSystemPath( Artifact artifact, Artifact replacement ) - { + public void manageArtifactSystemPath(Artifact artifact, Artifact replacement) { // only show msg if a change is actually taking place - if ( !replacement.getScope().equals( artifact.getScope() ) ) - { + if (!replacement.getScope().equals(artifact.getScope())) { String msg = indent + artifact + " (applying system path: " + replacement.getFile() + ")"; - logger.debug( msg ); + logger.debug(msg); } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java index 25e92c4202..dde86482f9 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import org.codehaus.plexus.component.annotations.Component; @@ -26,9 +25,6 @@ import org.codehaus.plexus.component.annotations.Component; * along with their metadata. No artifacts are downloaded. */ @Deprecated -@Component( role = ArtifactCollector.class ) -public class DefaultArtifactCollector - extends org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector - implements ArtifactCollector -{ -} +@Component(role = ArtifactCollector.class) +public class DefaultArtifactCollector extends org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector + implements ArtifactCollector {} diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java index 6dffccd2ee..5e7a32989d 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.io.File; import java.util.ArrayList; @@ -36,7 +35,6 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; @@ -70,10 +68,8 @@ import org.eclipse.aether.resolution.ArtifactResult; /** * @author Jason van Zyl */ -@Component( role = ArtifactResolver.class ) -public class DefaultArtifactResolver - implements ArtifactResolver, Disposable -{ +@Component(role = ArtifactResolver.class) +public class DefaultArtifactResolver implements ArtifactResolver, Disposable { @Requirement private Logger logger; @@ -100,262 +96,263 @@ public class DefaultArtifactResolver private final Executor executor; - public DefaultArtifactResolver() - { - int threads = Integer.getInteger( "maven.artifact.threads", 5 ); - if ( threads <= 1 ) - { + public DefaultArtifactResolver() { + int threads = Integer.getInteger("maven.artifact.threads", 5); + if (threads <= 1) { executor = Runnable::run; - } - else - { - executor = new ThreadPoolExecutor( threads, threads, 3, TimeUnit.SECONDS, - new LinkedBlockingQueue<>(), new DaemonThreadCreator() ); + } else { + executor = new ThreadPoolExecutor( + threads, threads, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new DaemonThreadCreator()); } } - private RepositorySystemSession getSession( ArtifactRepository localRepository ) - { - return LegacyLocalRepositoryManager.overlay( localRepository, legacySupport.getRepositorySession(), - repoSystem ); + private RepositorySystemSession getSession(ArtifactRepository localRepository) { + return LegacyLocalRepositoryManager.overlay(localRepository, legacySupport.getRepositorySession(), repoSystem); } - private void injectSession1( RepositoryRequest request, MavenSession session ) - { - if ( session != null ) - { - request.setOffline( session.isOffline() ); - request.setForceUpdate( session.getRequest().isUpdateSnapshots() ); + private void injectSession1(RepositoryRequest request, MavenSession session) { + if (session != null) { + request.setOffline(session.isOffline()); + request.setForceUpdate(session.getRequest().isUpdateSnapshots()); } } - private void injectSession2( ArtifactResolutionRequest request, MavenSession session ) - { - injectSession1( request, session ); + private void injectSession2(ArtifactResolutionRequest request, MavenSession session) { + injectSession1(request, session); - if ( session != null ) - { - request.setServers( session.getRequest().getServers() ); - request.setMirrors( session.getRequest().getMirrors() ); - request.setProxies( session.getRequest().getProxies() ); + if (session != null) { + request.setServers(session.getRequest().getServers()); + request.setMirrors(session.getRequest().getMirrors()); + request.setProxies(session.getRequest().getProxies()); } } - public void resolve( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository, TransferListener resolutionListener ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - resolve( artifact, remoteRepositories, getSession( localRepository ) ); + public void resolve( + Artifact artifact, + List remoteRepositories, + ArtifactRepository localRepository, + TransferListener resolutionListener) + throws ArtifactResolutionException, ArtifactNotFoundException { + resolve(artifact, remoteRepositories, getSession(localRepository)); } - public void resolveAlways( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - resolve( artifact, remoteRepositories, getSession( localRepository ) ); + public void resolveAlways( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException { + resolve(artifact, remoteRepositories, getSession(localRepository)); } - private void resolve( Artifact artifact, List remoteRepositories, - RepositorySystemSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - if ( artifact == null ) - { + private void resolve( + Artifact artifact, List remoteRepositories, RepositorySystemSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { + if (artifact == null) { return; } - if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) - { + if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { File systemFile = artifact.getFile(); - if ( systemFile == null ) - { - throw new ArtifactNotFoundException( "System artifact: " + artifact + " has no file attached", - artifact ); + if (systemFile == null) { + throw new ArtifactNotFoundException("System artifact: " + artifact + " has no file attached", artifact); } - if ( !systemFile.exists() ) - { - throw new ArtifactNotFoundException( "System artifact: " + artifact + " not found in path: " - + systemFile, artifact ); + if (!systemFile.exists()) { + throw new ArtifactNotFoundException( + "System artifact: " + artifact + " not found in path: " + systemFile, artifact); } - if ( !systemFile.isFile() ) - { - throw new ArtifactNotFoundException( "System artifact: " + artifact + " is not a file: " + systemFile, - artifact ); + if (!systemFile.isFile()) { + throw new ArtifactNotFoundException( + "System artifact: " + artifact + " is not a file: " + systemFile, artifact); } - artifact.setResolved( true ); + artifact.setResolved(true); return; } - if ( !artifact.isResolved() ) - { + if (!artifact.isResolved()) { ArtifactResult result; - try - { + try { ArtifactRequest artifactRequest = new ArtifactRequest(); - artifactRequest.setArtifact( RepositoryUtils.toArtifact( artifact ) ); - artifactRequest.setRepositories( RepositoryUtils.toRepos( remoteRepositories ) ); + artifactRequest.setArtifact(RepositoryUtils.toArtifact(artifact)); + artifactRequest.setRepositories(RepositoryUtils.toRepos(remoteRepositories)); // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not LocalRepositoryManager lrm = session.getLocalRepositoryManager(); - String path = lrm.getPathForLocalArtifact( artifactRequest.getArtifact() ); - artifact.setFile( new File( lrm.getRepository().getBasedir(), path ) ); + String path = lrm.getPathForLocalArtifact(artifactRequest.getArtifact()); + artifact.setFile(new File(lrm.getRepository().getBasedir(), path)); - result = repoSystem.resolveArtifact( session, artifactRequest ); - } - catch ( org.eclipse.aether.resolution.ArtifactResolutionException e ) - { - if ( e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException ) - { - throw new ArtifactNotFoundException( e.getMessage(), artifact, remoteRepositories, e ); - } - else - { - throw new ArtifactResolutionException( e.getMessage(), artifact, remoteRepositories, e ); + result = repoSystem.resolveArtifact(session, artifactRequest); + } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) { + if (e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException) { + throw new ArtifactNotFoundException(e.getMessage(), artifact, remoteRepositories, e); + } else { + throw new ArtifactResolutionException(e.getMessage(), artifact, remoteRepositories, e); } } - artifact.selectVersion( result.getArtifact().getVersion() ); - artifact.setFile( result.getArtifact().getFile() ); - artifact.setResolved( true ); + artifact.selectVersion(result.getArtifact().getVersion()); + artifact.setFile(result.getArtifact().getFile()); + artifact.setResolved(true); - if ( artifact.isSnapshot() ) - { - Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher( artifact.getVersion() ); - if ( matcher.matches() ) - { + if (artifact.isSnapshot()) { + Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(artifact.getVersion()); + if (matcher.matches()) { Snapshot snapshot = new Snapshot(); - snapshot.setTimestamp( matcher.group( 2 ) ); - try - { - snapshot.setBuildNumber( Integer.parseInt( matcher.group( 3 ) ) ); - artifact.addMetadata( new SnapshotArtifactRepositoryMetadata( artifact, snapshot ) ); - } - catch ( NumberFormatException e ) - { - logger.warn( "Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage() ); + snapshot.setTimestamp(matcher.group(2)); + try { + snapshot.setBuildNumber(Integer.parseInt(matcher.group(3))); + artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot)); + } catch (NumberFormatException e) { + logger.warn("Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage()); } } } } } - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter) + throws ArtifactResolutionException, ArtifactNotFoundException { return resolveTransitively( - artifacts, originatingArtifact, Collections.emptyMap(), localRepository, - remoteRepositories, source, filter ); - + artifacts, + originatingArtifact, + Collections.emptyMap(), + localRepository, + remoteRepositories, + source, + filter); } - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { - return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository, - remoteRepositories, source, null ); - } - - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { - return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository, - remoteRepositories, source, filter, null ); - } - - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - List remoteRepositories, - ArtifactRepository localRepository, - ArtifactMetadataSource source ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { - return resolveTransitively( artifacts, originatingArtifact, localRepository, remoteRepositories, source, null ); - } - - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - List remoteRepositories, - ArtifactRepository localRepository, - ArtifactMetadataSource source, - List listeners ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source) + throws ArtifactResolutionException, ArtifactNotFoundException { return resolveTransitively( - artifacts, originatingArtifact, Collections.emptyMap(), localRepository, - remoteRepositories, source, null, listeners ); + artifacts, originatingArtifact, managedVersions, localRepository, remoteRepositories, source, null); } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { - return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository, - remoteRepositories, source, filter, listeners, null ); + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolveTransitively( + artifacts, + originatingArtifact, + managedVersions, + localRepository, + remoteRepositories, + source, + filter, + null); } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners, - List conflictResolvers ) - throws ArtifactResolutionException, - ArtifactNotFoundException - { - ArtifactResolutionRequest request = new ArtifactResolutionRequest(). - setArtifact( originatingArtifact ). - setResolveRoot( false ). - // This is required by the surefire plugin - setArtifactDependencies( artifacts ). - setManagedVersionMap( managedVersions ). - setLocalRepository( localRepository ). - setRemoteRepositories( remoteRepositories ). - setCollectionFilter( filter ). - setListeners( listeners ); - - injectSession2( request, legacySupport.getSession() ); - - return resolveWithExceptions( request ); + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + List remoteRepositories, + ArtifactRepository localRepository, + ArtifactMetadataSource source) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolveTransitively(artifacts, originatingArtifact, localRepository, remoteRepositories, source, null); } - public ArtifactResolutionResult resolveWithExceptions( ArtifactResolutionRequest request ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - ArtifactResolutionResult result = resolve( request ); + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + List remoteRepositories, + ArtifactRepository localRepository, + ArtifactMetadataSource source, + List listeners) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolveTransitively( + artifacts, + originatingArtifact, + Collections.emptyMap(), + localRepository, + remoteRepositories, + source, + null, + listeners); + } + + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolveTransitively( + artifacts, + originatingArtifact, + managedVersions, + localRepository, + remoteRepositories, + source, + filter, + listeners, + null); + } + + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactResolutionResult resolveTransitively( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners, + List conflictResolvers) + throws ArtifactResolutionException, ArtifactNotFoundException { + ArtifactResolutionRequest request = new ArtifactResolutionRequest() + .setArtifact(originatingArtifact) + .setResolveRoot(false) + . + // This is required by the surefire plugin + setArtifactDependencies(artifacts) + .setManagedVersionMap(managedVersions) + .setLocalRepository(localRepository) + .setRemoteRepositories(remoteRepositories) + .setCollectionFilter(filter) + .setListeners(listeners); + + injectSession2(request, legacySupport.getSession()); + + return resolveWithExceptions(request); + } + + public ArtifactResolutionResult resolveWithExceptions(ArtifactResolutionRequest request) + throws ArtifactResolutionException, ArtifactNotFoundException { + ArtifactResolutionResult result = resolve(request); // We have collected all the problems so let's mimic the way the old code worked and just blow up right here. // That's right lets just let it rip right here and send a big incomprehensible blob of text at unsuspecting // users. Bad dog! - resolutionErrorHandler.throwErrors( request, result ); + resolutionErrorHandler.throwErrors(request, result); return result; } @@ -364,41 +361,34 @@ public class DefaultArtifactResolver // // ------------------------------------------------------------------------ - @SuppressWarnings( "checkstyle:methodlength" ) - public ArtifactResolutionResult resolve( ArtifactResolutionRequest request ) - { + @SuppressWarnings("checkstyle:methodlength") + public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) { Artifact rootArtifact = request.getArtifact(); Set artifacts = request.getArtifactDependencies(); Map managedVersions = request.getManagedVersionMap(); List listeners = request.getListeners(); ArtifactFilter collectionFilter = request.getCollectionFilter(); ArtifactFilter resolutionFilter = request.getResolutionFilter(); - RepositorySystemSession session = getSession( request.getLocalRepository() ); + RepositorySystemSession session = getSession(request.getLocalRepository()); // TODO: hack because metadata isn't generated in m2e correctly and i want to run the maven i have in the // workspace - if ( source == null ) - { - try - { - source = container.lookup( ArtifactMetadataSource.class ); - } - catch ( ComponentLookupException e ) - { + if (source == null) { + try { + source = container.lookup(ArtifactMetadataSource.class); + } catch (ComponentLookupException e) { // won't happen } } - if ( listeners == null ) - { + if (listeners == null) { listeners = new ArrayList<>(); - if ( logger.isDebugEnabled() ) - { - listeners.add( new DebugResolutionListener( logger ) ); + if (logger.isDebugEnabled()) { + listeners.add(new DebugResolutionListener(logger)); } - listeners.add( new WarningResolutionListener( logger ) ); + listeners.add(new WarningResolutionListener(logger)); } ArtifactResolutionResult result = new ArtifactResolutionResult(); @@ -408,182 +398,152 @@ public class DefaultArtifactResolver // file reference. But this may be a Maven Plugin that we need to resolve from a remote repository // as well as its dependencies. - if ( request.isResolveRoot() /* && rootArtifact.getFile() == null */ ) - { - try - { - resolve( rootArtifact, request.getRemoteRepositories(), session ); - } - catch ( ArtifactResolutionException e ) - { - result.addErrorArtifactException( e ); + if (request.isResolveRoot() /* && rootArtifact.getFile() == null */) { + try { + resolve(rootArtifact, request.getRemoteRepositories(), session); + } catch (ArtifactResolutionException e) { + result.addErrorArtifactException(e); return result; - } - catch ( ArtifactNotFoundException e ) - { - result.addMissingArtifact( request.getArtifact() ); + } catch (ArtifactNotFoundException e) { + result.addMissingArtifact(request.getArtifact()); return result; } } ArtifactResolutionRequest collectionRequest = request; - if ( request.isResolveTransitively() ) - { - MetadataResolutionRequest metadataRequest = new DefaultMetadataResolutionRequest( request ); + if (request.isResolveTransitively()) { + MetadataResolutionRequest metadataRequest = new DefaultMetadataResolutionRequest(request); - metadataRequest.setArtifact( rootArtifact ); - metadataRequest.setResolveManagedVersions( managedVersions == null ); + metadataRequest.setArtifact(rootArtifact); + metadataRequest.setResolveManagedVersions(managedVersions == null); - try - { - ResolutionGroup resolutionGroup = source.retrieve( metadataRequest ); + try { + ResolutionGroup resolutionGroup = source.retrieve(metadataRequest); - if ( managedVersions == null ) - { + if (managedVersions == null) { managedVersions = resolutionGroup.getManagedVersions(); } Set directArtifacts = resolutionGroup.getArtifacts(); - if ( artifacts == null || artifacts.isEmpty() ) - { + if (artifacts == null || artifacts.isEmpty()) { artifacts = directArtifacts; - } - else - { + } else { List allArtifacts = new ArrayList<>(); - allArtifacts.addAll( artifacts ); - allArtifacts.addAll( directArtifacts ); + allArtifacts.addAll(artifacts); + allArtifacts.addAll(directArtifacts); Map mergedArtifacts = new LinkedHashMap<>(); - for ( Artifact artifact : allArtifacts ) - { + for (Artifact artifact : allArtifacts) { String conflictId = artifact.getDependencyConflictId(); - if ( !mergedArtifacts.containsKey( conflictId ) ) - { - mergedArtifacts.put( conflictId, artifact ); + if (!mergedArtifacts.containsKey(conflictId)) { + mergedArtifacts.put(conflictId, artifact); } } - artifacts = new LinkedHashSet<>( mergedArtifacts.values() ); + artifacts = new LinkedHashSet<>(mergedArtifacts.values()); } - collectionRequest = new ArtifactResolutionRequest( request ); - collectionRequest.setServers( request.getServers() ); - collectionRequest.setMirrors( request.getMirrors() ); - collectionRequest.setProxies( request.getProxies() ); - collectionRequest.setRemoteRepositories( resolutionGroup.getResolutionRepositories() ); - } - catch ( ArtifactMetadataRetrievalException e ) - { - ArtifactResolutionException are = - new ArtifactResolutionException( "Unable to get dependency information for " + rootArtifact.getId() - + ": " + e.getMessage(), rootArtifact, metadataRequest.getRemoteRepositories(), e ); - result.addMetadataResolutionException( are ); + collectionRequest = new ArtifactResolutionRequest(request); + collectionRequest.setServers(request.getServers()); + collectionRequest.setMirrors(request.getMirrors()); + collectionRequest.setProxies(request.getProxies()); + collectionRequest.setRemoteRepositories(resolutionGroup.getResolutionRepositories()); + } catch (ArtifactMetadataRetrievalException e) { + ArtifactResolutionException are = new ArtifactResolutionException( + "Unable to get dependency information for " + rootArtifact.getId() + ": " + e.getMessage(), + rootArtifact, + metadataRequest.getRemoteRepositories(), + e); + result.addMetadataResolutionException(are); return result; } } - if ( artifacts == null || artifacts.isEmpty() ) - { - if ( request.isResolveRoot() ) - { - result.addArtifact( rootArtifact ); + if (artifacts == null || artifacts.isEmpty()) { + if (request.isResolveRoot()) { + result.addArtifact(rootArtifact); } return result; } // After the collection we will have the artifact object in the result but they will not be resolved yet. - result = artifactCollector.collect( artifacts, rootArtifact, managedVersions, collectionRequest, source, - collectionFilter, listeners, null ); + result = artifactCollector.collect( + artifacts, rootArtifact, managedVersions, collectionRequest, source, collectionFilter, listeners, null); // We have metadata retrieval problems, or there are cycles that have been detected // so we give this back to the calling code and let them deal with this information // appropriately. - if ( result.hasMetadataResolutionExceptions() || result.hasVersionRangeViolations() - || result.hasCircularDependencyExceptions() ) - { + if (result.hasMetadataResolutionExceptions() + || result.hasVersionRangeViolations() + || result.hasCircularDependencyExceptions()) { return result; } - if ( result.getArtifactResolutionNodes() != null ) - { + if (result.getArtifactResolutionNodes() != null) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - CountDownLatch latch = new CountDownLatch( result.getArtifactResolutionNodes().size() ); + CountDownLatch latch = + new CountDownLatch(result.getArtifactResolutionNodes().size()); - for ( ResolutionNode node : result.getArtifactResolutionNodes() ) - { + for (ResolutionNode node : result.getArtifactResolutionNodes()) { Artifact artifact = node.getArtifact(); - if ( resolutionFilter == null || resolutionFilter.include( artifact ) ) - { - executor.execute( new ResolveTask( classLoader, latch, artifact, session, - node.getRemoteRepositories(), result ) ); - } - else - { + if (resolutionFilter == null || resolutionFilter.include(artifact)) { + executor.execute(new ResolveTask( + classLoader, latch, artifact, session, node.getRemoteRepositories(), result)); + } else { latch.countDown(); } } - try - { + try { latch.await(); - } - catch ( InterruptedException e ) - { - result.addErrorArtifactException( new ArtifactResolutionException( "Resolution interrupted", - rootArtifact, e ) ); + } catch (InterruptedException e) { + result.addErrorArtifactException( + new ArtifactResolutionException("Resolution interrupted", rootArtifact, e)); } } // We want to send the root artifact back in the result but we need to do this after the other dependencies // have been resolved. - if ( request.isResolveRoot() ) - { + if (request.isResolveRoot()) { // Add the root artifact (as the first artifact to retain logical order of class path!) Set allArtifacts = new LinkedHashSet<>(); - allArtifacts.add( rootArtifact ); - allArtifacts.addAll( result.getArtifacts() ); - result.setArtifacts( allArtifacts ); + allArtifacts.add(rootArtifact); + allArtifacts.addAll(result.getArtifacts()); + result.setArtifacts(allArtifacts); } return result; } - public void resolve( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - resolve( artifact, remoteRepositories, localRepository, null ); + public void resolve( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException { + resolve(artifact, remoteRepositories, localRepository, null); } /** * ThreadCreator for creating daemon threads with fixed ThreadGroup-name. */ - static final class DaemonThreadCreator - implements ThreadFactory - { + static final class DaemonThreadCreator implements ThreadFactory { static final String THREADGROUP_NAME = "org.apache.maven.artifact.resolver.DefaultArtifactResolver"; - static final ThreadGroup GROUP = new ThreadGroup( THREADGROUP_NAME ); + static final ThreadGroup GROUP = new ThreadGroup(THREADGROUP_NAME); - static final AtomicInteger THREAD_NUMBER = new AtomicInteger( 1 ); + static final AtomicInteger THREAD_NUMBER = new AtomicInteger(1); - public Thread newThread( Runnable r ) - { - Thread newThread = new Thread( GROUP, r, "resolver-" + THREAD_NUMBER.getAndIncrement() ); - newThread.setDaemon( true ); - newThread.setContextClassLoader( null ); + public Thread newThread(Runnable r) { + Thread newThread = new Thread(GROUP, r, "resolver-" + THREAD_NUMBER.getAndIncrement()); + newThread.setDaemon(true); + newThread.setContextClassLoader(null); return newThread; } } - private class ResolveTask - implements Runnable - { + private class ResolveTask implements Runnable { private final ClassLoader classLoader; @@ -597,10 +557,13 @@ public class DefaultArtifactResolver private final ArtifactResolutionResult result; - ResolveTask( ClassLoader classLoader, CountDownLatch latch, Artifact artifact, - RepositorySystemSession session, List remoteRepositories, - ArtifactResolutionResult result ) - { + ResolveTask( + ClassLoader classLoader, + CountDownLatch latch, + Artifact artifact, + RepositorySystemSession session, + List remoteRepositories, + ArtifactResolutionResult result) { this.classLoader = classLoader; this.latch = latch; this.artifact = artifact; @@ -609,51 +572,36 @@ public class DefaultArtifactResolver this.result = result; } - public void run() - { + public void run() { ClassLoader old = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( classLoader ); - resolve( artifact, remoteRepositories, session ); - } - catch ( ArtifactNotFoundException anfe ) - { + try { + Thread.currentThread().setContextClassLoader(classLoader); + resolve(artifact, remoteRepositories, session); + } catch (ArtifactNotFoundException anfe) { // These are cases where the artifact just isn't present in any of the remote repositories // because it wasn't deployed, or it was deployed in the wrong place. - synchronized ( result ) - { - result.addMissingArtifact( artifact ); + synchronized (result) { + result.addMissingArtifact(artifact); } - } - catch ( ArtifactResolutionException e ) - { + } catch (ArtifactResolutionException e) { // This is really a wagon TransferFailedException so something went wrong after we successfully // retrieved the metadata. - synchronized ( result ) - { - result.addErrorArtifactException( e ); + synchronized (result) { + result.addErrorArtifactException(e); } - } - finally - { + } finally { latch.countDown(); - Thread.currentThread().setContextClassLoader( old ); - + Thread.currentThread().setContextClassLoader(old); } } - } @Override - public void dispose() - { - if ( executor instanceof ExecutorService ) - { - ( (ExecutorService) executor ).shutdownNow(); + public void dispose() { + if (executor instanceof ExecutorService) { + ((ExecutorService) executor).shutdownNow(); } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ResolutionListenerForDepMgmt.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ResolutionListenerForDepMgmt.java index 6cf06b16f9..288af42c2c 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ResolutionListenerForDepMgmt.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ResolutionListenerForDepMgmt.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import org.apache.maven.artifact.Artifact; @@ -30,14 +29,10 @@ import org.apache.maven.artifact.Artifact; * interface) has had a chance to propagate to all interested plugins. */ @Deprecated -public interface ResolutionListenerForDepMgmt -{ - void manageArtifactVersion( Artifact artifact, - Artifact replacement ); +public interface ResolutionListenerForDepMgmt { + void manageArtifactVersion(Artifact artifact, Artifact replacement); - void manageArtifactScope( Artifact artifact, - Artifact replacement ); + void manageArtifactScope(Artifact artifact, Artifact replacement); - void manageArtifactSystemPath( Artifact artifact, - Artifact replacement ); + void manageArtifactSystemPath(Artifact artifact, Artifact replacement); } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/UnresolvedArtifacts.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/UnresolvedArtifacts.java index b9ccf7067e..9af55207b0 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/UnresolvedArtifacts.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/UnresolvedArtifacts.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -30,18 +28,15 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * * @author Jason van Zyl */ -public class UnresolvedArtifacts -{ +public class UnresolvedArtifacts { private Artifact originatingArtifact; private List artifacts; private List remoteRepositories; - public UnresolvedArtifacts( Artifact originatingArtifact, - List artifacts, - List remoteRepositories ) - { + public UnresolvedArtifacts( + Artifact originatingArtifact, List artifacts, List remoteRepositories) { this.originatingArtifact = originatingArtifact; this.artifacts = artifacts; @@ -49,18 +44,15 @@ public class UnresolvedArtifacts this.remoteRepositories = remoteRepositories; } - public Artifact getOriginatingArtifact() - { + public Artifact getOriginatingArtifact() { return originatingArtifact; } - public List getArtifacts() - { + public List getArtifacts() { return artifacts; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/WarningResolutionListener.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/WarningResolutionListener.java index 825d595a2d..f33a661968 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/WarningResolutionListener.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/WarningResolutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; @@ -28,63 +27,32 @@ import org.codehaus.plexus.logging.Logger; * * @author Brett Porter */ -public class WarningResolutionListener - implements ResolutionListener -{ +public class WarningResolutionListener implements ResolutionListener { private Logger logger; - public WarningResolutionListener( Logger logger ) - { + public WarningResolutionListener(Logger logger) { this.logger = logger; } - public void testArtifact( Artifact node ) - { - } + public void testArtifact(Artifact node) {} - public void startProcessChildren( Artifact artifact ) - { - } + public void startProcessChildren(Artifact artifact) {} - public void endProcessChildren( Artifact artifact ) - { - } + public void endProcessChildren(Artifact artifact) {} - public void includeArtifact( Artifact artifact ) - { - } + public void includeArtifact(Artifact artifact) {} - public void omitForNearer( Artifact omitted, - Artifact kept ) - { - } + public void omitForNearer(Artifact omitted, Artifact kept) {} - public void omitForCycle( Artifact omitted ) - { - } + public void omitForCycle(Artifact omitted) {} - public void updateScopeCurrentPom( Artifact artifact, - String scope ) - { - } + public void updateScopeCurrentPom(Artifact artifact, String scope) {} - public void updateScope( Artifact artifact, - String scope ) - { - } + public void updateScope(Artifact artifact, String scope) {} - public void manageArtifact( Artifact artifact, - Artifact replacement ) - { - } + public void manageArtifact(Artifact artifact, Artifact replacement) {} - public void selectVersionFromRange( Artifact artifact ) - { - } + public void selectVersionFromRange(Artifact artifact) {} - public void restrictRange( Artifact artifact, - Artifact replacement, - VersionRange newRange ) - { - } + public void restrictRange(Artifact artifact, Artifact replacement, VersionRange newRange) {} } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/InversionArtifactFilter.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/InversionArtifactFilter.java index fa66574d60..b13678c167 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/InversionArtifactFilter.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/InversionArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,51 +16,43 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import org.apache.maven.artifact.Artifact; /** * InversionArtifactFilter */ -public class InversionArtifactFilter - implements ArtifactFilter -{ +public class InversionArtifactFilter implements ArtifactFilter { private final ArtifactFilter toInvert; - public InversionArtifactFilter( ArtifactFilter toInvert ) - { + public InversionArtifactFilter(ArtifactFilter toInvert) { this.toInvert = toInvert; } - public boolean include( Artifact artifact ) - { - return !toInvert.include( artifact ); + public boolean include(Artifact artifact) { + return !toInvert.include(artifact); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + toInvert.hashCode(); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof InversionArtifactFilter ) ) - { + if (!(obj instanceof InversionArtifactFilter)) { return false; } InversionArtifactFilter other = (InversionArtifactFilter) obj; - return toInvert.equals( other.toInvert ); + return toInvert.equals(other.toInvert); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilter.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilter.java index 24bfbf404f..8529c1a8ed 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilter.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; /** @@ -30,28 +28,21 @@ import org.apache.maven.artifact.Artifact; * * @author Benjamin Bentmann */ -public class OrArtifactFilter - implements ArtifactFilter -{ +public class OrArtifactFilter implements ArtifactFilter { private Set filters; - public OrArtifactFilter() - { + public OrArtifactFilter() { this.filters = new LinkedHashSet<>(); } - public OrArtifactFilter( Collection filters ) - { - this.filters = new LinkedHashSet<>( filters ); + public OrArtifactFilter(Collection filters) { + this.filters = new LinkedHashSet<>(filters); } - public boolean include( Artifact artifact ) - { - for ( ArtifactFilter filter : filters ) - { - if ( filter.include( artifact ) ) - { + public boolean include(Artifact artifact) { + for (ArtifactFilter filter : filters) { + if (filter.include(artifact)) { return true; } } @@ -59,35 +50,29 @@ public class OrArtifactFilter return false; } - public void add( ArtifactFilter artifactFilter ) - { - filters.add( artifactFilter ); + public void add(ArtifactFilter artifactFilter) { + filters.add(artifactFilter); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + filters.hashCode(); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof OrArtifactFilter ) ) - { + if (!(obj instanceof OrArtifactFilter)) { return false; } OrArtifactFilter other = (OrArtifactFilter) obj; - return filters.equals( other.filters ); + return filters.equals(other.filters); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/TypeArtifactFilter.java b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/TypeArtifactFilter.java index 76c39ec357..270f3e7f7b 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/TypeArtifactFilter.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/TypeArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,49 +16,41 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import org.apache.maven.artifact.Artifact; /** Artifact Filter which filters on artifact type */ -public class TypeArtifactFilter - implements ArtifactFilter -{ +public class TypeArtifactFilter implements ArtifactFilter { private String type = "jar"; - public TypeArtifactFilter( String type ) - { + public TypeArtifactFilter(String type) { this.type = type; } - public boolean include( Artifact artifact ) - { - return type.equals( artifact.getType() ); + public boolean include(Artifact artifact) { + return type.equals(artifact.getType()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + type.hashCode(); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof TypeArtifactFilter ) ) - { + if (!(obj instanceof TypeArtifactFilter)) { return false; } TypeArtifactFilter other = (TypeArtifactFilter) obj; - return type.equals( other.type ); + return type.equals(other.type); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/versioning/ManagedVersionMap.java b/maven-compat/src/main/java/org/apache/maven/artifact/versioning/ManagedVersionMap.java index c098d7fdea..62738d50cc 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/versioning/ManagedVersionMap.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/versioning/ManagedVersionMap.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.versioning; * "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 + * 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 @@ -18,40 +16,33 @@ package org.apache.maven.artifact.versioning; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.versioning; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import org.apache.maven.artifact.Artifact; /** * ManagedVersionMap */ @Deprecated -public class ManagedVersionMap - extends HashMap -{ - public ManagedVersionMap( Map map ) - { +public class ManagedVersionMap extends HashMap { + public ManagedVersionMap(Map map) { super(); - if ( map != null ) - { - putAll( map ); + if (map != null) { + putAll(map); } } - public String toString() - { - StringBuilder buffer = new StringBuilder( "ManagedVersionMap (" + size() + " entries)\n" ); + public String toString() { + StringBuilder buffer = new StringBuilder("ManagedVersionMap (" + size() + " entries)\n"); Iterator iter = keySet().iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { String key = iter.next(); - buffer.append( key ).append( '=' ).append( get( key ) ); - if ( iter.hasNext() ) - { - buffer.append( '\n' ); + buffer.append(key).append('=').append(get(key)); + if (iter.hasNext()) { + buffer.append('\n'); } } return buffer.toString(); diff --git a/maven-compat/src/main/java/org/apache/maven/execution/DefaultRuntimeInformation.java b/maven-compat/src/main/java/org/apache/maven/execution/DefaultRuntimeInformation.java index 7767aff1e0..dd03a98bc8 100644 --- a/maven-compat/src/main/java/org/apache/maven/execution/DefaultRuntimeInformation.java +++ b/maven-compat/src/main/java/org/apache/maven/execution/DefaultRuntimeInformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; @@ -33,32 +32,25 @@ import org.codehaus.plexus.util.StringUtils; * @author Brett Porter */ @Deprecated -@Component( role = RuntimeInformation.class ) -public class DefaultRuntimeInformation - implements RuntimeInformation, Initializable -{ +@Component(role = RuntimeInformation.class) +public class DefaultRuntimeInformation implements RuntimeInformation, Initializable { @Requirement private org.apache.maven.rtinfo.RuntimeInformation rtInfo; private ArtifactVersion applicationVersion; - public ArtifactVersion getApplicationVersion() - { + public ArtifactVersion getApplicationVersion() { return applicationVersion; } - public void initialize() - throws InitializationException - { + public void initialize() throws InitializationException { String mavenVersion = rtInfo.getMavenVersion(); - if ( StringUtils.isEmpty( mavenVersion ) ) - { - throw new InitializationException( "Unable to read Maven version from maven-core" ); + if (StringUtils.isEmpty(mavenVersion)) { + throw new InitializationException("Unable to read Maven version from maven-core"); } - applicationVersion = new DefaultArtifactVersion( mavenVersion ); + applicationVersion = new DefaultArtifactVersion(mavenVersion); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/execution/RuntimeInformation.java b/maven-compat/src/main/java/org/apache/maven/execution/RuntimeInformation.java index 22e522d289..f5f7df172a 100644 --- a/maven-compat/src/main/java/org/apache/maven/execution/RuntimeInformation.java +++ b/maven-compat/src/main/java/org/apache/maven/execution/RuntimeInformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -28,7 +27,6 @@ import org.apache.maven.artifact.versioning.ArtifactVersion; * @author Brett Porter */ @Deprecated -public interface RuntimeInformation -{ +public interface RuntimeInformation { ArtifactVersion getApplicationVersion(); } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java b/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java index 8ee9001c89..0ad8165c1c 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles; * "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 + * 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 @@ -18,7 +16,13 @@ package org.apache.maven.profiles; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; import org.apache.maven.profiles.io.xpp3.ProfilesXpp3Reader; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.interpolation.EnvarBasedValueSource; @@ -28,63 +32,45 @@ import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; - /** * DefaultMavenProfilesBuilder */ @Deprecated -@Component( role = MavenProfilesBuilder.class ) -public class DefaultMavenProfilesBuilder - extends AbstractLogEnabled - implements MavenProfilesBuilder -{ +@Component(role = MavenProfilesBuilder.class) +public class DefaultMavenProfilesBuilder extends AbstractLogEnabled implements MavenProfilesBuilder { private static final String PROFILES_XML_FILE = "profiles.xml"; - public ProfilesRoot buildProfiles( File basedir ) - throws IOException, XmlPullParserException - { - File profilesXml = new File( basedir, PROFILES_XML_FILE ); + public ProfilesRoot buildProfiles(File basedir) throws IOException, XmlPullParserException { + File profilesXml = new File(basedir, PROFILES_XML_FILE); ProfilesRoot profilesRoot = null; - if ( profilesXml.exists() ) - { + if (profilesXml.exists()) { ProfilesXpp3Reader reader = new ProfilesXpp3Reader(); - try ( Reader profileReader = ReaderFactory.newXmlReader( profilesXml ); - StringWriter sWriter = new StringWriter() ) - { - IOUtil.copy( profileReader, sWriter ); + try (Reader profileReader = ReaderFactory.newXmlReader(profilesXml); + StringWriter sWriter = new StringWriter()) { + IOUtil.copy(profileReader, sWriter); String rawInput = sWriter.toString(); - try - { + try { RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); - interpolator.addValueSource( new EnvarBasedValueSource() ); + interpolator.addValueSource(new EnvarBasedValueSource()); - rawInput = interpolator.interpolate( rawInput, "settings" ); - } - catch ( Exception e ) - { - getLogger().warn( - "Failed to initialize environment variable resolver. Skipping environment " + "substitution in " - + PROFILES_XML_FILE + "." ); - getLogger().debug( "Failed to initialize envar resolver. Skipping resolution.", e ); + rawInput = interpolator.interpolate(rawInput, "settings"); + } catch (Exception e) { + getLogger() + .warn("Failed to initialize environment variable resolver. Skipping environment " + + "substitution in " + PROFILES_XML_FILE + "."); + getLogger().debug("Failed to initialize envar resolver. Skipping resolution.", e); } - StringReader sReader = new StringReader( rawInput ); + StringReader sReader = new StringReader(rawInput); - profilesRoot = reader.read( sReader ); + profilesRoot = reader.read(sReader); } - } return profilesRoot; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java b/maven-compat/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java index 11dc0a3322..59f40e4a4c 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles; * "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 + * 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 @@ -18,7 +16,13 @@ package org.apache.maven.profiles; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import org.apache.maven.model.Activation; import org.apache.maven.model.Profile; import org.apache.maven.model.building.ModelProblem; @@ -31,19 +35,11 @@ import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.logging.Logger; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - /** * DefaultProfileManager */ @Deprecated -public class DefaultProfileManager - implements ProfileManager -{ +public class DefaultProfileManager implements ProfileManager { @Requirement private Logger logger; @@ -65,9 +61,8 @@ public class DefaultProfileManager * @deprecated without passing in the system properties, the SystemPropertiesProfileActivator will not work * correctly in embedded environments. */ - public DefaultProfileManager( PlexusContainer container ) - { - this( container, null ); + public DefaultProfileManager(PlexusContainer container) { + this(container, null); } /** @@ -75,127 +70,105 @@ public class DefaultProfileManager * are passed to maven, possibly containing profile activator properties * */ - public DefaultProfileManager( PlexusContainer container, Properties props ) - { - try - { - this.profileSelector = container.lookup( ProfileSelector.class ); - this.logger = ( (MutablePlexusContainer) container ).getLogger(); - } - catch ( ComponentLookupException e ) - { - throw new IllegalStateException( e ); + public DefaultProfileManager(PlexusContainer container, Properties props) { + try { + this.profileSelector = container.lookup(ProfileSelector.class); + this.logger = ((MutablePlexusContainer) container).getLogger(); + } catch (ComponentLookupException e) { + throw new IllegalStateException(e); } this.requestProperties = props; } - public Properties getRequestProperties() - { + public Properties getRequestProperties() { return requestProperties; } - public Map getProfilesById() - { + public Map getProfilesById() { return profilesById; } /* (non-Javadoc) - * @see org.apache.maven.profiles.ProfileManager#addProfile(org.apache.maven.model.Profile) - */ - public void addProfile( Profile profile ) - { + * @see org.apache.maven.profiles.ProfileManager#addProfile(org.apache.maven.model.Profile) + */ + public void addProfile(Profile profile) { String profileId = profile.getId(); - Profile existing = profilesById.get( profileId ); - if ( existing != null ) - { - logger.warn( "Overriding profile: '" + profileId + "' (source: " + existing.getSource() - + ") with new instance from source: " + profile.getSource() ); + Profile existing = profilesById.get(profileId); + if (existing != null) { + logger.warn("Overriding profile: '" + profileId + "' (source: " + existing.getSource() + + ") with new instance from source: " + profile.getSource()); } - profilesById.put( profile.getId(), profile ); + profilesById.put(profile.getId(), profile); Activation activation = profile.getActivation(); - if ( activation != null && activation.isActiveByDefault() ) - { - activateAsDefault( profileId ); + if (activation != null && activation.isActiveByDefault()) { + activateAsDefault(profileId); } } /* (non-Javadoc) - * @see org.apache.maven.profiles.ProfileManager#explicitlyActivate(java.lang.String) - */ - public void explicitlyActivate( String profileId ) - { - if ( !activatedIds.contains( profileId ) ) - { - logger.debug( "Profile with id: '" + profileId + "' has been explicitly activated." ); + * @see org.apache.maven.profiles.ProfileManager#explicitlyActivate(java.lang.String) + */ + public void explicitlyActivate(String profileId) { + if (!activatedIds.contains(profileId)) { + logger.debug("Profile with id: '" + profileId + "' has been explicitly activated."); - activatedIds.add( profileId ); + activatedIds.add(profileId); } } /* (non-Javadoc) - * @see org.apache.maven.profiles.ProfileManager#explicitlyActivate(java.util.List) - */ - public void explicitlyActivate( List profileIds ) - { - for ( String profileId1 : profileIds ) - { - explicitlyActivate( profileId1 ); + * @see org.apache.maven.profiles.ProfileManager#explicitlyActivate(java.util.List) + */ + public void explicitlyActivate(List profileIds) { + for (String profileId1 : profileIds) { + explicitlyActivate(profileId1); } } /* (non-Javadoc) - * @see org.apache.maven.profiles.ProfileManager#explicitlyDeactivate(java.lang.String) - */ - public void explicitlyDeactivate( String profileId ) - { - if ( !deactivatedIds.contains( profileId ) ) - { - logger.debug( "Profile with id: '" + profileId + "' has been explicitly deactivated." ); + * @see org.apache.maven.profiles.ProfileManager#explicitlyDeactivate(java.lang.String) + */ + public void explicitlyDeactivate(String profileId) { + if (!deactivatedIds.contains(profileId)) { + logger.debug("Profile with id: '" + profileId + "' has been explicitly deactivated."); - deactivatedIds.add( profileId ); + deactivatedIds.add(profileId); } } /* (non-Javadoc) - * @see org.apache.maven.profiles.ProfileManager#explicitlyDeactivate(java.util.List) - */ - public void explicitlyDeactivate( List profileIds ) - { - for ( String profileId1 : profileIds ) - { - explicitlyDeactivate( profileId1 ); + * @see org.apache.maven.profiles.ProfileManager#explicitlyDeactivate(java.util.List) + */ + public void explicitlyDeactivate(List profileIds) { + for (String profileId1 : profileIds) { + explicitlyDeactivate(profileId1); } } /* (non-Javadoc) - * @see org.apache.maven.profiles.ProfileManager#getActiveProfiles() - */ - public List getActiveProfiles() - throws ProfileActivationException - { + * @see org.apache.maven.profiles.ProfileManager#getActiveProfiles() + */ + public List getActiveProfiles() throws ProfileActivationException { DefaultProfileActivationContext context = new DefaultProfileActivationContext(); - context.setActiveProfileIds( activatedIds ); - context.setInactiveProfileIds( deactivatedIds ); - context.setSystemProperties( System.getProperties() ); - context.setUserProperties( requestProperties ); + context.setActiveProfileIds(activatedIds); + context.setInactiveProfileIds(deactivatedIds); + context.setSystemProperties(System.getProperties()); + context.setUserProperties(requestProperties); final List errors = new ArrayList<>(); - List profiles = profileSelector.getActiveProfiles( profilesById.values(), context, req -> - { - if ( !ModelProblem.Severity.WARNING.equals( req.getSeverity() ) ) - { - errors.add( new ProfileActivationException( req.getMessage(), req.getException() ) ); + List profiles = profileSelector.getActiveProfiles(profilesById.values(), context, req -> { + if (!ModelProblem.Severity.WARNING.equals(req.getSeverity())) { + errors.add(new ProfileActivationException(req.getMessage(), req.getException())); } - } ); + }); - if ( !errors.isEmpty() ) - { - throw errors.get( 0 ); + if (!errors.isEmpty()) { + throw errors.get(0); } return profiles; @@ -204,35 +177,27 @@ public class DefaultProfileManager /* (non-Javadoc) * @see org.apache.maven.profiles.ProfileManager#addProfiles(java.util.List) */ - public void addProfiles( List profiles ) - { - for ( Profile profile1 : profiles ) - { - addProfile( profile1 ); + public void addProfiles(List profiles) { + for (Profile profile1 : profiles) { + addProfile(profile1); } } - public void activateAsDefault( String profileId ) - { - if ( !defaultIds.contains( profileId ) ) - { - defaultIds.add( profileId ); + public void activateAsDefault(String profileId) { + if (!defaultIds.contains(profileId)) { + defaultIds.add(profileId); } } - public List getExplicitlyActivatedIds() - { + public List getExplicitlyActivatedIds() { return activatedIds; } - public List getExplicitlyDeactivatedIds() - { + public List getExplicitlyDeactivatedIds() { return deactivatedIds; } - public List getIdsActivatedByDefault() - { + public List getIdsActivatedByDefault() { return defaultIds; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/MavenProfilesBuilder.java b/maven-compat/src/main/java/org/apache/maven/profiles/MavenProfilesBuilder.java index 32fb6aaa42..2765fa68e6 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/MavenProfilesBuilder.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/MavenProfilesBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles; * "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 + * 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 @@ -18,20 +16,18 @@ package org.apache.maven.profiles; * specific language governing permissions and limitations * under the License. */ - -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +package org.apache.maven.profiles; import java.io.File; import java.io.IOException; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * @author jdcasey */ @Deprecated -public interface MavenProfilesBuilder -{ +public interface MavenProfilesBuilder { String ROLE = MavenProfilesBuilder.class.getName(); - ProfilesRoot buildProfiles( File basedir ) - throws IOException, XmlPullParserException; + ProfilesRoot buildProfiles(File basedir) throws IOException, XmlPullParserException; } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/ProfileManager.java b/maven-compat/src/main/java/org/apache/maven/profiles/ProfileManager.java index 5fab100684..33aa6717eb 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/ProfileManager.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/ProfileManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles; * "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 + * 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 @@ -18,35 +16,33 @@ package org.apache.maven.profiles; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.model.Profile; -import org.apache.maven.profiles.activation.ProfileActivationException; +package org.apache.maven.profiles; import java.util.List; import java.util.Map; import java.util.Properties; +import org.apache.maven.model.Profile; +import org.apache.maven.profiles.activation.ProfileActivationException; /** * ProfileManager */ @Deprecated -public interface ProfileManager -{ +public interface ProfileManager { - void addProfile( Profile profile ); + void addProfile(Profile profile); - void explicitlyActivate( String profileId ); + void explicitlyActivate(String profileId); - void explicitlyActivate( List profileIds ); + void explicitlyActivate(List profileIds); - void explicitlyDeactivate( String profileId ); + void explicitlyDeactivate(String profileId); - void explicitlyDeactivate( List profileIds ); + void explicitlyDeactivate(List profileIds); - List getActiveProfiles() - throws ProfileActivationException; + List getActiveProfiles() throws ProfileActivationException; - void addProfiles( List profiles ); + void addProfiles(List profiles); Map getProfilesById(); @@ -57,5 +53,4 @@ public interface ProfileManager List getIdsActivatedByDefault(); Properties getRequestProperties(); - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/ProfilesConversionUtils.java b/maven-compat/src/main/java/org/apache/maven/profiles/ProfilesConversionUtils.java index 154176eecf..27a90388f8 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/ProfilesConversionUtils.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/ProfilesConversionUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles; * "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 + * 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 @@ -18,137 +16,119 @@ package org.apache.maven.profiles; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles; +import java.util.List; import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationFile; import org.apache.maven.model.ActivationProperty; import org.apache.maven.model.Profile; import org.apache.maven.model.Repository; -import java.util.List; - /** * ProfilesConversionUtils */ @Deprecated -public class ProfilesConversionUtils -{ - private ProfilesConversionUtils() - { - } +public class ProfilesConversionUtils { + private ProfilesConversionUtils() {} - public static Profile convertFromProfileXmlProfile( org.apache.maven.profiles.Profile profileXmlProfile ) - { + public static Profile convertFromProfileXmlProfile(org.apache.maven.profiles.Profile profileXmlProfile) { Profile profile = new Profile(); - profile.setId( profileXmlProfile.getId() ); + profile.setId(profileXmlProfile.getId()); - profile.setSource( "profiles.xml" ); + profile.setSource("profiles.xml"); org.apache.maven.profiles.Activation profileActivation = profileXmlProfile.getActivation(); - if ( profileActivation != null ) - { + if (profileActivation != null) { Activation activation = new Activation(); - activation.setActiveByDefault( profileActivation.isActiveByDefault() ); + activation.setActiveByDefault(profileActivation.isActiveByDefault()); - activation.setJdk( profileActivation.getJdk() ); + activation.setJdk(profileActivation.getJdk()); org.apache.maven.profiles.ActivationProperty profileProp = profileActivation.getProperty(); - if ( profileProp != null ) - { + if (profileProp != null) { ActivationProperty prop = new ActivationProperty(); - prop.setName( profileProp.getName() ); - prop.setValue( profileProp.getValue() ); + prop.setName(profileProp.getName()); + prop.setValue(profileProp.getValue()); - activation.setProperty( prop ); + activation.setProperty(prop); } - ActivationOS profileOs = profileActivation.getOs(); - if ( profileOs != null ) - { + if (profileOs != null) { org.apache.maven.model.ActivationOS os = new org.apache.maven.model.ActivationOS(); - os.setArch( profileOs.getArch() ); - os.setFamily( profileOs.getFamily() ); - os.setName( profileOs.getName() ); - os.setVersion( profileOs.getVersion() ); + os.setArch(profileOs.getArch()); + os.setFamily(profileOs.getFamily()); + os.setName(profileOs.getName()); + os.setVersion(profileOs.getVersion()); - activation.setOs( os ); + activation.setOs(os); } org.apache.maven.profiles.ActivationFile profileFile = profileActivation.getFile(); - if ( profileFile != null ) - { + if (profileFile != null) { ActivationFile file = new ActivationFile(); - file.setExists( profileFile.getExists() ); - file.setMissing( profileFile.getMissing() ); + file.setExists(profileFile.getExists()); + file.setMissing(profileFile.getMissing()); - activation.setFile( file ); + activation.setFile(file); } - profile.setActivation( activation ); + profile.setActivation(activation); } - profile.setProperties( profileXmlProfile.getProperties() ); + profile.setProperties(profileXmlProfile.getProperties()); List repos = profileXmlProfile.getRepositories(); - if ( repos != null ) - { - for ( Object repo : repos ) - { - profile.addRepository( convertFromProfileXmlRepository( (org.apache.maven.profiles.Repository) repo ) ); + if (repos != null) { + for (Object repo : repos) { + profile.addRepository(convertFromProfileXmlRepository((org.apache.maven.profiles.Repository) repo)); } } List pluginRepos = profileXmlProfile.getPluginRepositories(); - if ( pluginRepos != null ) - { - for ( Object pluginRepo : pluginRepos ) - { + if (pluginRepos != null) { + for (Object pluginRepo : pluginRepos) { profile.addPluginRepository( - convertFromProfileXmlRepository( (org.apache.maven.profiles.Repository) pluginRepo ) ); + convertFromProfileXmlRepository((org.apache.maven.profiles.Repository) pluginRepo)); } } return profile; } - private static Repository convertFromProfileXmlRepository( org.apache.maven.profiles.Repository profileXmlRepo ) - { + private static Repository convertFromProfileXmlRepository(org.apache.maven.profiles.Repository profileXmlRepo) { Repository repo = new Repository(); - repo.setId( profileXmlRepo.getId() ); - repo.setLayout( profileXmlRepo.getLayout() ); - repo.setName( profileXmlRepo.getName() ); - repo.setUrl( profileXmlRepo.getUrl() ); + repo.setId(profileXmlRepo.getId()); + repo.setLayout(profileXmlRepo.getLayout()); + repo.setName(profileXmlRepo.getName()); + repo.setUrl(profileXmlRepo.getUrl()); - if ( profileXmlRepo.getSnapshots() != null ) - { - repo.setSnapshots( convertRepositoryPolicy( profileXmlRepo.getSnapshots() ) ); + if (profileXmlRepo.getSnapshots() != null) { + repo.setSnapshots(convertRepositoryPolicy(profileXmlRepo.getSnapshots())); } - if ( profileXmlRepo.getReleases() != null ) - { - repo.setReleases( convertRepositoryPolicy( profileXmlRepo.getReleases() ) ); + if (profileXmlRepo.getReleases() != null) { + repo.setReleases(convertRepositoryPolicy(profileXmlRepo.getReleases())); } return repo; } - private static org.apache.maven.model.RepositoryPolicy convertRepositoryPolicy( RepositoryPolicy profileXmlRepo ) - { + private static org.apache.maven.model.RepositoryPolicy convertRepositoryPolicy(RepositoryPolicy profileXmlRepo) { org.apache.maven.model.RepositoryPolicy policy = new org.apache.maven.model.RepositoryPolicy(); - policy.setEnabled( profileXmlRepo.isEnabled() ); - policy.setUpdatePolicy( profileXmlRepo.getUpdatePolicy() ); - policy.setChecksumPolicy( profileXmlRepo.getChecksumPolicy() ); + policy.setEnabled(profileXmlRepo.isEnabled()); + policy.setUpdatePolicy(profileXmlRepo.getUpdatePolicy()); + policy.setChecksumPolicy(profileXmlRepo.getChecksumPolicy()); return policy; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/DetectedProfileActivator.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/DetectedProfileActivator.java index f034245053..ee023ff77c 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/DetectedProfileActivator.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/DetectedProfileActivator.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; import org.apache.maven.model.Profile; @@ -25,14 +24,10 @@ import org.apache.maven.model.Profile; * DetectedProfileActivator */ @Deprecated -public abstract class DetectedProfileActivator - implements ProfileActivator -{ - public boolean canDetermineActivation( Profile profile ) - { - return canDetectActivation( profile ); +public abstract class DetectedProfileActivator implements ProfileActivator { + public boolean canDetermineActivation(Profile profile) { + return canDetectActivation(profile); } - protected abstract boolean canDetectActivation( Profile profile ); - + protected abstract boolean canDetectActivation(Profile profile); } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/FileProfileActivator.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/FileProfileActivator.java index 586f57f7fb..eaa0ac3b06 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/FileProfileActivator.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/FileProfileActivator.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; import java.io.IOException; - import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationFile; import org.apache.maven.model.Profile; @@ -37,67 +35,49 @@ import org.codehaus.plexus.util.StringUtils; * FileProfileActivator */ @Deprecated -public class FileProfileActivator - extends DetectedProfileActivator - implements LogEnabled -{ +public class FileProfileActivator extends DetectedProfileActivator implements LogEnabled { private Logger logger; - protected boolean canDetectActivation( Profile profile ) - { + protected boolean canDetectActivation(Profile profile) { return profile.getActivation() != null && profile.getActivation().getFile() != null; } - public boolean isActive( Profile profile ) - { + public boolean isActive(Profile profile) { Activation activation = profile.getActivation(); ActivationFile actFile = activation.getFile(); - if ( actFile != null ) - { + if (actFile != null) { // check if the file exists, if it does then the profile will be active String fileString = actFile.getExists(); RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); - try - { - interpolator.addValueSource( new EnvarBasedValueSource() ); - } - catch ( IOException e ) - { + try { + interpolator.addValueSource(new EnvarBasedValueSource()); + } catch (IOException e) { // ignored } - interpolator.addValueSource( new MapBasedValueSource( System.getProperties() ) ); + interpolator.addValueSource(new MapBasedValueSource(System.getProperties())); - try - { - if ( StringUtils.isNotEmpty( fileString ) ) - { - fileString = StringUtils.replace( interpolator.interpolate( fileString, "" ), "\\", "/" ); - return FileUtils.fileExists( fileString ); + try { + if (StringUtils.isNotEmpty(fileString)) { + fileString = StringUtils.replace(interpolator.interpolate(fileString, ""), "\\", "/"); + return FileUtils.fileExists(fileString); } // check if the file is missing, if it is then the profile will be active fileString = actFile.getMissing(); - if ( StringUtils.isNotEmpty( fileString ) ) - { - fileString = StringUtils.replace( interpolator.interpolate( fileString, "" ), "\\", "/" ); - return !FileUtils.fileExists( fileString ); + if (StringUtils.isNotEmpty(fileString)) { + fileString = StringUtils.replace(interpolator.interpolate(fileString, ""), "\\", "/"); + return !FileUtils.fileExists(fileString); } - } - catch ( InterpolationException e ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Failed to interpolate missing file location for profile activator: " + fileString, - e ); - } - else - { - logger.warn( "Failed to interpolate missing file location for profile activator: " + fileString - + ", enable verbose output (-X) for more details" ); + } catch (InterpolationException e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to interpolate missing file location for profile activator: " + fileString, e); + } else { + logger.warn("Failed to interpolate missing file location for profile activator: " + fileString + + ", enable verbose output (-X) for more details"); } } } @@ -105,8 +85,7 @@ public class FileProfileActivator return false; } - public void enableLogging( Logger logger ) - { + public void enableLogging(Logger logger) { this.logger = logger; } } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/JdkPrefixProfileActivator.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/JdkPrefixProfileActivator.java index 1c835f814b..736f8fdd56 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/JdkPrefixProfileActivator.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/JdkPrefixProfileActivator.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; @@ -30,71 +29,54 @@ import org.codehaus.plexus.util.StringUtils; * JdkPrefixProfileActivator */ @Deprecated -public class JdkPrefixProfileActivator - extends DetectedProfileActivator -{ - private static final String JDK_VERSION = System.getProperty( "java.version" ); +public class JdkPrefixProfileActivator extends DetectedProfileActivator { + private static final String JDK_VERSION = System.getProperty("java.version"); - public boolean isActive( Profile profile ) - throws ProfileActivationException - { + public boolean isActive(Profile profile) throws ProfileActivationException { Activation activation = profile.getActivation(); String jdk = activation.getJdk(); // null case is covered by canDetermineActivation(), so we can do a straight startsWith() here. - if ( jdk.startsWith( "[" ) || jdk.startsWith( "(" ) ) - { - try - { - return matchJdkVersionRange( jdk ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new ProfileActivationException( "Invalid JDK version in profile '" + profile.getId() + "': " - + e.getMessage() ); + if (jdk.startsWith("[") || jdk.startsWith("(")) { + try { + return matchJdkVersionRange(jdk); + } catch (InvalidVersionSpecificationException e) { + throw new ProfileActivationException( + "Invalid JDK version in profile '" + profile.getId() + "': " + e.getMessage()); } } boolean reverse = false; - if ( jdk.startsWith( "!" ) ) - { + if (jdk.startsWith("!")) { reverse = true; - jdk = jdk.substring( 1 ); + jdk = jdk.substring(1); } - if ( getJdkVersion().startsWith( jdk ) ) - { + if (getJdkVersion().startsWith(jdk)) { return !reverse; - } - else - { + } else { return reverse; } } - private boolean matchJdkVersionRange( String jdk ) - throws InvalidVersionSpecificationException - { - VersionRange jdkVersionRange = VersionRange.createFromVersionSpec( convertJdkToMavenVersion( jdk ) ); - DefaultArtifactVersion jdkVersion = new DefaultArtifactVersion( convertJdkToMavenVersion( getJdkVersion() ) ); - return jdkVersionRange.containsVersion( jdkVersion ); + private boolean matchJdkVersionRange(String jdk) throws InvalidVersionSpecificationException { + VersionRange jdkVersionRange = VersionRange.createFromVersionSpec(convertJdkToMavenVersion(jdk)); + DefaultArtifactVersion jdkVersion = new DefaultArtifactVersion(convertJdkToMavenVersion(getJdkVersion())); + return jdkVersionRange.containsVersion(jdkVersion); } - private String convertJdkToMavenVersion( String jdk ) - { - return jdk.replaceAll( "_", "-" ); + private String convertJdkToMavenVersion(String jdk) { + return jdk.replaceAll("_", "-"); } - protected String getJdkVersion() - { + protected String getJdkVersion() { return JDK_VERSION; } - protected boolean canDetectActivation( Profile profile ) - { - return profile.getActivation() != null && StringUtils.isNotEmpty( profile.getActivation().getJdk() ); + protected boolean canDetectActivation(Profile profile) { + return profile.getActivation() != null + && StringUtils.isNotEmpty(profile.getActivation().getJdk()); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java index 378c3c9481..3ec25d87b4 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationOS; @@ -28,137 +27,107 @@ import org.codehaus.plexus.util.Os; * OperatingSystemProfileActivator */ @Deprecated -public class OperatingSystemProfileActivator - implements ProfileActivator -{ +public class OperatingSystemProfileActivator implements ProfileActivator { - public boolean canDetermineActivation( Profile profile ) - { + public boolean canDetermineActivation(Profile profile) { Activation activation = profile.getActivation(); return activation != null && activation.getOs() != null; } - public boolean isActive( Profile profile ) - { + public boolean isActive(Profile profile) { Activation activation = profile.getActivation(); ActivationOS os = activation.getOs(); - boolean result = ensureAtLeastOneNonNull( os ); + boolean result = ensureAtLeastOneNonNull(os); - if ( result && os.getFamily() != null ) - { - result = determineFamilyMatch( os.getFamily() ); + if (result && os.getFamily() != null) { + result = determineFamilyMatch(os.getFamily()); } - if ( result && os.getName() != null ) - { - result = determineNameMatch( os.getName() ); + if (result && os.getName() != null) { + result = determineNameMatch(os.getName()); } - if ( result && os.getArch() != null ) - { - result = determineArchMatch( os.getArch() ); + if (result && os.getArch() != null) { + result = determineArchMatch(os.getArch()); } - if ( result && os.getVersion() != null ) - { - result = determineVersionMatch( os.getVersion() ); + if (result && os.getVersion() != null) { + result = determineVersionMatch(os.getVersion()); } return result; } - private boolean ensureAtLeastOneNonNull( ActivationOS os ) - { + private boolean ensureAtLeastOneNonNull(ActivationOS os) { return os.getArch() != null || os.getFamily() != null || os.getName() != null || os.getVersion() != null; } - private boolean determineVersionMatch( String version ) - { + private boolean determineVersionMatch(String version) { String test = version; boolean reverse = false; - if ( test.startsWith( "!" ) ) - { + if (test.startsWith("!")) { reverse = true; - test = test.substring( 1 ); + test = test.substring(1); } - boolean result = Os.isVersion( test ); + boolean result = Os.isVersion(test); - if ( reverse ) - { + if (reverse) { return !result; - } - else - { + } else { return result; } } - private boolean determineArchMatch( String arch ) - { + private boolean determineArchMatch(String arch) { String test = arch; boolean reverse = false; - if ( test.startsWith( "!" ) ) - { + if (test.startsWith("!")) { reverse = true; - test = test.substring( 1 ); + test = test.substring(1); } - boolean result = Os.isArch( test ); + boolean result = Os.isArch(test); - if ( reverse ) - { + if (reverse) { return !result; - } - else - { + } else { return result; } } - private boolean determineNameMatch( String name ) - { + private boolean determineNameMatch(String name) { String test = name; boolean reverse = false; - if ( test.startsWith( "!" ) ) - { + if (test.startsWith("!")) { reverse = true; - test = test.substring( 1 ); + test = test.substring(1); } - boolean result = Os.isName( test ); + boolean result = Os.isName(test); - if ( reverse ) - { + if (reverse) { return !result; - } - else - { + } else { return result; } } - private boolean determineFamilyMatch( String family ) - { + private boolean determineFamilyMatch(String family) { String test = family; boolean reverse = false; - if ( test.startsWith( "!" ) ) - { + if (test.startsWith("!")) { reverse = true; - test = test.substring( 1 ); + test = test.substring(1); } - boolean result = Os.isFamily( test ); + boolean result = Os.isFamily(test); - if ( reverse ) - { + if (reverse) { return !result; - } - else - { + } else { return result; } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivationException.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivationException.java index 59f70bed0e..5215d9e191 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivationException.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,25 +16,21 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; /** * ProfileActivationException */ @Deprecated -public class ProfileActivationException - extends Exception -{ +public class ProfileActivationException extends Exception { private static final long serialVersionUID = -90820222109103638L; - public ProfileActivationException( String message, Throwable cause ) - { - super( message, cause ); + public ProfileActivationException(String message, Throwable cause) { + super(message, cause); } - public ProfileActivationException( String message ) - { - super( message ); + public ProfileActivationException(String message) { + super(message); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivator.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivator.java index 6482018560..fc8a6e7f00 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivator.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/ProfileActivator.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; import org.apache.maven.model.Profile; @@ -25,14 +24,11 @@ import org.apache.maven.model.Profile; * ProfileActivator */ @Deprecated -public interface ProfileActivator -{ +public interface ProfileActivator { String ROLE = ProfileActivator.class.getName(); - boolean canDetermineActivation( Profile profile ); - - boolean isActive( Profile profile ) - throws ProfileActivationException; + boolean canDetermineActivation(Profile profile); + boolean isActive(Profile profile) throws ProfileActivationException; } diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/activation/SystemPropertyProfileActivator.java b/maven-compat/src/main/java/org/apache/maven/profiles/activation/SystemPropertyProfileActivator.java index d7e4003428..356a3e4e18 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/activation/SystemPropertyProfileActivator.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/activation/SystemPropertyProfileActivator.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.activation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.activation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.profiles.activation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.activation; import java.util.Properties; import org.apache.maven.model.Activation; @@ -32,80 +31,60 @@ import org.codehaus.plexus.util.StringUtils; * SystemPropertyProfileActivator */ @Deprecated -public class SystemPropertyProfileActivator - extends DetectedProfileActivator implements Contextualizable -{ +public class SystemPropertyProfileActivator extends DetectedProfileActivator implements Contextualizable { private Properties properties; - public void contextualize( Context context ) - throws ContextException - { - properties = (Properties) context.get( "SystemProperties" ); + public void contextualize(Context context) throws ContextException { + properties = (Properties) context.get("SystemProperties"); } - protected boolean canDetectActivation( Profile profile ) - { + protected boolean canDetectActivation(Profile profile) { return profile.getActivation() != null && profile.getActivation().getProperty() != null; } - public boolean isActive( Profile profile ) - throws ProfileActivationException - { + public boolean isActive(Profile profile) throws ProfileActivationException { Activation activation = profile.getActivation(); ActivationProperty property = activation.getProperty(); - if ( property != null ) - { + if (property != null) { String name = property.getName(); boolean reverseName = false; - if ( name == null ) - { - throw new ProfileActivationException( "The property name is required to activate the profile '" - + profile.getId() + "'" ); + if (name == null) { + throw new ProfileActivationException( + "The property name is required to activate the profile '" + profile.getId() + "'"); } - if ( name.startsWith( "!" ) ) - { + if (name.startsWith("!")) { reverseName = true; - name = name.substring( 1 ); + name = name.substring(1); } - String sysValue = properties.getProperty( name ); + String sysValue = properties.getProperty(name); String propValue = property.getValue(); - if ( StringUtils.isNotEmpty( propValue ) ) - { + if (StringUtils.isNotEmpty(propValue)) { boolean reverseValue = false; - if ( propValue.startsWith( "!" ) ) - { + if (propValue.startsWith("!")) { reverseValue = true; - propValue = propValue.substring( 1 ); + propValue = propValue.substring(1); } // we have a value, so it has to match the system value... - boolean result = propValue.equals( sysValue ); + boolean result = propValue.equals(sysValue); - if ( reverseValue ) - { + if (reverseValue) { return !result; - } - else - { + } else { return result; } - } - else - { - boolean result = StringUtils.isNotEmpty( sysValue ); + } else { + boolean result = StringUtils.isNotEmpty(sysValue); - if ( reverseName ) - { + if (reverseName) { return !result; - } - else - { + } else { return result; } } @@ -113,5 +92,4 @@ public class SystemPropertyProfileActivator return false; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java b/maven-compat/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java index 7bc5a5c3a4..d59d8a4d1e 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java +++ b/maven-compat/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -47,11 +45,9 @@ import org.codehaus.plexus.component.annotations.Requirement; /** */ -@Component( role = MavenProjectBuilder.class ) +@Component(role = MavenProjectBuilder.class) @Deprecated -public class DefaultMavenProjectBuilder - implements MavenProjectBuilder -{ +public class DefaultMavenProjectBuilder implements MavenProjectBuilder { @Requirement private ProjectBuilder projectBuilder; @@ -66,26 +62,22 @@ public class DefaultMavenProjectBuilder // MavenProjectBuilder Implementation // ---------------------------------------------------------------------- - private ProjectBuildingRequest toRequest( ProjectBuilderConfiguration configuration ) - { + private ProjectBuildingRequest toRequest(ProjectBuilderConfiguration configuration) { DefaultProjectBuildingRequest request = new DefaultProjectBuildingRequest(); - request.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ); - request.setResolveDependencies( false ); + request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0); + request.setResolveDependencies(false); - request.setLocalRepository( configuration.getLocalRepository() ); - request.setBuildStartTime( configuration.getBuildStartTime() ); - request.setUserProperties( configuration.getUserProperties() ); - request.setSystemProperties( configuration.getExecutionProperties() ); + request.setLocalRepository(configuration.getLocalRepository()); + request.setBuildStartTime(configuration.getBuildStartTime()); + request.setUserProperties(configuration.getUserProperties()); + request.setSystemProperties(configuration.getExecutionProperties()); ProfileManager profileManager = configuration.getGlobalProfileManager(); - if ( profileManager != null ) - { - request.setActiveProfileIds( profileManager.getExplicitlyActivatedIds() ); - request.setInactiveProfileIds( profileManager.getExplicitlyDeactivatedIds() ); - } - else - { + if (profileManager != null) { + request.setActiveProfileIds(profileManager.getExplicitlyActivatedIds()); + request.setInactiveProfileIds(profileManager.getExplicitlyDeactivatedIds()); + } else { /* * MNG-4900: Hack to workaround deficiency of legacy API which makes it impossible for plugins to access the * global profile manager which is required to build a POM like a CLI invocation does. Failure to consider @@ -94,13 +86,11 @@ public class DefaultMavenProjectBuilder * based on the configured remote repos. */ MavenSession session = legacySupport.getSession(); - if ( session != null ) - { + if (session != null) { MavenExecutionRequest req = session.getRequest(); - if ( req != null ) - { - request.setActiveProfileIds( req.getActiveProfiles() ); - request.setInactiveProfileIds( req.getInactiveProfiles() ); + if (req != null) { + request.setActiveProfileIds(req.getActiveProfiles()); + request.setInactiveProfileIds(req.getInactiveProfiles()); } } } @@ -108,77 +98,60 @@ public class DefaultMavenProjectBuilder return request; } - private ProjectBuildingRequest injectSession( ProjectBuildingRequest request ) - { + private ProjectBuildingRequest injectSession(ProjectBuildingRequest request) { MavenSession session = legacySupport.getSession(); - if ( session != null ) - { - request.setRepositorySession( session.getRepositorySession() ); - request.setSystemProperties( session.getSystemProperties() ); - if ( request.getUserProperties().isEmpty() ) - { - request.setUserProperties( session.getUserProperties() ); + if (session != null) { + request.setRepositorySession(session.getRepositorySession()); + request.setSystemProperties(session.getSystemProperties()); + if (request.getUserProperties().isEmpty()) { + request.setUserProperties(session.getUserProperties()); } MavenExecutionRequest req = session.getRequest(); - if ( req != null ) - { - request.setRemoteRepositories( req.getRemoteRepositories() ); + if (req != null) { + request.setRemoteRepositories(req.getRemoteRepositories()); } - } - else - { + } else { Properties props = new Properties(); - EnvironmentUtils.addEnvVars( props ); - props.putAll( System.getProperties() ); - request.setSystemProperties( props ); + EnvironmentUtils.addEnvVars(props); + props.putAll(System.getProperties()); + request.setSystemProperties(props); } return request; } - @SuppressWarnings( "unchecked" ) - private List normalizeToArtifactRepositories( List repositories, - ProjectBuildingRequest request ) - throws ProjectBuildingException - { + @SuppressWarnings("unchecked") + private List normalizeToArtifactRepositories( + List repositories, ProjectBuildingRequest request) throws ProjectBuildingException { /* * This provides backward-compat with 2.x that allowed plugins like the maven-remote-resources-plugin:1.0 to * populate the builder configuration with model repositories instead of artifact repositories. */ - if ( repositories != null ) - { + if (repositories != null) { boolean normalized = false; - List repos = new ArrayList<>( repositories.size() ); + List repos = new ArrayList<>(repositories.size()); - for ( Object repository : repositories ) - { - if ( repository instanceof Repository ) - { - try - { - ArtifactRepository repo = repositorySystem.buildArtifactRepository( (Repository) repository ); - repositorySystem.injectMirror( request.getRepositorySession(), Arrays.asList( repo ) ); - repositorySystem.injectProxy( request.getRepositorySession(), Arrays.asList( repo ) ); - repositorySystem.injectAuthentication( request.getRepositorySession(), Arrays.asList( repo ) ); - repos.add( repo ); - } - catch ( InvalidRepositoryException e ) - { - throw new ProjectBuildingException( "", "Invalid remote repository " + repository, e ); + for (Object repository : repositories) { + if (repository instanceof Repository) { + try { + ArtifactRepository repo = repositorySystem.buildArtifactRepository((Repository) repository); + repositorySystem.injectMirror(request.getRepositorySession(), Arrays.asList(repo)); + repositorySystem.injectProxy(request.getRepositorySession(), Arrays.asList(repo)); + repositorySystem.injectAuthentication(request.getRepositorySession(), Arrays.asList(repo)); + repos.add(repo); + } catch (InvalidRepositoryException e) { + throw new ProjectBuildingException("", "Invalid remote repository " + repository, e); } normalized = true; - } - else - { - repos.add( (ArtifactRepository) repository ); + } else { + repos.add((ArtifactRepository) repository); } } - if ( normalized ) - { + if (normalized) { return repos; } } @@ -186,139 +159,125 @@ public class DefaultMavenProjectBuilder return (List) repositories; } - private ProjectBuildingException transformError( ProjectBuildingException e ) - { - if ( e.getCause() instanceof ModelBuildingException ) - { - return new InvalidProjectModelException( e.getProjectId(), e.getMessage(), e.getPomFile() ); + private ProjectBuildingException transformError(ProjectBuildingException e) { + if (e.getCause() instanceof ModelBuildingException) { + return new InvalidProjectModelException(e.getProjectId(), e.getMessage(), e.getPomFile()); } return e; } - public MavenProject build( File pom, ProjectBuilderConfiguration configuration ) - throws ProjectBuildingException - { - ProjectBuildingRequest request = injectSession( toRequest( configuration ) ); + public MavenProject build(File pom, ProjectBuilderConfiguration configuration) throws ProjectBuildingException { + ProjectBuildingRequest request = injectSession(toRequest(configuration)); - try - { - return projectBuilder.build( pom, request ).getProject(); - } - catch ( ProjectBuildingException e ) - { - throw transformError( e ); + try { + return projectBuilder.build(pom, request).getProject(); + } catch (ProjectBuildingException e) { + throw transformError(e); } } // This is used by the SITE plugin. - public MavenProject build( File pom, ArtifactRepository localRepository, ProfileManager profileManager ) - throws ProjectBuildingException - { + public MavenProject build(File pom, ArtifactRepository localRepository, ProfileManager profileManager) + throws ProjectBuildingException { ProjectBuilderConfiguration configuration = new DefaultProjectBuilderConfiguration(); - configuration.setLocalRepository( localRepository ); - configuration.setGlobalProfileManager( profileManager ); + configuration.setLocalRepository(localRepository); + configuration.setGlobalProfileManager(profileManager); - return build( pom, configuration ); + return build(pom, configuration); } - public MavenProject buildFromRepository( Artifact artifact, List remoteRepositories, - ProjectBuilderConfiguration configuration, boolean allowStubModel ) - throws ProjectBuildingException - { - ProjectBuildingRequest request = injectSession( toRequest( configuration ) ); - request.setRemoteRepositories( normalizeToArtifactRepositories( remoteRepositories, request ) ); - request.setProcessPlugins( false ); - request.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); + public MavenProject buildFromRepository( + Artifact artifact, + List remoteRepositories, + ProjectBuilderConfiguration configuration, + boolean allowStubModel) + throws ProjectBuildingException { + ProjectBuildingRequest request = injectSession(toRequest(configuration)); + request.setRemoteRepositories(normalizeToArtifactRepositories(remoteRepositories, request)); + request.setProcessPlugins(false); + request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); - try - { - return projectBuilder.build( artifact, allowStubModel, request ).getProject(); - } - catch ( ProjectBuildingException e ) - { - throw transformError( e ); + try { + return projectBuilder.build(artifact, allowStubModel, request).getProject(); + } catch (ProjectBuildingException e) { + throw transformError(e); } } - public MavenProject buildFromRepository( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository, boolean allowStubModel ) - throws ProjectBuildingException - { + public MavenProject buildFromRepository( + Artifact artifact, + List remoteRepositories, + ArtifactRepository localRepository, + boolean allowStubModel) + throws ProjectBuildingException { ProjectBuilderConfiguration configuration = new DefaultProjectBuilderConfiguration(); - configuration.setLocalRepository( localRepository ); + configuration.setLocalRepository(localRepository); - return buildFromRepository( artifact, remoteRepositories, configuration, allowStubModel ); + return buildFromRepository(artifact, remoteRepositories, configuration, allowStubModel); } - public MavenProject buildFromRepository( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ProjectBuildingException - { - return buildFromRepository( artifact, remoteRepositories, localRepository, true ); + public MavenProject buildFromRepository( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ProjectBuildingException { + return buildFromRepository(artifact, remoteRepositories, localRepository, true); } /** * This is used for pom-less execution like running archetype:generate. I am taking out the profile handling and the * interpolation of the base directory until we spec this out properly. */ - public MavenProject buildStandaloneSuperProject( ProjectBuilderConfiguration configuration ) - throws ProjectBuildingException - { - ProjectBuildingRequest request = injectSession( toRequest( configuration ) ); - request.setProcessPlugins( false ); - request.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); + public MavenProject buildStandaloneSuperProject(ProjectBuilderConfiguration configuration) + throws ProjectBuildingException { + ProjectBuildingRequest request = injectSession(toRequest(configuration)); + request.setProcessPlugins(false); + request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); - ModelSource modelSource = new UrlModelSource( getClass().getResource( "standalone.xml" ) ); + ModelSource modelSource = new UrlModelSource(getClass().getResource("standalone.xml")); - MavenProject project = projectBuilder.build( modelSource, request ).getProject(); - project.setExecutionRoot( true ); + MavenProject project = projectBuilder.build(modelSource, request).getProject(); + project.setExecutionRoot(true); return project; } - public MavenProject buildStandaloneSuperProject( ArtifactRepository localRepository ) - throws ProjectBuildingException - { - return buildStandaloneSuperProject( localRepository, null ); + public MavenProject buildStandaloneSuperProject(ArtifactRepository localRepository) + throws ProjectBuildingException { + return buildStandaloneSuperProject(localRepository, null); } - public MavenProject buildStandaloneSuperProject( ArtifactRepository localRepository, ProfileManager profileManager ) - throws ProjectBuildingException - { + public MavenProject buildStandaloneSuperProject(ArtifactRepository localRepository, ProfileManager profileManager) + throws ProjectBuildingException { ProjectBuilderConfiguration configuration = new DefaultProjectBuilderConfiguration(); - configuration.setLocalRepository( localRepository ); - configuration.setGlobalProfileManager( profileManager ); + configuration.setLocalRepository(localRepository); + configuration.setGlobalProfileManager(profileManager); - return buildStandaloneSuperProject( configuration ); + return buildStandaloneSuperProject(configuration); } - public MavenProject buildWithDependencies( File pom, ArtifactRepository localRepository, - ProfileManager profileManager, TransferListener transferListener ) - throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException - { + public MavenProject buildWithDependencies( + File pom, + ArtifactRepository localRepository, + ProfileManager profileManager, + TransferListener transferListener) + throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException { ProjectBuilderConfiguration configuration = new DefaultProjectBuilderConfiguration(); - configuration.setLocalRepository( localRepository ); - configuration.setGlobalProfileManager( profileManager ); + configuration.setLocalRepository(localRepository); + configuration.setGlobalProfileManager(profileManager); - ProjectBuildingRequest request = injectSession( toRequest( configuration ) ); + ProjectBuildingRequest request = injectSession(toRequest(configuration)); - request.setResolveDependencies( true ); + request.setResolveDependencies(true); - try - { - return projectBuilder.build( pom, request ).getProject(); - } - catch ( ProjectBuildingException e ) - { - throw transformError( e ); + try { + return projectBuilder.build(pom, request).getProject(); + } catch (ProjectBuildingException e) { + throw transformError(e); } } - public MavenProject buildWithDependencies( File pom, ArtifactRepository localRepository, - ProfileManager profileManager ) - throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException - { - return buildWithDependencies( pom, localRepository, profileManager, null ); + public MavenProject buildWithDependencies( + File pom, ArtifactRepository localRepository, ProfileManager profileManager) + throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException { + return buildWithDependencies(pom, localRepository, profileManager, null); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/DefaultProjectBuilderConfiguration.java b/maven-compat/src/main/java/org/apache/maven/project/DefaultProjectBuilderConfiguration.java index aca6a0342a..b407bb4693 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/DefaultProjectBuilderConfiguration.java +++ b/maven-compat/src/main/java/org/apache/maven/project/DefaultProjectBuilderConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Date; import java.util.Properties; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.profiles.ProfileManager; @@ -29,9 +27,7 @@ import org.apache.maven.profiles.ProfileManager; * DefaultProjectBuilderConfiguration */ @Deprecated -public class DefaultProjectBuilderConfiguration - implements ProjectBuilderConfiguration -{ +public class DefaultProjectBuilderConfiguration implements ProjectBuilderConfiguration { private ProfileManager globalProfileManager; @@ -43,68 +39,54 @@ public class DefaultProjectBuilderConfiguration private Date buildStartTime; - public DefaultProjectBuilderConfiguration() - { - } + public DefaultProjectBuilderConfiguration() {} - public ProjectBuilderConfiguration setGlobalProfileManager( ProfileManager globalProfileManager ) - { + public ProjectBuilderConfiguration setGlobalProfileManager(ProfileManager globalProfileManager) { this.globalProfileManager = globalProfileManager; return this; } - public ProfileManager getGlobalProfileManager() - { + public ProfileManager getGlobalProfileManager() { return globalProfileManager; } - public ProjectBuilderConfiguration setLocalRepository( ArtifactRepository localRepository ) - { + public ProjectBuilderConfiguration setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; return this; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } - public ProjectBuilderConfiguration setUserProperties( Properties userProperties ) - { + public ProjectBuilderConfiguration setUserProperties(Properties userProperties) { this.userProperties = userProperties; return this; } - public Properties getUserProperties() - { - if ( userProperties == null ) - { + public Properties getUserProperties() { + if (userProperties == null) { userProperties = new Properties(); } return userProperties; } - public Properties getExecutionProperties() - { + public Properties getExecutionProperties() { return executionProperties; } - public ProjectBuilderConfiguration setExecutionProperties( Properties executionProperties ) - { + public ProjectBuilderConfiguration setExecutionProperties(Properties executionProperties) { this.executionProperties = executionProperties; return this; } - public Date getBuildStartTime() - { + public Date getBuildStartTime() { return buildStartTime; } - public ProjectBuilderConfiguration setBuildStartTime( Date buildStartTime ) - { + public ProjectBuilderConfiguration setBuildStartTime(Date buildStartTime) { this.buildStartTime = buildStartTime; return this; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/InvalidProjectModelException.java b/maven-compat/src/main/java/org/apache/maven/project/InvalidProjectModelException.java index d7241fdc36..9949071d4f 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/InvalidProjectModelException.java +++ b/maven-compat/src/main/java/org/apache/maven/project/InvalidProjectModelException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,23 +16,20 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; - import org.apache.maven.project.validation.ModelValidationResult; /** * InvalidProjectModelException */ @Deprecated -public class InvalidProjectModelException - extends ProjectBuildingException -{ +public class InvalidProjectModelException extends ProjectBuildingException { private ModelValidationResult validationResult; - public InvalidProjectModelException( String projectId, String message, File pomLocation ) - { - super( projectId, message, pomLocation ); + public InvalidProjectModelException(String projectId, String message, File pomLocation) { + super(projectId, message, pomLocation); } /** @@ -44,16 +39,14 @@ public class InvalidProjectModelException * @param validationResult * @deprecated use {@link File} constructor for pomLocation */ - public InvalidProjectModelException( String projectId, String pomLocation, String message, - ModelValidationResult validationResult ) - { - this( projectId, message, new File( pomLocation ), validationResult ); + public InvalidProjectModelException( + String projectId, String pomLocation, String message, ModelValidationResult validationResult) { + this(projectId, message, new File(pomLocation), validationResult); } - public InvalidProjectModelException( String projectId, String message, File pomFile, - ModelValidationResult validationResult ) - { - super( projectId, message, pomFile ); + public InvalidProjectModelException( + String projectId, String message, File pomFile, ModelValidationResult validationResult) { + super(projectId, message, pomFile); this.validationResult = validationResult; } @@ -64,14 +57,11 @@ public class InvalidProjectModelException * @param message * @deprecated use {@link File} constructor for pomLocation */ - public InvalidProjectModelException( String projectId, String pomLocation, String message ) - { - this( projectId, message, new File( pomLocation ) ); + public InvalidProjectModelException(String projectId, String pomLocation, String message) { + this(projectId, message, new File(pomLocation)); } - public final ModelValidationResult getValidationResult() - { + public final ModelValidationResult getValidationResult() { return validationResult; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/MavenProjectBuilder.java b/maven-compat/src/main/java/org/apache/maven/project/MavenProjectBuilder.java index df97948149..c23db02feb 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/MavenProjectBuilder.java +++ b/maven-compat/src/main/java/org/apache/maven/project/MavenProjectBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; @@ -33,45 +31,46 @@ import org.apache.maven.wagon.events.TransferListener; * @deprecated use {@link ProjectBuilder} instead */ @Deprecated -public interface MavenProjectBuilder -{ +public interface MavenProjectBuilder { - MavenProject build( File pom, ProjectBuilderConfiguration configuration ) - throws ProjectBuildingException; + MavenProject build(File pom, ProjectBuilderConfiguration configuration) throws ProjectBuildingException; - //TODO maven-site-plugin -- not used by the plugin directly, but used by Doxia Integration Tool & MPIR + // TODO maven-site-plugin -- not used by the plugin directly, but used by Doxia Integration Tool & MPIR // see DOXIASITETOOLS-167 & MPIR-349 - MavenProject build( File pom, ArtifactRepository localRepository, ProfileManager profileManager ) - throws ProjectBuildingException; + MavenProject build(File pom, ArtifactRepository localRepository, ProfileManager profileManager) + throws ProjectBuildingException; - //TODO remote-resources-plugin - MavenProject buildFromRepository( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ProjectBuildingException; + // TODO remote-resources-plugin + MavenProject buildFromRepository( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ProjectBuildingException; - //TODO remote-resources-plugin - MavenProject buildFromRepository( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository, boolean allowStubModel ) - throws ProjectBuildingException; + // TODO remote-resources-plugin + MavenProject buildFromRepository( + Artifact artifact, + List remoteRepositories, + ArtifactRepository localRepository, + boolean allowStubModel) + throws ProjectBuildingException; // TODO this is only to provide a project for plugins that don't need a project to execute but need some // of the values from a MavenProject. Ideally this should be something internal and nothing outside Maven // would ever need this so it should not be exposed in a public API - MavenProject buildStandaloneSuperProject( ProjectBuilderConfiguration configuration ) - throws ProjectBuildingException; + MavenProject buildStandaloneSuperProject(ProjectBuilderConfiguration configuration) throws ProjectBuildingException; - MavenProject buildStandaloneSuperProject( ArtifactRepository localRepository ) - throws ProjectBuildingException; + MavenProject buildStandaloneSuperProject(ArtifactRepository localRepository) throws ProjectBuildingException; - MavenProject buildStandaloneSuperProject( ArtifactRepository localRepository, ProfileManager profileManager ) - throws ProjectBuildingException; + MavenProject buildStandaloneSuperProject(ArtifactRepository localRepository, ProfileManager profileManager) + throws ProjectBuildingException; - MavenProject buildWithDependencies( File pom, ArtifactRepository localRepository, - ProfileManager globalProfileManager, TransferListener transferListener ) - throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException; - - MavenProject buildWithDependencies( File pom, ArtifactRepository localRepository, - ProfileManager globalProfileManager ) - throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException; + MavenProject buildWithDependencies( + File pom, + ArtifactRepository localRepository, + ProfileManager globalProfileManager, + TransferListener transferListener) + throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException; + MavenProject buildWithDependencies( + File pom, ArtifactRepository localRepository, ProfileManager globalProfileManager) + throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException; } diff --git a/maven-compat/src/main/java/org/apache/maven/project/MissingRepositoryElementException.java b/maven-compat/src/main/java/org/apache/maven/project/MissingRepositoryElementException.java index 75384e1515..b528c6a2e5 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/MissingRepositoryElementException.java +++ b/maven-compat/src/main/java/org/apache/maven/project/MissingRepositoryElementException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,23 +16,20 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import org.apache.maven.artifact.InvalidRepositoryException; + /** * Error constructing an artifact repository. */ -public class MissingRepositoryElementException - extends InvalidRepositoryException -{ +public class MissingRepositoryElementException extends InvalidRepositoryException { - public MissingRepositoryElementException( String message, String repositoryId ) - { - super( message, repositoryId ); + public MissingRepositoryElementException(String message, String repositoryId) { + super(message, repositoryId); } - public MissingRepositoryElementException( String message ) - { - super( message, "-unknown-" ); + public MissingRepositoryElementException(String message) { + super(message, "-unknown-"); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/ModelUtils.java b/maven-compat/src/main/java/org/apache/maven/project/ModelUtils.java index 2c94f7a6f6..7fa4853681 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/ModelUtils.java +++ b/maven-compat/src/main/java/org/apache/maven/project/ModelUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.List; - import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginContainer; /** @deprecated */ @Deprecated -public final class ModelUtils -{ +public final class ModelUtils { /** * This should be the resulting ordering of plugins after merging: @@ -42,27 +39,21 @@ public final class ModelUtils * X -> Y -> A -> B -> C -> D -> E -> F * */ - public static void mergePluginLists( PluginContainer childContainer, PluginContainer parentContainer, - boolean handleAsInheritance ) - { + public static void mergePluginLists( + PluginContainer childContainer, PluginContainer parentContainer, boolean handleAsInheritance) { throw new UnsupportedOperationException(); } - public static List orderAfterMerge( List merged, List highPrioritySource, - List lowPrioritySource ) - { + public static List orderAfterMerge( + List merged, List highPrioritySource, List lowPrioritySource) { throw new UnsupportedOperationException(); } - - public static void mergePluginDefinitions( Plugin child, Plugin parent, boolean handleAsInheritance ) - { + public static void mergePluginDefinitions(Plugin child, Plugin parent, boolean handleAsInheritance) { throw new UnsupportedOperationException(); } - public static void mergeFilterLists( List childFilters, List parentFilters ) - { + public static void mergeFilterLists(List childFilters, List parentFilters) { throw new UnsupportedOperationException(); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/ProjectBuilderConfiguration.java b/maven-compat/src/main/java/org/apache/maven/project/ProjectBuilderConfiguration.java index ddfad3cb0b..f8aefe7226 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/ProjectBuilderConfiguration.java +++ b/maven-compat/src/main/java/org/apache/maven/project/ProjectBuilderConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Date; import java.util.Properties; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.profiles.ProfileManager; @@ -29,8 +27,7 @@ import org.apache.maven.profiles.ProfileManager; * @deprecated use {@link ProjectBuildingRequest} instead */ @Deprecated -public interface ProjectBuilderConfiguration -{ +public interface ProjectBuilderConfiguration { ArtifactRepository getLocalRepository(); @@ -40,16 +37,15 @@ public interface ProjectBuilderConfiguration Properties getExecutionProperties(); - ProjectBuilderConfiguration setGlobalProfileManager( ProfileManager globalProfileManager ); + ProjectBuilderConfiguration setGlobalProfileManager(ProfileManager globalProfileManager); - ProjectBuilderConfiguration setLocalRepository( ArtifactRepository localRepository ); + ProjectBuilderConfiguration setLocalRepository(ArtifactRepository localRepository); - ProjectBuilderConfiguration setUserProperties( Properties userProperties ); + ProjectBuilderConfiguration setUserProperties(Properties userProperties); - ProjectBuilderConfiguration setExecutionProperties( Properties executionProperties ); + ProjectBuilderConfiguration setExecutionProperties(Properties executionProperties); Date getBuildStartTime(); - ProjectBuilderConfiguration setBuildStartTime( Date buildStartTime ); - + ProjectBuilderConfiguration setBuildStartTime(Date buildStartTime); } diff --git a/maven-compat/src/main/java/org/apache/maven/project/ProjectUtils.java b/maven-compat/src/main/java/org/apache/maven/project/ProjectUtils.java index 8d4234427b..73d39604a7 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/ProjectUtils.java +++ b/maven-compat/src/main/java/org/apache/maven/project/ProjectUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; @@ -41,78 +39,61 @@ import org.eclipse.aether.RepositorySystemSession; * ProjectUtils */ @Deprecated -public final class ProjectUtils -{ +public final class ProjectUtils { - private ProjectUtils() - { - } + private ProjectUtils() {} public static List buildArtifactRepositories( - List repositories, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c ) - throws InvalidRepositoryException - { + List repositories, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c) + throws InvalidRepositoryException { List remoteRepositories = new ArrayList<>(); - for ( Repository r : repositories ) - { - remoteRepositories.add( buildArtifactRepository( r, artifactRepositoryFactory, c ) ); + for (Repository r : repositories) { + remoteRepositories.add(buildArtifactRepository(r, artifactRepositoryFactory, c)); } return remoteRepositories; } public static ArtifactRepository buildDeploymentArtifactRepository( - DeploymentRepository repo, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c ) - throws InvalidRepositoryException - { - return buildArtifactRepository( repo, artifactRepositoryFactory, c ); + DeploymentRepository repo, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c) + throws InvalidRepositoryException { + return buildArtifactRepository(repo, artifactRepositoryFactory, c); } public static ArtifactRepository buildArtifactRepository( - Repository repo, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c ) - throws InvalidRepositoryException - { - RepositorySystem repositorySystem = rs( c ); - RepositorySystemSession session = rss( c ); + Repository repo, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c) + throws InvalidRepositoryException { + RepositorySystem repositorySystem = rs(c); + RepositorySystemSession session = rss(c); - ArtifactRepository repository = repositorySystem.buildArtifactRepository( repo ); + ArtifactRepository repository = repositorySystem.buildArtifactRepository(repo); - if ( session != null ) - { - repositorySystem.injectMirror( session, Arrays.asList( repository ) ); - repositorySystem.injectProxy( session, Arrays.asList( repository ) ); - repositorySystem.injectAuthentication( session, Arrays.asList( repository ) ); + if (session != null) { + repositorySystem.injectMirror(session, Arrays.asList(repository)); + repositorySystem.injectProxy(session, Arrays.asList(repository)); + repositorySystem.injectAuthentication(session, Arrays.asList(repository)); } return repository; } - private static RepositorySystem rs( PlexusContainer c ) - { - try - { - return c.lookup( RepositorySystem.class ); - } - catch ( ComponentLookupException e ) - { - throw new IllegalStateException( e ); + private static RepositorySystem rs(PlexusContainer c) { + try { + return c.lookup(RepositorySystem.class); + } catch (ComponentLookupException e) { + throw new IllegalStateException(e); } } - private static RepositorySystemSession rss( PlexusContainer c ) - { - try - { - LegacySupport legacySupport = c.lookup( LegacySupport.class ); + private static RepositorySystemSession rss(PlexusContainer c) { + try { + LegacySupport legacySupport = c.lookup(LegacySupport.class); return legacySupport.getRepositorySession(); - } - catch ( ComponentLookupException e ) - { - throw new IllegalStateException( e ); + } catch (ComponentLookupException e) { + throw new IllegalStateException(e); } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java b/maven-compat/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java index b6dd90d81b..215f6ae6cf 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java +++ b/maven-compat/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.inheritance; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance; import org.apache.maven.model.Build; import org.apache.maven.model.Model; @@ -26,31 +25,25 @@ import org.codehaus.plexus.component.annotations.Component; /** * DefaultModelInheritanceAssembler */ -@Component( role = ModelInheritanceAssembler.class ) -public class DefaultModelInheritanceAssembler - implements ModelInheritanceAssembler -{ +@Component(role = ModelInheritanceAssembler.class) +public class DefaultModelInheritanceAssembler implements ModelInheritanceAssembler { @Override - public void assembleModelInheritance( Model child, Model parent, String childPathAdjustment ) - { + public void assembleModelInheritance(Model child, Model parent, String childPathAdjustment) { throw new UnsupportedOperationException(); } @Override - public void assembleModelInheritance( Model child, Model parent ) - { + public void assembleModelInheritance(Model child, Model parent) { throw new UnsupportedOperationException(); } @Override - public void assembleBuildInheritance( Build childBuild, Build parentBuild, boolean handleAsInheritance ) - { + public void assembleBuildInheritance(Build childBuild, Build parentBuild, boolean handleAsInheritance) { throw new UnsupportedOperationException(); } @Override - public void copyModel( Model dest, Model source ) - { + public void copyModel(Model dest, Model source) { throw new UnsupportedOperationException(); } -} \ No newline at end of file +} diff --git a/maven-compat/src/main/java/org/apache/maven/project/inheritance/ModelInheritanceAssembler.java b/maven-compat/src/main/java/org/apache/maven/project/inheritance/ModelInheritanceAssembler.java index bf8a63b4e4..fc6d3bcde4 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/inheritance/ModelInheritanceAssembler.java +++ b/maven-compat/src/main/java/org/apache/maven/project/inheritance/ModelInheritanceAssembler.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.inheritance; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance; import org.apache.maven.model.Build; import org.apache.maven.model.Model; @@ -27,15 +26,14 @@ import org.apache.maven.model.Model; * @deprecated */ @Deprecated -public interface ModelInheritanceAssembler -{ +public interface ModelInheritanceAssembler { String ROLE = ModelInheritanceAssembler.class.getName(); - void assembleModelInheritance( Model child, Model parent, String childPathAdjustment ); + void assembleModelInheritance(Model child, Model parent, String childPathAdjustment); - void assembleModelInheritance( Model child, Model parent ); + void assembleModelInheritance(Model child, Model parent); - void assembleBuildInheritance( Build childBuild, Build parentBuild, boolean handleAsInheritance ); + void assembleBuildInheritance(Build childBuild, Build parentBuild, boolean handleAsInheritance); - void copyModel( Model dest, Model source ); + void copyModel(Model dest, Model source); } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/AbstractStringBasedModelInterpolator.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/AbstractStringBasedModelInterpolator.java index 996baef590..1247308768 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/AbstractStringBasedModelInterpolator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/AbstractStringBasedModelInterpolator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,7 +16,18 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.interpolation; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Properties; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; @@ -43,17 +52,6 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; - /** * Use a regular expression search to find and resolve expressions within the POM. * @@ -61,17 +59,14 @@ import java.util.Properties; * TODO Consolidate this logic with the PluginParameterExpressionEvaluator, minus deprecations/bans. */ @Deprecated -public abstract class AbstractStringBasedModelInterpolator - extends AbstractLogEnabled - implements ModelInterpolator, Initializable -{ +public abstract class AbstractStringBasedModelInterpolator extends AbstractLogEnabled + implements ModelInterpolator, Initializable { - private static final List PROJECT_PREFIXES = Arrays.asList( "pom.", "project." ); + private static final List PROJECT_PREFIXES = Arrays.asList("pom.", "project."); private static final List TRANSLATED_PATH_EXPRESSIONS; - static - { + static { List translatedPrefixes = new ArrayList<>(); // MNG-1927, MNG-2124, MNG-3355: @@ -79,13 +74,13 @@ public abstract class AbstractStringBasedModelInterpolator // sure interpolation of the directories below uses translated paths. // Afterward, we'll double back and translate any paths that weren't covered during interpolation via the // code below... - translatedPrefixes.add( "build.directory" ); - translatedPrefixes.add( "build.outputDirectory" ); - translatedPrefixes.add( "build.testOutputDirectory" ); - translatedPrefixes.add( "build.sourceDirectory" ); - translatedPrefixes.add( "build.testSourceDirectory" ); - translatedPrefixes.add( "build.scriptSourceDirectory" ); - translatedPrefixes.add( "reporting.outputDirectory" ); + translatedPrefixes.add("build.directory"); + translatedPrefixes.add("build.outputDirectory"); + translatedPrefixes.add("build.testOutputDirectory"); + translatedPrefixes.add("build.sourceDirectory"); + translatedPrefixes.add("build.testSourceDirectory"); + translatedPrefixes.add("build.scriptSourceDirectory"); + translatedPrefixes.add("reporting.outputDirectory"); TRANSLATED_PATH_EXPRESSIONS = translatedPrefixes; } @@ -98,19 +93,14 @@ public abstract class AbstractStringBasedModelInterpolator private RecursionInterceptor recursionInterceptor; // for testing. - protected AbstractStringBasedModelInterpolator( PathTranslator pathTranslator ) - { + protected AbstractStringBasedModelInterpolator(PathTranslator pathTranslator) { this.pathTranslator = pathTranslator; } - protected AbstractStringBasedModelInterpolator() - { - } + protected AbstractStringBasedModelInterpolator() {} - public Model interpolate( Model model, Map context ) - throws ModelInterpolationException - { - return interpolate( model, context, true ); + public Model interpolate(Model model, Map context) throws ModelInterpolationException { + return interpolate(model, context, true); } /** @@ -126,50 +116,35 @@ public abstract class AbstractStringBasedModelInterpolator * * @deprecated Use {@link ModelInterpolator#interpolate(Model, File, ProjectBuilderConfiguration, boolean)} instead. */ - public Model interpolate( Model model, Map context, boolean strict ) - throws ModelInterpolationException - { + public Model interpolate(Model model, Map context, boolean strict) throws ModelInterpolationException { Properties props = new Properties(); - props.putAll( context ); + props.putAll(context); - return interpolate( model, - null, - new DefaultProjectBuilderConfiguration().setExecutionProperties( props ), - true ); + return interpolate(model, null, new DefaultProjectBuilderConfiguration().setExecutionProperties(props), true); } - public Model interpolate( Model model, - File projectDir, - ProjectBuilderConfiguration config, - boolean debugEnabled ) - throws ModelInterpolationException - { - StringWriter sWriter = new StringWriter( 1024 ); + public Model interpolate(Model model, File projectDir, ProjectBuilderConfiguration config, boolean debugEnabled) + throws ModelInterpolationException { + StringWriter sWriter = new StringWriter(1024); MavenXpp3Writer writer = new MavenXpp3Writer(); - try - { - writer.write( sWriter, model ); - } - catch ( IOException e ) - { - throw new ModelInterpolationException( "Cannot serialize project model for interpolation.", e ); + try { + writer.write(sWriter, model); + } catch (IOException e) { + throw new ModelInterpolationException("Cannot serialize project model for interpolation.", e); } String serializedModel = sWriter.toString(); - serializedModel = interpolate( serializedModel, model, projectDir, config, debugEnabled ); + serializedModel = interpolate(serializedModel, model, projectDir, config, debugEnabled); - StringReader sReader = new StringReader( serializedModel ); + StringReader sReader = new StringReader(serializedModel); MavenXpp3Reader modelReader = new MavenXpp3Reader(); - try - { - model = modelReader.read( sReader ); - } - catch ( IOException | XmlPullParserException e ) - { + try { + model = modelReader.read(sReader); + } catch (IOException | XmlPullParserException e) { throw new ModelInterpolationException( - "Cannot read project model from interpolating filter of serialized version.", e ); + "Cannot read project model from interpolating filter of serialized version.", e); } return model; @@ -187,191 +162,146 @@ public abstract class AbstractStringBasedModelInterpolator *
  • If the value is null, get it from the model properties.
  • *
*/ - public String interpolate( String src, - Model model, - final File projectDir, - ProjectBuilderConfiguration config, - boolean debug ) - throws ModelInterpolationException - { - try - { - List valueSources = createValueSources( model, projectDir, config ); - List postProcessors = createPostProcessors( model, projectDir, config ); + public String interpolate( + String src, Model model, final File projectDir, ProjectBuilderConfiguration config, boolean debug) + throws ModelInterpolationException { + try { + List valueSources = createValueSources(model, projectDir, config); + List postProcessors = createPostProcessors(model, projectDir, config); - return interpolateInternal( src, valueSources, postProcessors, debug ); - } - finally - { + return interpolateInternal(src, valueSources, postProcessors, debug); + } finally { interpolator.clearAnswers(); } } - protected List createValueSources( final Model model, final File projectDir, - final ProjectBuilderConfiguration config ) - { + protected List createValueSources( + final Model model, final File projectDir, final ProjectBuilderConfiguration config) { String timestampFormat = DEFAULT_BUILD_TIMESTAMP_FORMAT; Properties modelProperties = model.getProperties(); - if ( modelProperties != null ) - { - timestampFormat = modelProperties.getProperty( BUILD_TIMESTAMP_FORMAT_PROPERTY, timestampFormat ); + if (modelProperties != null) { + timestampFormat = modelProperties.getProperty(BUILD_TIMESTAMP_FORMAT_PROPERTY, timestampFormat); } - ValueSource modelValueSource1 = new PrefixedObjectValueSource( PROJECT_PREFIXES, model, false ); - ValueSource modelValueSource2 = new ObjectBasedValueSource( model ); + ValueSource modelValueSource1 = new PrefixedObjectValueSource(PROJECT_PREFIXES, model, false); + ValueSource modelValueSource2 = new ObjectBasedValueSource(model); - ValueSource basedirValueSource = new PrefixedValueSourceWrapper( new AbstractValueSource( false ) - { + ValueSource basedirValueSource = new PrefixedValueSourceWrapper( + new AbstractValueSource(false) { - public Object getValue( String expression ) - { - if ( projectDir != null && "basedir".equals( expression ) ) - { - return projectDir.getAbsolutePath(); - } - return null; - } + public Object getValue(String expression) { + if (projectDir != null && "basedir".equals(expression)) { + return projectDir.getAbsolutePath(); + } + return null; + } + }, + PROJECT_PREFIXES, + true); + ValueSource baseUriValueSource = new PrefixedValueSourceWrapper( + new AbstractValueSource(false) { - }, PROJECT_PREFIXES, true ); - ValueSource baseUriValueSource = new PrefixedValueSourceWrapper( new AbstractValueSource( false ) - { + public Object getValue(String expression) { + if (projectDir != null && "baseUri".equals(expression)) { + return projectDir.getAbsoluteFile().toPath().toUri().toASCIIString(); + } + return null; + } + }, + PROJECT_PREFIXES, + false); - public Object getValue( String expression ) - { - if ( projectDir != null && "baseUri".equals( expression ) ) - { - return projectDir.getAbsoluteFile().toPath().toUri().toASCIIString(); - } - return null; - } - - }, PROJECT_PREFIXES, false ); - - List valueSources = new ArrayList<>( 9 ); + List valueSources = new ArrayList<>(9); // NOTE: Order counts here! - valueSources.add( basedirValueSource ); - valueSources.add( baseUriValueSource ); - valueSources.add( new BuildTimestampValueSource( config.getBuildStartTime(), timestampFormat ) ); - valueSources.add( modelValueSource1 ); - valueSources.add( new MapBasedValueSource( config.getUserProperties() ) ); - valueSources.add( new MapBasedValueSource( modelProperties ) ); - valueSources.add( new MapBasedValueSource( config.getExecutionProperties() ) ); - valueSources.add( new AbstractValueSource( false ) - { + valueSources.add(basedirValueSource); + valueSources.add(baseUriValueSource); + valueSources.add(new BuildTimestampValueSource(config.getBuildStartTime(), timestampFormat)); + valueSources.add(modelValueSource1); + valueSources.add(new MapBasedValueSource(config.getUserProperties())); + valueSources.add(new MapBasedValueSource(modelProperties)); + valueSources.add(new MapBasedValueSource(config.getExecutionProperties())); + valueSources.add(new AbstractValueSource(false) { - public Object getValue( String expression ) - { - return config.getExecutionProperties().getProperty( "env." + expression ); + public Object getValue(String expression) { + return config.getExecutionProperties().getProperty("env." + expression); } - - } ); - valueSources.add( modelValueSource2 ); + }); + valueSources.add(modelValueSource2); return valueSources; } - protected List createPostProcessors( final Model model, final File projectDir, - final ProjectBuilderConfiguration config ) - { - return Collections.singletonList( - (InterpolationPostProcessor) new PathTranslatingPostProcessor( - PROJECT_PREFIXES, - TRANSLATED_PATH_EXPRESSIONS, - projectDir, - pathTranslator ) ); - + protected List createPostProcessors( + final Model model, final File projectDir, final ProjectBuilderConfiguration config) { + return Collections.singletonList((InterpolationPostProcessor) new PathTranslatingPostProcessor( + PROJECT_PREFIXES, TRANSLATED_PATH_EXPRESSIONS, projectDir, pathTranslator)); } - @SuppressWarnings( "unchecked" ) - protected String interpolateInternal( String src, List valueSources, - List postProcessors, boolean debug ) - throws ModelInterpolationException - { - if ( !src.contains( "${" ) ) - { + @SuppressWarnings("unchecked") + protected String interpolateInternal( + String src, List valueSources, List postProcessors, boolean debug) + throws ModelInterpolationException { + if (!src.contains("${")) { return src; } Logger logger = getLogger(); String result = src; - synchronized ( this ) - { - - for ( ValueSource vs : valueSources ) - { - interpolator.addValueSource( vs ); + synchronized (this) { + for (ValueSource vs : valueSources) { + interpolator.addValueSource(vs); } - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - interpolator.addPostProcessor( postProcessor ); + for (InterpolationPostProcessor postProcessor : postProcessors) { + interpolator.addPostProcessor(postProcessor); } - try - { - try - { - result = interpolator.interpolate( result, recursionInterceptor ); - } - catch ( InterpolationException e ) - { - throw new ModelInterpolationException( e.getMessage(), e ); + try { + try { + result = interpolator.interpolate(result, recursionInterceptor); + } catch (InterpolationException e) { + throw new ModelInterpolationException(e.getMessage(), e); } - if ( debug ) - { + if (debug) { List feedback = interpolator.getFeedback(); - if ( feedback != null && !feedback.isEmpty() ) - { - logger.debug( "Maven encountered the following problems during initial POM interpolation:" ); + if (feedback != null && !feedback.isEmpty()) { + logger.debug("Maven encountered the following problems during initial POM interpolation:"); Object last = null; - for ( Object next : feedback ) - { - if ( next instanceof Throwable ) - { - if ( last == null ) - { - logger.debug( "", ( (Throwable) next ) ); + for (Object next : feedback) { + if (next instanceof Throwable) { + if (last == null) { + logger.debug("", ((Throwable) next)); + } else { + logger.debug(String.valueOf(last), ((Throwable) next)); } - else - { - logger.debug( String.valueOf( last ), ( (Throwable) next ) ); - } - } - else - { - if ( last != null ) - { - logger.debug( String.valueOf( last ) ); + } else { + if (last != null) { + logger.debug(String.valueOf(last)); } last = next; } } - if ( last != null ) - { - logger.debug( String.valueOf( last ) ); + if (last != null) { + logger.debug(String.valueOf(last)); } } } interpolator.clearFeedback(); - } - finally - { - for ( ValueSource vs : valueSources ) - { - interpolator.removeValuesSource( vs ); + } finally { + for (ValueSource vs : valueSources) { + interpolator.removeValuesSource(vs); } - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - interpolator.removePostProcessor( postProcessor ); + for (InterpolationPostProcessor postProcessor : postProcessors) { + interpolator.removePostProcessor(postProcessor); } } } @@ -379,28 +309,22 @@ public abstract class AbstractStringBasedModelInterpolator return result; } - protected RecursionInterceptor getRecursionInterceptor() - { + protected RecursionInterceptor getRecursionInterceptor() { return recursionInterceptor; } - protected void setRecursionInterceptor( RecursionInterceptor recursionInterceptor ) - { + protected void setRecursionInterceptor(RecursionInterceptor recursionInterceptor) { this.recursionInterceptor = recursionInterceptor; } protected abstract Interpolator createInterpolator(); - public void initialize() - throws InitializationException - { + public void initialize() throws InitializationException { interpolator = createInterpolator(); - recursionInterceptor = new PrefixAwareRecursionInterceptor( PROJECT_PREFIXES ); + recursionInterceptor = new PrefixAwareRecursionInterceptor(PROJECT_PREFIXES); } - protected final Interpolator getInterpolator() - { + protected final Interpolator getInterpolator() { return interpolator; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/BuildTimestampValueSource.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/BuildTimestampValueSource.java index f6319fa664..e416743e62 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/BuildTimestampValueSource.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/BuildTimestampValueSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,19 +16,17 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.interpolation; import java.text.SimpleDateFormat; import java.util.Date; - import org.codehaus.plexus.interpolation.AbstractValueSource; /** * */ @Deprecated -public class BuildTimestampValueSource - extends AbstractValueSource -{ +public class BuildTimestampValueSource extends AbstractValueSource { private final Date startTime; @@ -38,20 +34,16 @@ public class BuildTimestampValueSource private String formattedDate; - public BuildTimestampValueSource( Date startTime, String format ) - { - super( false ); + public BuildTimestampValueSource(Date startTime, String format) { + super(false); this.startTime = startTime; this.format = format; } - public Object getValue( String expression ) - { - if ( "build.timestamp".equals( expression ) || "maven.build.timestamp".equals( expression ) ) - { - if ( formattedDate == null && startTime != null ) - { - formattedDate = new SimpleDateFormat( format ).format( startTime ); + public Object getValue(String expression) { + if ("build.timestamp".equals(expression) || "maven.build.timestamp".equals(expression)) { + if (formattedDate == null && startTime != null) { + formattedDate = new SimpleDateFormat(format).format(startTime); } return formattedDate; @@ -59,5 +51,4 @@ public class BuildTimestampValueSource return null; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolationException.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolationException.java index ea60f16299..11217b53f8 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolationException.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,53 +16,45 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.interpolation; /** * @author jdcasey */ -@SuppressWarnings( "serial" ) +@SuppressWarnings("serial") @Deprecated -public class ModelInterpolationException - extends Exception -{ +public class ModelInterpolationException extends Exception { private String expression; private String originalMessage; - public ModelInterpolationException( String message ) - { - super( message ); + public ModelInterpolationException(String message) { + super(message); } - public ModelInterpolationException( String message, Throwable cause ) - { - super( message, cause ); + public ModelInterpolationException(String message, Throwable cause) { + super(message, cause); } - public ModelInterpolationException( String expression, String message, Throwable cause ) - { - super( "The POM expression: " + expression + " could not be evaluated. Reason: " + message, cause ); + public ModelInterpolationException(String expression, String message, Throwable cause) { + super("The POM expression: " + expression + " could not be evaluated. Reason: " + message, cause); this.expression = expression; this.originalMessage = message; } - public ModelInterpolationException( String expression, String message ) - { - super( "The POM expression: " + expression + " could not be evaluated. Reason: " + message ); + public ModelInterpolationException(String expression, String message) { + super("The POM expression: " + expression + " could not be evaluated. Reason: " + message); this.expression = expression; this.originalMessage = message; } - public String getExpression() - { + public String getExpression() { return expression; } - public String getOriginalMessage() - { + public String getOriginalMessage() { return originalMessage; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolator.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolator.java index 036e7f0481..6349f4a039 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/ModelInterpolator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,19 +16,18 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.model.Model; -import org.apache.maven.project.ProjectBuilderConfiguration; +package org.apache.maven.project.interpolation; import java.io.File; import java.util.Map; +import org.apache.maven.model.Model; +import org.apache.maven.project.ProjectBuilderConfiguration; /** * @author jdcasey */ @Deprecated -public interface ModelInterpolator -{ +public interface ModelInterpolator { String DEFAULT_BUILD_TIMESTAMP_FORMAT = "yyyyMMdd-HHmm"; String BUILD_TIMESTAMP_FORMAT_PROPERTY = "maven.build.timestamp.format"; @@ -40,25 +37,17 @@ public interface ModelInterpolator /** * @deprecated Use {@link ModelInterpolator#interpolate(Model, File, ProjectBuilderConfiguration, boolean)} instead. */ - Model interpolate( Model project, Map context ) - throws ModelInterpolationException; + Model interpolate(Model project, Map context) throws ModelInterpolationException; /** * @deprecated Use {@link ModelInterpolator#interpolate(Model, File, ProjectBuilderConfiguration, boolean)} instead. */ - Model interpolate( Model model, Map context, boolean strict ) - throws ModelInterpolationException; + Model interpolate(Model model, Map context, boolean strict) throws ModelInterpolationException; - Model interpolate( Model model, - File projectDir, - ProjectBuilderConfiguration config, - boolean debugEnabled ) - throws ModelInterpolationException; + Model interpolate(Model model, File projectDir, ProjectBuilderConfiguration config, boolean debugEnabled) + throws ModelInterpolationException; - String interpolate( String src, - Model model, - File projectDir, - ProjectBuilderConfiguration config, - boolean debugEnabled ) - throws ModelInterpolationException; + String interpolate( + String src, Model model, File projectDir, ProjectBuilderConfiguration config, boolean debugEnabled) + throws ModelInterpolationException; } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/PathTranslatingPostProcessor.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/PathTranslatingPostProcessor.java index da2ba05632..0ab1738a83 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/PathTranslatingPostProcessor.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/PathTranslatingPostProcessor.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,47 +16,43 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.project.path.PathTranslator; -import org.codehaus.plexus.interpolation.InterpolationPostProcessor; -import org.codehaus.plexus.interpolation.util.ValueSourceUtils; +package org.apache.maven.project.interpolation; import java.io.File; import java.util.List; +import org.apache.maven.project.path.PathTranslator; +import org.codehaus.plexus.interpolation.InterpolationPostProcessor; +import org.codehaus.plexus.interpolation.util.ValueSourceUtils; /** * */ @Deprecated -public class PathTranslatingPostProcessor - implements InterpolationPostProcessor -{ +public class PathTranslatingPostProcessor implements InterpolationPostProcessor { private final List unprefixedPathKeys; private final File projectDir; private final PathTranslator pathTranslator; private final List expressionPrefixes; - public PathTranslatingPostProcessor( List expressionPrefixes, List unprefixedPathKeys, - File projectDir, PathTranslator pathTranslator ) - { + public PathTranslatingPostProcessor( + List expressionPrefixes, + List unprefixedPathKeys, + File projectDir, + PathTranslator pathTranslator) { this.expressionPrefixes = expressionPrefixes; this.unprefixedPathKeys = unprefixedPathKeys; this.projectDir = projectDir; this.pathTranslator = pathTranslator; } - public Object execute( String expression, - Object value ) - { - expression = ValueSourceUtils.trimPrefix( expression, expressionPrefixes, true ); + public Object execute(String expression, Object value) { + expression = ValueSourceUtils.trimPrefix(expression, expressionPrefixes, true); - if ( projectDir != null && value != null && unprefixedPathKeys.contains( expression ) ) - { - return pathTranslator.alignToBaseDirectory( String.valueOf( value ), projectDir ); + if (projectDir != null && value != null && unprefixedPathKeys.contains(expression)) { + return pathTranslator.alignToBaseDirectory(String.valueOf(value), projectDir); } return value; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/RegexBasedModelInterpolator.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/RegexBasedModelInterpolator.java index 78990ea76e..bb8831be6e 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/RegexBasedModelInterpolator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/RegexBasedModelInterpolator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.interpolation; import java.io.IOException; import java.util.Properties; - import org.apache.maven.project.path.PathTranslator; import org.codehaus.plexus.interpolation.Interpolator; import org.codehaus.plexus.interpolation.RegexBasedInterpolator; @@ -33,26 +31,17 @@ import org.codehaus.plexus.interpolation.RegexBasedInterpolator; * TODO Consolidate this logic with the PluginParameterExpressionEvaluator, minus deprecations/bans. */ @Deprecated -public class RegexBasedModelInterpolator - extends AbstractStringBasedModelInterpolator -{ +public class RegexBasedModelInterpolator extends AbstractStringBasedModelInterpolator { - public RegexBasedModelInterpolator() - throws IOException - { + public RegexBasedModelInterpolator() throws IOException {} + + public RegexBasedModelInterpolator(PathTranslator pathTranslator) { + super(pathTranslator); } - public RegexBasedModelInterpolator( PathTranslator pathTranslator ) - { - super( pathTranslator ); - } + public RegexBasedModelInterpolator(Properties envars) {} - public RegexBasedModelInterpolator( Properties envars ) - { - } - - protected Interpolator createInterpolator() - { - return new RegexBasedInterpolator( true ); + protected Interpolator createInterpolator() { + return new RegexBasedInterpolator(true); } } diff --git a/maven-compat/src/main/java/org/apache/maven/project/interpolation/StringSearchModelInterpolator.java b/maven-compat/src/main/java/org/apache/maven/project/interpolation/StringSearchModelInterpolator.java index 71da2ed3b0..f3eec8e153 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/interpolation/StringSearchModelInterpolator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/interpolation/StringSearchModelInterpolator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.interpolation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.interpolation; * "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 + * 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 @@ -18,16 +16,7 @@ package org.apache.maven.project.interpolation; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.model.Model; -import org.apache.maven.project.ProjectBuilderConfiguration; -import org.apache.maven.project.path.PathTranslator; -import org.codehaus.plexus.component.annotations.Component; -import org.codehaus.plexus.interpolation.InterpolationPostProcessor; -import org.codehaus.plexus.interpolation.Interpolator; -import org.codehaus.plexus.interpolation.StringSearchInterpolator; -import org.codehaus.plexus.interpolation.ValueSource; -import org.codehaus.plexus.logging.Logger; +package org.apache.maven.project.interpolation; import java.io.File; import java.lang.reflect.Array; @@ -40,72 +29,67 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; +import org.apache.maven.model.Model; +import org.apache.maven.project.ProjectBuilderConfiguration; +import org.apache.maven.project.path.PathTranslator; +import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.interpolation.InterpolationPostProcessor; +import org.codehaus.plexus.interpolation.Interpolator; +import org.codehaus.plexus.interpolation.StringSearchInterpolator; +import org.codehaus.plexus.interpolation.ValueSource; +import org.codehaus.plexus.logging.Logger; /** * StringSearchModelInterpolator */ @Deprecated -@Component( role = ModelInterpolator.class ) -public class StringSearchModelInterpolator - extends AbstractStringBasedModelInterpolator -{ +@Component(role = ModelInterpolator.class) +public class StringSearchModelInterpolator extends AbstractStringBasedModelInterpolator { private static final Map, Field[]> FIELDS_BY_CLASS = new WeakHashMap<>(); private static final Map, Boolean> PRIMITIVE_BY_CLASS = new WeakHashMap<>(); - public StringSearchModelInterpolator() - { + public StringSearchModelInterpolator() {} + + public StringSearchModelInterpolator(PathTranslator pathTranslator) { + super(pathTranslator); } - public StringSearchModelInterpolator( PathTranslator pathTranslator ) - { - super( pathTranslator ); - } - - public Model interpolate( Model model, File projectDir, ProjectBuilderConfiguration config, boolean debugEnabled ) - throws ModelInterpolationException - { - interpolateObject( model, model, projectDir, config, debugEnabled ); + public Model interpolate(Model model, File projectDir, ProjectBuilderConfiguration config, boolean debugEnabled) + throws ModelInterpolationException { + interpolateObject(model, model, projectDir, config, debugEnabled); return model; } - protected void interpolateObject( Object obj, Model model, File projectDir, ProjectBuilderConfiguration config, - boolean debugEnabled ) - throws ModelInterpolationException - { - try - { - List valueSources = createValueSources( model, projectDir, config ); - List postProcessors = createPostProcessors( model, projectDir, config ); + protected void interpolateObject( + Object obj, Model model, File projectDir, ProjectBuilderConfiguration config, boolean debugEnabled) + throws ModelInterpolationException { + try { + List valueSources = createValueSources(model, projectDir, config); + List postProcessors = createPostProcessors(model, projectDir, config); InterpolateObjectAction action = - new InterpolateObjectAction( obj, valueSources, postProcessors, debugEnabled, - this, getLogger() ); + new InterpolateObjectAction(obj, valueSources, postProcessors, debugEnabled, this, getLogger()); - ModelInterpolationException error = AccessController.doPrivileged( action ); + ModelInterpolationException error = AccessController.doPrivileged(action); - if ( error != null ) - { + if (error != null) { throw error; } - } - finally - { + } finally { getInterpolator().clearAnswers(); } } - protected Interpolator createInterpolator() - { + protected Interpolator createInterpolator() { StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.setCacheAnswers( true ); + interpolator.setCacheAnswers(true); return interpolator; } - private static final class InterpolateObjectAction implements PrivilegedAction - { + private static final class InterpolateObjectAction implements PrivilegedAction { private final boolean debugEnabled; private final LinkedList interpolationTargets; @@ -114,33 +98,31 @@ public class StringSearchModelInterpolator private final List valueSources; private final List postProcessors; - InterpolateObjectAction( Object target, List valueSources, - List postProcessors, boolean debugEnabled, - StringSearchModelInterpolator modelInterpolator, Logger logger ) - { + InterpolateObjectAction( + Object target, + List valueSources, + List postProcessors, + boolean debugEnabled, + StringSearchModelInterpolator modelInterpolator, + Logger logger) { this.valueSources = valueSources; this.postProcessors = postProcessors; this.debugEnabled = debugEnabled; this.interpolationTargets = new LinkedList<>(); - interpolationTargets.add( target ); + interpolationTargets.add(target); this.modelInterpolator = modelInterpolator; this.logger = logger; } - public ModelInterpolationException run() - { - while ( !interpolationTargets.isEmpty() ) - { + public ModelInterpolationException run() { + while (!interpolationTargets.isEmpty()) { Object obj = interpolationTargets.removeFirst(); - try - { - traverseObjectWithParents( obj.getClass(), obj ); - } - catch ( ModelInterpolationException e ) - { + try { + traverseObjectWithParents(obj.getClass(), obj); + } catch (ModelInterpolationException e) { return e; } } @@ -148,252 +130,170 @@ public class StringSearchModelInterpolator return null; } - @SuppressWarnings( { "unchecked", "checkstyle:methodlength" } ) - private void traverseObjectWithParents( Class cls, Object target ) - throws ModelInterpolationException - { - if ( cls == null ) - { + @SuppressWarnings({"unchecked", "checkstyle:methodlength"}) + private void traverseObjectWithParents(Class cls, Object target) throws ModelInterpolationException { + if (cls == null) { return; } + if (cls.isArray()) { + evaluateArray(target); + } else if (isQualifiedForInterpolation(cls)) { + Field[] fields = FIELDS_BY_CLASS.computeIfAbsent(cls, k -> cls.getDeclaredFields()); - if ( cls.isArray() ) - { - evaluateArray( target ); - } - else if ( isQualifiedForInterpolation( cls ) ) - { - Field[] fields = FIELDS_BY_CLASS.computeIfAbsent( cls, k -> cls.getDeclaredFields() ); - - for ( Field field : fields ) - { + for (Field field : fields) { Class type = field.getType(); - if ( isQualifiedForInterpolation( field, type ) ) - { + if (isQualifiedForInterpolation(field, type)) { boolean isAccessible = field.isAccessible(); - field.setAccessible( true ); - try - { - try - { - if ( String.class == type ) - { - String value = (String) field.get( target ); - if ( value != null ) - { - String interpolated = - modelInterpolator.interpolateInternal( value, valueSources, postProcessors, - debugEnabled ); + field.setAccessible(true); + try { + try { + if (String.class == type) { + String value = (String) field.get(target); + if (value != null) { + String interpolated = modelInterpolator.interpolateInternal( + value, valueSources, postProcessors, debugEnabled); - if ( !interpolated.equals( value ) ) - { - field.set( target, interpolated ); + if (!interpolated.equals(value)) { + field.set(target, interpolated); } } - } - else if ( Collection.class.isAssignableFrom( type ) ) - { - Collection c = (Collection) field.get( target ); - if ( c != null && !c.isEmpty() ) - { - List originalValues = new ArrayList<>( c ); - try - { + } else if (Collection.class.isAssignableFrom(type)) { + Collection c = (Collection) field.get(target); + if (c != null && !c.isEmpty()) { + List originalValues = new ArrayList<>(c); + try { c.clear(); - } - catch ( UnsupportedOperationException e ) - { - if ( debugEnabled && logger != null ) - { - logger.debug( "Skipping interpolation of field: " + field + " in: " - + cls.getName() - + "; it is an unmodifiable collection." ); + } catch (UnsupportedOperationException e) { + if (debugEnabled && logger != null) { + logger.debug("Skipping interpolation of field: " + field + " in: " + + cls.getName() + + "; it is an unmodifiable collection."); } continue; } - for ( Object value : originalValues ) - { - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = - modelInterpolator.interpolateInternal( (String) value, - valueSources, - postProcessors, - debugEnabled ); + for (Object value : originalValues) { + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = modelInterpolator.interpolateInternal( + (String) value, valueSources, postProcessors, debugEnabled); - if ( !interpolated.equals( value ) ) - { - c.add( interpolated ); + if (!interpolated.equals(value)) { + c.add(interpolated); + } else { + c.add(value); } - else - { - c.add( value ); + } else { + c.add(value); + if (value.getClass().isArray()) { + evaluateArray(value); + } else { + interpolationTargets.add(value); } } - else - { - c.add( value ); - if ( value.getClass().isArray() ) - { - evaluateArray( value ); - } - else - { - interpolationTargets.add( value ); - } - } - } - else - { + } else { // add the null back in...not sure what else to do... - c.add( value ); + c.add(value); } } } - } - else if ( Map.class.isAssignableFrom( type ) ) - { - Map m = (Map) field.get( target ); - if ( m != null && !m.isEmpty() ) - { - for ( Map.Entry entry : m.entrySet() ) - { + } else if (Map.class.isAssignableFrom(type)) { + Map m = (Map) field.get(target); + if (m != null && !m.isEmpty()) { + for (Map.Entry entry : m.entrySet()) { Object value = entry.getValue(); - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = - modelInterpolator.interpolateInternal( (String) value, - valueSources, - postProcessors, - debugEnabled ); + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = modelInterpolator.interpolateInternal( + (String) value, valueSources, postProcessors, debugEnabled); - if ( !interpolated.equals( value ) ) - { - try - { - entry.setValue( interpolated ); - } - catch ( UnsupportedOperationException e ) - { - if ( debugEnabled && logger != null ) - { - logger.debug( - "Skipping interpolation of field: " + field + if (!interpolated.equals(value)) { + try { + entry.setValue(interpolated); + } catch (UnsupportedOperationException e) { + if (debugEnabled && logger != null) { + logger.debug("Skipping interpolation of field: " + field + " (key: " + entry.getKey() + ") in: " + cls.getName() - + "; it is an unmodifiable collection." ); + + "; it is an unmodifiable collection."); } } } - } - else - { - if ( value.getClass().isArray() ) - { - evaluateArray( value ); - } - else - { - interpolationTargets.add( value ); + } else { + if (value.getClass().isArray()) { + evaluateArray(value); + } else { + interpolationTargets.add(value); } } } } } - } - else - { - Object value = field.get( target ); - if ( value != null ) - { - if ( field.getType().isArray() ) - { - evaluateArray( value ); - } - else - { - interpolationTargets.add( value ); + } else { + Object value = field.get(target); + if (value != null) { + if (field.getType().isArray()) { + evaluateArray(value); + } else { + interpolationTargets.add(value); } } } - } - catch ( IllegalArgumentException | IllegalAccessException e ) - { + } catch (IllegalArgumentException | IllegalAccessException e) { throw new ModelInterpolationException( - "Failed to interpolate field: " + field + " on class: " + cls.getName(), e ); + "Failed to interpolate field: " + field + " on class: " + cls.getName(), e); } - } - finally - { - field.setAccessible( isAccessible ); + } finally { + field.setAccessible(isAccessible); } } } - traverseObjectWithParents( cls.getSuperclass(), target ); + traverseObjectWithParents(cls.getSuperclass(), target); } } - private boolean isQualifiedForInterpolation( Class cls ) - { - return !cls.getPackage().getName().startsWith( "java" ) - && !cls.getPackage().getName().startsWith( "sun.nio.fs" ); + private boolean isQualifiedForInterpolation(Class cls) { + return !cls.getPackage().getName().startsWith("java") + && !cls.getPackage().getName().startsWith("sun.nio.fs"); } - private boolean isQualifiedForInterpolation( Field field, Class fieldType ) - { - if ( !PRIMITIVE_BY_CLASS.containsKey( fieldType ) ) - { - PRIMITIVE_BY_CLASS.put( fieldType, fieldType.isPrimitive() ); + private boolean isQualifiedForInterpolation(Field field, Class fieldType) { + if (!PRIMITIVE_BY_CLASS.containsKey(fieldType)) { + PRIMITIVE_BY_CLASS.put(fieldType, fieldType.isPrimitive()); } - if ( PRIMITIVE_BY_CLASS.get( fieldType ) ) - { + if (PRIMITIVE_BY_CLASS.get(fieldType)) { return false; } -// if ( fieldType.isPrimitive() ) -// { -// return false; -// } + // if ( fieldType.isPrimitive() ) + // { + // return false; + // } - return !"parent".equals( field.getName() ); + return !"parent".equals(field.getName()); } - private void evaluateArray( Object target ) - throws ModelInterpolationException - { - int len = Array.getLength( target ); - for ( int i = 0; i < len; i++ ) - { - Object value = Array.get( target, i ); - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = - modelInterpolator.interpolateInternal( (String) value, valueSources, postProcessors, - debugEnabled ); + private void evaluateArray(Object target) throws ModelInterpolationException { + int len = Array.getLength(target); + for (int i = 0; i < len; i++) { + Object value = Array.get(target, i); + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = modelInterpolator.interpolateInternal( + (String) value, valueSources, postProcessors, debugEnabled); - if ( !interpolated.equals( value ) ) - { - Array.set( target, i, interpolated ); + if (!interpolated.equals(value)) { + Array.set(target, i, interpolated); } - } - else - { - interpolationTargets.add( value ); + } else { + interpolationTargets.add(value); } } } } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java b/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java index 79e1f410e1..68e5880f4d 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.path; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.path; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.project.path; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.path; import java.io.File; import java.util.ArrayList; import java.util.List; - import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.Reporting; @@ -33,119 +31,93 @@ import org.codehaus.plexus.component.annotations.Component; * DefaultPathTranslator */ @Deprecated -@Component( role = PathTranslator.class ) -public class DefaultPathTranslator - implements PathTranslator -{ +@Component(role = PathTranslator.class) +public class DefaultPathTranslator implements PathTranslator { private static final String[] BASEDIR_EXPRESSIONS = {"${basedir}", "${pom.basedir}", "${project.basedir}"}; - public void alignToBaseDirectory( Model model, File basedir ) - { - if ( basedir == null ) - { + public void alignToBaseDirectory(Model model, File basedir) { + if (basedir == null) { return; } Build build = model.getBuild(); - if ( build != null ) - { - build.setDirectory( alignToBaseDirectory( build.getDirectory(), basedir ) ); + if (build != null) { + build.setDirectory(alignToBaseDirectory(build.getDirectory(), basedir)); - build.setSourceDirectory( alignToBaseDirectory( build.getSourceDirectory(), basedir ) ); + build.setSourceDirectory(alignToBaseDirectory(build.getSourceDirectory(), basedir)); - build.setTestSourceDirectory( alignToBaseDirectory( build.getTestSourceDirectory(), basedir ) ); + build.setTestSourceDirectory(alignToBaseDirectory(build.getTestSourceDirectory(), basedir)); - for ( Resource resource : build.getResources() ) - { - resource.setDirectory( alignToBaseDirectory( resource.getDirectory(), basedir ) ); + for (Resource resource : build.getResources()) { + resource.setDirectory(alignToBaseDirectory(resource.getDirectory(), basedir)); } - for ( Resource resource : build.getTestResources() ) - { - resource.setDirectory( alignToBaseDirectory( resource.getDirectory(), basedir ) ); + for (Resource resource : build.getTestResources()) { + resource.setDirectory(alignToBaseDirectory(resource.getDirectory(), basedir)); } - if ( build.getFilters() != null ) - { + if (build.getFilters() != null) { List filters = new ArrayList<>(); - for ( String filter : build.getFilters() ) - { - filters.add( alignToBaseDirectory( filter, basedir ) ); + for (String filter : build.getFilters()) { + filters.add(alignToBaseDirectory(filter, basedir)); } - build.setFilters( filters ); + build.setFilters(filters); } - build.setOutputDirectory( alignToBaseDirectory( build.getOutputDirectory(), basedir ) ); + build.setOutputDirectory(alignToBaseDirectory(build.getOutputDirectory(), basedir)); - build.setTestOutputDirectory( alignToBaseDirectory( build.getTestOutputDirectory(), basedir ) ); + build.setTestOutputDirectory(alignToBaseDirectory(build.getTestOutputDirectory(), basedir)); } Reporting reporting = model.getReporting(); - if ( reporting != null ) - { - reporting.setOutputDirectory( alignToBaseDirectory( reporting.getOutputDirectory(), basedir ) ); + if (reporting != null) { + reporting.setOutputDirectory(alignToBaseDirectory(reporting.getOutputDirectory(), basedir)); } } - public String alignToBaseDirectory( String path, File basedir ) - { - if ( basedir == null ) - { + public String alignToBaseDirectory(String path, File basedir) { + if (basedir == null) { return path; } - if ( path == null ) - { + if (path == null) { return null; } - String s = stripBasedirToken( path ); + String s = stripBasedirToken(path); - File file = new File( s ); - if ( file.isAbsolute() ) - { + File file = new File(s); + if (file.isAbsolute()) { // path was already absolute, just normalize file separator and we're done s = file.getPath(); - } - else if ( file.getPath().startsWith( File.separator ) ) - { + } else if (file.getPath().startsWith(File.separator)) { // drive-relative Windows path, don't align with project directory but with drive root s = file.getAbsolutePath(); - } - else - { + } else { // an ordinary relative path, align with project directory - s = new File( new File( basedir, s ).toURI().normalize() ).getAbsolutePath(); + s = new File(new File(basedir, s).toURI().normalize()).getAbsolutePath(); } return s; } - private String stripBasedirToken( String s ) - { - if ( s != null ) - { + private String stripBasedirToken(String s) { + if (s != null) { String basedirExpr = null; - for ( String expression : BASEDIR_EXPRESSIONS ) - { - if ( s.startsWith( expression ) ) - { + for (String expression : BASEDIR_EXPRESSIONS) { + if (s.startsWith(expression)) { basedirExpr = expression; break; } } - if ( basedirExpr != null ) - { - if ( s.length() > basedirExpr.length() ) - { + if (basedirExpr != null) { + if (s.length() > basedirExpr.length()) { // Take out basedir expression and the leading slash - s = chopLeadingFileSeparator( s.substring( basedirExpr.length() ) ); - } - else - { + s = chopLeadingFileSeparator(s.substring(basedirExpr.length())); + } else { s = "."; } } @@ -161,100 +133,81 @@ public class DefaultPathTranslator * @param path The filesystem path, may be null. * @return The altered filesystem path or null if the input path was null. */ - private String chopLeadingFileSeparator( String path ) - { - if ( path != null ) - { - if ( path.startsWith( "/" ) || path.startsWith( "\\" ) ) - { - path = path.substring( 1 ); + private String chopLeadingFileSeparator(String path) { + if (path != null) { + if (path.startsWith("/") || path.startsWith("\\")) { + path = path.substring(1); } } return path; } - public void unalignFromBaseDirectory( Model model, File basedir ) - { - if ( basedir == null ) - { + public void unalignFromBaseDirectory(Model model, File basedir) { + if (basedir == null) { return; } Build build = model.getBuild(); - if ( build != null ) - { - build.setDirectory( unalignFromBaseDirectory( build.getDirectory(), basedir ) ); + if (build != null) { + build.setDirectory(unalignFromBaseDirectory(build.getDirectory(), basedir)); - build.setSourceDirectory( unalignFromBaseDirectory( build.getSourceDirectory(), basedir ) ); + build.setSourceDirectory(unalignFromBaseDirectory(build.getSourceDirectory(), basedir)); - build.setTestSourceDirectory( unalignFromBaseDirectory( build.getTestSourceDirectory(), basedir ) ); + build.setTestSourceDirectory(unalignFromBaseDirectory(build.getTestSourceDirectory(), basedir)); - for ( Resource resource : build.getResources() ) - { - resource.setDirectory( unalignFromBaseDirectory( resource.getDirectory(), basedir ) ); + for (Resource resource : build.getResources()) { + resource.setDirectory(unalignFromBaseDirectory(resource.getDirectory(), basedir)); } - for ( Resource resource : build.getTestResources() ) - { - resource.setDirectory( unalignFromBaseDirectory( resource.getDirectory(), basedir ) ); + for (Resource resource : build.getTestResources()) { + resource.setDirectory(unalignFromBaseDirectory(resource.getDirectory(), basedir)); } - if ( build.getFilters() != null ) - { + if (build.getFilters() != null) { List filters = new ArrayList<>(); - for ( String filter : build.getFilters() ) - { - filters.add( unalignFromBaseDirectory( filter, basedir ) ); + for (String filter : build.getFilters()) { + filters.add(unalignFromBaseDirectory(filter, basedir)); } - build.setFilters( filters ); + build.setFilters(filters); } - build.setOutputDirectory( unalignFromBaseDirectory( build.getOutputDirectory(), basedir ) ); + build.setOutputDirectory(unalignFromBaseDirectory(build.getOutputDirectory(), basedir)); - build.setTestOutputDirectory( unalignFromBaseDirectory( build.getTestOutputDirectory(), basedir ) ); + build.setTestOutputDirectory(unalignFromBaseDirectory(build.getTestOutputDirectory(), basedir)); } Reporting reporting = model.getReporting(); - if ( reporting != null ) - { - reporting.setOutputDirectory( unalignFromBaseDirectory( reporting.getOutputDirectory(), basedir ) ); + if (reporting != null) { + reporting.setOutputDirectory(unalignFromBaseDirectory(reporting.getOutputDirectory(), basedir)); } } - public String unalignFromBaseDirectory( String path, File basedir ) - { - if ( basedir == null ) - { + public String unalignFromBaseDirectory(String path, File basedir) { + if (basedir == null) { return path; } - if ( path == null ) - { + if (path == null) { return null; } path = path.trim(); String base = basedir.getAbsolutePath(); - if ( path.startsWith( base ) ) - { - path = chopLeadingFileSeparator( path.substring( base.length() ) ); + if (path.startsWith(base)) { + path = chopLeadingFileSeparator(path.substring(base.length())); } - if ( path.length() <= 0 ) - { + if (path.length() <= 0) { path = "."; } - if ( !new File( path ).isAbsolute() ) - { - path = path.replace( '\\', '/' ); + if (!new File(path).isAbsolute()) { + path = path.replace('\\', '/'); } return path; } - } - diff --git a/maven-compat/src/main/java/org/apache/maven/project/validation/DefaultModelValidator.java b/maven-compat/src/main/java/org/apache/maven/project/validation/DefaultModelValidator.java index 6406b5844d..87cf801b56 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/validation/DefaultModelValidator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/validation/DefaultModelValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.validation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.validation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.validation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.validation; import org.apache.maven.model.Model; import org.apache.maven.model.building.DefaultModelBuildingRequest; @@ -31,45 +30,37 @@ import org.codehaus.plexus.component.annotations.Requirement; /** * @author Trygve Laugstøl */ -@Component( role = ModelValidator.class ) +@Component(role = ModelValidator.class) @Deprecated -public class DefaultModelValidator - implements ModelValidator -{ +public class DefaultModelValidator implements ModelValidator { @Requirement private org.apache.maven.model.validation.ModelValidator modelValidator; - public ModelValidationResult validate( Model model ) - { + public ModelValidationResult validate(Model model) { ModelValidationResult result = new ModelValidationResult(); ModelBuildingRequest request = - new DefaultModelBuildingRequest().setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ); + new DefaultModelBuildingRequest().setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0); - SimpleModelProblemCollector problems = new SimpleModelProblemCollector( result ); + SimpleModelProblemCollector problems = new SimpleModelProblemCollector(result); - modelValidator.validateEffectiveModel( model, request, problems ); + modelValidator.validateEffectiveModel(model, request, problems); return result; } - private static class SimpleModelProblemCollector - implements ModelProblemCollector - { + private static class SimpleModelProblemCollector implements ModelProblemCollector { ModelValidationResult result; - SimpleModelProblemCollector( ModelValidationResult result ) - { + SimpleModelProblemCollector(ModelValidationResult result) { this.result = result; } - public void add( ModelProblemCollectorRequest req ) - { - if ( !ModelProblem.Severity.WARNING.equals( req.getSeverity() ) ) - { - result.addMessage( req.getMessage() ); + public void add(ModelProblemCollectorRequest req) { + if (!ModelProblem.Severity.WARNING.equals(req.getSeverity())) { + result.addMessage(req.getMessage()); } } } diff --git a/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidationResult.java b/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidationResult.java index 9e2966e92d..b44fc280c0 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidationResult.java +++ b/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidationResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.validation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.validation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.validation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.validation; import java.util.ArrayList; import java.util.Collections; @@ -26,8 +25,7 @@ import java.util.List; /** * @author Trygve Laugstøl */ -public class ModelValidationResult -{ +public class ModelValidationResult { /** */ private static final String LS = System.lineSeparator(); @@ -35,61 +33,55 @@ public class ModelValidationResult /** */ private List messages; - public ModelValidationResult() - { + public ModelValidationResult() { messages = new ArrayList<>(); } - public int getMessageCount() - { + public int getMessageCount() { return messages.size(); } - public String getMessage( int i ) - { - return messages.get( i ); + public String getMessage(int i) { + return messages.get(i); } - public List getMessages() - { - return Collections.unmodifiableList( messages ); + public List getMessages() { + return Collections.unmodifiableList(messages); } - public void addMessage( String message ) - { - messages.add( message ); + public void addMessage(String message) { + messages.add(message); } - public String toString() - { - return render( "" ); + public String toString() { + return render(""); } - public String render( String indentation ) - { - if ( messages.size() == 0 ) - { + public String render(String indentation) { + if (messages.size() == 0) { return indentation + "There were no validation errors."; } StringBuilder message = new StringBuilder(); -// if ( messages.size() == 1 ) -// { -// message.append( "There was 1 validation error: " ); -// } -// else -// { -// message.append( "There was " + messages.size() + " validation errors: " + LS ); -// } -// - for ( int i = 0; i < messages.size(); i++ ) - { - message.append( indentation ).append( '[' ).append( i ).append( "] " ).append( messages.get( i ) ).append( - LS ); + // if ( messages.size() == 1 ) + // { + // message.append( "There was 1 validation error: " ); + // } + // else + // { + // message.append( "There was " + messages.size() + " validation errors: " + LS ); + // } + // + for (int i = 0; i < messages.size(); i++) { + message.append(indentation) + .append('[') + .append(i) + .append("] ") + .append(messages.get(i)) + .append(LS); } return message.toString(); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidator.java b/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidator.java index 54fd04cad8..81d69694da 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.validation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.validation; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.validation; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.validation; import org.apache.maven.model.Model; @@ -27,11 +26,9 @@ import org.apache.maven.model.Model; * @author Trygve Laugstøl */ @Deprecated -public interface ModelValidator -{ +public interface ModelValidator { String ROLE = ModelValidator.class.getName(); - ModelValidationResult validate( Model model ); - + ModelValidationResult validate(Model model); } diff --git a/maven-compat/src/main/java/org/apache/maven/reporting/MavenReportException.java b/maven-compat/src/main/java/org/apache/maven/reporting/MavenReportException.java index af27a84056..06c1ebefed 100644 --- a/maven-compat/src/main/java/org/apache/maven/reporting/MavenReportException.java +++ b/maven-compat/src/main/java/org/apache/maven/reporting/MavenReportException.java @@ -1,5 +1,3 @@ -package org.apache.maven.reporting; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.reporting; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.reporting; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.reporting; /** * An exception occurring during the execution of a Maven report. @@ -25,15 +24,12 @@ package org.apache.maven.reporting; * @author Brett Porter * @author Emmanuel Venisse */ -public class MavenReportException extends Exception -{ - public MavenReportException( String msg ) - { - super( msg ); +public class MavenReportException extends Exception { + public MavenReportException(String msg) { + super(msg); } - public MavenReportException( String msg, Exception e ) - { - super( msg, e ); + public MavenReportException(String msg, Exception e) { + super(msg, e); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/DefaultMirrorSelector.java b/maven-compat/src/main/java/org/apache/maven/repository/DefaultMirrorSelector.java index 5c176e69b3..697dd484b5 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/DefaultMirrorSelector.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/DefaultMirrorSelector.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.net.MalformedURLException; import java.net.URL; import java.util.List; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.settings.Mirror; @@ -32,10 +30,8 @@ import org.codehaus.plexus.util.StringUtils; /** * DefaultMirrorSelector */ -@Component( role = MirrorSelector.class ) -public class DefaultMirrorSelector - implements MirrorSelector -{ +@Component(role = MirrorSelector.class) +public class DefaultMirrorSelector implements MirrorSelector { private static final String WILDCARD = "*"; @@ -43,24 +39,18 @@ public class DefaultMirrorSelector private static final String EXTERNAL_HTTP_WILDCARD = "external:http:*"; - public Mirror getMirror( ArtifactRepository repository, List mirrors ) - { + public Mirror getMirror(ArtifactRepository repository, List mirrors) { String repoId = repository.getId(); - if ( repoId != null && mirrors != null ) - { - for ( Mirror mirror : mirrors ) - { - if ( repoId.equals( mirror.getMirrorOf() ) && matchesLayout( repository, mirror ) ) - { + if (repoId != null && mirrors != null) { + for (Mirror mirror : mirrors) { + if (repoId.equals(mirror.getMirrorOf()) && matchesLayout(repository, mirror)) { return mirror; } } - for ( Mirror mirror : mirrors ) - { - if ( matchPattern( repository, mirror.getMirrorOf() ) && matchesLayout( repository, mirror ) ) - { + for (Mirror mirror : mirrors) { + if (matchPattern(repository, mirror.getMirrorOf()) && matchesLayout(repository, mirror)) { return mirror; } } @@ -83,53 +73,41 @@ public class DefaultMirrorSelector * @param pattern used for match. * @return true if the repository is a match to this pattern. */ - static boolean matchPattern( ArtifactRepository originalRepository, String pattern ) - { + static boolean matchPattern(ArtifactRepository originalRepository, String pattern) { boolean result = false; String originalId = originalRepository.getId(); // simple checks first to short circuit processing below. - if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) ) - { + if (WILDCARD.equals(pattern) || pattern.equals(originalId)) { result = true; - } - else - { + } else { // process the list - String[] repos = pattern.split( "," ); - for ( String repo : repos ) - { + String[] repos = pattern.split(","); + for (String repo : repos) { repo = repo.trim(); // see if this is a negative match - if ( repo.length() > 1 && repo.startsWith( "!" ) ) - { - if ( repo.substring( 1 ).equals( originalId ) ) - { + if (repo.length() > 1 && repo.startsWith("!")) { + if (repo.substring(1).equals(originalId)) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match - else if ( repo.equals( originalId ) ) - { + else if (repo.equals(originalId)) { result = true; break; } // check for external:* - else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( originalRepository ) ) - { + else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } // check for external:http:* - else if ( EXTERNAL_HTTP_WILDCARD.equals( repo ) && isExternalHttpRepo( originalRepository ) ) - { + else if (EXTERNAL_HTTP_WILDCARD.equals(repo) && isExternalHttpRepo(originalRepository)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo - } - else if ( WILDCARD.equals( repo ) ) - { + } else if (WILDCARD.equals(repo)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } @@ -144,23 +122,18 @@ public class DefaultMirrorSelector * @param originalRepository * @return true if external. */ - static boolean isExternalRepo( ArtifactRepository originalRepository ) - { - try - { - URL url = new URL( originalRepository.getUrl() ); - return !( isLocal( url.getHost() ) || url.getProtocol().equals( "file" ) ); - } - catch ( MalformedURLException e ) - { + static boolean isExternalRepo(ArtifactRepository originalRepository) { + try { + URL url = new URL(originalRepository.getUrl()); + return !(isLocal(url.getHost()) || url.getProtocol().equals("file")); + } catch (MalformedURLException e) { // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it return false; } } - private static boolean isLocal( String host ) - { - return "localhost".equals( host ) || "127.0.0.1".equals( host ); + private static boolean isLocal(String host) { + return "localhost".equals(host) || "127.0.0.1".equals(host); } /** @@ -169,25 +142,22 @@ public class DefaultMirrorSelector * @param originalRepository * @return true if external. */ - static boolean isExternalHttpRepo( ArtifactRepository originalRepository ) - { - try - { - URL url = new URL( originalRepository.getUrl() ); - return ( "http".equalsIgnoreCase( url.getProtocol() ) || "dav".equalsIgnoreCase( url.getProtocol() ) - || "dav:http".equalsIgnoreCase( url.getProtocol() ) - || "dav+http".equalsIgnoreCase( url.getProtocol() ) ) && !isLocal( url.getHost() ); - } - catch ( MalformedURLException e ) - { + static boolean isExternalHttpRepo(ArtifactRepository originalRepository) { + try { + URL url = new URL(originalRepository.getUrl()); + return ("http".equalsIgnoreCase(url.getProtocol()) + || "dav".equalsIgnoreCase(url.getProtocol()) + || "dav:http".equalsIgnoreCase(url.getProtocol()) + || "dav+http".equalsIgnoreCase(url.getProtocol())) + && !isLocal(url.getHost()); + } catch (MalformedURLException e) { // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it return false; } } - static boolean matchesLayout( ArtifactRepository repository, Mirror mirror ) - { - return matchesLayout( RepositoryUtils.getLayout( repository ), mirror.getMirrorOfLayouts() ); + static boolean matchesLayout(ArtifactRepository repository, Mirror mirror) { + return matchesLayout(RepositoryUtils.getLayout(repository), mirror.getMirrorOfLayouts()); } /** @@ -198,43 +168,31 @@ public class DefaultMirrorSelector * @return {@code true} if the layouts associated with the mirror match the layout of the original repository, * {@code false} otherwise. */ - static boolean matchesLayout( String repoLayout, String mirrorLayout ) - { + static boolean matchesLayout(String repoLayout, String mirrorLayout) { boolean result = false; // simple checks first to short circuit processing below. - if ( StringUtils.isEmpty( mirrorLayout ) || WILDCARD.equals( mirrorLayout ) ) - { + if (StringUtils.isEmpty(mirrorLayout) || WILDCARD.equals(mirrorLayout)) { result = true; - } - else if ( mirrorLayout.equals( repoLayout ) ) - { + } else if (mirrorLayout.equals(repoLayout)) { result = true; - } - else - { + } else { // process the list - String[] layouts = mirrorLayout.split( "," ); - for ( String layout : layouts ) - { + String[] layouts = mirrorLayout.split(","); + for (String layout : layouts) { // see if this is a negative match - if ( layout.length() > 1 && layout.startsWith( "!" ) ) - { - if ( layout.substring( 1 ).equals( repoLayout ) ) - { + if (layout.length() > 1 && layout.startsWith("!")) { + if (layout.substring(1).equals(repoLayout)) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match - else if ( layout.equals( repoLayout ) ) - { + else if (layout.equals(repoLayout)) { result = true; break; - } - else if ( WILDCARD.equals( layout ) ) - { + } else if (WILDCARD.equals(layout)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } @@ -243,5 +201,4 @@ public class DefaultMirrorSelector return result; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/MavenArtifactMetadata.java b/maven-compat/src/main/java/org/apache/maven/repository/MavenArtifactMetadata.java index c507bf7027..fc66a970c7 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/MavenArtifactMetadata.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/MavenArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; /** * @@ -25,8 +24,7 @@ package org.apache.maven.repository; * @author Oleg Gusakov * */ -public class MavenArtifactMetadata -{ +public class MavenArtifactMetadata { public static final String DEFAULT_TYPE = "jar"; String groupId; @@ -38,82 +36,66 @@ public class MavenArtifactMetadata transient Object datum; - public String getGroupId() - { + public String getGroupId() { return groupId; } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public void setClassifier( String classifier ) - { + public void setClassifier(String classifier) { this.classifier = classifier; } - public String getType() - { + public String getType() { return type; } - public void setType( String type ) - { + public void setType(String type) { this.type = type; } - public Object getDatum() - { + public Object getDatum() { return datum; } - public void setDatum( Object datum ) - { + public void setDatum(Object datum) { this.datum = datum; } - public String getScope() - { + public String getScope() { return scope; } - public void setScope( String scope ) - { + public void setScope(String scope) { this.scope = scope; } @Override - public String toString() - { + public String toString() { return getGroupId() + ":" + getArtifactId() + ":" + getVersion() + ":" - + ( getClassifier() == null ? "" : getClassifier() ) + ":" - + ( getType() == null ? DEFAULT_TYPE : getType() ); + + (getClassifier() == null ? "" : getClassifier()) + ":" + + (getType() == null ? DEFAULT_TYPE : getType()); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraph.java b/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraph.java index 3568ff0260..3ebc60e7b0 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraph.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraph.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.util.ArrayList; import java.util.Collection; @@ -28,29 +27,25 @@ import java.util.Collection; * @author Oleg Gusakov * */ -public class MetadataGraph -{ +public class MetadataGraph { /** all graph nodes */ Collection nodes; /** entry point for tree-like structures */ MetadataGraphNode entry; - public MetadataGraph( MetadataGraphNode entry ) - { + public MetadataGraph(MetadataGraphNode entry) { this(); this.entry = entry; } - public MetadataGraph() - { - nodes = new ArrayList<>( 64 ); + public MetadataGraph() { + nodes = new ArrayList<>(64); } - public void addNode( MetadataGraphNode node ) - { - nodes.add( node ); + public void addNode(MetadataGraphNode node) { + nodes.add(node); } /** @@ -58,34 +53,29 @@ public class MetadataGraph * * @param md */ - public MetadataGraphNode findNode( MavenArtifactMetadata md ) - { - for ( MetadataGraphNode mgn : nodes ) - { - if ( mgn.metadata.equals( md ) ) - { + public MetadataGraphNode findNode(MavenArtifactMetadata md) { + for (MetadataGraphNode mgn : nodes) { + if (mgn.metadata.equals(md)) { return mgn; } } - MetadataGraphNode node = new MetadataGraphNode( md ); - addNode( node ); + MetadataGraphNode node = new MetadataGraphNode(md); + addNode(node); return node; } /** * getter */ - public MetadataGraphNode getEntry() - { + public MetadataGraphNode getEntry() { return entry; } /** * getter */ - public Collection getNodes() - { + public Collection getNodes() { return nodes; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraphNode.java b/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraphNode.java index c258f05a6e..a91647165b 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraphNode.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraphNode.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.util.ArrayList; import java.util.List; @@ -28,8 +27,7 @@ import java.util.List; * @author Oleg Gusakov * */ -public class MetadataGraphNode -{ +public class MetadataGraphNode { /** node payload */ MavenArtifactMetadata metadata; @@ -39,60 +37,48 @@ public class MetadataGraphNode /** nodes, exident to this (I depend on) */ List exNodes; - public MetadataGraphNode() - { - inNodes = new ArrayList<>( 4 ); - exNodes = new ArrayList<>( 8 ); + public MetadataGraphNode() { + inNodes = new ArrayList<>(4); + exNodes = new ArrayList<>(8); } - public MetadataGraphNode( MavenArtifactMetadata metadata ) - { + public MetadataGraphNode(MavenArtifactMetadata metadata) { this(); this.metadata = metadata; } - public MetadataGraphNode addIncident( MetadataGraphNode node ) - { - inNodes.add( node ); + public MetadataGraphNode addIncident(MetadataGraphNode node) { + inNodes.add(node); return this; } - public MetadataGraphNode addExident( MetadataGraphNode node ) - { - exNodes.add( node ); + public MetadataGraphNode addExident(MetadataGraphNode node) { + exNodes.add(node); return this; } @Override - public boolean equals( Object obj ) - { - if ( obj == null ) - { + public boolean equals(Object obj) { + if (obj == null) { return false; } - if ( MetadataGraphNode.class.isAssignableFrom( obj.getClass() ) ) - { + if (MetadataGraphNode.class.isAssignableFrom(obj.getClass())) { MetadataGraphNode node2 = (MetadataGraphNode) obj; - if ( node2.metadata == null ) - { + if (node2.metadata == null) { return metadata == null; } - return metadata != null && metadata.toString().equals( node2.metadata.toString() ); - } - else - { - return super.equals( obj ); + return metadata != null && metadata.toString().equals(node2.metadata.toString()); + } else { + return super.equals(obj); } } @Override - public int hashCode() - { - if ( metadata == null ) - { + public int hashCode() { + if (metadata == null) { return super.hashCode(); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionRequest.java b/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionRequest.java index ea0cd73431..c44eafe2b9 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionRequest.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -32,8 +30,7 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * @author Oleg Gusakov * */ -public class MetadataResolutionRequest -{ +public class MetadataResolutionRequest { private MavenArtifactMetadata mad; private String scope; @@ -60,49 +57,40 @@ public class MetadataResolutionRequest /** result type - graph */ private boolean asGraph = false; - public MetadataResolutionRequest() - { - } + public MetadataResolutionRequest() {} - public MetadataResolutionRequest( MavenArtifactMetadata md, ArtifactRepository localRepository, - List remoteRepositories ) - { + public MetadataResolutionRequest( + MavenArtifactMetadata md, ArtifactRepository localRepository, List remoteRepositories) { this.mad = md; this.localRepository = localRepository; this.remoteRepositories = remoteRepositories; } - public MavenArtifactMetadata getArtifactMetadata() - { + public MavenArtifactMetadata getArtifactMetadata() { return mad; } - public MetadataResolutionRequest setArtifactMetadata( MavenArtifactMetadata md ) - { + public MetadataResolutionRequest setArtifactMetadata(MavenArtifactMetadata md) { this.mad = md; return this; } - public MetadataResolutionRequest setArtifactDependencies( Set artifactDependencies ) - { + public MetadataResolutionRequest setArtifactDependencies(Set artifactDependencies) { this.artifactDependencies = artifactDependencies; return this; } - public Set getArtifactDependencies() - { + public Set getArtifactDependencies() { return artifactDependencies; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } - public MetadataResolutionRequest setLocalRepository( ArtifactRepository localRepository ) - { + public MetadataResolutionRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; return this; @@ -112,13 +100,11 @@ public class MetadataResolutionRequest * @deprecated instead use {@link #getRemoteRepositories()} */ @Deprecated - public List getRemoteRepostories() - { + public List getRemoteRepostories() { return remoteRepositories; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return getRemoteRepostories(); } @@ -126,95 +112,87 @@ public class MetadataResolutionRequest * @deprecated instead use {@link #setRemoteRepositories(List)} */ @Deprecated - public MetadataResolutionRequest setRemoteRepostories( List remoteRepositories ) - { + public MetadataResolutionRequest setRemoteRepostories(List remoteRepositories) { this.remoteRepositories = remoteRepositories; return this; } - public MetadataResolutionRequest setRemoteRepositories( List remoteRepositories ) - { - return setRemoteRepostories( remoteRepositories ); + public MetadataResolutionRequest setRemoteRepositories(List remoteRepositories) { + return setRemoteRepostories(remoteRepositories); } - public Map getManagedVersionMap() - { + public Map getManagedVersionMap() { return managedVersionMap; } - public MetadataResolutionRequest setManagedVersionMap( Map managedVersionMap ) - { + public MetadataResolutionRequest setManagedVersionMap(Map managedVersionMap) { this.managedVersionMap = managedVersionMap; return this; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder() - .append( "REQUEST: " ).append( "\n" ) - .append( "artifact: " ).append( mad ).append( "\n" ) - .append( artifactDependencies ).append( "\n" ) - .append( "localRepository: " ).append( localRepository ).append( "\n" ) - .append( "remoteRepositories: " ).append( remoteRepositories ).append( "\n" ) - ; + .append("REQUEST: ") + .append("\n") + .append("artifact: ") + .append(mad) + .append("\n") + .append(artifactDependencies) + .append("\n") + .append("localRepository: ") + .append(localRepository) + .append("\n") + .append("remoteRepositories: ") + .append(remoteRepositories) + .append("\n"); return sb.toString(); } - public boolean isAsList() - { + public boolean isAsList() { return asList; } - public MetadataResolutionRequest setAsList( boolean asList ) - { + public MetadataResolutionRequest setAsList(boolean asList) { this.asList = asList; return this; } - public boolean isAsDirtyTree() - { + public boolean isAsDirtyTree() { return asDirtyTree; } - public MetadataResolutionRequest setAsDirtyTree( boolean asDirtyTree ) - { + public MetadataResolutionRequest setAsDirtyTree(boolean asDirtyTree) { this.asDirtyTree = asDirtyTree; return this; } - public boolean isAsResolvedTree() - { + public boolean isAsResolvedTree() { return asResolvedTree; } - public MetadataResolutionRequest setAsResolvedTree( boolean asResolvedTree ) - { + public MetadataResolutionRequest setAsResolvedTree(boolean asResolvedTree) { this.asResolvedTree = asResolvedTree; return this; } - public boolean isAsGraph() - { + public boolean isAsGraph() { return asGraph; } - public MetadataResolutionRequest setAsGraph( boolean asGraph ) - { + public MetadataResolutionRequest setAsGraph(boolean asGraph) { this.asGraph = asGraph; return this; } - public MetadataResolutionRequest setScope( String scope ) - { + public MetadataResolutionRequest setScope(String scope) { this.scope = scope; return this; } - public String getScope() - { + public String getScope() { return scope; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionResult.java b/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionResult.java index 2d1c5db44b..d22c0a24a4 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionResult.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionException; @@ -37,8 +35,7 @@ import org.apache.maven.artifact.versioning.OverConstrainedVersionException; * @author Oleg Gusakov * */ -public class MetadataResolutionResult -{ +public class MetadataResolutionResult { private Artifact originatingArtifact; private List missingArtifacts; @@ -69,72 +66,57 @@ public class MetadataResolutionResult private MetadataGraph resolvedGraph; - public Artifact getOriginatingArtifact() - { + public Artifact getOriginatingArtifact() { return originatingArtifact; } - public MetadataResolutionResult listOriginatingArtifact( final Artifact originatingArtifact ) - { + public MetadataResolutionResult listOriginatingArtifact(final Artifact originatingArtifact) { this.originatingArtifact = originatingArtifact; return this; } - public void addArtifact( Artifact artifact ) - { - if ( artifacts == null ) - { + public void addArtifact(Artifact artifact) { + if (artifacts == null) { artifacts = new LinkedHashSet<>(); } - artifacts.add( artifact ); + artifacts.add(artifact); } - public Set getArtifacts() - { + public Set getArtifacts() { return artifacts; } - public void addRequestedArtifact( Artifact artifact ) - { - if ( requestedArtifacts == null ) - { + public void addRequestedArtifact(Artifact artifact) { + if (requestedArtifacts == null) { requestedArtifacts = new LinkedHashSet<>(); } - requestedArtifacts.add( artifact ); + requestedArtifacts.add(artifact); } - public Set getRequestedArtifacts() - { + public Set getRequestedArtifacts() { return requestedArtifacts; } - public boolean hasMissingArtifacts() - { + public boolean hasMissingArtifacts() { return missingArtifacts != null && !missingArtifacts.isEmpty(); } - public List getMissingArtifacts() - { - return missingArtifacts == null - ? Collections.emptyList() - : Collections.unmodifiableList( missingArtifacts ); - + public List getMissingArtifacts() { + return missingArtifacts == null ? Collections.emptyList() : Collections.unmodifiableList(missingArtifacts); } - public MetadataResolutionResult addMissingArtifact( Artifact artifact ) - { - missingArtifacts = initList( missingArtifacts ); + public MetadataResolutionResult addMissingArtifact(Artifact artifact) { + missingArtifacts = initList(missingArtifacts); - missingArtifacts.add( artifact ); + missingArtifacts.add(artifact); return this; } - public MetadataResolutionResult setUnresolvedArtifacts( final List unresolvedArtifacts ) - { + public MetadataResolutionResult setUnresolvedArtifacts(final List unresolvedArtifacts) { this.missingArtifacts = unresolvedArtifacts; return this; @@ -144,25 +126,19 @@ public class MetadataResolutionResult // Exceptions // ------------------------------------------------------------------------ - public boolean hasExceptions() - { + public boolean hasExceptions() { return exceptions != null && !exceptions.isEmpty(); } - public List getExceptions() - { - return exceptions == null - ? Collections.emptyList() - : Collections.unmodifiableList( exceptions ); - + public List getExceptions() { + return exceptions == null ? Collections.emptyList() : Collections.unmodifiableList(exceptions); } // ------------------------------------------------------------------------ // Version Range Violations // ------------------------------------------------------------------------ - public boolean hasVersionRangeViolations() - { + public boolean hasVersionRangeViolations() { return versionRangeViolations != null; } @@ -171,148 +147,127 @@ public class MetadataResolutionResult * {@link #getVersionRangeViolation(int)} but it's not used like that in * {@link org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector} */ - public MetadataResolutionResult addVersionRangeViolation( Exception e ) - { - versionRangeViolations = initList( versionRangeViolations ); + public MetadataResolutionResult addVersionRangeViolation(Exception e) { + versionRangeViolations = initList(versionRangeViolations); - versionRangeViolations.add( e ); + versionRangeViolations.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public OverConstrainedVersionException getVersionRangeViolation( int i ) - { - return (OverConstrainedVersionException) versionRangeViolations.get( i ); + public OverConstrainedVersionException getVersionRangeViolation(int i) { + return (OverConstrainedVersionException) versionRangeViolations.get(i); } - public List getVersionRangeViolations() - { + public List getVersionRangeViolations() { return versionRangeViolations == null - ? Collections.emptyList() - : Collections.unmodifiableList( versionRangeViolations ); - + ? Collections.emptyList() + : Collections.unmodifiableList(versionRangeViolations); } // ------------------------------------------------------------------------ // Metadata Resolution Exceptions: ArtifactResolutionExceptions // ------------------------------------------------------------------------ - public boolean hasMetadataResolutionExceptions() - { + public boolean hasMetadataResolutionExceptions() { return metadataResolutionExceptions != null; } - public MetadataResolutionResult addMetadataResolutionException( ArtifactResolutionException e ) - { - metadataResolutionExceptions = initList( metadataResolutionExceptions ); + public MetadataResolutionResult addMetadataResolutionException(ArtifactResolutionException e) { + metadataResolutionExceptions = initList(metadataResolutionExceptions); - metadataResolutionExceptions.add( e ); + metadataResolutionExceptions.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public ArtifactResolutionException getMetadataResolutionException( int i ) - { - return metadataResolutionExceptions.get( i ); + public ArtifactResolutionException getMetadataResolutionException(int i) { + return metadataResolutionExceptions.get(i); } - public List getMetadataResolutionExceptions() - { + public List getMetadataResolutionExceptions() { return metadataResolutionExceptions == null - ? Collections.emptyList() - : Collections.unmodifiableList( metadataResolutionExceptions ); - + ? Collections.emptyList() + : Collections.unmodifiableList(metadataResolutionExceptions); } // ------------------------------------------------------------------------ // ErrorArtifactExceptions: ArtifactResolutionExceptions // ------------------------------------------------------------------------ - public boolean hasErrorArtifactExceptions() - { + public boolean hasErrorArtifactExceptions() { return errorArtifactExceptions != null; } - public MetadataResolutionResult addError( Exception e ) - { - exceptions = initList( exceptions ); + public MetadataResolutionResult addError(Exception e) { + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public List getErrorArtifactExceptions() - { - if ( errorArtifactExceptions == null ) - { + public List getErrorArtifactExceptions() { + if (errorArtifactExceptions == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( errorArtifactExceptions ); + return Collections.unmodifiableList(errorArtifactExceptions); } // ------------------------------------------------------------------------ // Circular Dependency Exceptions // ------------------------------------------------------------------------ - public boolean hasCircularDependencyExceptions() - { + public boolean hasCircularDependencyExceptions() { return circularDependencyExceptions != null; } - public MetadataResolutionResult addCircularDependencyException( CyclicDependencyException e ) - { - circularDependencyExceptions = initList( circularDependencyExceptions ); + public MetadataResolutionResult addCircularDependencyException(CyclicDependencyException e) { + circularDependencyExceptions = initList(circularDependencyExceptions); - circularDependencyExceptions.add( e ); + circularDependencyExceptions.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public CyclicDependencyException getCircularDependencyException( int i ) - { - return circularDependencyExceptions.get( i ); + public CyclicDependencyException getCircularDependencyException(int i) { + return circularDependencyExceptions.get(i); } - public List getCircularDependencyExceptions() - { - if ( circularDependencyExceptions == null ) - { + public List getCircularDependencyExceptions() { + if (circularDependencyExceptions == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( circularDependencyExceptions ); + return Collections.unmodifiableList(circularDependencyExceptions); } // ------------------------------------------------------------------------ // Repositories // ------------------------------------------------------------------------ - public List getRepositories() - { - if ( repositories == null ) - { + public List getRepositories() { + if (repositories == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( repositories ); + return Collections.unmodifiableList(repositories); } - public MetadataResolutionResult setRepositories( final List repositories ) - { + public MetadataResolutionResult setRepositories(final List repositories) { this.repositories = repositories; return this; @@ -322,42 +277,34 @@ public class MetadataResolutionResult // Internal // - private List initList( final List l ) - { - if ( l == null ) - { + private List initList(final List l) { + if (l == null) { return new ArrayList<>(); } return l; } - public String toString() - { - if ( artifacts == null ) - { + public String toString() { + if (artifacts == null) { return ""; } - StringBuilder sb = new StringBuilder( 256 ); + StringBuilder sb = new StringBuilder(256); int i = 1; - sb.append( "---------\n" ); - sb.append( artifacts.size() ).append( '\n' ); - for ( Artifact a : artifacts ) - { - sb.append( i ).append( ' ' ).append( a ).append( '\n' ); + sb.append("---------\n"); + sb.append(artifacts.size()).append('\n'); + for (Artifact a : artifacts) { + sb.append(i).append(' ').append(a).append('\n'); i++; } - sb.append( "---------\n" ); + sb.append("---------\n"); return sb.toString(); } - public MetadataGraph getResolvedTree() - { + public MetadataGraph getResolvedTree() { return resolvedTree; } - public void setResolvedTree( MetadataGraph resolvedTree ) - { + public void setResolvedTree(MetadataGraph resolvedTree) { this.resolvedTree = resolvedTree; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/MirrorSelector.java b/maven-compat/src/main/java/org/apache/maven/repository/MirrorSelector.java index c15899ed44..b5f0bb3db8 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/MirrorSelector.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/MirrorSelector.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.util.List; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.settings.Mirror; @@ -29,8 +27,7 @@ import org.apache.maven.settings.Mirror; * * @author Benjamin Bentmann */ -public interface MirrorSelector -{ +public interface MirrorSelector { /** * Determines the mirror for the specified repository. @@ -39,6 +36,5 @@ public interface MirrorSelector * @param mirrors The available mirrors, may be {@code null}. * @return The mirror specification for the repository or {@code null} if no mirror matched. */ - Mirror getMirror( ArtifactRepository repository, List mirrors ); - + Mirror getMirror(ArtifactRepository repository, List mirrors); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/UserLocalArtifactRepository.java b/maven-compat/src/main/java/org/apache/maven/repository/UserLocalArtifactRepository.java index a88b0096e4..3915ea1960 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/UserLocalArtifactRepository.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/UserLocalArtifactRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.io.File; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -28,50 +26,42 @@ import org.apache.maven.artifact.repository.ArtifactRepository; /** * UserLocalArtifactRepository */ -public class UserLocalArtifactRepository - extends LocalArtifactRepository -{ +public class UserLocalArtifactRepository extends LocalArtifactRepository { private ArtifactRepository localRepository; - public UserLocalArtifactRepository( ArtifactRepository localRepository ) - { + public UserLocalArtifactRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; - setLayout( localRepository.getLayout() ); + setLayout(localRepository.getLayout()); } @Override - public Artifact find( Artifact artifact ) - { - File artifactFile = new File( localRepository.getBasedir(), pathOf( artifact ) ); + public Artifact find(Artifact artifact) { + File artifactFile = new File(localRepository.getBasedir(), pathOf(artifact)); // We need to set the file here or the resolver will fail with an NPE, not fully equipped to deal // with multiple local repository implementations yet. - artifact.setFile( artifactFile ); + artifact.setFile(artifactFile); return artifact; } @Override - public String getId() - { + public String getId() { return localRepository.getId(); } @Override - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return localRepository.pathOfLocalRepositoryMetadata( metadata, repository ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return localRepository.pathOfLocalRepositoryMetadata(metadata, repository); } @Override - public String pathOf( Artifact artifact ) - { - return localRepository.pathOf( artifact ); + public String pathOf(Artifact artifact) { + return localRepository.pathOf(artifact); } @Override - public boolean hasLocalMetadata() - { + public boolean hasLocalMetadata() { return true; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/VersionNotFoundException.java b/maven-compat/src/main/java/org/apache/maven/repository/VersionNotFoundException.java index 77b1af1273..ba11652838 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/VersionNotFoundException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/VersionNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.io.File; - import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.model.Dependency; @@ -30,20 +28,19 @@ import org.apache.maven.model.Dependency; * * @author Brett Porter */ -public class VersionNotFoundException - extends Exception -{ +public class VersionNotFoundException extends Exception { private Dependency dependency; private String projectId; private File pomFile; private InvalidVersionSpecificationException cause; - public VersionNotFoundException( String projectId, Dependency dependency, File pomFile, - InvalidVersionSpecificationException cause ) - { - super( projectId + ", " + formatLocationInPom( dependency ) + " " + dependency.getVersion() + ", pom file " - + pomFile, cause ); + public VersionNotFoundException( + String projectId, Dependency dependency, File pomFile, InvalidVersionSpecificationException cause) { + super( + projectId + ", " + formatLocationInPom(dependency) + " " + dependency.getVersion() + ", pom file " + + pomFile, + cause); this.projectId = projectId; @@ -54,30 +51,23 @@ public class VersionNotFoundException this.dependency = dependency; } - private static String formatLocationInPom( Dependency dependency ) - { - return "Dependency: " + ArtifactUtils.versionlessKey( dependency.getGroupId(), dependency.getArtifactId() ); + private static String formatLocationInPom(Dependency dependency) { + return "Dependency: " + ArtifactUtils.versionlessKey(dependency.getGroupId(), dependency.getArtifactId()); } - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } - public String getProjectId() - { + public String getProjectId() { return projectId; } - public File getPomFile() - { + public File getPomFile() { return pomFile; } - public InvalidVersionSpecificationException getCauseException() - { + public InvalidVersionSpecificationException getCauseException() { return cause; } - - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/ChecksumFailedException.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/ChecksumFailedException.java index 4e0c4a6bfc..7236a6120b 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/ChecksumFailedException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/ChecksumFailedException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import org.apache.maven.wagon.TransferFailedException; @@ -26,17 +25,12 @@ import org.apache.maven.wagon.TransferFailedException; * * @author Brett Porter */ -public class ChecksumFailedException - extends TransferFailedException -{ - public ChecksumFailedException( String s ) - { - super( s ); +public class ChecksumFailedException extends TransferFailedException { + public ChecksumFailedException(String s) { + super(s); } - public ChecksumFailedException( String message, - Throwable cause ) - { - super( message, cause ); + public ChecksumFailedException(String message, Throwable cause) { + super(message, cause); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java index 993ac5efd4..e538c934e5 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,16 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; -import org.apache.maven.artifact.repository.Authentication; -import org.apache.maven.artifact.repository.metadata.RepositoryMetadata; -import org.apache.maven.repository.Proxy; -import org.codehaus.plexus.component.annotations.Component; -import org.codehaus.plexus.logging.AbstractLogEnabled; -import org.codehaus.plexus.logging.Logger; +package org.apache.maven.repository.legacy; import java.io.File; import java.io.FileInputStream; @@ -38,359 +27,300 @@ import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.Date; import java.util.Properties; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +import org.apache.maven.artifact.repository.Authentication; +import org.apache.maven.artifact.repository.metadata.RepositoryMetadata; +import org.apache.maven.repository.Proxy; +import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.logging.AbstractLogEnabled; +import org.codehaus.plexus.logging.Logger; /** * DefaultUpdateCheckManager */ -@Component( role = UpdateCheckManager.class ) -public class DefaultUpdateCheckManager - extends AbstractLogEnabled - implements UpdateCheckManager -{ +@Component(role = UpdateCheckManager.class) +public class DefaultUpdateCheckManager extends AbstractLogEnabled implements UpdateCheckManager { private static final String ERROR_KEY_SUFFIX = ".error"; - public DefaultUpdateCheckManager() - { + public DefaultUpdateCheckManager() {} - } - - public DefaultUpdateCheckManager( Logger logger ) - { - enableLogging( logger ); + public DefaultUpdateCheckManager(Logger logger) { + enableLogging(logger); } public static final String LAST_UPDATE_TAG = ".lastUpdated"; private static final String TOUCHFILE_NAME = "resolver-status.properties"; - public boolean isUpdateRequired( Artifact artifact, ArtifactRepository repository ) - { + public boolean isUpdateRequired(Artifact artifact, ArtifactRepository repository) { File file = artifact.getFile(); ArtifactRepositoryPolicy policy = artifact.isSnapshot() ? repository.getSnapshots() : repository.getReleases(); - if ( !policy.isEnabled() ) - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( - "Skipping update check for " + artifact + " (" + file + ") from " + repository.getId() + " (" - + repository.getUrl() + ")" ); + if (!policy.isEnabled()) { + if (getLogger().isDebugEnabled()) { + getLogger() + .debug("Skipping update check for " + artifact + " (" + file + ") from " + repository.getId() + + " (" + repository.getUrl() + ")"); } return false; } - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( - "Determining update check for " + artifact + " (" + file + ") from " + repository.getId() + " (" - + repository.getUrl() + ")" ); + if (getLogger().isDebugEnabled()) { + getLogger() + .debug("Determining update check for " + artifact + " (" + file + ") from " + repository.getId() + + " (" + repository.getUrl() + ")"); } - if ( file == null ) - { + if (file == null) { // TODO throw something instead? return true; } Date lastCheckDate; - if ( file.exists() ) - { - lastCheckDate = new Date( file.lastModified() ); - } - else - { - File touchfile = getTouchfile( artifact ); - lastCheckDate = readLastUpdated( touchfile, getRepositoryKey( repository ) ); + if (file.exists()) { + lastCheckDate = new Date(file.lastModified()); + } else { + File touchfile = getTouchfile(artifact); + lastCheckDate = readLastUpdated(touchfile, getRepositoryKey(repository)); } - return ( lastCheckDate == null ) || policy.checkOutOfDate( lastCheckDate ); + return (lastCheckDate == null) || policy.checkOutOfDate(lastCheckDate); } - public boolean isUpdateRequired( RepositoryMetadata metadata, ArtifactRepository repository, File file ) - { + public boolean isUpdateRequired(RepositoryMetadata metadata, ArtifactRepository repository, File file) { // Here, we need to determine which policy to use. Release updateInterval will be used when // the metadata refers to a release artifact or meta-version, and snapshot updateInterval will be used when // it refers to a snapshot artifact or meta-version. // NOTE: Release metadata includes version information about artifacts that have been released, to allow // meta-versions like RELEASE and LATEST to resolve, and also to allow retrieval of the range of valid, released // artifacts available. - ArtifactRepositoryPolicy policy = metadata.getPolicy( repository ); + ArtifactRepositoryPolicy policy = metadata.getPolicy(repository); - if ( !policy.isEnabled() ) - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( - "Skipping update check for " + metadata.getKey() + " (" + file + ") from " + repository.getId() - + " (" + repository.getUrl() + ")" ); + if (!policy.isEnabled()) { + if (getLogger().isDebugEnabled()) { + getLogger() + .debug("Skipping update check for " + metadata.getKey() + " (" + file + ") from " + + repository.getId() + " (" + repository.getUrl() + ")"); } return false; } - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( - "Determining update check for " + metadata.getKey() + " (" + file + ") from " + repository.getId() - + " (" + repository.getUrl() + ")" ); + if (getLogger().isDebugEnabled()) { + getLogger() + .debug("Determining update check for " + metadata.getKey() + " (" + file + ") from " + + repository.getId() + " (" + repository.getUrl() + ")"); } - if ( file == null ) - { + if (file == null) { // TODO throw something instead? return true; } - Date lastCheckDate = readLastUpdated( metadata, repository, file ); + Date lastCheckDate = readLastUpdated(metadata, repository, file); - return ( lastCheckDate == null ) || policy.checkOutOfDate( lastCheckDate ); + return (lastCheckDate == null) || policy.checkOutOfDate(lastCheckDate); } - private Date readLastUpdated( RepositoryMetadata metadata, ArtifactRepository repository, File file ) - { - File touchfile = getTouchfile( metadata, file ); + private Date readLastUpdated(RepositoryMetadata metadata, ArtifactRepository repository, File file) { + File touchfile = getTouchfile(metadata, file); - String key = getMetadataKey( repository, file ); + String key = getMetadataKey(repository, file); - return readLastUpdated( touchfile, key ); + return readLastUpdated(touchfile, key); } - public String getError( Artifact artifact, ArtifactRepository repository ) - { - File touchFile = getTouchfile( artifact ); - return getError( touchFile, getRepositoryKey( repository ) ); + public String getError(Artifact artifact, ArtifactRepository repository) { + File touchFile = getTouchfile(artifact); + return getError(touchFile, getRepositoryKey(repository)); } - public void touch( Artifact artifact, ArtifactRepository repository, String error ) - { + public void touch(Artifact artifact, ArtifactRepository repository, String error) { File file = artifact.getFile(); - File touchfile = getTouchfile( artifact ); + File touchfile = getTouchfile(artifact); - if ( file.exists() ) - { + if (file.exists()) { touchfile.delete(); - } - else - { - writeLastUpdated( touchfile, getRepositoryKey( repository ), error ); + } else { + writeLastUpdated(touchfile, getRepositoryKey(repository), error); } } - public void touch( RepositoryMetadata metadata, ArtifactRepository repository, File file ) - { - File touchfile = getTouchfile( metadata, file ); + public void touch(RepositoryMetadata metadata, ArtifactRepository repository, File file) { + File touchfile = getTouchfile(metadata, file); - String key = getMetadataKey( repository, file ); + String key = getMetadataKey(repository, file); - writeLastUpdated( touchfile, key, null ); + writeLastUpdated(touchfile, key, null); } - String getMetadataKey( ArtifactRepository repository, File file ) - { + String getMetadataKey(ArtifactRepository repository, File file) { return repository.getId() + '.' + file.getName() + LAST_UPDATE_TAG; } - String getRepositoryKey( ArtifactRepository repository ) - { - StringBuilder buffer = new StringBuilder( 256 ); + String getRepositoryKey(ArtifactRepository repository) { + StringBuilder buffer = new StringBuilder(256); Proxy proxy = repository.getProxy(); - if ( proxy != null ) - { - if ( proxy.getUserName() != null ) - { - int hash = ( proxy.getUserName() + proxy.getPassword() ).hashCode(); - buffer.append( hash ).append( '@' ); + if (proxy != null) { + if (proxy.getUserName() != null) { + int hash = (proxy.getUserName() + proxy.getPassword()).hashCode(); + buffer.append(hash).append('@'); } - buffer.append( proxy.getHost() ).append( ':' ).append( proxy.getPort() ).append( '>' ); + buffer.append(proxy.getHost()).append(':').append(proxy.getPort()).append('>'); } // consider the username&password because a repo manager might block artifacts depending on authorization Authentication auth = repository.getAuthentication(); - if ( auth != null ) - { - int hash = ( auth.getUsername() + auth.getPassword() ).hashCode(); - buffer.append( hash ).append( '@' ); + if (auth != null) { + int hash = (auth.getUsername() + auth.getPassword()).hashCode(); + buffer.append(hash).append('@'); } // consider the URL (instead of the id) as this most closely relates to the contents in the repo - buffer.append( repository.getUrl() ); + buffer.append(repository.getUrl()); return buffer.toString(); } - private void writeLastUpdated( File touchfile, String key, String error ) - { - synchronized ( touchfile.getAbsolutePath().intern() ) - { - if ( !touchfile.getParentFile().exists() && !touchfile.getParentFile().mkdirs() ) - { - getLogger().debug( "Failed to create directory: " + touchfile.getParent() - + " for tracking artifact metadata resolution." ); + private void writeLastUpdated(File touchfile, String key, String error) { + synchronized (touchfile.getAbsolutePath().intern()) { + if (!touchfile.getParentFile().exists() + && !touchfile.getParentFile().mkdirs()) { + getLogger() + .debug("Failed to create directory: " + touchfile.getParent() + + " for tracking artifact metadata resolution."); return; } FileChannel channel = null; FileLock lock = null; - try - { + try { Properties props = new Properties(); - channel = new RandomAccessFile( touchfile, "rw" ).getChannel(); + channel = new RandomAccessFile(touchfile, "rw").getChannel(); lock = channel.lock(); - if ( touchfile.canRead() ) - { - getLogger().debug( "Reading resolution-state from: " + touchfile ); - props.load( Channels.newInputStream( channel ) ); + if (touchfile.canRead()) { + getLogger().debug("Reading resolution-state from: " + touchfile); + props.load(Channels.newInputStream(channel)); } - props.setProperty( key, Long.toString( System.currentTimeMillis() ) ); + props.setProperty(key, Long.toString(System.currentTimeMillis())); - if ( error != null ) - { - props.setProperty( key + ERROR_KEY_SUFFIX, error ); - } - else - { - props.remove( key + ERROR_KEY_SUFFIX ); + if (error != null) { + props.setProperty(key + ERROR_KEY_SUFFIX, error); + } else { + props.remove(key + ERROR_KEY_SUFFIX); } - getLogger().debug( "Writing resolution-state to: " + touchfile ); - channel.truncate( 0 ); - props.store( Channels.newOutputStream( channel ), "Last modified on: " + new Date() ); + getLogger().debug("Writing resolution-state to: " + touchfile); + channel.truncate(0); + props.store(Channels.newOutputStream(channel), "Last modified on: " + new Date()); lock.release(); lock = null; channel.close(); channel = null; - } - catch ( IOException e ) - { - getLogger().debug( - "Failed to record lastUpdated information for resolution.\nFile: " + touchfile.toString() - + "; key: " + key, e ); - } - finally - { - if ( lock != null ) - { - try - { + } catch (IOException e) { + getLogger() + .debug( + "Failed to record lastUpdated information for resolution.\nFile: " + + touchfile.toString() + "; key: " + key, + e); + } finally { + if (lock != null) { + try { lock.release(); - } - catch ( IOException e ) - { - getLogger().debug( "Error releasing exclusive lock for resolution tracking file: " + touchfile, - e ); + } catch (IOException e) { + getLogger() + .debug("Error releasing exclusive lock for resolution tracking file: " + touchfile, e); } } - if ( channel != null ) - { - try - { + if (channel != null) { + try { channel.close(); - } - catch ( IOException e ) - { - getLogger().debug( "Error closing FileChannel for resolution tracking file: " + touchfile, e ); + } catch (IOException e) { + getLogger().debug("Error closing FileChannel for resolution tracking file: " + touchfile, e); } } } } } - Date readLastUpdated( File touchfile, String key ) - { - getLogger().debug( "Searching for " + key + " in resolution tracking file." ); + Date readLastUpdated(File touchfile, String key) { + getLogger().debug("Searching for " + key + " in resolution tracking file."); - Properties props = read( touchfile ); - if ( props != null ) - { - String rawVal = props.getProperty( key ); - if ( rawVal != null ) - { - try - { - return new Date( Long.parseLong( rawVal ) ); - } - catch ( NumberFormatException e ) - { - getLogger().debug( "Cannot parse lastUpdated date: '" + rawVal + "'. Ignoring.", e ); + Properties props = read(touchfile); + if (props != null) { + String rawVal = props.getProperty(key); + if (rawVal != null) { + try { + return new Date(Long.parseLong(rawVal)); + } catch (NumberFormatException e) { + getLogger().debug("Cannot parse lastUpdated date: '" + rawVal + "'. Ignoring.", e); } } } return null; } - private String getError( File touchFile, String key ) - { - Properties props = read( touchFile ); - if ( props != null ) - { - return props.getProperty( key + ERROR_KEY_SUFFIX ); + private String getError(File touchFile, String key) { + Properties props = read(touchFile); + if (props != null) { + return props.getProperty(key + ERROR_KEY_SUFFIX); } return null; } - private Properties read( File touchfile ) - { - if ( !touchfile.canRead() ) - { - getLogger().debug( "Skipped unreadable resolution tracking file: " + touchfile ); + private Properties read(File touchfile) { + if (!touchfile.canRead()) { + getLogger().debug("Skipped unreadable resolution tracking file: " + touchfile); return null; } - synchronized ( touchfile.getAbsolutePath().intern() ) - { - try - { + synchronized (touchfile.getAbsolutePath().intern()) { + try { Properties props = new Properties(); - try ( FileInputStream in = new FileInputStream( touchfile ) ) - { - try ( FileLock lock = in.getChannel().lock( 0, Long.MAX_VALUE, true ) ) - { - getLogger().debug( "Reading resolution-state from: " + touchfile ); - props.load( in ); + try (FileInputStream in = new FileInputStream(touchfile)) { + try (FileLock lock = in.getChannel().lock(0, Long.MAX_VALUE, true)) { + getLogger().debug("Reading resolution-state from: " + touchfile); + props.load(in); return props; } } - } - catch ( IOException e ) - { - getLogger().debug( "Failed to read resolution tracking file: " + touchfile, e ); + } catch (IOException e) { + getLogger().debug("Failed to read resolution tracking file: " + touchfile, e); return null; } } } - File getTouchfile( Artifact artifact ) - { - StringBuilder sb = new StringBuilder( 128 ); - sb.append( artifact.getArtifactId() ); - sb.append( '-' ).append( artifact.getBaseVersion() ); - if ( artifact.getClassifier() != null ) - { - sb.append( '-' ).append( artifact.getClassifier() ); + File getTouchfile(Artifact artifact) { + StringBuilder sb = new StringBuilder(128); + sb.append(artifact.getArtifactId()); + sb.append('-').append(artifact.getBaseVersion()); + if (artifact.getClassifier() != null) { + sb.append('-').append(artifact.getClassifier()); } - sb.append( '.' ).append( artifact.getType() ).append( LAST_UPDATE_TAG ); - return new File( artifact.getFile().getParentFile(), sb.toString() ); + sb.append('.').append(artifact.getType()).append(LAST_UPDATE_TAG); + return new File(artifact.getFile().getParentFile(), sb.toString()); } - File getTouchfile( RepositoryMetadata metadata, File file ) - { - return new File( file.getParent(), TOUCHFILE_NAME ); + File getTouchfile(RepositoryMetadata metadata, File file) { + return new File(file.getParent(), TOUCHFILE_NAME); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java index 3272ddec91..1fc946b99f 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import java.io.File; import java.io.IOException; @@ -28,7 +27,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -56,30 +54,22 @@ import org.codehaus.plexus.util.FileUtils; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.util.ConfigUtils; -//TODO remove the update check manager -//TODO separate into retriever and publisher -//TODO remove hardcoding of checksum logic +// TODO remove the update check manager +// TODO separate into retriever and publisher +// TODO remove hardcoding of checksum logic /** * Manages Wagon related operations in Maven. */ -@Component( role = WagonManager.class ) -public class DefaultWagonManager - implements WagonManager -{ +@Component(role = WagonManager.class) +public class DefaultWagonManager implements WagonManager { - private static final String[] CHECKSUM_IDS = - { - "md5", "sha1" - }; + private static final String[] CHECKSUM_IDS = {"md5", "sha1"}; /** * have to match the CHECKSUM_IDS */ - private static final String[] CHECKSUM_ALGORITHMS = - { - "MD5", "SHA-1" - }; + private static final String[] CHECKSUM_ALGORITHMS = {"MD5", "SHA-1"}; @Requirement private Logger logger; @@ -97,154 +87,132 @@ public class DefaultWagonManager // Retriever // @Override - public void getArtifact( Artifact artifact, ArtifactRepository repository, TransferListener downloadMonitor, - boolean force ) - throws TransferFailedException, ResourceDoesNotExistException - { - String remotePath = repository.pathOf( artifact ); + public void getArtifact( + Artifact artifact, ArtifactRepository repository, TransferListener downloadMonitor, boolean force) + throws TransferFailedException, ResourceDoesNotExistException { + String remotePath = repository.pathOf(artifact); ArtifactRepositoryPolicy policy = artifact.isSnapshot() ? repository.getSnapshots() : repository.getReleases(); - if ( !policy.isEnabled() ) - { - logger.debug( "Skipping disabled repository " + repository.getId() + " for resolution of " - + artifact.getId() ); + if (!policy.isEnabled()) { + logger.debug( + "Skipping disabled repository " + repository.getId() + " for resolution of " + artifact.getId()); - } - else if ( artifact.isSnapshot() || !artifact.getFile().exists() ) - { - if ( force || updateCheckManager.isUpdateRequired( artifact, repository ) ) - { - logger.debug( "Trying repository " + repository.getId() + " for resolution of " + artifact.getId() - + " from " + remotePath ); + } else if (artifact.isSnapshot() || !artifact.getFile().exists()) { + if (force || updateCheckManager.isUpdateRequired(artifact, repository)) { + logger.debug("Trying repository " + repository.getId() + " for resolution of " + artifact.getId() + + " from " + remotePath); - try - { - getRemoteFile( repository, artifact.getFile(), remotePath, downloadMonitor, - policy.getChecksumPolicy(), false ); + try { + getRemoteFile( + repository, + artifact.getFile(), + remotePath, + downloadMonitor, + policy.getChecksumPolicy(), + false); - updateCheckManager.touch( artifact, repository, null ); - } - catch ( ResourceDoesNotExistException e ) - { - updateCheckManager.touch( artifact, repository, null ); + updateCheckManager.touch(artifact, repository, null); + } catch (ResourceDoesNotExistException e) { + updateCheckManager.touch(artifact, repository, null); throw e; - } - catch ( TransferFailedException e ) - { - String error = ( e.getMessage() != null ) ? e.getMessage() : e.getClass().getSimpleName(); - updateCheckManager.touch( artifact, repository, error ); + } catch (TransferFailedException e) { + String error = (e.getMessage() != null) + ? e.getMessage() + : e.getClass().getSimpleName(); + updateCheckManager.touch(artifact, repository, error); throw e; } - logger.debug( " Artifact " + artifact.getId() + " resolved to " + artifact.getFile() ); + logger.debug(" Artifact " + artifact.getId() + " resolved to " + artifact.getFile()); - artifact.setResolved( true ); - } - else if ( !artifact.getFile().exists() ) - { - String error = updateCheckManager.getError( artifact, repository ); - if ( error != null ) - { - throw new TransferFailedException( - "Failure to resolve " + remotePath + " from " + repository.getUrl() + artifact.setResolved(true); + } else if (!artifact.getFile().exists()) { + String error = updateCheckManager.getError(artifact, repository); + if (error != null) { + throw new TransferFailedException("Failure to resolve " + remotePath + " from " + + repository.getUrl() + " was cached in the local repository. " + "Resolution will not be reattempted until the update interval of " - + repository.getId() + " has elapsed or updates are forced. Original error: " + error ); + + repository.getId() + " has elapsed or updates are forced. Original error: " + error); - } - else - { + } else { throw new ResourceDoesNotExistException( - "Failure to resolve " + remotePath + " from " + repository.getUrl() - + " was cached in the local repository. " - + "Resolution will not be reattempted until the update interval of " - + repository.getId() + " has elapsed or updates are forced." ); - + "Failure to resolve " + remotePath + " from " + repository.getUrl() + + " was cached in the local repository. " + + "Resolution will not be reattempted until the update interval of " + + repository.getId() + " has elapsed or updates are forced."); } } } } @Override - public void getArtifact( Artifact artifact, List remoteRepositories, - TransferListener downloadMonitor, boolean force ) - throws TransferFailedException, ResourceDoesNotExistException - { + public void getArtifact( + Artifact artifact, + List remoteRepositories, + TransferListener downloadMonitor, + boolean force) + throws TransferFailedException, ResourceDoesNotExistException { TransferFailedException tfe = null; - for ( ArtifactRepository repository : remoteRepositories ) - { - try - { - getArtifact( artifact, repository, downloadMonitor, force ); + for (ArtifactRepository repository : remoteRepositories) { + try { + getArtifact(artifact, repository, downloadMonitor, force); - if ( artifact.isResolved() ) - { - artifact.setRepository( repository ); + if (artifact.isResolved()) { + artifact.setRepository(repository); break; } - } - catch ( ResourceDoesNotExistException e ) - { + } catch (ResourceDoesNotExistException e) { // This one we will eat when looking through remote repositories // because we want to cycle through them all before squawking. - logger.debug( "Unable to find artifact " + artifact.getId() + " in repository " + repository.getId() - + " (" + repository.getUrl() + ")", e ); + logger.debug( + "Unable to find artifact " + artifact.getId() + " in repository " + repository.getId() + " (" + + repository.getUrl() + ")", + e); - } - catch ( TransferFailedException e ) - { + } catch (TransferFailedException e) { tfe = e; - String msg = - "Unable to get artifact " + artifact.getId() + " from repository " + repository.getId() + " (" - + repository.getUrl() + "): " + e.getMessage(); + String msg = "Unable to get artifact " + artifact.getId() + " from repository " + repository.getId() + + " (" + repository.getUrl() + "): " + e.getMessage(); - if ( logger.isDebugEnabled() ) - { - logger.warn( msg, e ); - } - else - { - logger.warn( msg ); + if (logger.isDebugEnabled()) { + logger.warn(msg, e); + } else { + logger.warn(msg); } } } // if it already exists locally we were just trying to force it - ignore the update - if ( !artifact.getFile().exists() ) - { - if ( tfe != null ) - { + if (!artifact.getFile().exists()) { + if (tfe != null) { throw tfe; - } - else - { - throw new ResourceDoesNotExistException( "Unable to download the artifact from any repository" ); + } else { + throw new ResourceDoesNotExistException("Unable to download the artifact from any repository"); } } } @Override - public void getArtifactMetadata( ArtifactMetadata metadata, ArtifactRepository repository, File destination, - String checksumPolicy ) - throws TransferFailedException, ResourceDoesNotExistException - { - String remotePath = repository.pathOfRemoteRepositoryMetadata( metadata ); + public void getArtifactMetadata( + ArtifactMetadata metadata, ArtifactRepository repository, File destination, String checksumPolicy) + throws TransferFailedException, ResourceDoesNotExistException { + String remotePath = repository.pathOfRemoteRepositoryMetadata(metadata); - getRemoteFile( repository, destination, remotePath, null, checksumPolicy, true ); + getRemoteFile(repository, destination, remotePath, null, checksumPolicy, true); } @Override - public void getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository repository, - File destination, String checksumPolicy ) - throws TransferFailedException, ResourceDoesNotExistException - { - String remotePath = repository.pathOfRemoteRepositoryMetadata( metadata ); + public void getArtifactMetadataFromDeploymentRepository( + ArtifactMetadata metadata, ArtifactRepository repository, File destination, String checksumPolicy) + throws TransferFailedException, ResourceDoesNotExistException { + String remotePath = repository.pathOfRemoteRepositoryMetadata(metadata); - getRemoteFile( repository, destination, remotePath, null, checksumPolicy, true ); + getRemoteFile(repository, destination, remotePath, null, checksumPolicy, true); } /** @@ -256,120 +224,104 @@ public class DefaultWagonManager * @throws ConnectionException * @throws AuthenticationException */ - private void connectWagon( Wagon wagon, ArtifactRepository repository ) - throws ConnectionException, AuthenticationException - { + private void connectWagon(Wagon wagon, ArtifactRepository repository) + throws ConnectionException, AuthenticationException { // MNG-5509 // See org.eclipse.aether.connector.wagon.WagonRepositoryConnector.connectWagon(Wagon) - if ( legacySupport.getRepositorySession() != null ) - { - String userAgent = ConfigUtils.getString( legacySupport.getRepositorySession(), null, - ConfigurationProperties.USER_AGENT ); + if (legacySupport.getRepositorySession() != null) { + String userAgent = ConfigUtils.getString( + legacySupport.getRepositorySession(), null, ConfigurationProperties.USER_AGENT); - if ( userAgent == null ) - { + if (userAgent == null) { Properties headers = new Properties(); - headers.put( "User-Agent", ConfigUtils.getString( legacySupport.getRepositorySession(), "Maven", - ConfigurationProperties.USER_AGENT ) ); - try - { - Method setHttpHeaders = wagon.getClass().getMethod( "setHttpHeaders", Properties.class ); - setHttpHeaders.invoke( wagon, headers ); - } - catch ( NoSuchMethodException e ) - { + headers.put( + "User-Agent", + ConfigUtils.getString( + legacySupport.getRepositorySession(), "Maven", ConfigurationProperties.USER_AGENT)); + try { + Method setHttpHeaders = wagon.getClass().getMethod("setHttpHeaders", Properties.class); + setHttpHeaders.invoke(wagon, headers); + } catch (NoSuchMethodException e) { // normal for non-http wagons - } - catch ( Exception e ) - { - logger.debug( "Could not set user agent for wagon " + wagon.getClass().getName() + ": " + e ); + } catch (Exception e) { + logger.debug("Could not set user agent for wagon " + + wagon.getClass().getName() + ": " + e); } } } - if ( repository.getProxy() != null && logger.isDebugEnabled() ) - { - logger.debug( "Using proxy " + repository.getProxy().getHost() + ":" + repository.getProxy().getPort() - + " for " + repository.getUrl() ); - + if (repository.getProxy() != null && logger.isDebugEnabled()) { + logger.debug("Using proxy " + repository.getProxy().getHost() + ":" + + repository.getProxy().getPort() + " for " + repository.getUrl()); } - if ( repository.getAuthentication() != null && repository.getProxy() != null ) - { - wagon.connect( new Repository( repository.getId(), repository.getUrl() ), authenticationInfo( repository ), - proxyInfo( repository ) ); + if (repository.getAuthentication() != null && repository.getProxy() != null) { + wagon.connect( + new Repository(repository.getId(), repository.getUrl()), + authenticationInfo(repository), + proxyInfo(repository)); - } - else if ( repository.getAuthentication() != null ) - { - wagon.connect( new Repository( repository.getId(), repository.getUrl() ), - authenticationInfo( repository ) ); + } else if (repository.getAuthentication() != null) { + wagon.connect(new Repository(repository.getId(), repository.getUrl()), authenticationInfo(repository)); - } - else if ( repository.getProxy() != null ) - { - wagon.connect( new Repository( repository.getId(), repository.getUrl() ), proxyInfo( repository ) ); - } - else - { - wagon.connect( new Repository( repository.getId(), repository.getUrl() ) ); + } else if (repository.getProxy() != null) { + wagon.connect(new Repository(repository.getId(), repository.getUrl()), proxyInfo(repository)); + } else { + wagon.connect(new Repository(repository.getId(), repository.getUrl())); } } - private AuthenticationInfo authenticationInfo( ArtifactRepository repository ) - { + private AuthenticationInfo authenticationInfo(ArtifactRepository repository) { AuthenticationInfo ai = new AuthenticationInfo(); - ai.setUserName( repository.getAuthentication().getUsername() ); - ai.setPassword( repository.getAuthentication().getPassword() ); + ai.setUserName(repository.getAuthentication().getUsername()); + ai.setPassword(repository.getAuthentication().getPassword()); return ai; } - private ProxyInfo proxyInfo( ArtifactRepository repository ) - { + private ProxyInfo proxyInfo(ArtifactRepository repository) { ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setHost( repository.getProxy().getHost() ); - proxyInfo.setType( repository.getProxy().getProtocol() ); - proxyInfo.setPort( repository.getProxy().getPort() ); - proxyInfo.setNonProxyHosts( repository.getProxy().getNonProxyHosts() ); - proxyInfo.setUserName( repository.getProxy().getUserName() ); - proxyInfo.setPassword( repository.getProxy().getPassword() ); + proxyInfo.setHost(repository.getProxy().getHost()); + proxyInfo.setType(repository.getProxy().getProtocol()); + proxyInfo.setPort(repository.getProxy().getPort()); + proxyInfo.setNonProxyHosts(repository.getProxy().getNonProxyHosts()); + proxyInfo.setUserName(repository.getProxy().getUserName()); + proxyInfo.setPassword(repository.getProxy().getPassword()); return proxyInfo; } - @SuppressWarnings( "checkstyle:methodlength" ) + @SuppressWarnings("checkstyle:methodlength") @Override - public void getRemoteFile( ArtifactRepository repository, File destination, String remotePath, - TransferListener downloadMonitor, String checksumPolicy, boolean force ) - throws TransferFailedException, ResourceDoesNotExistException - { + public void getRemoteFile( + ArtifactRepository repository, + File destination, + String remotePath, + TransferListener downloadMonitor, + String checksumPolicy, + boolean force) + throws TransferFailedException, ResourceDoesNotExistException { String protocol = repository.getProtocol(); Wagon wagon; - try - { - wagon = getWagon( protocol ); - } - catch ( UnsupportedProtocolException e ) - { - throw new TransferFailedException( "Unsupported Protocol: '" + protocol + "': " + e.getMessage(), e ); + try { + wagon = getWagon(protocol); + } catch (UnsupportedProtocolException e) { + throw new TransferFailedException("Unsupported Protocol: '" + protocol + "': " + e.getMessage(), e); } - if ( downloadMonitor != null ) - { - wagon.addTransferListener( downloadMonitor ); + if (downloadMonitor != null) { + wagon.addTransferListener(downloadMonitor); } - File temp = new File( destination + ".tmp" ); + File temp = new File(destination + ".tmp"); temp.deleteOnExit(); boolean downloaded = false; - try - { - connectWagon( wagon, repository ); + try { + connectWagon(wagon, repository); boolean firstRun = true; boolean retry = true; @@ -377,155 +329,116 @@ public class DefaultWagonManager // this will run at most twice. The first time, the firstRun flag is turned off, and if the retry flag // is set on the first run, it will be turned off and not re-set on the second try. This is because the // only way the retry flag can be set is if ( firstRun == true ). - while ( firstRun || retry ) - { + while (firstRun || retry) { ChecksumObserver md5ChecksumObserver = null; ChecksumObserver sha1ChecksumObserver = null; - try - { + try { // TODO configure on repository int i = 0; - md5ChecksumObserver = addChecksumObserver( wagon, CHECKSUM_ALGORITHMS[i++] ); - sha1ChecksumObserver = addChecksumObserver( wagon, CHECKSUM_ALGORITHMS[i++] ); + md5ChecksumObserver = addChecksumObserver(wagon, CHECKSUM_ALGORITHMS[i++]); + sha1ChecksumObserver = addChecksumObserver(wagon, CHECKSUM_ALGORITHMS[i++]); // reset the retry flag. retry = false; // This should take care of creating destination directory now on - if ( destination.exists() && !force ) - { - try - { - downloaded = wagon.getIfNewer( remotePath, temp, destination.lastModified() ); + if (destination.exists() && !force) { + try { + downloaded = wagon.getIfNewer(remotePath, temp, destination.lastModified()); - if ( !downloaded ) - { + if (!downloaded) { // prevent additional checks of this artifact until it expires again - destination.setLastModified( System.currentTimeMillis() ); + destination.setLastModified(System.currentTimeMillis()); } - } - catch ( UnsupportedOperationException e ) - { + } catch (UnsupportedOperationException e) { // older wagons throw this. Just get() instead - wagon.get( remotePath, temp ); + wagon.get(remotePath, temp); downloaded = true; } - } - else - { - wagon.get( remotePath, temp ); + } else { + wagon.get(remotePath, temp); downloaded = true; } - } - finally - { - wagon.removeTransferListener( md5ChecksumObserver ); - wagon.removeTransferListener( sha1ChecksumObserver ); + } finally { + wagon.removeTransferListener(md5ChecksumObserver); + wagon.removeTransferListener(sha1ChecksumObserver); } - if ( downloaded ) - { + if (downloaded) { // keep the checksum files from showing up on the download monitor... - if ( downloadMonitor != null ) - { - wagon.removeTransferListener( downloadMonitor ); + if (downloadMonitor != null) { + wagon.removeTransferListener(downloadMonitor); } // try to verify the SHA-1 checksum for this file. - try - { - verifyChecksum( sha1ChecksumObserver, destination, temp, remotePath, ".sha1", wagon ); - } - catch ( ChecksumFailedException e ) - { + try { + verifyChecksum(sha1ChecksumObserver, destination, temp, remotePath, ".sha1", wagon); + } catch (ChecksumFailedException e) { // if we catch a ChecksumFailedException, it means the transfer/read succeeded, but the // checksum doesn't match. This could be a problem with the server (ibiblio HTTP-200 error // page), so we'll try this up to two times. On the second try, we'll handle it as a bona-fide // error, based on the repository's checksum checking policy. - if ( firstRun ) - { - logger.warn( "*** CHECKSUM FAILED - " + e.getMessage() + " - RETRYING" ); + if (firstRun) { + logger.warn("*** CHECKSUM FAILED - " + e.getMessage() + " - RETRYING"); retry = true; + } else { + handleChecksumFailure(checksumPolicy, e.getMessage(), e.getCause()); } - else - { - handleChecksumFailure( checksumPolicy, e.getMessage(), e.getCause() ); - } - } - catch ( ResourceDoesNotExistException sha1TryException ) - { - logger.debug( "SHA1 not found, trying MD5: " + sha1TryException.getMessage() ); + } catch (ResourceDoesNotExistException sha1TryException) { + logger.debug("SHA1 not found, trying MD5: " + sha1TryException.getMessage()); // if this IS NOT a ChecksumFailedException, it was a problem with transfer/read of the checksum // file...we'll try again with the MD5 checksum. - try - { - verifyChecksum( md5ChecksumObserver, destination, temp, remotePath, ".md5", wagon ); - } - catch ( ChecksumFailedException e ) - { + try { + verifyChecksum(md5ChecksumObserver, destination, temp, remotePath, ".md5", wagon); + } catch (ChecksumFailedException e) { // if we also fail to verify based on the MD5 checksum, and the checksum transfer/read // succeeded, then we need to determine whether to retry or handle it as a failure. - if ( firstRun ) - { + if (firstRun) { retry = true; + } else { + handleChecksumFailure(checksumPolicy, e.getMessage(), e.getCause()); } - else - { - handleChecksumFailure( checksumPolicy, e.getMessage(), e.getCause() ); - } - } - catch ( ResourceDoesNotExistException md5TryException ) - { + } catch (ResourceDoesNotExistException md5TryException) { // this was a failed transfer, and we don't want to retry. - handleChecksumFailure( checksumPolicy, "Error retrieving checksum file for " + remotePath, - md5TryException ); + handleChecksumFailure( + checksumPolicy, + "Error retrieving checksum file for " + remotePath, + md5TryException); } } // reinstate the download monitor... - if ( downloadMonitor != null ) - { - wagon.addTransferListener( downloadMonitor ); + if (downloadMonitor != null) { + wagon.addTransferListener(downloadMonitor); } } // unset the firstRun flag, so we don't get caught in an infinite loop... firstRun = false; } - } - catch ( ConnectionException e ) - { - throw new TransferFailedException( "Connection failed: " + e.getMessage(), e ); - } - catch ( AuthenticationException e ) - { - throw new TransferFailedException( "Authentication failed: " + e.getMessage(), e ); - } - catch ( AuthorizationException e ) - { - throw new TransferFailedException( "Authorization failed: " + e.getMessage(), e ); - } - finally - { + } catch (ConnectionException e) { + throw new TransferFailedException("Connection failed: " + e.getMessage(), e); + } catch (AuthenticationException e) { + throw new TransferFailedException("Authentication failed: " + e.getMessage(), e); + } catch (AuthorizationException e) { + throw new TransferFailedException("Authorization failed: " + e.getMessage(), e); + } finally { // Remove remaining TransferListener instances (checksum handlers removed in above finally clause) - if ( downloadMonitor != null ) - { - wagon.removeTransferListener( downloadMonitor ); + if (downloadMonitor != null) { + wagon.removeTransferListener(downloadMonitor); } - disconnectWagon( wagon ); + disconnectWagon(wagon); - releaseWagon( protocol, wagon ); + releaseWagon(protocol, wagon); } - if ( downloaded ) - { - if ( !temp.exists() ) - { - throw new ResourceDoesNotExistException( "Downloaded file does not exist: " + temp ); + if (downloaded) { + if (!temp.exists()) { + throw new ResourceDoesNotExistException("Downloaded file does not exist: " + temp); } // The temporary file is named destination + ".tmp" and is done this way to ensure @@ -533,22 +446,16 @@ public class DefaultWagonManager // File.renameTo operation doesn't really work across file systems. // So we will attempt to do a File.renameTo for efficiency and atomicity, if this fails // then we will use a brute force copy and delete the temporary file. - if ( !temp.renameTo( destination ) ) - { - try - { - FileUtils.copyFile( temp, destination ); + if (!temp.renameTo(destination)) { + try { + FileUtils.copyFile(temp, destination); - if ( !temp.delete() ) - { + if (!temp.delete()) { temp.deleteOnExit(); } - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error copying temporary file to the final destination: " - + e.getMessage(), e ); - + } catch (IOException e) { + throw new TransferFailedException( + "Error copying temporary file to the final destination: " + e.getMessage(), e); } } } @@ -558,294 +465,225 @@ public class DefaultWagonManager // Publisher // @Override - public void putArtifact( File source, Artifact artifact, ArtifactRepository deploymentRepository, - TransferListener downloadMonitor ) - throws TransferFailedException - { - putRemoteFile( deploymentRepository, source, deploymentRepository.pathOf( artifact ), downloadMonitor ); + public void putArtifact( + File source, Artifact artifact, ArtifactRepository deploymentRepository, TransferListener downloadMonitor) + throws TransferFailedException { + putRemoteFile(deploymentRepository, source, deploymentRepository.pathOf(artifact), downloadMonitor); } @Override - public void putArtifactMetadata( File source, ArtifactMetadata artifactMetadata, ArtifactRepository repository ) - throws TransferFailedException - { - logger.info( "Uploading " + artifactMetadata ); - putRemoteFile( repository, source, repository.pathOfRemoteRepositoryMetadata( artifactMetadata ), null ); + public void putArtifactMetadata(File source, ArtifactMetadata artifactMetadata, ArtifactRepository repository) + throws TransferFailedException { + logger.info("Uploading " + artifactMetadata); + putRemoteFile(repository, source, repository.pathOfRemoteRepositoryMetadata(artifactMetadata), null); } @Override - public void putRemoteFile( ArtifactRepository repository, File source, String remotePath, - TransferListener downloadMonitor ) - throws TransferFailedException - { + public void putRemoteFile( + ArtifactRepository repository, File source, String remotePath, TransferListener downloadMonitor) + throws TransferFailedException { String protocol = repository.getProtocol(); Wagon wagon; - try - { - wagon = getWagon( protocol ); - } - catch ( UnsupportedProtocolException e ) - { - throw new TransferFailedException( "Unsupported Protocol: '" + protocol + "': " + e.getMessage(), e ); + try { + wagon = getWagon(protocol); + } catch (UnsupportedProtocolException e) { + throw new TransferFailedException("Unsupported Protocol: '" + protocol + "': " + e.getMessage(), e); } - if ( downloadMonitor != null ) - { - wagon.addTransferListener( downloadMonitor ); + if (downloadMonitor != null) { + wagon.addTransferListener(downloadMonitor); } - Map checksums = new HashMap<>( 2 ); + Map checksums = new HashMap<>(2); - Map sums = new HashMap<>( 2 ); + Map sums = new HashMap<>(2); // TODO configure these on the repository - for ( int i = 0; i < CHECKSUM_IDS.length; i++ ) - { - checksums.put( CHECKSUM_IDS[i], addChecksumObserver( wagon, CHECKSUM_ALGORITHMS[i] ) ); + for (int i = 0; i < CHECKSUM_IDS.length; i++) { + checksums.put(CHECKSUM_IDS[i], addChecksumObserver(wagon, CHECKSUM_ALGORITHMS[i])); } List temporaryFiles = new ArrayList<>(); - try - { - try - { - connectWagon( wagon, repository ); + try { + try { + connectWagon(wagon, repository); - wagon.put( source, remotePath ); - } - finally - { - if ( downloadMonitor != null ) - { - wagon.removeTransferListener( downloadMonitor ); + wagon.put(source, remotePath); + } finally { + if (downloadMonitor != null) { + wagon.removeTransferListener(downloadMonitor); } } // Pre-store the checksums as any future puts will overwrite them - for ( String extension : checksums.keySet() ) - { - ChecksumObserver observer = checksums.get( extension ); - sums.put( extension, observer.getActualChecksum() ); + for (String extension : checksums.keySet()) { + ChecksumObserver observer = checksums.get(extension); + sums.put(extension, observer.getActualChecksum()); } // We do this in here so we can checksum the artifact metadata too, otherwise it could be metadata itself - for ( String extension : checksums.keySet() ) - { + for (String extension : checksums.keySet()) { // TODO shouldn't need a file intermediary - improve wagon to take a stream - File temp = File.createTempFile( "maven-artifact", null ); + File temp = File.createTempFile("maven-artifact", null); temp.deleteOnExit(); - FileUtils.fileWrite( temp.getAbsolutePath(), "UTF-8", sums.get( extension ) ); + FileUtils.fileWrite(temp.getAbsolutePath(), "UTF-8", sums.get(extension)); - temporaryFiles.add( temp ); - wagon.put( temp, remotePath + "." + extension ); + temporaryFiles.add(temp); + wagon.put(temp, remotePath + "." + extension); } - } - catch ( ConnectionException e ) - { - throw new TransferFailedException( "Connection failed: " + e.getMessage(), e ); - } - catch ( AuthenticationException e ) - { - throw new TransferFailedException( "Authentication failed: " + e.getMessage(), e ); - } - catch ( AuthorizationException e ) - { - throw new TransferFailedException( "Authorization failed: " + e.getMessage(), e ); - } - catch ( ResourceDoesNotExistException e ) - { - throw new TransferFailedException( "Resource to deploy not found: " + e.getMessage(), e ); - } - catch ( IOException e ) - { - throw new TransferFailedException( "Error creating temporary file for deployment: " + e.getMessage(), e ); - } - finally - { + } catch (ConnectionException e) { + throw new TransferFailedException("Connection failed: " + e.getMessage(), e); + } catch (AuthenticationException e) { + throw new TransferFailedException("Authentication failed: " + e.getMessage(), e); + } catch (AuthorizationException e) { + throw new TransferFailedException("Authorization failed: " + e.getMessage(), e); + } catch (ResourceDoesNotExistException e) { + throw new TransferFailedException("Resource to deploy not found: " + e.getMessage(), e); + } catch (IOException e) { + throw new TransferFailedException("Error creating temporary file for deployment: " + e.getMessage(), e); + } finally { // MNG-4543 - cleanupTemporaryFiles( temporaryFiles ); + cleanupTemporaryFiles(temporaryFiles); // Remove every checksum listener - for ( String id : CHECKSUM_IDS ) - { - TransferListener checksumListener = checksums.get( id ); - if ( checksumListener != null ) - { - wagon.removeTransferListener( checksumListener ); + for (String id : CHECKSUM_IDS) { + TransferListener checksumListener = checksums.get(id); + if (checksumListener != null) { + wagon.removeTransferListener(checksumListener); } } - disconnectWagon( wagon ); + disconnectWagon(wagon); - releaseWagon( protocol, wagon ); + releaseWagon(protocol, wagon); } } - private void cleanupTemporaryFiles( List files ) - { - for ( File file : files ) - { + private void cleanupTemporaryFiles(List files) { + for (File file : files) { // really don't care if it failed here only log warning - if ( !file.delete() ) - { - logger.warn( "skip failed to delete temporary file : " + file.getAbsolutePath() ); + if (!file.delete()) { + logger.warn("skip failed to delete temporary file : " + file.getAbsolutePath()); file.deleteOnExit(); } } - } - private ChecksumObserver addChecksumObserver( Wagon wagon, String algorithm ) - throws TransferFailedException - { - try - { - ChecksumObserver checksumObserver = new ChecksumObserver( algorithm ); - wagon.addTransferListener( checksumObserver ); + private ChecksumObserver addChecksumObserver(Wagon wagon, String algorithm) throws TransferFailedException { + try { + ChecksumObserver checksumObserver = new ChecksumObserver(algorithm); + wagon.addTransferListener(checksumObserver); return checksumObserver; - } - catch ( NoSuchAlgorithmException e ) - { - throw new TransferFailedException( "Unable to add checksum for unsupported algorithm " + algorithm, e ); + } catch (NoSuchAlgorithmException e) { + throw new TransferFailedException("Unable to add checksum for unsupported algorithm " + algorithm, e); } } - private void handleChecksumFailure( String checksumPolicy, String message, Throwable cause ) - throws ChecksumFailedException - { - if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals( checksumPolicy ) ) - { - throw new ChecksumFailedException( message, cause ); - } - else if ( !ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals( checksumPolicy ) ) - { + private void handleChecksumFailure(String checksumPolicy, String message, Throwable cause) + throws ChecksumFailedException { + if (ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals(checksumPolicy)) { + throw new ChecksumFailedException(message, cause); + } else if (!ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals(checksumPolicy)) { // warn if it is set to anything other than ignore - logger.warn( "*** CHECKSUM FAILED - " + message + " - IGNORING" ); + logger.warn("*** CHECKSUM FAILED - " + message + " - IGNORING"); } // otherwise it is ignore } - private void verifyChecksum( ChecksumObserver checksumObserver, File destination, File tempDestination, - String remotePath, String checksumFileExtension, Wagon wagon ) - throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException - { - try - { + private void verifyChecksum( + ChecksumObserver checksumObserver, + File destination, + File tempDestination, + String remotePath, + String checksumFileExtension, + Wagon wagon) + throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException { + try { // grab it first, because it's about to change... String actualChecksum = checksumObserver.getActualChecksum(); - File tempChecksumFile = new File( tempDestination + checksumFileExtension + ".tmp" ); + File tempChecksumFile = new File(tempDestination + checksumFileExtension + ".tmp"); tempChecksumFile.deleteOnExit(); - wagon.get( remotePath + checksumFileExtension, tempChecksumFile ); + wagon.get(remotePath + checksumFileExtension, tempChecksumFile); - String expectedChecksum = FileUtils.fileRead( tempChecksumFile, "UTF-8" ); + String expectedChecksum = FileUtils.fileRead(tempChecksumFile, "UTF-8"); // remove whitespaces at the end expectedChecksum = expectedChecksum.trim(); // check for 'ALGO (name) = CHECKSUM' like used by openssl - if ( expectedChecksum.regionMatches( true, 0, "MD", 0, 2 ) - || expectedChecksum.regionMatches( true, 0, "SHA", 0, 3 ) ) - { - int lastSpacePos = expectedChecksum.lastIndexOf( ' ' ); - expectedChecksum = expectedChecksum.substring( lastSpacePos + 1 ); - } - else - { + if (expectedChecksum.regionMatches(true, 0, "MD", 0, 2) + || expectedChecksum.regionMatches(true, 0, "SHA", 0, 3)) { + int lastSpacePos = expectedChecksum.lastIndexOf(' '); + expectedChecksum = expectedChecksum.substring(lastSpacePos + 1); + } else { // remove everything after the first space (if available) - int spacePos = expectedChecksum.indexOf( ' ' ); + int spacePos = expectedChecksum.indexOf(' '); - if ( spacePos != -1 ) - { - expectedChecksum = expectedChecksum.substring( 0, spacePos ); + if (spacePos != -1) { + expectedChecksum = expectedChecksum.substring(0, spacePos); } } - if ( expectedChecksum.equalsIgnoreCase( actualChecksum ) ) - { - File checksumFile = new File( destination + checksumFileExtension ); - if ( checksumFile.exists() ) - { + if (expectedChecksum.equalsIgnoreCase(actualChecksum)) { + File checksumFile = new File(destination + checksumFileExtension); + if (checksumFile.exists()) { checksumFile.delete(); // ignore if failed as we will overwrite } - FileUtils.copyFile( tempChecksumFile, checksumFile ); - if ( !tempChecksumFile.delete() ) - { + FileUtils.copyFile(tempChecksumFile, checksumFile); + if (!tempChecksumFile.delete()) { tempChecksumFile.deleteOnExit(); } + } else { + throw new ChecksumFailedException("Checksum failed on download: local = '" + actualChecksum + + "'; remote = '" + expectedChecksum + "'"); } - else - { - throw new ChecksumFailedException( "Checksum failed on download: local = '" + actualChecksum - + "'; remote = '" + expectedChecksum + "'" ); - - } - } - catch ( IOException e ) - { - throw new ChecksumFailedException( "Invalid checksum file", e ); + } catch (IOException e) { + throw new ChecksumFailedException("Invalid checksum file", e); } } - private void disconnectWagon( Wagon wagon ) - { - try - { + private void disconnectWagon(Wagon wagon) { + try { wagon.disconnect(); - } - catch ( ConnectionException e ) - { - logger.error( "Problem disconnecting from wagon - ignoring: " + e.getMessage() ); + } catch (ConnectionException e) { + logger.error("Problem disconnecting from wagon - ignoring: " + e.getMessage()); } } - private void releaseWagon( String protocol, Wagon wagon ) - { - try - { - container.release( wagon ); - } - catch ( ComponentLifecycleException e ) - { - logger.error( "Problem releasing wagon - ignoring: " + e.getMessage() ); - logger.debug( "", e ); + private void releaseWagon(String protocol, Wagon wagon) { + try { + container.release(wagon); + } catch (ComponentLifecycleException e) { + logger.error("Problem releasing wagon - ignoring: " + e.getMessage()); + logger.debug("", e); } } @Override @Deprecated - public Wagon getWagon( Repository repository ) - throws UnsupportedProtocolException - { - return getWagon( repository.getProtocol() ); + public Wagon getWagon(Repository repository) throws UnsupportedProtocolException { + return getWagon(repository.getProtocol()); } @Override @Deprecated - public Wagon getWagon( String protocol ) - throws UnsupportedProtocolException - { - if ( protocol == null ) - { - throw new UnsupportedProtocolException( "Unspecified protocol" ); + public Wagon getWagon(String protocol) throws UnsupportedProtocolException { + if (protocol == null) { + throw new UnsupportedProtocolException("Unspecified protocol"); } - String hint = protocol.toLowerCase( java.util.Locale.ENGLISH ); + String hint = protocol.toLowerCase(java.util.Locale.ENGLISH); Wagon wagon; - try - { - wagon = container.lookup( Wagon.class, hint ); - } - catch ( ComponentLookupException e ) - { - throw new UnsupportedProtocolException( "Cannot find wagon which supports the requested protocol: " - + protocol, e ); - + try { + wagon = container.lookup(Wagon.class, hint); + } catch (ComponentLookupException e) { + throw new UnsupportedProtocolException( + "Cannot find wagon which supports the requested protocol: " + protocol, e); } return wagon; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/LegacyRepositorySystem.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/LegacyRepositorySystem.java index 0ace040c23..85bc5b3558 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/LegacyRepositorySystem.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/LegacyRepositorySystem.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import java.io.File; import java.io.IOException; @@ -28,14 +27,12 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.Authentication; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; @@ -50,14 +47,15 @@ import org.apache.maven.model.Exclusion; import org.apache.maven.model.Plugin; import org.apache.maven.model.Repository; import org.apache.maven.model.RepositoryPolicy; +import org.apache.maven.repository.ArtifactDoesNotExistException; +import org.apache.maven.repository.ArtifactTransferFailedException; +import org.apache.maven.repository.ArtifactTransferListener; import org.apache.maven.repository.DelegatingLocalArtifactRepository; import org.apache.maven.repository.LocalArtifactRepository; -import org.apache.maven.repository.ArtifactTransferListener; import org.apache.maven.repository.MirrorSelector; import org.apache.maven.repository.Proxy; import org.apache.maven.repository.RepositorySystem; -import org.apache.maven.repository.ArtifactDoesNotExistException; -import org.apache.maven.repository.ArtifactTransferFailedException; +import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Server; import org.apache.maven.settings.building.SettingsProblem; @@ -82,10 +80,8 @@ import org.eclipse.aether.repository.RemoteRepository; /** * @author Jason van Zyl */ -@Component( role = RepositorySystem.class, hint = "default" ) -public class LegacyRepositorySystem - implements RepositorySystem -{ +@Component(role = RepositorySystem.class, hint = "default") +public class LegacyRepositorySystem implements RepositorySystem { @Requirement private Logger logger; @@ -99,7 +95,7 @@ public class LegacyRepositorySystem @Requirement private ArtifactRepositoryFactory artifactRepositoryFactory; - @Requirement( role = ArtifactRepositoryLayout.class ) + @Requirement(role = ArtifactRepositoryLayout.class) private Map layouts; @Requirement @@ -114,186 +110,168 @@ public class LegacyRepositorySystem @Requirement private SettingsDecrypter settingsDecrypter; - public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ) - { - return artifactFactory.createArtifact( groupId, artifactId, version, scope, type ); + public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) { + return artifactFactory.createArtifact(groupId, artifactId, version, scope, type); } - public Artifact createArtifact( String groupId, String artifactId, String version, String packaging ) - { - return artifactFactory.createBuildArtifact( groupId, artifactId, version, packaging ); + public Artifact createArtifact(String groupId, String artifactId, String version, String packaging) { + return artifactFactory.createBuildArtifact(groupId, artifactId, version, packaging); } - public Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, - String classifier ) - { - return artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, type, classifier ); + public Artifact createArtifactWithClassifier( + String groupId, String artifactId, String version, String type, String classifier) { + return artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier); } - public Artifact createProjectArtifact( String groupId, String artifactId, String metaVersionId ) - { - return artifactFactory.createProjectArtifact( groupId, artifactId, metaVersionId ); + public Artifact createProjectArtifact(String groupId, String artifactId, String metaVersionId) { + return artifactFactory.createProjectArtifact(groupId, artifactId, metaVersionId); } - public Artifact createDependencyArtifact( Dependency d ) - { + public Artifact createDependencyArtifact(Dependency d) { VersionRange versionRange; - try - { - versionRange = VersionRange.createFromVersionSpec( d.getVersion() ); - } - catch ( InvalidVersionSpecificationException e ) - { + try { + versionRange = VersionRange.createFromVersionSpec(d.getVersion()); + } catch (InvalidVersionSpecificationException e) { // MNG-5368: Log a message instead of returning 'null' silently. - this.logger.error( String.format( "Invalid version specification '%s' creating dependency artifact '%s'.", - d.getVersion(), d ), e ); + this.logger.error( + String.format( + "Invalid version specification '%s' creating dependency artifact '%s'.", d.getVersion(), d), + e); return null; } - Artifact artifact = - artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), - d.getClassifier(), d.getScope(), d.isOptional() ); + Artifact artifact = artifactFactory.createDependencyArtifact( + d.getGroupId(), + d.getArtifactId(), + versionRange, + d.getType(), + d.getClassifier(), + d.getScope(), + d.isOptional()); - if ( Artifact.SCOPE_SYSTEM.equals( d.getScope() ) && d.getSystemPath() != null ) - { - artifact.setFile( new File( d.getSystemPath() ) ); + if (Artifact.SCOPE_SYSTEM.equals(d.getScope()) && d.getSystemPath() != null) { + artifact.setFile(new File(d.getSystemPath())); } - if ( !d.getExclusions().isEmpty() ) - { + if (!d.getExclusions().isEmpty()) { List exclusions = new ArrayList<>(); - for ( Exclusion exclusion : d.getExclusions() ) - { - exclusions.add( exclusion.getGroupId() + ':' + exclusion.getArtifactId() ); + for (Exclusion exclusion : d.getExclusions()) { + exclusions.add(exclusion.getGroupId() + ':' + exclusion.getArtifactId()); } - artifact.setDependencyFilter( new ExcludesArtifactFilter( exclusions ) ); + artifact.setDependencyFilter(new ExcludesArtifactFilter(exclusions)); } return artifact; } - public Artifact createExtensionArtifact( String groupId, String artifactId, String version ) - { + public Artifact createExtensionArtifact(String groupId, String artifactId, String version) { VersionRange versionRange; - try - { - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { + try { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { // MNG-5368: Log a message instead of returning 'null' silently. - this.logger.error( String.format( - "Invalid version specification '%s' creating extension artifact '%s:%s:%s'.", - version, groupId, artifactId, version ), e ); + this.logger.error( + String.format( + "Invalid version specification '%s' creating extension artifact '%s:%s:%s'.", + version, groupId, artifactId, version), + e); return null; } - return artifactFactory.createExtensionArtifact( groupId, artifactId, versionRange ); + return artifactFactory.createExtensionArtifact(groupId, artifactId, versionRange); } - public Artifact createParentArtifact( String groupId, String artifactId, String version ) - { - return artifactFactory.createParentArtifact( groupId, artifactId, version ); + public Artifact createParentArtifact(String groupId, String artifactId, String version) { + return artifactFactory.createParentArtifact(groupId, artifactId, version); } - public Artifact createPluginArtifact( Plugin plugin ) - { + public Artifact createPluginArtifact(Plugin plugin) { String version = plugin.getVersion(); - if ( StringUtils.isEmpty( version ) ) - { + if (StringUtils.isEmpty(version)) { version = "RELEASE"; } VersionRange versionRange; - try - { - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { + try { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { // MNG-5368: Log a message instead of returning 'null' silently. - this.logger.error( String.format( - "Invalid version specification '%s' creating plugin artifact '%s'.", - version, plugin ), e ); + this.logger.error( + String.format("Invalid version specification '%s' creating plugin artifact '%s'.", version, plugin), + e); return null; } - return artifactFactory.createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange ); + return artifactFactory.createPluginArtifact(plugin.getGroupId(), plugin.getArtifactId(), versionRange); } - public ArtifactRepositoryPolicy buildArtifactRepositoryPolicy( RepositoryPolicy policy ) - { + public ArtifactRepositoryPolicy buildArtifactRepositoryPolicy(RepositoryPolicy policy) { boolean enabled = true; String updatePolicy = null; String checksumPolicy = null; - if ( policy != null ) - { + if (policy != null) { enabled = policy.isEnabled(); - if ( policy.getUpdatePolicy() != null ) - { + if (policy.getUpdatePolicy() != null) { updatePolicy = policy.getUpdatePolicy(); } - if ( policy.getChecksumPolicy() != null ) - { + if (policy.getChecksumPolicy() != null) { checksumPolicy = policy.getChecksumPolicy(); } } - return new ArtifactRepositoryPolicy( enabled, updatePolicy, checksumPolicy ); + return new ArtifactRepositoryPolicy(enabled, updatePolicy, checksumPolicy); } - public ArtifactRepository createDefaultLocalRepository() - throws InvalidRepositoryException - { - return createLocalRepository( RepositorySystem.defaultUserLocalRepository ); + public ArtifactRepository createDefaultLocalRepository() throws InvalidRepositoryException { + return createLocalRepository(RepositorySystem.defaultUserLocalRepository); } - public ArtifactRepository createLocalRepository( File localRepository ) - throws InvalidRepositoryException - { - return createRepository( "file://" + localRepository.toURI().getRawPath(), - RepositorySystem.DEFAULT_LOCAL_REPO_ID, true, - ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, true, + public ArtifactRepository createLocalRepository(File localRepository) throws InvalidRepositoryException { + return createRepository( + "file://" + localRepository.toURI().getRawPath(), + RepositorySystem.DEFAULT_LOCAL_REPO_ID, + true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE ); + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, + ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE); } - public ArtifactRepository createDefaultRemoteRepository() - throws InvalidRepositoryException - { - return createRepository( RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID, - true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, false, + public ArtifactRepository createDefaultRemoteRepository() throws InvalidRepositoryException { + return createRepository( + RepositorySystem.DEFAULT_REMOTE_REPO_URL, + RepositorySystem.DEFAULT_REMOTE_REPO_ID, + true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN ); + false, + ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, + ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); } - public ArtifactRepository createLocalRepository( String url, String repositoryId ) - throws IOException - { - return createRepository( canonicalFileUrl( url ), repositoryId, true, - ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, true, + public ArtifactRepository createLocalRepository(String url, String repositoryId) throws IOException { + return createRepository( + canonicalFileUrl(url), + repositoryId, + true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE ); + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, + ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE); } - private String canonicalFileUrl( String url ) - throws IOException - { - if ( !url.startsWith( "file:" ) ) - { + private String canonicalFileUrl(String url) throws IOException { + if (!url.startsWith("file:")) { url = "file://" + url; - } - else if ( url.startsWith( "file:" ) && !url.startsWith( "file://" ) ) - { - url = "file://" + url.substring( "file:".length() ); + } else if (url.startsWith("file:") && !url.startsWith("file://")) { + url = "file://" + url.substring("file:".length()); } // So now we have an url of the form file:// @@ -303,68 +281,54 @@ public class LegacyRepositorySystem // when you are using a custom settings.xml that contains a relative path entry // for the local repository setting. - File localRepository = new File( url.substring( "file://".length() ) ); + File localRepository = new File(url.substring("file://".length())); - if ( !localRepository.isAbsolute() ) - { + if (!localRepository.isAbsolute()) { url = "file://" + localRepository.getCanonicalPath(); } return url; } - public ArtifactResolutionResult resolve( ArtifactResolutionRequest request ) - { + public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) { /* * Probably is not worth it, but here I make sure I restore request * to its original state. */ - try - { + try { LocalArtifactRepository ideWorkspace = - plexus.lookup( LocalArtifactRepository.class, LocalArtifactRepository.IDE_WORKSPACE ); + plexus.lookup(LocalArtifactRepository.class, LocalArtifactRepository.IDE_WORKSPACE); - if ( request.getLocalRepository() instanceof DelegatingLocalArtifactRepository ) - { + if (request.getLocalRepository() instanceof DelegatingLocalArtifactRepository) { DelegatingLocalArtifactRepository delegatingLocalRepository = (DelegatingLocalArtifactRepository) request.getLocalRepository(); LocalArtifactRepository orig = delegatingLocalRepository.getIdeWorkspace(); - delegatingLocalRepository.setIdeWorkspace( ideWorkspace ); + delegatingLocalRepository.setIdeWorkspace(ideWorkspace); - try - { - return artifactResolver.resolve( request ); + try { + return artifactResolver.resolve(request); + } finally { + delegatingLocalRepository.setIdeWorkspace(orig); } - finally - { - delegatingLocalRepository.setIdeWorkspace( orig ); - } - } - else - { + } else { ArtifactRepository localRepository = request.getLocalRepository(); DelegatingLocalArtifactRepository delegatingLocalRepository = - new DelegatingLocalArtifactRepository( localRepository ); - delegatingLocalRepository.setIdeWorkspace( ideWorkspace ); - request.setLocalRepository( delegatingLocalRepository ); - try - { - return artifactResolver.resolve( request ); - } - finally - { - request.setLocalRepository( localRepository ); + new DelegatingLocalArtifactRepository(localRepository); + delegatingLocalRepository.setIdeWorkspace(ideWorkspace); + request.setLocalRepository(delegatingLocalRepository); + try { + return artifactResolver.resolve(request); + } finally { + request.setLocalRepository(localRepository); } } - } - catch ( ComponentLookupException e ) - { + } catch (ComponentLookupException e) { // no ide workspace artifact resolution } - return artifactResolver.resolve( request ); + return artifactResolver.resolve(request); } // public void addProxy( String protocol, String host, int port, String username, String password, @@ -383,122 +347,100 @@ public class LegacyRepositorySystem // wagonManager.addProxy( protocol, host, port, username, password, nonProxyHosts ); // } - public List getEffectiveRepositories( List repositories ) - { - if ( repositories == null ) - { + public List getEffectiveRepositories(List repositories) { + if (repositories == null) { return null; } Map> reposByKey = new LinkedHashMap<>(); - for ( ArtifactRepository repository : repositories ) - { + for (ArtifactRepository repository : repositories) { String key = repository.getId(); - List aliasedRepos = reposByKey.computeIfAbsent( key, k -> new ArrayList<>() ); + List aliasedRepos = reposByKey.computeIfAbsent(key, k -> new ArrayList<>()); - aliasedRepos.add( repository ); + aliasedRepos.add(repository); } List effectiveRepositories = new ArrayList<>(); - for ( List aliasedRepos : reposByKey.values() ) - { + for (List aliasedRepos : reposByKey.values()) { List mirroredRepos = new ArrayList<>(); - List releasePolicies = - new ArrayList<>( aliasedRepos.size() ); + List releasePolicies = new ArrayList<>(aliasedRepos.size()); - for ( ArtifactRepository aliasedRepo : aliasedRepos ) - { - releasePolicies.add( aliasedRepo.getReleases() ); - mirroredRepos.addAll( aliasedRepo.getMirroredRepositories() ); + for (ArtifactRepository aliasedRepo : aliasedRepos) { + releasePolicies.add(aliasedRepo.getReleases()); + mirroredRepos.addAll(aliasedRepo.getMirroredRepositories()); } - ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy( releasePolicies ); + ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy(releasePolicies); - List snapshotPolicies = - new ArrayList<>( aliasedRepos.size() ); + List snapshotPolicies = new ArrayList<>(aliasedRepos.size()); - for ( ArtifactRepository aliasedRepo : aliasedRepos ) - { - snapshotPolicies.add( aliasedRepo.getSnapshots() ); + for (ArtifactRepository aliasedRepo : aliasedRepos) { + snapshotPolicies.add(aliasedRepo.getSnapshots()); } - ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy( snapshotPolicies ); + ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy(snapshotPolicies); - ArtifactRepository aliasedRepo = aliasedRepos.get( 0 ); + ArtifactRepository aliasedRepo = aliasedRepos.get(0); - ArtifactRepository effectiveRepository = - createArtifactRepository( aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), - snapshotPolicy, releasePolicy ); + ArtifactRepository effectiveRepository = createArtifactRepository( + aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), snapshotPolicy, releasePolicy); - effectiveRepository.setAuthentication( aliasedRepo.getAuthentication() ); + effectiveRepository.setAuthentication(aliasedRepo.getAuthentication()); - effectiveRepository.setProxy( aliasedRepo.getProxy() ); + effectiveRepository.setProxy(aliasedRepo.getProxy()); - effectiveRepository.setMirroredRepositories( mirroredRepos ); + effectiveRepository.setMirroredRepositories(mirroredRepos); - effectiveRepository.setBlocked( aliasedRepo.isBlocked() ); + effectiveRepository.setBlocked(aliasedRepo.isBlocked()); - effectiveRepositories.add( effectiveRepository ); + effectiveRepositories.add(effectiveRepository); } return effectiveRepositories; } - private ArtifactRepositoryPolicy getEffectivePolicy( Collection policies ) - { + private ArtifactRepositoryPolicy getEffectivePolicy(Collection policies) { ArtifactRepositoryPolicy effectivePolicy = null; - for ( ArtifactRepositoryPolicy policy : policies ) - { - if ( effectivePolicy == null ) - { - effectivePolicy = new ArtifactRepositoryPolicy( policy ); - } - else - { - effectivePolicy.merge( policy ); + for (ArtifactRepositoryPolicy policy : policies) { + if (effectivePolicy == null) { + effectivePolicy = new ArtifactRepositoryPolicy(policy); + } else { + effectivePolicy.merge(policy); } } return effectivePolicy; } - public Mirror getMirror( ArtifactRepository repository, List mirrors ) - { - return mirrorSelector.getMirror( repository, mirrors ); + public Mirror getMirror(ArtifactRepository repository, List mirrors) { + return mirrorSelector.getMirror(repository, mirrors); } - public void injectMirror( List repositories, List mirrors ) - { - if ( repositories != null && mirrors != null ) - { - for ( ArtifactRepository repository : repositories ) - { - Mirror mirror = getMirror( repository, mirrors ); - injectMirror( repository, mirror ); + public void injectMirror(List repositories, List mirrors) { + if (repositories != null && mirrors != null) { + for (ArtifactRepository repository : repositories) { + Mirror mirror = getMirror(repository, mirrors); + injectMirror(repository, mirror); } } } - private Mirror getMirror( RepositorySystemSession session, ArtifactRepository repository ) - { - if ( session != null ) - { + private Mirror getMirror(RepositorySystemSession session, ArtifactRepository repository) { + if (session != null) { org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector(); - if ( selector != null ) - { - RemoteRepository repo = selector.getMirror( RepositoryUtils.toRepo( repository ) ); - if ( repo != null ) - { + if (selector != null) { + RemoteRepository repo = selector.getMirror(RepositoryUtils.toRepo(repository)); + if (repo != null) { Mirror mirror = new Mirror(); - mirror.setId( repo.getId() ); - mirror.setUrl( repo.getUrl() ); - mirror.setLayout( repo.getContentType() ); - mirror.setBlocked( repo.isBlocked() ); + mirror.setId(repo.getId()); + mirror.setUrl(repo.getUrl()); + mirror.setLayout(repo.getContentType()); + mirror.setBlocked(repo.isBlocked()); return mirror; } } @@ -506,107 +448,90 @@ public class LegacyRepositorySystem return null; } - public void injectMirror( RepositorySystemSession session, List repositories ) - { - if ( repositories != null && session != null ) - { - for ( ArtifactRepository repository : repositories ) - { - Mirror mirror = getMirror( session, repository ); - injectMirror( repository, mirror ); + public void injectMirror(RepositorySystemSession session, List repositories) { + if (repositories != null && session != null) { + for (ArtifactRepository repository : repositories) { + Mirror mirror = getMirror(session, repository); + injectMirror(repository, mirror); } } } - private void injectMirror( ArtifactRepository repository, Mirror mirror ) - { - if ( mirror != null ) - { - ArtifactRepository original = - createArtifactRepository( repository.getId(), repository.getUrl(), repository.getLayout(), - repository.getSnapshots(), repository.getReleases() ); + private void injectMirror(ArtifactRepository repository, Mirror mirror) { + if (mirror != null) { + ArtifactRepository original = createArtifactRepository( + repository.getId(), + repository.getUrl(), + repository.getLayout(), + repository.getSnapshots(), + repository.getReleases()); - repository.setMirroredRepositories( Collections.singletonList( original ) ); + repository.setMirroredRepositories(Collections.singletonList(original)); - repository.setId( mirror.getId() ); - repository.setUrl( mirror.getUrl() ); + repository.setId(mirror.getId()); + repository.setUrl(mirror.getUrl()); - if ( StringUtils.isNotEmpty( mirror.getLayout() ) ) - { - repository.setLayout( getLayout( mirror.getLayout() ) ); + if (StringUtils.isNotEmpty(mirror.getLayout())) { + repository.setLayout(getLayout(mirror.getLayout())); } - repository.setBlocked( mirror.isBlocked() ); + repository.setBlocked(mirror.isBlocked()); } } - public void injectAuthentication( List repositories, List servers ) - { - if ( repositories != null ) - { + public void injectAuthentication(List repositories, List servers) { + if (repositories != null) { Map serversById = new HashMap<>(); - if ( servers != null ) - { - for ( Server server : servers ) - { - if ( !serversById.containsKey( server.getId() ) ) - { - serversById.put( server.getId(), server ); + if (servers != null) { + for (Server server : servers) { + if (!serversById.containsKey(server.getId())) { + serversById.put(server.getId(), server); } } } - for ( ArtifactRepository repository : repositories ) - { - Server server = serversById.get( repository.getId() ); + for (ArtifactRepository repository : repositories) { + Server server = serversById.get(repository.getId()); - if ( server != null ) - { - SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest( server ); - SettingsDecryptionResult result = settingsDecrypter.decrypt( request ); + if (server != null) { + SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server); + SettingsDecryptionResult result = settingsDecrypter.decrypt(request); server = result.getServer(); - if ( logger.isDebugEnabled() ) - { - for ( SettingsProblem problem : result.getProblems() ) - { - logger.debug( problem.getMessage(), problem.getException() ); + if (logger.isDebugEnabled()) { + for (SettingsProblem problem : result.getProblems()) { + logger.debug(problem.getMessage(), problem.getException()); } } - Authentication authentication = new Authentication( server.getUsername(), server.getPassword() ); - authentication.setPrivateKey( server.getPrivateKey() ); - authentication.setPassphrase( server.getPassphrase() ); + Authentication authentication = new Authentication(server.getUsername(), server.getPassword()); + authentication.setPrivateKey(server.getPrivateKey()); + authentication.setPassphrase(server.getPassphrase()); - repository.setAuthentication( authentication ); - } - else - { - repository.setAuthentication( null ); + repository.setAuthentication(authentication); + } else { + repository.setAuthentication(null); } } } } - private Authentication getAuthentication( RepositorySystemSession session, ArtifactRepository repository ) - { - if ( session != null ) - { + private Authentication getAuthentication(RepositorySystemSession session, ArtifactRepository repository) { + if (session != null) { AuthenticationSelector selector = session.getAuthenticationSelector(); - if ( selector != null ) - { - RemoteRepository repo = RepositoryUtils.toRepo( repository ); - org.eclipse.aether.repository.Authentication auth = selector.getAuthentication( repo ); - if ( auth != null ) - { - repo = new RemoteRepository.Builder( repo ).setAuthentication( auth ).build(); - AuthenticationContext authCtx = AuthenticationContext.forRepository( session, repo ); - Authentication result = - new Authentication( authCtx.get( AuthenticationContext.USERNAME ), - authCtx.get( AuthenticationContext.PASSWORD ) ); - result.setPrivateKey( authCtx.get( AuthenticationContext.PRIVATE_KEY_PATH ) ); - result.setPassphrase( authCtx.get( AuthenticationContext.PRIVATE_KEY_PASSPHRASE ) ); + if (selector != null) { + RemoteRepository repo = RepositoryUtils.toRepo(repository); + org.eclipse.aether.repository.Authentication auth = selector.getAuthentication(repo); + if (auth != null) { + repo = new RemoteRepository.Builder(repo) + .setAuthentication(auth) + .build(); + AuthenticationContext authCtx = AuthenticationContext.forRepository(session, repo); + Authentication result = new Authentication( + authCtx.get(AuthenticationContext.USERNAME), authCtx.get(AuthenticationContext.PASSWORD)); + result.setPrivateKey(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH)); + result.setPassphrase(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE)); authCtx.close(); return result; } @@ -615,42 +540,31 @@ public class LegacyRepositorySystem return null; } - public void injectAuthentication( RepositorySystemSession session, List repositories ) - { - if ( repositories != null && session != null ) - { - for ( ArtifactRepository repository : repositories ) - { - repository.setAuthentication( getAuthentication( session, repository ) ); + public void injectAuthentication(RepositorySystemSession session, List repositories) { + if (repositories != null && session != null) { + for (ArtifactRepository repository : repositories) { + repository.setAuthentication(getAuthentication(session, repository)); } } } - private org.apache.maven.settings.Proxy getProxy( ArtifactRepository repository, - List proxies ) - { - if ( proxies != null && repository.getProtocol() != null ) - { - for ( org.apache.maven.settings.Proxy proxy : proxies ) - { - if ( proxy.isActive() && repository.getProtocol().equalsIgnoreCase( proxy.getProtocol() ) ) - { - if ( StringUtils.isNotEmpty( proxy.getNonProxyHosts() ) ) - { + private org.apache.maven.settings.Proxy getProxy( + ArtifactRepository repository, List proxies) { + if (proxies != null && repository.getProtocol() != null) { + for (org.apache.maven.settings.Proxy proxy : proxies) { + if (proxy.isActive() && repository.getProtocol().equalsIgnoreCase(proxy.getProtocol())) { + if (StringUtils.isNotEmpty(proxy.getNonProxyHosts())) { ProxyInfo pi = new ProxyInfo(); - pi.setNonProxyHosts( proxy.getNonProxyHosts() ); + pi.setNonProxyHosts(proxy.getNonProxyHosts()); org.apache.maven.wagon.repository.Repository repo = new org.apache.maven.wagon.repository.Repository( - repository.getId(), repository.getUrl() ); + repository.getId(), repository.getUrl()); - if ( !ProxyUtils.validateNonProxyHosts( pi, repo.getHost() ) ) - { + if (!ProxyUtils.validateNonProxyHosts(pi, repo.getHost())) { return proxy; } - } - else - { + } else { return proxy; } } @@ -660,69 +574,58 @@ public class LegacyRepositorySystem return null; } - public void injectProxy( List repositories, List proxies ) - { - if ( repositories != null ) - { - for ( ArtifactRepository repository : repositories ) - { - org.apache.maven.settings.Proxy proxy = getProxy( repository, proxies ); + public void injectProxy(List repositories, List proxies) { + if (repositories != null) { + for (ArtifactRepository repository : repositories) { + org.apache.maven.settings.Proxy proxy = getProxy(repository, proxies); - if ( proxy != null ) - { - SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest( proxy ); - SettingsDecryptionResult result = settingsDecrypter.decrypt( request ); + if (proxy != null) { + SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(proxy); + SettingsDecryptionResult result = settingsDecrypter.decrypt(request); proxy = result.getProxy(); - if ( logger.isDebugEnabled() ) - { - for ( SettingsProblem problem : result.getProblems() ) - { - logger.debug( problem.getMessage(), problem.getException() ); + if (logger.isDebugEnabled()) { + for (SettingsProblem problem : result.getProblems()) { + logger.debug(problem.getMessage(), problem.getException()); } } Proxy p = new Proxy(); - p.setHost( proxy.getHost() ); - p.setProtocol( proxy.getProtocol() ); - p.setPort( proxy.getPort() ); - p.setNonProxyHosts( proxy.getNonProxyHosts() ); - p.setUserName( proxy.getUsername() ); - p.setPassword( proxy.getPassword() ); + p.setHost(proxy.getHost()); + p.setProtocol(proxy.getProtocol()); + p.setPort(proxy.getPort()); + p.setNonProxyHosts(proxy.getNonProxyHosts()); + p.setUserName(proxy.getUsername()); + p.setPassword(proxy.getPassword()); - repository.setProxy( p ); - } - else - { - repository.setProxy( null ); + repository.setProxy(p); + } else { + repository.setProxy(null); } } } } - private Proxy getProxy( RepositorySystemSession session, ArtifactRepository repository ) - { - if ( session != null ) - { + private Proxy getProxy(RepositorySystemSession session, ArtifactRepository repository) { + if (session != null) { ProxySelector selector = session.getProxySelector(); - if ( selector != null ) - { - RemoteRepository repo = RepositoryUtils.toRepo( repository ); - org.eclipse.aether.repository.Proxy proxy = selector.getProxy( repo ); - if ( proxy != null ) - { + if (selector != null) { + RemoteRepository repo = RepositoryUtils.toRepo(repository); + org.eclipse.aether.repository.Proxy proxy = selector.getProxy(repo); + if (proxy != null) { Proxy p = new Proxy(); - p.setHost( proxy.getHost() ); - p.setProtocol( proxy.getType() ); - p.setPort( proxy.getPort() ); - if ( proxy.getAuthentication() != null ) - { - repo = new RemoteRepository.Builder( repo ).setProxy( proxy ).build(); - AuthenticationContext authCtx = AuthenticationContext.forProxy( session, repo ); - p.setUserName( authCtx.get( AuthenticationContext.USERNAME ) ); - p.setPassword( authCtx.get( AuthenticationContext.PASSWORD ) ); - p.setNtlmDomain( authCtx.get( AuthenticationContext.NTLM_DOMAIN ) ); - p.setNtlmHost( authCtx.get( AuthenticationContext.NTLM_WORKSTATION ) ); + p.setHost(proxy.getHost()); + p.setProtocol(proxy.getType()); + p.setPort(proxy.getPort()); + if (proxy.getAuthentication() != null) { + repo = new RemoteRepository.Builder(repo) + .setProxy(proxy) + .build(); + AuthenticationContext authCtx = AuthenticationContext.forProxy(session, repo); + p.setUserName(authCtx.get(AuthenticationContext.USERNAME)); + p.setPassword(authCtx.get(AuthenticationContext.PASSWORD)); + p.setNtlmDomain(authCtx.get(AuthenticationContext.NTLM_DOMAIN)); + p.setNtlmHost(authCtx.get(AuthenticationContext.NTLM_WORKSTATION)); authCtx.close(); } return p; @@ -732,133 +635,119 @@ public class LegacyRepositorySystem return null; } - public void injectProxy( RepositorySystemSession session, List repositories ) - { - if ( repositories != null && session != null ) - { - for ( ArtifactRepository repository : repositories ) - { - repository.setProxy( getProxy( session, repository ) ); + public void injectProxy(RepositorySystemSession session, List repositories) { + if (repositories != null && session != null) { + for (ArtifactRepository repository : repositories) { + repository.setProxy(getProxy(session, repository)); } } } - public void retrieve( ArtifactRepository repository, File destination, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException, ArtifactDoesNotExistException - { - try - { - wagonManager.getRemoteFile( repository, destination, remotePath, - TransferListenerAdapter.newAdapter( transferListener ), - ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN, true ); - } - catch ( org.apache.maven.wagon.TransferFailedException e ) - { - throw new ArtifactTransferFailedException( getMessage( e, "Error transferring artifact." ), e ); - } - catch ( org.apache.maven.wagon.ResourceDoesNotExistException e ) - { - throw new ArtifactDoesNotExistException( getMessage( e, "Requested artifact does not exist." ), e ); + public void retrieve( + ArtifactRepository repository, + File destination, + String remotePath, + ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException, ArtifactDoesNotExistException { + try { + wagonManager.getRemoteFile( + repository, + destination, + remotePath, + TransferListenerAdapter.newAdapter(transferListener), + ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN, + true); + } catch (org.apache.maven.wagon.TransferFailedException e) { + throw new ArtifactTransferFailedException(getMessage(e, "Error transferring artifact."), e); + } catch (org.apache.maven.wagon.ResourceDoesNotExistException e) { + throw new ArtifactDoesNotExistException(getMessage(e, "Requested artifact does not exist."), e); } } - public void publish( ArtifactRepository repository, File source, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException - { - try - { - wagonManager.putRemoteFile( repository, source, remotePath, - TransferListenerAdapter.newAdapter( transferListener ) ); - } - catch ( org.apache.maven.wagon.TransferFailedException e ) - { - throw new ArtifactTransferFailedException( getMessage( e, "Error transferring artifact." ), e ); + public void publish( + ArtifactRepository repository, File source, String remotePath, ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException { + try { + wagonManager.putRemoteFile( + repository, source, remotePath, TransferListenerAdapter.newAdapter(transferListener)); + } catch (org.apache.maven.wagon.TransferFailedException e) { + throw new ArtifactTransferFailedException(getMessage(e, "Error transferring artifact."), e); } } // // Artifact Repository Creation // - public ArtifactRepository buildArtifactRepository( Repository repo ) - throws InvalidRepositoryException - { - if ( repo != null ) - { + public ArtifactRepository buildArtifactRepository(Repository repo) throws InvalidRepositoryException { + if (repo != null) { String id = repo.getId(); - if ( StringUtils.isEmpty( id ) ) - { - throw new InvalidRepositoryException( "Repository identifier missing", "" ); + if (StringUtils.isEmpty(id)) { + throw new InvalidRepositoryException("Repository identifier missing", ""); } String url = repo.getUrl(); - if ( StringUtils.isEmpty( url ) ) - { - throw new InvalidRepositoryException( "URL missing for repository " + id, id ); + if (StringUtils.isEmpty(url)) { + throw new InvalidRepositoryException("URL missing for repository " + id, id); } - ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy( repo.getSnapshots() ); + ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy(repo.getSnapshots()); - ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy( repo.getReleases() ); + ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy(repo.getReleases()); - return createArtifactRepository( id, url, getLayout( repo.getLayout() ), snapshots, releases ); - } - else - { + return createArtifactRepository(id, url, getLayout(repo.getLayout()), snapshots, releases); + } else { return null; } } - private ArtifactRepository createRepository( String url, String repositoryId, boolean releases, - String releaseUpdates, boolean snapshots, String snapshotUpdates, - String checksumPolicy ) - { + private ArtifactRepository createRepository( + String url, + String repositoryId, + boolean releases, + String releaseUpdates, + boolean snapshots, + String snapshotUpdates, + String checksumPolicy) { ArtifactRepositoryPolicy snapshotsPolicy = - new ArtifactRepositoryPolicy( snapshots, snapshotUpdates, checksumPolicy ); + new ArtifactRepositoryPolicy(snapshots, snapshotUpdates, checksumPolicy); ArtifactRepositoryPolicy releasesPolicy = - new ArtifactRepositoryPolicy( releases, releaseUpdates, checksumPolicy ); + new ArtifactRepositoryPolicy(releases, releaseUpdates, checksumPolicy); - return createArtifactRepository( repositoryId, url, null, snapshotsPolicy, releasesPolicy ); + return createArtifactRepository(repositoryId, url, null, snapshotsPolicy, releasesPolicy); } - public ArtifactRepository createArtifactRepository( String repositoryId, String url, - ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - { - if ( repositoryLayout == null ) - { - repositoryLayout = layouts.get( "default" ); + public ArtifactRepository createArtifactRepository( + String repositoryId, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + if (repositoryLayout == null) { + repositoryLayout = layouts.get("default"); } - return artifactRepositoryFactory.createArtifactRepository( repositoryId, url, repositoryLayout, snapshots, - releases ); + return artifactRepositoryFactory.createArtifactRepository( + repositoryId, url, repositoryLayout, snapshots, releases); } - private static String getMessage( Throwable error, String def ) - { - if ( error == null ) - { + private static String getMessage(Throwable error, String def) { + if (error == null) { return def; } String msg = error.getMessage(); - if ( StringUtils.isNotEmpty( msg ) ) - { + if (StringUtils.isNotEmpty(msg)) { return msg; } - return getMessage( error.getCause(), def ); + return getMessage(error.getCause(), def); } - private ArtifactRepositoryLayout getLayout( String id ) - { - ArtifactRepositoryLayout layout = layouts.get( id ); + private ArtifactRepositoryLayout getLayout(String id) { + ArtifactRepositoryLayout layout = layouts.get(id); - if ( layout == null ) - { - layout = new UnknownRepositoryLayout( id, layouts.get( "default" ) ); + if (layout == null) { + layout = new UnknownRepositoryLayout(id, layouts.get("default")); } return layout; @@ -870,46 +759,36 @@ public class LegacyRepositorySystem * needs to retain the id of this layout so that the content type of the remote repository can still be accurately * described. */ - static class UnknownRepositoryLayout - implements ArtifactRepositoryLayout - { + static class UnknownRepositoryLayout implements ArtifactRepositoryLayout { private final String id; private final ArtifactRepositoryLayout fallback; - UnknownRepositoryLayout( String id, ArtifactRepositoryLayout fallback ) - { + UnknownRepositoryLayout(String id, ArtifactRepositoryLayout fallback) { this.id = id; this.fallback = fallback; } - public String getId() - { + public String getId() { return id; } - public String pathOf( Artifact artifact ) - { - return fallback.pathOf( artifact ); + public String pathOf(Artifact artifact) { + return fallback.pathOf(artifact); } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return fallback.pathOfLocalRepositoryMetadata( metadata, repository ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return fallback.pathOfLocalRepositoryMetadata(metadata, repository); } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata metadata ) - { - return fallback.pathOfRemoteRepositoryMetadata( metadata ); + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) { + return fallback.pathOfRemoteRepositoryMetadata(metadata); } @Override - public String toString() - { + public String toString() { return getId(); } - } - -} \ No newline at end of file +} diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/MavenArtifact.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/MavenArtifact.java index 07d2cdb67f..1696f38d8d 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/MavenArtifact.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/MavenArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,12 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import org.apache.maven.repository.ArtifactTransferResource; import org.apache.maven.wagon.resource.Resource; -class MavenArtifact - implements ArtifactTransferResource -{ +class MavenArtifact implements ArtifactTransferResource { private String repositoryUrl; @@ -32,18 +29,12 @@ class MavenArtifact private long transferStartTime; - MavenArtifact( String repositoryUrl, Resource resource ) - { - if ( repositoryUrl == null ) - { + MavenArtifact(String repositoryUrl, Resource resource) { + if (repositoryUrl == null) { this.repositoryUrl = ""; - } - else if ( !repositoryUrl.endsWith( "/" ) && repositoryUrl.length() > 0 ) - { + } else if (!repositoryUrl.endsWith("/") && repositoryUrl.length() > 0) { this.repositoryUrl = repositoryUrl + '/'; - } - else - { + } else { this.repositoryUrl = repositoryUrl; } this.resource = resource; @@ -51,46 +42,36 @@ class MavenArtifact this.transferStartTime = System.currentTimeMillis(); } - public String getRepositoryUrl() - { + public String getRepositoryUrl() { return repositoryUrl; } - public String getName() - { + public String getName() { String name = resource.getName(); - if ( name == null ) - { + if (name == null) { name = ""; - } - else if ( name.startsWith( "/" ) ) - { - name = name.substring( 1 ); + } else if (name.startsWith("/")) { + name = name.substring(1); } return name; } - public String getUrl() - { + public String getUrl() { return getRepositoryUrl() + getName(); } - public long getContentLength() - { + public long getContentLength() { return resource.getContentLength(); } - public long getTransferStartTime() - { + public long getTransferStartTime() { return transferStartTime; } @Override - public String toString() - { + public String toString() { return getUrl(); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/TransferListenerAdapter.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/TransferListenerAdapter.java index c3bc5e9518..af2439146a 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/TransferListenerAdapter.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/TransferListenerAdapter.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import java.util.IdentityHashMap; import java.util.Map; - import org.apache.maven.repository.ArtifactTransferEvent; import org.apache.maven.repository.ArtifactTransferListener; import org.apache.maven.repository.ArtifactTransferResource; @@ -33,9 +31,7 @@ import org.apache.maven.wagon.resource.Resource; /** * TransferListenerAdapter */ -public class TransferListenerAdapter - implements TransferListener -{ +public class TransferListenerAdapter implements TransferListener { private final ArtifactTransferListener listener; @@ -43,148 +39,113 @@ public class TransferListenerAdapter private final Map transfers; - public static TransferListener newAdapter( ArtifactTransferListener listener ) - { - if ( listener == null ) - { + public static TransferListener newAdapter(ArtifactTransferListener listener) { + if (listener == null) { return null; - } - else - { - return new TransferListenerAdapter( listener ); + } else { + return new TransferListenerAdapter(listener); } } - private TransferListenerAdapter( ArtifactTransferListener listener ) - { + private TransferListenerAdapter(ArtifactTransferListener listener) { this.listener = listener; this.artifacts = new IdentityHashMap<>(); this.transfers = new IdentityHashMap<>(); } - public void debug( String message ) - { - } + public void debug(String message) {} - public void transferCompleted( TransferEvent transferEvent ) - { - ArtifactTransferEvent event = wrap( transferEvent ); + public void transferCompleted(TransferEvent transferEvent) { + ArtifactTransferEvent event = wrap(transferEvent); Long transferred; - synchronized ( transfers ) - { - transferred = transfers.remove( transferEvent.getResource() ); + synchronized (transfers) { + transferred = transfers.remove(transferEvent.getResource()); } - if ( transferred != null ) - { - event.setTransferredBytes( transferred ); + if (transferred != null) { + event.setTransferredBytes(transferred); } - synchronized ( artifacts ) - { - artifacts.remove( transferEvent.getResource() ); + synchronized (artifacts) { + artifacts.remove(transferEvent.getResource()); } - listener.transferCompleted( event ); + listener.transferCompleted(event); } - public void transferError( TransferEvent transferEvent ) - { - synchronized ( transfers ) - { - transfers.remove( transferEvent.getResource() ); + public void transferError(TransferEvent transferEvent) { + synchronized (transfers) { + transfers.remove(transferEvent.getResource()); } - synchronized ( artifacts ) - { - artifacts.remove( transferEvent.getResource() ); + synchronized (artifacts) { + artifacts.remove(transferEvent.getResource()); } } - public void transferInitiated( TransferEvent transferEvent ) - { - listener.transferInitiated( wrap( transferEvent ) ); + public void transferInitiated(TransferEvent transferEvent) { + listener.transferInitiated(wrap(transferEvent)); } - public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ) - { + public void transferProgress(TransferEvent transferEvent, byte[] buffer, int length) { Long transferred; - synchronized ( transfers ) - { - transferred = transfers.get( transferEvent.getResource() ); - if ( transferred == null ) - { + synchronized (transfers) { + transferred = transfers.get(transferEvent.getResource()); + if (transferred == null) { transferred = (long) length; - } - else - { + } else { transferred = transferred + length; } - transfers.put( transferEvent.getResource(), transferred ); + transfers.put(transferEvent.getResource(), transferred); } - ArtifactTransferEvent event = wrap( transferEvent ); - event.setDataBuffer( buffer ); - event.setDataOffset( 0 ); - event.setDataLength( length ); - event.setTransferredBytes( transferred ); + ArtifactTransferEvent event = wrap(transferEvent); + event.setDataBuffer(buffer); + event.setDataOffset(0); + event.setDataLength(length); + event.setTransferredBytes(transferred); - listener.transferProgress( event ); + listener.transferProgress(event); } - public void transferStarted( TransferEvent transferEvent ) - { - listener.transferStarted( wrap( transferEvent ) ); + public void transferStarted(TransferEvent transferEvent) { + listener.transferStarted(wrap(transferEvent)); } - private ArtifactTransferEvent wrap( TransferEvent event ) - { - if ( event == null ) - { + private ArtifactTransferEvent wrap(TransferEvent event) { + if (event == null) { return null; - } - else - { + } else { String wagon = event.getWagon().getClass().getName(); - ArtifactTransferResource artifact = wrap( event.getWagon().getRepository(), event.getResource() ); + ArtifactTransferResource artifact = wrap(event.getWagon().getRepository(), event.getResource()); ArtifactTransferEvent evt; - if ( event.getException() != null ) - { - evt = new ArtifactTransferEvent( wagon, event.getException(), event.getRequestType(), artifact ); - } - else - { - evt = new ArtifactTransferEvent( wagon, event.getEventType(), event.getRequestType(), artifact ); + if (event.getException() != null) { + evt = new ArtifactTransferEvent(wagon, event.getException(), event.getRequestType(), artifact); + } else { + evt = new ArtifactTransferEvent(wagon, event.getEventType(), event.getRequestType(), artifact); } - evt.setLocalFile( event.getLocalFile() ); + evt.setLocalFile(event.getLocalFile()); return evt; } } - private ArtifactTransferResource wrap( Repository repository, Resource resource ) - { - if ( resource == null ) - { + private ArtifactTransferResource wrap(Repository repository, Resource resource) { + if (resource == null) { return null; - } - else - { - synchronized ( artifacts ) - { - ArtifactTransferResource artifact = artifacts.get( resource ); + } else { + synchronized (artifacts) { + ArtifactTransferResource artifact = artifacts.get(resource); - if ( artifact == null ) - { - artifact = new MavenArtifact( repository.getUrl(), resource ); - artifacts.put( resource, artifact ); + if (artifact == null) { + artifact = new MavenArtifact(repository.getUrl(), resource); + artifacts.put(resource, artifact); } return artifact; } } } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/UpdateCheckManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/UpdateCheckManager.java index 0ef8c6ae4a..a22f03b87c 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/UpdateCheckManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/UpdateCheckManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import java.io.File; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.metadata.RepositoryMetadata; @@ -28,17 +26,15 @@ import org.apache.maven.artifact.repository.metadata.RepositoryMetadata; /** * UpdateCheckManager */ -public interface UpdateCheckManager -{ +public interface UpdateCheckManager { - boolean isUpdateRequired( Artifact artifact, ArtifactRepository repository ); + boolean isUpdateRequired(Artifact artifact, ArtifactRepository repository); - void touch( Artifact artifact, ArtifactRepository repository, String error ); + void touch(Artifact artifact, ArtifactRepository repository, String error); - String getError( Artifact artifact, ArtifactRepository repository ); + String getError(Artifact artifact, ArtifactRepository repository); - boolean isUpdateRequired( RepositoryMetadata metadata, ArtifactRepository repository, File file ); - - void touch( RepositoryMetadata metadata, ArtifactRepository repository, File file ); + boolean isUpdateRequired(RepositoryMetadata metadata, ArtifactRepository repository, File file); + void touch(RepositoryMetadata metadata, ArtifactRepository repository, File file); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonConfigurationException.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonConfigurationException.java index 67b9ec76d4..9236849e2e 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonConfigurationException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonConfigurationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,48 +16,39 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import org.apache.maven.wagon.TransferFailedException; /** * WagonConfigurationException */ -public class WagonConfigurationException - extends TransferFailedException -{ +public class WagonConfigurationException extends TransferFailedException { static final long serialVersionUID = 1; private final String originalMessage; private final String repositoryId; - public WagonConfigurationException( String repositoryId, - String message, - Throwable cause ) - { - super( "While configuring wagon for '" + repositoryId + "': " + message, cause ); + public WagonConfigurationException(String repositoryId, String message, Throwable cause) { + super("While configuring wagon for '" + repositoryId + "': " + message, cause); this.repositoryId = repositoryId; this.originalMessage = message; } - public WagonConfigurationException( String repositoryId, - String message ) - { - super( "While configuring wagon for '" + repositoryId + "': " + message ); + public WagonConfigurationException(String repositoryId, String message) { + super("While configuring wagon for '" + repositoryId + "': " + message); this.repositoryId = repositoryId; this.originalMessage = message; } - public final String getRepositoryId() - { + public final String getRepositoryId() { return repositoryId; } - public final String getOriginalMessage() - { + public final String getOriginalMessage() { return originalMessage; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonManager.java index 61568186ee..1652305528 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/WagonManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import java.io.File; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -35,50 +33,53 @@ import org.apache.maven.wagon.repository.Repository; /** * WagonManager */ -public interface WagonManager -{ +public interface WagonManager { @Deprecated - Wagon getWagon( String protocol ) - throws UnsupportedProtocolException; + Wagon getWagon(String protocol) throws UnsupportedProtocolException; @Deprecated - Wagon getWagon( Repository repository ) - throws UnsupportedProtocolException, WagonConfigurationException; + Wagon getWagon(Repository repository) throws UnsupportedProtocolException, WagonConfigurationException; // // Retriever // - void getArtifact( Artifact artifact, ArtifactRepository repository, TransferListener transferListener, - boolean force ) - throws TransferFailedException, ResourceDoesNotExistException; + void getArtifact(Artifact artifact, ArtifactRepository repository, TransferListener transferListener, boolean force) + throws TransferFailedException, ResourceDoesNotExistException; - void getArtifact( Artifact artifact, List remoteRepositories, - TransferListener transferListener, boolean force ) - throws TransferFailedException, ResourceDoesNotExistException; + void getArtifact( + Artifact artifact, + List remoteRepositories, + TransferListener transferListener, + boolean force) + throws TransferFailedException, ResourceDoesNotExistException; - void getRemoteFile( ArtifactRepository repository, File destination, String remotePath, - TransferListener downloadMonitor, String checksumPolicy, boolean force ) - throws TransferFailedException, ResourceDoesNotExistException; + void getRemoteFile( + ArtifactRepository repository, + File destination, + String remotePath, + TransferListener downloadMonitor, + String checksumPolicy, + boolean force) + throws TransferFailedException, ResourceDoesNotExistException; - void getArtifactMetadata( ArtifactMetadata metadata, ArtifactRepository remoteRepository, File destination, - String checksumPolicy ) - throws TransferFailedException, ResourceDoesNotExistException; + void getArtifactMetadata( + ArtifactMetadata metadata, ArtifactRepository remoteRepository, File destination, String checksumPolicy) + throws TransferFailedException, ResourceDoesNotExistException; - void getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository remoteRepository, - File file, String checksumPolicyWarn ) - throws TransferFailedException, ResourceDoesNotExistException; + void getArtifactMetadataFromDeploymentRepository( + ArtifactMetadata metadata, ArtifactRepository remoteRepository, File file, String checksumPolicyWarn) + throws TransferFailedException, ResourceDoesNotExistException; // // Deployer // - void putArtifact( File source, Artifact artifact, ArtifactRepository deploymentRepository, - TransferListener downloadMonitor ) - throws TransferFailedException; + void putArtifact( + File source, Artifact artifact, ArtifactRepository deploymentRepository, TransferListener downloadMonitor) + throws TransferFailedException; - void putRemoteFile( ArtifactRepository repository, File source, String remotePath, - TransferListener downloadMonitor ) - throws TransferFailedException; + void putRemoteFile(ArtifactRepository repository, File source, String remotePath, TransferListener downloadMonitor) + throws TransferFailedException; - void putArtifactMetadata( File source, ArtifactMetadata artifactMetadata, ArtifactRepository repository ) - throws TransferFailedException; + void putArtifactMetadata(File source, ArtifactMetadata artifactMetadata, ArtifactRepository repository) + throws TransferFailedException; } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/ArtifactRepositoryFactory.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/ArtifactRepositoryFactory.java index aeb5739d78..5fc0882985 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/ArtifactRepositoryFactory.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/ArtifactRepositoryFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.repository; import org.apache.maven.artifact.UnknownRepositoryLayoutException; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -25,34 +24,38 @@ import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; /** @author jdcasey */ -public interface ArtifactRepositoryFactory -{ +public interface ArtifactRepositoryFactory { String DEFAULT_LAYOUT_ID = "default"; String LOCAL_REPOSITORY_ID = "local"; @Deprecated - ArtifactRepositoryLayout getLayout( String layoutId ) - throws UnknownRepositoryLayoutException; + ArtifactRepositoryLayout getLayout(String layoutId) throws UnknownRepositoryLayoutException; @Deprecated - ArtifactRepository createDeploymentArtifactRepository( String id, String url, String layoutId, - boolean uniqueVersion ) - throws UnknownRepositoryLayoutException; + ArtifactRepository createDeploymentArtifactRepository(String id, String url, String layoutId, boolean uniqueVersion) + throws UnknownRepositoryLayoutException; - ArtifactRepository createDeploymentArtifactRepository( String id, String url, ArtifactRepositoryLayout layout, - boolean uniqueVersion ); + ArtifactRepository createDeploymentArtifactRepository( + String id, String url, ArtifactRepositoryLayout layout, boolean uniqueVersion); - ArtifactRepository createArtifactRepository( String id, String url, String layoutId, - ArtifactRepositoryPolicy snapshots, ArtifactRepositoryPolicy releases ) - throws UnknownRepositoryLayoutException; + ArtifactRepository createArtifactRepository( + String id, + String url, + String layoutId, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) + throws UnknownRepositoryLayoutException; - ArtifactRepository createArtifactRepository( String id, String url, ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ); + ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases); - void setGlobalUpdatePolicy( String snapshotPolicy ); + void setGlobalUpdatePolicy(String snapshotPolicy); - void setGlobalChecksumPolicy( String checksumPolicy ); + void setGlobalChecksumPolicy(String checksumPolicy); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory.java index fc6b441286..0570859208 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.repository; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.repository; import java.util.Map; - import org.apache.maven.artifact.UnknownRepositoryLayoutException; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -33,112 +31,95 @@ import org.codehaus.plexus.component.annotations.Requirement; /** * @author jdcasey */ -@Component( role = ArtifactRepositoryFactory.class ) -public class DefaultArtifactRepositoryFactory - implements ArtifactRepositoryFactory -{ +@Component(role = ArtifactRepositoryFactory.class) +public class DefaultArtifactRepositoryFactory implements ArtifactRepositoryFactory { // TODO use settings? private String globalUpdatePolicy; private String globalChecksumPolicy; - @Requirement( role = ArtifactRepositoryLayout.class ) + @Requirement(role = ArtifactRepositoryLayout.class) private Map repositoryLayouts; - public ArtifactRepositoryLayout getLayout( String layoutId ) - throws UnknownRepositoryLayoutException - { - return repositoryLayouts.get( layoutId ); + public ArtifactRepositoryLayout getLayout(String layoutId) throws UnknownRepositoryLayoutException { + return repositoryLayouts.get(layoutId); } - public ArtifactRepository createDeploymentArtifactRepository( String id, String url, String layoutId, - boolean uniqueVersion ) - throws UnknownRepositoryLayoutException - { - ArtifactRepositoryLayout layout = repositoryLayouts.get( layoutId ); + public ArtifactRepository createDeploymentArtifactRepository( + String id, String url, String layoutId, boolean uniqueVersion) throws UnknownRepositoryLayoutException { + ArtifactRepositoryLayout layout = repositoryLayouts.get(layoutId); - checkLayout( id, layoutId, layout ); + checkLayout(id, layoutId, layout); - return createDeploymentArtifactRepository( id, url, layout, uniqueVersion ); + return createDeploymentArtifactRepository(id, url, layout, uniqueVersion); } - private void checkLayout( String repositoryId, String layoutId, ArtifactRepositoryLayout layout ) - throws UnknownRepositoryLayoutException - { - if ( layout == null ) - { - throw new UnknownRepositoryLayoutException( repositoryId, layoutId ); + private void checkLayout(String repositoryId, String layoutId, ArtifactRepositoryLayout layout) + throws UnknownRepositoryLayoutException { + if (layout == null) { + throw new UnknownRepositoryLayoutException(repositoryId, layoutId); } } - public ArtifactRepository createDeploymentArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - boolean uniqueVersion ) - { - return createArtifactRepository( id, url, repositoryLayout, null, null ); + public ArtifactRepository createDeploymentArtifactRepository( + String id, String url, ArtifactRepositoryLayout repositoryLayout, boolean uniqueVersion) { + return createArtifactRepository(id, url, repositoryLayout, null, null); } - public ArtifactRepository createArtifactRepository( String id, String url, String layoutId, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - throws UnknownRepositoryLayoutException - { - ArtifactRepositoryLayout layout = repositoryLayouts.get( layoutId ); + public ArtifactRepository createArtifactRepository( + String id, + String url, + String layoutId, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) + throws UnknownRepositoryLayoutException { + ArtifactRepositoryLayout layout = repositoryLayouts.get(layoutId); - checkLayout( id, layoutId, layout ); + checkLayout(id, layoutId, layout); - return createArtifactRepository( id, url, layout, snapshots, releases ); + return createArtifactRepository(id, url, layout, snapshots, releases); } - public ArtifactRepository createArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - { - if ( snapshots == null ) - { + public ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + if (snapshots == null) { snapshots = new ArtifactRepositoryPolicy(); } - if ( releases == null ) - { + if (releases == null) { releases = new ArtifactRepositoryPolicy(); } - if ( globalUpdatePolicy != null ) - { - snapshots.setUpdatePolicy( globalUpdatePolicy ); - releases.setUpdatePolicy( globalUpdatePolicy ); + if (globalUpdatePolicy != null) { + snapshots.setUpdatePolicy(globalUpdatePolicy); + releases.setUpdatePolicy(globalUpdatePolicy); } - if ( globalChecksumPolicy != null ) - { - snapshots.setChecksumPolicy( globalChecksumPolicy ); - releases.setChecksumPolicy( globalChecksumPolicy ); + if (globalChecksumPolicy != null) { + snapshots.setChecksumPolicy(globalChecksumPolicy); + releases.setChecksumPolicy(globalChecksumPolicy); } ArtifactRepository repository; - if ( repositoryLayout instanceof ArtifactRepositoryLayout2 ) - { - repository = - ( (ArtifactRepositoryLayout2) repositoryLayout ).newMavenArtifactRepository( id, url, snapshots, - releases ); - } - else - { - repository = new MavenArtifactRepository( id, url, repositoryLayout, snapshots, releases ); + if (repositoryLayout instanceof ArtifactRepositoryLayout2) { + repository = ((ArtifactRepositoryLayout2) repositoryLayout) + .newMavenArtifactRepository(id, url, snapshots, releases); + } else { + repository = new MavenArtifactRepository(id, url, repositoryLayout, snapshots, releases); } return repository; } - public void setGlobalUpdatePolicy( String updatePolicy ) - { + public void setGlobalUpdatePolicy(String updatePolicy) { globalUpdatePolicy = updatePolicy; } - public void setGlobalChecksumPolicy( String checksumPolicy ) - { + public void setGlobalChecksumPolicy(String checksumPolicy) { globalChecksumPolicy = checksumPolicy; } - } +} diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/DefaultLegacyArtifactCollector.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/DefaultLegacyArtifactCollector.java index a14db6c416..2bfbac0ac0 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/DefaultLegacyArtifactCollector.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/DefaultLegacyArtifactCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver; import java.util.ArrayList; import java.util.Collections; @@ -27,7 +26,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.metadata.ResolutionGroup; @@ -59,12 +57,10 @@ import org.codehaus.plexus.logging.Logger; * @author Brett Porter * @author Jason van Zyl */ -@Component( role = LegacyArtifactCollector.class ) -public class DefaultLegacyArtifactCollector - implements LegacyArtifactCollector -{ +@Component(role = LegacyArtifactCollector.class) +public class DefaultLegacyArtifactCollector implements LegacyArtifactCollector { - @Requirement( hint = "nearest" ) + @Requirement(hint = "nearest") private ConflictResolver defaultConflictResolver; @Requirement @@ -73,133 +69,123 @@ public class DefaultLegacyArtifactCollector @Requirement private LegacySupport legacySupport; - private void injectSession( ArtifactResolutionRequest request ) - { + private void injectSession(ArtifactResolutionRequest request) { MavenSession session = legacySupport.getSession(); - if ( session != null ) - { - request.setOffline( session.isOffline() ); - request.setForceUpdate( session.getRequest().isUpdateSnapshots() ); - request.setServers( session.getRequest().getServers() ); - request.setMirrors( session.getRequest().getMirrors() ); - request.setProxies( session.getRequest().getProxies() ); + if (session != null) { + request.setOffline(session.isOffline()); + request.setForceUpdate(session.getRequest().isUpdateSnapshots()); + request.setServers(session.getRequest().getServers()); + request.setMirrors(session.getRequest().getMirrors()); + request.setProxies(session.getRequest().getProxies()); } } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - Map managedVersions, ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners, - List conflictResolvers ) - { + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners, + List conflictResolvers) { ArtifactResolutionRequest request = new ArtifactResolutionRequest(); - request.setLocalRepository( localRepository ); - request.setRemoteRepositories( remoteRepositories ); - injectSession( request ); - return collect( artifacts, originatingArtifact, managedVersions, request, source, filter, listeners, - conflictResolvers ); + request.setLocalRepository(localRepository); + request.setRemoteRepositories(remoteRepositories); + injectSession(request); + return collect( + artifacts, originatingArtifact, managedVersions, request, source, filter, listeners, conflictResolvers); } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactResolutionRequest repositoryRequest, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners, - List conflictResolvers ) - { + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactResolutionRequest repositoryRequest, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners, + List conflictResolvers) { ArtifactResolutionResult result = new ArtifactResolutionResult(); - result.setOriginatingArtifact( originatingArtifact ); + result.setOriginatingArtifact(originatingArtifact); - if ( conflictResolvers == null ) - { - conflictResolvers = Collections.singletonList( defaultConflictResolver ); + if (conflictResolvers == null) { + conflictResolvers = Collections.singletonList(defaultConflictResolver); } Map> resolvedArtifacts = new LinkedHashMap<>(); - ResolutionNode root = new ResolutionNode( originatingArtifact, repositoryRequest.getRemoteRepositories() ); + ResolutionNode root = new ResolutionNode(originatingArtifact, repositoryRequest.getRemoteRepositories()); - try - { - root.addDependencies( artifacts, repositoryRequest.getRemoteRepositories(), filter ); - } - catch ( CyclicDependencyException e ) - { - result.addCircularDependencyException( e ); + try { + root.addDependencies(artifacts, repositoryRequest.getRemoteRepositories(), filter); + } catch (CyclicDependencyException e) { + result.addCircularDependencyException(e); return result; - } - catch ( OverConstrainedVersionException e ) - { - result.addVersionRangeViolation( e ); + } catch (OverConstrainedVersionException e) { + result.addVersionRangeViolation(e); return result; } - ManagedVersionMap versionMap = getManagedVersionsMap( originatingArtifact, managedVersions ); + ManagedVersionMap versionMap = getManagedVersionsMap(originatingArtifact, managedVersions); - try - { - recurse( result, root, resolvedArtifacts, versionMap, repositoryRequest, source, filter, listeners, - conflictResolvers ); - } - catch ( CyclicDependencyException e ) - { - logger.debug( "While recursing: " + e.getMessage(), e ); - result.addCircularDependencyException( e ); - } - catch ( OverConstrainedVersionException e ) - { - logger.debug( "While recursing: " + e.getMessage(), e ); - result.addVersionRangeViolation( e ); - } - catch ( ArtifactResolutionException e ) - { - logger.debug( "While recursing: " + e.getMessage(), e ); - result.addErrorArtifactException( e ); + try { + recurse( + result, + root, + resolvedArtifacts, + versionMap, + repositoryRequest, + source, + filter, + listeners, + conflictResolvers); + } catch (CyclicDependencyException e) { + logger.debug("While recursing: " + e.getMessage(), e); + result.addCircularDependencyException(e); + } catch (OverConstrainedVersionException e) { + logger.debug("While recursing: " + e.getMessage(), e); + result.addVersionRangeViolation(e); + } catch (ArtifactResolutionException e) { + logger.debug("While recursing: " + e.getMessage(), e); + result.addErrorArtifactException(e); } Set set = new LinkedHashSet<>(); - for ( List nodes : resolvedArtifacts.values() ) - { - for ( ResolutionNode node : nodes ) - { - if ( !node.equals( root ) && node.isActive() ) - { + for (List nodes : resolvedArtifacts.values()) { + for (ResolutionNode node : nodes) { + if (!node.equals(root) && node.isActive()) { Artifact artifact = node.getArtifact(); - try - { - if ( node.filterTrail( filter ) ) - { + try { + if (node.filterTrail(filter)) { // If it was optional and not a direct dependency, // we don't add it or its children, just allow the update of the version and artifactScope - if ( node.isChildOfRootNode() || !artifact.isOptional() ) - { - artifact.setDependencyTrail( node.getDependencyTrail() ); + if (node.isChildOfRootNode() || !artifact.isOptional()) { + artifact.setDependencyTrail(node.getDependencyTrail()); - set.add( node ); + set.add(node); // This is required right now. - result.addArtifact( artifact ); + result.addArtifact(artifact); } } - } - catch ( OverConstrainedVersionException e ) - { - result.addVersionRangeViolation( e ); + } catch (OverConstrainedVersionException e) { + result.addVersionRangeViolation(e); } } } } - result.setArtifactResolutionNodes( set ); + result.setArtifactResolutionNodes(set); return result; } @@ -210,179 +196,158 @@ public class DefaultLegacyArtifactCollector * @param originatingArtifact artifact we are processing * @param managedVersions original managed versions */ - private ManagedVersionMap getManagedVersionsMap( Artifact originatingArtifact, - Map managedVersions ) - { + private ManagedVersionMap getManagedVersionsMap( + Artifact originatingArtifact, Map managedVersions) { ManagedVersionMap versionMap; - if ( managedVersions instanceof ManagedVersionMap ) - { + if (managedVersions instanceof ManagedVersionMap) { versionMap = (ManagedVersionMap) managedVersions; - } - else - { - versionMap = new ManagedVersionMap( managedVersions ); + } else { + versionMap = new ManagedVersionMap(managedVersions); } // remove the originating artifact if it is also in managed versions to avoid being modified during resolution - Artifact managedOriginatingArtifact = versionMap.get( originatingArtifact.getDependencyConflictId() ); + Artifact managedOriginatingArtifact = versionMap.get(originatingArtifact.getDependencyConflictId()); - if ( managedOriginatingArtifact != null ) - { + if (managedOriginatingArtifact != null) { // TODO we probably want to warn the user that he is building an artifact with // different values than in dependencyManagement - if ( managedVersions instanceof ManagedVersionMap ) - { + if (managedVersions instanceof ManagedVersionMap) { /* avoid modifying the managedVersions parameter creating a new map */ - versionMap = new ManagedVersionMap( managedVersions ); + versionMap = new ManagedVersionMap(managedVersions); } - versionMap.remove( originatingArtifact.getDependencyConflictId() ); + versionMap.remove(originatingArtifact.getDependencyConflictId()); } return versionMap; } - @SuppressWarnings( { "checkstyle:parameternumber", "checkstyle:methodlength" } ) - private void recurse( ArtifactResolutionResult result, ResolutionNode node, - Map> resolvedArtifacts, ManagedVersionMap managedVersions, - ArtifactResolutionRequest request, ArtifactMetadataSource source, ArtifactFilter filter, - List listeners, List conflictResolvers ) - throws ArtifactResolutionException - { - fireEvent( ResolutionListener.TEST_ARTIFACT, listeners, node ); + @SuppressWarnings({"checkstyle:parameternumber", "checkstyle:methodlength"}) + private void recurse( + ArtifactResolutionResult result, + ResolutionNode node, + Map> resolvedArtifacts, + ManagedVersionMap managedVersions, + ArtifactResolutionRequest request, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners, + List conflictResolvers) + throws ArtifactResolutionException { + fireEvent(ResolutionListener.TEST_ARTIFACT, listeners, node); Object key = node.getKey(); // TODO Does this check need to happen here? Had to add the same call // below when we iterate on child nodes -- will that suffice? - if ( managedVersions.containsKey( key ) ) - { - manageArtifact( node, managedVersions, listeners ); + if (managedVersions.containsKey(key)) { + manageArtifact(node, managedVersions, listeners); } - List previousNodes = resolvedArtifacts.get( key ); + List previousNodes = resolvedArtifacts.get(key); - if ( previousNodes != null ) - { - for ( ResolutionNode previous : previousNodes ) - { - try - { - if ( previous.isActive() ) - { + if (previousNodes != null) { + for (ResolutionNode previous : previousNodes) { + try { + if (previous.isActive()) { // Version mediation VersionRange previousRange = previous.getArtifact().getVersionRange(); VersionRange currentRange = node.getArtifact().getVersionRange(); - if ( ( previousRange != null ) && ( currentRange != null ) ) - { + if ((previousRange != null) && (currentRange != null)) { // TODO shouldn't need to double up on this work, only done for simplicity of handling // recommended // version but the restriction is identical - VersionRange newRange = previousRange.restrict( currentRange ); + VersionRange newRange = previousRange.restrict(currentRange); // TODO ick. this forces the OCE that should have come from the previous call. It is still // correct - if ( newRange.isSelectedVersionKnown( previous.getArtifact() ) ) - { - fireEvent( ResolutionListener.RESTRICT_RANGE, listeners, node, previous.getArtifact(), - newRange ); + if (newRange.isSelectedVersionKnown(previous.getArtifact())) { + fireEvent( + ResolutionListener.RESTRICT_RANGE, + listeners, + node, + previous.getArtifact(), + newRange); } - previous.getArtifact().setVersionRange( newRange ); - node.getArtifact().setVersionRange( currentRange.restrict( previousRange ) ); + previous.getArtifact().setVersionRange(newRange); + node.getArtifact().setVersionRange(currentRange.restrict(previousRange)); // Select an appropriate available version from the (now restricted) range // Note this version was selected before to get the appropriate POM // But it was reset by the call to setVersionRange on restricting the version - ResolutionNode[] resetNodes = - { - previous, node - }; - for ( int j = 0; j < 2; j++ ) - { + ResolutionNode[] resetNodes = {previous, node}; + for (int j = 0; j < 2; j++) { Artifact resetArtifact = resetNodes[j].getArtifact(); // MNG-2123: if the previous node was not a range, then it wouldn't have any available // versions. We just clobbered the selected version above. (why? I have no idea.) // So since we are here and this is ranges we must go figure out the version (for a // third time...) - if ( resetArtifact.getVersion() == null && resetArtifact.getVersionRange() != null ) - { + if (resetArtifact.getVersion() == null && resetArtifact.getVersionRange() != null) { // go find the version. This is a total hack. See previous comment. List versions = resetArtifact.getAvailableVersions(); - if ( versions == null ) - { - try - { + if (versions == null) { + try { MetadataResolutionRequest metadataRequest = - new DefaultMetadataResolutionRequest( request ); + new DefaultMetadataResolutionRequest(request); - metadataRequest.setArtifact( resetArtifact ); - versions = source.retrieveAvailableVersions( metadataRequest ); - resetArtifact.setAvailableVersions( versions ); - } - catch ( ArtifactMetadataRetrievalException e ) - { - resetArtifact.setDependencyTrail( node.getDependencyTrail() ); + metadataRequest.setArtifact(resetArtifact); + versions = source.retrieveAvailableVersions(metadataRequest); + resetArtifact.setAvailableVersions(versions); + } catch (ArtifactMetadataRetrievalException e) { + resetArtifact.setDependencyTrail(node.getDependencyTrail()); throw new ArtifactResolutionException( - "Unable to get dependency information: " - + e.getMessage(), resetArtifact, request.getRemoteRepositories(), - e ); - + "Unable to get dependency information: " + e.getMessage(), + resetArtifact, + request.getRemoteRepositories(), + e); } } // end hack // MNG-2861: match version can return null - ArtifactVersion selectedVersion = resetArtifact.getVersionRange(). - matchVersion( resetArtifact.getAvailableVersions() ); + ArtifactVersion selectedVersion = resetArtifact + .getVersionRange() + .matchVersion(resetArtifact.getAvailableVersions()); - if ( selectedVersion != null ) - { - resetArtifact.selectVersion( selectedVersion.toString() ); - } - else - { + if (selectedVersion != null) { + resetArtifact.selectVersion(selectedVersion.toString()); + } else { throw new OverConstrainedVersionException( - "Unable to find a version in " + resetArtifact.getAvailableVersions() - + " to match the range " + resetArtifact.getVersionRange(), - resetArtifact ); - + "Unable to find a version in " + resetArtifact.getAvailableVersions() + + " to match the range " + resetArtifact.getVersionRange(), + resetArtifact); } - fireEvent( ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, resetNodes[j] ); + fireEvent(ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, resetNodes[j]); } } } // Conflict Resolution ResolutionNode resolved = null; - for ( Iterator j = conflictResolvers.iterator(); - resolved == null && j.hasNext(); ) - { + for (Iterator j = conflictResolvers.iterator(); + resolved == null && j.hasNext(); ) { ConflictResolver conflictResolver = j.next(); - resolved = conflictResolver.resolveConflict( previous, node ); + resolved = conflictResolver.resolveConflict(previous, node); } - if ( resolved == null ) - { + if (resolved == null) { // TODO add better exception that can detail the two conflicting artifacts - ArtifactResolutionException are = - new ArtifactResolutionException( "Cannot resolve artifact version conflict between " - + previous.getArtifact().getVersion() + " and " - + node.getArtifact().getVersion(), - previous.getArtifact() ); + ArtifactResolutionException are = new ArtifactResolutionException( + "Cannot resolve artifact version conflict between " + + previous.getArtifact().getVersion() + " and " + + node.getArtifact().getVersion(), + previous.getArtifact()); - result.addVersionRangeViolation( are ); + result.addVersionRangeViolation(are); } - if ( ( resolved != previous ) && ( resolved != node ) ) - { + if ((resolved != previous) && (resolved != node)) { // TODO add better exception - result.addVersionRangeViolation( new ArtifactResolutionException( - "Conflict resolver returned unknown resolution node: ", - resolved.getArtifact() ) ); - + result.addVersionRangeViolation(new ArtifactResolutionException( + "Conflict resolver returned unknown resolution node: ", resolved.getArtifact())); } // TODO should this be part of mediation? @@ -390,176 +355,146 @@ public class DefaultLegacyArtifactCollector ResolutionNode nearest; ResolutionNode farthest; - if ( resolved == previous ) - { + if (resolved == previous) { nearest = previous; farthest = node; - } - else - { + } else { nearest = node; farthest = previous; } - if ( checkScopeUpdate( farthest, nearest, listeners ) ) - { + if (checkScopeUpdate(farthest, nearest, listeners)) { // if we need to update artifactScope of nearest to use farthest artifactScope, use the // nearest version, but farthest artifactScope nearest.disable(); - farthest.getArtifact().setVersion( nearest.getArtifact().getVersion() ); - fireEvent( ResolutionListener.OMIT_FOR_NEARER, listeners, nearest, farthest.getArtifact() ); - } - else - { + farthest.getArtifact() + .setVersion(nearest.getArtifact().getVersion()); + fireEvent(ResolutionListener.OMIT_FOR_NEARER, listeners, nearest, farthest.getArtifact()); + } else { farthest.disable(); - fireEvent( ResolutionListener.OMIT_FOR_NEARER, listeners, farthest, nearest.getArtifact() ); + fireEvent(ResolutionListener.OMIT_FOR_NEARER, listeners, farthest, nearest.getArtifact()); } } - } - catch ( OverConstrainedVersionException e ) - { - result.addVersionRangeViolation( e ); + } catch (OverConstrainedVersionException e) { + result.addVersionRangeViolation(e); } } - } - else - { + } else { previousNodes = new ArrayList<>(); - resolvedArtifacts.put( key, previousNodes ); + resolvedArtifacts.put(key, previousNodes); } - previousNodes.add( node ); + previousNodes.add(node); - if ( node.isActive() ) - { - fireEvent( ResolutionListener.INCLUDE_ARTIFACT, listeners, node ); + if (node.isActive()) { + fireEvent(ResolutionListener.INCLUDE_ARTIFACT, listeners, node); } // don't pull in the transitive deps of a system-scoped dependency. - if ( node.isActive() && !Artifact.SCOPE_SYSTEM.equals( node.getArtifact().getScope() ) ) - { - fireEvent( ResolutionListener.PROCESS_CHILDREN, listeners, node ); + if (node.isActive() && !Artifact.SCOPE_SYSTEM.equals(node.getArtifact().getScope())) { + fireEvent(ResolutionListener.PROCESS_CHILDREN, listeners, node); Artifact parentArtifact = node.getArtifact(); - for ( Iterator i = node.getChildrenIterator(); i.hasNext(); ) - { + for (Iterator i = node.getChildrenIterator(); i.hasNext(); ) { ResolutionNode child = i.next(); - try - { + try { // We leave in optional ones, but don't pick up its dependencies - if ( !child.isResolved() && ( !child.getArtifact().isOptional() || child.isChildOfRootNode() ) ) - { + if (!child.isResolved() && (!child.getArtifact().isOptional() || child.isChildOfRootNode())) { Artifact artifact = child.getArtifact(); - artifact.setDependencyTrail( node.getDependencyTrail() ); + artifact.setDependencyTrail(node.getDependencyTrail()); List childRemoteRepositories = child.getRemoteRepositories(); - MetadataResolutionRequest metadataRequest = - new DefaultMetadataResolutionRequest( request ); - metadataRequest.setArtifact( artifact ); - metadataRequest.setRemoteRepositories( childRemoteRepositories ); + MetadataResolutionRequest metadataRequest = new DefaultMetadataResolutionRequest(request); + metadataRequest.setArtifact(artifact); + metadataRequest.setRemoteRepositories(childRemoteRepositories); - try - { + try { ResolutionGroup rGroup; Object childKey; - do - { + do { childKey = child.getKey(); - if ( managedVersions.containsKey( childKey ) ) - { + if (managedVersions.containsKey(childKey)) { // If this child node is a managed dependency, ensure // we are using the dependency management version // of this child if applicable b/c we want to use the // managed version's POM, *not* any other version's POM. // We retrieve the POM below in the retrieval step. - manageArtifact( child, managedVersions, listeners ); + manageArtifact(child, managedVersions, listeners); // Also, we need to ensure that any exclusions it presents are // added to the artifact before we retrieve the metadata // for the artifact; otherwise we may end up with unwanted // dependencies. - Artifact ma = managedVersions.get( childKey ); + Artifact ma = managedVersions.get(childKey); ArtifactFilter managedExclusionFilter = ma.getDependencyFilter(); - if ( null != managedExclusionFilter ) - { - if ( null != artifact.getDependencyFilter() ) - { + if (null != managedExclusionFilter) { + if (null != artifact.getDependencyFilter()) { AndArtifactFilter aaf = new AndArtifactFilter(); - aaf.add( artifact.getDependencyFilter() ); - aaf.add( managedExclusionFilter ); - artifact.setDependencyFilter( aaf ); - } - else - { - artifact.setDependencyFilter( managedExclusionFilter ); + aaf.add(artifact.getDependencyFilter()); + aaf.add(managedExclusionFilter); + artifact.setDependencyFilter(aaf); + } else { + artifact.setDependencyFilter(managedExclusionFilter); } } } - if ( artifact.getVersion() == null ) - { + if (artifact.getVersion() == null) { // set the recommended version // TODO maybe its better to just pass the range through to retrieval and use a // transformation? ArtifactVersion version; - if ( !artifact.isSelectedVersionKnown() ) - { + if (!artifact.isSelectedVersionKnown()) { List versions = artifact.getAvailableVersions(); - if ( versions == null ) - { - versions = source.retrieveAvailableVersions( metadataRequest ); - artifact.setAvailableVersions( versions ); + if (versions == null) { + versions = source.retrieveAvailableVersions(metadataRequest); + artifact.setAvailableVersions(versions); } - Collections.sort( versions ); + Collections.sort(versions); VersionRange versionRange = artifact.getVersionRange(); - version = versionRange.matchVersion( versions ); + version = versionRange.matchVersion(versions); - if ( version == null ) - { - if ( versions.isEmpty() ) - { + if (version == null) { + if (versions.isEmpty()) { throw new OverConstrainedVersionException( - "No versions are present in the repository for the artifact" - + " with a range " + versionRange, artifact, - childRemoteRepositories ); - + "No versions are present in the repository for the artifact" + + " with a range " + versionRange, + artifact, + childRemoteRepositories); } throw new OverConstrainedVersionException( - "Couldn't find a version in " + versions + " to match range " - + versionRange, artifact, childRemoteRepositories ); - + "Couldn't find a version in " + versions + " to match range " + + versionRange, + artifact, + childRemoteRepositories); } - } - else - { + } else { version = artifact.getSelectedVersion(); } - artifact.selectVersion( version.toString() ); - fireEvent( ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, child ); + artifact.selectVersion(version.toString()); + fireEvent(ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, child); } - rGroup = source.retrieve( metadataRequest ); + rGroup = source.retrieve(metadataRequest); - if ( rGroup == null ) - { + if (rGroup == null) { break; } - } - while ( !childKey.equals( child.getKey() ) ); + } while (!childKey.equals(child.getKey())); - if ( parentArtifact != null && parentArtifact.getDependencyFilter() != null - && !parentArtifact.getDependencyFilter().include( artifact ) ) - { + if (parentArtifact != null + && parentArtifact.getDependencyFilter() != null + && !parentArtifact.getDependencyFilter().include(artifact)) { // MNG-3769: the [probably relocated] artifact is excluded. // We could process exclusions on relocated artifact details in the // MavenMetadataSource.createArtifacts(..) step, BUT that would @@ -571,60 +506,61 @@ public class DefaultLegacyArtifactCollector // TODO might be better to have source.retrieve() throw a specific exception for this // situation // and catch here rather than have it return null - if ( rGroup == null ) - { + if (rGroup == null) { // relocated dependency artifact is declared excluded, no need to add and recurse // further continue; } - child.addDependencies( rGroup.getArtifacts(), rGroup.getResolutionRepositories(), filter ); + child.addDependencies(rGroup.getArtifacts(), rGroup.getResolutionRepositories(), filter); - } - catch ( CyclicDependencyException e ) - { + } catch (CyclicDependencyException e) { // would like to throw this, but we have crappy stuff in the repo - fireEvent( ResolutionListener.OMIT_FOR_CYCLE, listeners, - new ResolutionNode( e.getArtifact(), childRemoteRepositories, child ) ); - } - catch ( ArtifactMetadataRetrievalException e ) - { - artifact.setDependencyTrail( node.getDependencyTrail() ); - - throw new ArtifactResolutionException( "Unable to get dependency information for " - + artifact.getId() + ": " + e.getMessage(), - artifact, childRemoteRepositories, e ); + fireEvent( + ResolutionListener.OMIT_FOR_CYCLE, + listeners, + new ResolutionNode(e.getArtifact(), childRemoteRepositories, child)); + } catch (ArtifactMetadataRetrievalException e) { + artifact.setDependencyTrail(node.getDependencyTrail()); + throw new ArtifactResolutionException( + "Unable to get dependency information for " + artifact.getId() + ": " + + e.getMessage(), + artifact, + childRemoteRepositories, + e); } - ArtifactResolutionRequest subRequest = new ArtifactResolutionRequest( metadataRequest ); - subRequest.setServers( request.getServers() ); - subRequest.setMirrors( request.getMirrors() ); - subRequest.setProxies( request.getProxies() ); - recurse( result, child, resolvedArtifacts, managedVersions, subRequest, source, filter, - listeners, conflictResolvers ); - + ArtifactResolutionRequest subRequest = new ArtifactResolutionRequest(metadataRequest); + subRequest.setServers(request.getServers()); + subRequest.setMirrors(request.getMirrors()); + subRequest.setProxies(request.getProxies()); + recurse( + result, + child, + resolvedArtifacts, + managedVersions, + subRequest, + source, + filter, + listeners, + conflictResolvers); } - } - catch ( OverConstrainedVersionException e ) - { - result.addVersionRangeViolation( e ); - } - catch ( ArtifactResolutionException e ) - { - result.addMetadataResolutionException( e ); + } catch (OverConstrainedVersionException e) { + result.addVersionRangeViolation(e); + } catch (ArtifactResolutionException e) { + result.addMetadataResolutionException(e); } } - fireEvent( ResolutionListener.FINISH_PROCESSING_CHILDREN, listeners, node ); + fireEvent(ResolutionListener.FINISH_PROCESSING_CHILDREN, listeners, node); } } - private void manageArtifact( ResolutionNode node, ManagedVersionMap managedVersions, - List listeners ) - { - Artifact artifact = managedVersions.get( node.getKey() ); + private void manageArtifact( + ResolutionNode node, ManagedVersionMap managedVersions, List listeners) { + Artifact artifact = managedVersions.get(node.getKey()); // Before we update the version of the artifact, we need to know // whether we are working on a transitive dependency or not. This @@ -632,24 +568,23 @@ public class DefaultLegacyArtifactCollector // explicit child override depMgmt (viz. depMgmt should only // provide defaults to children, but should override transitives). // We can do this by calling isChildOfRootNode on the current node. - if ( ( artifact.getVersion() != null ) - && ( !node.isChildOfRootNode() || node.getArtifact().getVersion() == null ) ) - { - fireEvent( ResolutionListener.MANAGE_ARTIFACT_VERSION, listeners, node, artifact ); - node.getArtifact().setVersion( artifact.getVersion() ); + if ((artifact.getVersion() != null) + && (!node.isChildOfRootNode() || node.getArtifact().getVersion() == null)) { + fireEvent(ResolutionListener.MANAGE_ARTIFACT_VERSION, listeners, node, artifact); + node.getArtifact().setVersion(artifact.getVersion()); } - if ( ( artifact.getScope() != null ) && ( !node.isChildOfRootNode() || node.getArtifact().getScope() == null ) ) - { - fireEvent( ResolutionListener.MANAGE_ARTIFACT_SCOPE, listeners, node, artifact ); - node.getArtifact().setScope( artifact.getScope() ); + if ((artifact.getScope() != null) + && (!node.isChildOfRootNode() || node.getArtifact().getScope() == null)) { + fireEvent(ResolutionListener.MANAGE_ARTIFACT_SCOPE, listeners, node, artifact); + node.getArtifact().setScope(artifact.getScope()); } - if ( Artifact.SCOPE_SYSTEM.equals( node.getArtifact().getScope() ) && ( node.getArtifact().getFile() == null ) - && ( artifact.getFile() != null ) ) - { - fireEvent( ResolutionListener.MANAGE_ARTIFACT_SYSTEM_PATH, listeners, node, artifact ); - node.getArtifact().setFile( artifact.getFile() ); + if (Artifact.SCOPE_SYSTEM.equals(node.getArtifact().getScope()) + && (node.getArtifact().getFile() == null) + && (artifact.getFile() != null)) { + fireEvent(ResolutionListener.MANAGE_ARTIFACT_SYSTEM_PATH, listeners, node, artifact); + node.getArtifact().setFile(artifact.getFile()); } } @@ -661,158 +596,154 @@ public class DefaultLegacyArtifactCollector * @param nearest nearest resolution node * @param listeners */ - boolean checkScopeUpdate( ResolutionNode farthest, ResolutionNode nearest, List listeners ) - { + boolean checkScopeUpdate(ResolutionNode farthest, ResolutionNode nearest, List listeners) { boolean updateScope = false; Artifact farthestArtifact = farthest.getArtifact(); Artifact nearestArtifact = nearest.getArtifact(); /* farthest is runtime and nearest has lower priority, change to runtime */ - if ( Artifact.SCOPE_RUNTIME.equals( farthestArtifact.getScope() ) - && ( Artifact.SCOPE_TEST.equals( nearestArtifact.getScope() ) - || Artifact.SCOPE_PROVIDED.equals( nearestArtifact.getScope() ) ) ) - { + if (Artifact.SCOPE_RUNTIME.equals(farthestArtifact.getScope()) + && (Artifact.SCOPE_TEST.equals(nearestArtifact.getScope()) + || Artifact.SCOPE_PROVIDED.equals(nearestArtifact.getScope()))) { updateScope = true; } /* farthest is compile and nearest is not (has lower priority), change to compile */ - if ( Artifact.SCOPE_COMPILE.equals( farthestArtifact.getScope() ) - && !Artifact.SCOPE_COMPILE.equals( nearestArtifact.getScope() ) ) - { + if (Artifact.SCOPE_COMPILE.equals(farthestArtifact.getScope()) + && !Artifact.SCOPE_COMPILE.equals(nearestArtifact.getScope())) { updateScope = true; } /* current POM rules all, if nearest is in current pom, do not update its artifactScope */ - if ( ( nearest.getDepth() < 2 ) && updateScope ) - { + if ((nearest.getDepth() < 2) && updateScope) { updateScope = false; - fireEvent( ResolutionListener.UPDATE_SCOPE_CURRENT_POM, listeners, nearest, farthestArtifact ); + fireEvent(ResolutionListener.UPDATE_SCOPE_CURRENT_POM, listeners, nearest, farthestArtifact); } - if ( updateScope ) - { - fireEvent( ResolutionListener.UPDATE_SCOPE, listeners, nearest, farthestArtifact ); + if (updateScope) { + fireEvent(ResolutionListener.UPDATE_SCOPE, listeners, nearest, farthestArtifact); // previously we cloned the artifact, but it is more efficient to just update the artifactScope // if problems are later discovered that the original object needs its original artifactScope value, // cloning may // again be appropriate - nearestArtifact.setScope( farthestArtifact.getScope() ); + nearestArtifact.setScope(farthestArtifact.getScope()); } return updateScope; } - private void fireEvent( int event, List listeners, ResolutionNode node ) - { - fireEvent( event, listeners, node, null ); + private void fireEvent(int event, List listeners, ResolutionNode node) { + fireEvent(event, listeners, node, null); } - private void fireEvent( int event, List listeners, ResolutionNode node, Artifact replacement ) - { - fireEvent( event, listeners, node, replacement, null ); + private void fireEvent(int event, List listeners, ResolutionNode node, Artifact replacement) { + fireEvent(event, listeners, node, replacement, null); } - private void fireEvent( int event, List listeners, ResolutionNode node, Artifact replacement, - VersionRange newRange ) - { - for ( ResolutionListener listener : listeners ) - { - switch ( event ) - { + private void fireEvent( + int event, + List listeners, + ResolutionNode node, + Artifact replacement, + VersionRange newRange) { + for (ResolutionListener listener : listeners) { + switch (event) { case ResolutionListener.TEST_ARTIFACT: - listener.testArtifact( node.getArtifact() ); + listener.testArtifact(node.getArtifact()); break; case ResolutionListener.PROCESS_CHILDREN: - listener.startProcessChildren( node.getArtifact() ); + listener.startProcessChildren(node.getArtifact()); break; case ResolutionListener.FINISH_PROCESSING_CHILDREN: - listener.endProcessChildren( node.getArtifact() ); + listener.endProcessChildren(node.getArtifact()); break; case ResolutionListener.INCLUDE_ARTIFACT: - listener.includeArtifact( node.getArtifact() ); + listener.includeArtifact(node.getArtifact()); break; case ResolutionListener.OMIT_FOR_NEARER: - listener.omitForNearer( node.getArtifact(), replacement ); + listener.omitForNearer(node.getArtifact(), replacement); break; case ResolutionListener.OMIT_FOR_CYCLE: - listener.omitForCycle( node.getArtifact() ); + listener.omitForCycle(node.getArtifact()); break; case ResolutionListener.UPDATE_SCOPE: - listener.updateScope( node.getArtifact(), replacement.getScope() ); + listener.updateScope(node.getArtifact(), replacement.getScope()); break; case ResolutionListener.UPDATE_SCOPE_CURRENT_POM: - listener.updateScopeCurrentPom( node.getArtifact(), replacement.getScope() ); + listener.updateScopeCurrentPom(node.getArtifact(), replacement.getScope()); break; case ResolutionListener.MANAGE_ARTIFACT_VERSION: - if ( listener instanceof ResolutionListenerForDepMgmt ) - { + if (listener instanceof ResolutionListenerForDepMgmt) { ResolutionListenerForDepMgmt asImpl = (ResolutionListenerForDepMgmt) listener; - asImpl.manageArtifactVersion( node.getArtifact(), replacement ); - } - else - { - listener.manageArtifact( node.getArtifact(), replacement ); + asImpl.manageArtifactVersion(node.getArtifact(), replacement); + } else { + listener.manageArtifact(node.getArtifact(), replacement); } break; case ResolutionListener.MANAGE_ARTIFACT_SCOPE: - if ( listener instanceof ResolutionListenerForDepMgmt ) - { + if (listener instanceof ResolutionListenerForDepMgmt) { ResolutionListenerForDepMgmt asImpl = (ResolutionListenerForDepMgmt) listener; - asImpl.manageArtifactScope( node.getArtifact(), replacement ); - } - else - { - listener.manageArtifact( node.getArtifact(), replacement ); + asImpl.manageArtifactScope(node.getArtifact(), replacement); + } else { + listener.manageArtifact(node.getArtifact(), replacement); } break; case ResolutionListener.MANAGE_ARTIFACT_SYSTEM_PATH: - if ( listener instanceof ResolutionListenerForDepMgmt ) - { + if (listener instanceof ResolutionListenerForDepMgmt) { ResolutionListenerForDepMgmt asImpl = (ResolutionListenerForDepMgmt) listener; - asImpl.manageArtifactSystemPath( node.getArtifact(), replacement ); - } - else - { - listener.manageArtifact( node.getArtifact(), replacement ); + asImpl.manageArtifactSystemPath(node.getArtifact(), replacement); + } else { + listener.manageArtifact(node.getArtifact(), replacement); } break; case ResolutionListener.SELECT_VERSION_FROM_RANGE: - listener.selectVersionFromRange( node.getArtifact() ); + listener.selectVersionFromRange(node.getArtifact()); break; case ResolutionListener.RESTRICT_RANGE: - if ( node.getArtifact().getVersionRange().hasRestrictions() - || replacement.getVersionRange().hasRestrictions() ) - { - listener.restrictRange( node.getArtifact(), replacement, newRange ); + if (node.getArtifact().getVersionRange().hasRestrictions() + || replacement.getVersionRange().hasRestrictions()) { + listener.restrictRange(node.getArtifact(), replacement, newRange); } break; default: - throw new IllegalStateException( "Unknown event: " + event ); + throw new IllegalStateException("Unknown event: " + event); } } } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - Map managedVersions, ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners ) - { - return collect( artifacts, originatingArtifact, managedVersions, localRepository, remoteRepositories, source, - filter, listeners, null ); + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners) { + return collect( + artifacts, + originatingArtifact, + managedVersions, + localRepository, + remoteRepositories, + source, + filter, + listeners, + null); } - public ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - ArtifactRepository localRepository, - List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners ) - { - return collect( artifacts, originatingArtifact, null, localRepository, remoteRepositories, source, filter, - listeners ); + public ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners) { + return collect( + artifacts, originatingArtifact, null, localRepository, remoteRepositories, source, filter, listeners); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/LegacyArtifactCollector.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/LegacyArtifactCollector.java index 90b869f298..6ce350d548 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/LegacyArtifactCollector.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/LegacyArtifactCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.repository.legacy.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -39,28 +37,39 @@ import org.apache.maven.repository.legacy.resolver.conflict.ConflictResolver; * @author Brett Porter */ @Deprecated -@SuppressWarnings( "checkstyle:parameternumber" ) -public interface LegacyArtifactCollector -{ +@SuppressWarnings("checkstyle:parameternumber") +public interface LegacyArtifactCollector { - ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactResolutionRequest repositoryRequest, ArtifactMetadataSource source, - ArtifactFilter filter, List listeners, - List conflictResolvers ); + ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactResolutionRequest repositoryRequest, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners, + List conflictResolvers); - ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactRepository localRepository, List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners, List conflictResolvers ); + ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners, + List conflictResolvers); // used by maven-dependency-tree and maven-dependency-plugin @Deprecated - ArtifactResolutionResult collect( Set artifacts, Artifact originatingArtifact, - Map managedVersions, - ArtifactRepository localRepository, List remoteRepositories, - ArtifactMetadataSource source, ArtifactFilter filter, - List listeners ); - + ArtifactResolutionResult collect( + Set artifacts, + Artifact originatingArtifact, + Map managedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ArtifactMetadataSource source, + ArtifactFilter filter, + List listeners); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolver.java index 4d129b7e76..89635e95dc 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; @@ -27,8 +26,7 @@ import org.apache.maven.artifact.resolver.ResolutionNode; * @author Jason van Zyl * @author Mark Hobson */ -public interface ConflictResolver -{ +public interface ConflictResolver { String ROLE = ConflictResolver.class.getName(); /** @@ -40,5 +38,5 @@ public interface ConflictResolver * this conflict cannot be resolved * @since 3.0 */ - ResolutionNode resolveConflict( ResolutionNode node1, ResolutionNode node2 ); + ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverFactory.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverFactory.java index 8f3f9f43e6..adbb30fd19 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverFactory.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; /** * A factory that produces conflict resolvers of various types. @@ -26,8 +25,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * @see ConflictResolver * @since 3.0 */ -public interface ConflictResolverFactory -{ +public interface ConflictResolverFactory { // constants -------------------------------------------------------------- /** The plexus role for this component. */ @@ -43,6 +41,5 @@ public interface ConflictResolverFactory * @throws ConflictResolverNotFoundException * if the specified type was not found */ - ConflictResolver getConflictResolver( String type ) - throws ConflictResolverNotFoundException; + ConflictResolver getConflictResolver(String type) throws ConflictResolverNotFoundException; } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverNotFoundException.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverNotFoundException.java index b5f61ed130..18516a759a 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverNotFoundException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; /** * Indicates that a specified conflict resolver implementation could not be found. @@ -25,9 +24,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * @author Mark Hobson * @since 3.0 */ -public class ConflictResolverNotFoundException - extends Exception -{ +public class ConflictResolverNotFoundException extends Exception { // constants -------------------------------------------------------------- /** The serial version ID. */ @@ -40,8 +37,7 @@ public class ConflictResolverNotFoundException * * @param message the message */ - public ConflictResolverNotFoundException( String message ) - { - super( message ); + public ConflictResolverNotFoundException(String message) { + super(message); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolver.java index 76f1929db5..d99798986c 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.codehaus.plexus.component.annotations.Component; @@ -29,8 +28,5 @@ import org.codehaus.plexus.component.annotations.Component; * @deprecated As of 3.0, use a specific implementation instead, e.g. {@link NearestConflictResolver} */ @Deprecated -@Component( role = ConflictResolver.class ) -public class DefaultConflictResolver - extends NearestConflictResolver -{ -} +@Component(role = ConflictResolver.class) +public class DefaultConflictResolver extends NearestConflictResolver {} diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolverFactory.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolverFactory.java index 9192b1857a..5a6dffb0d6 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolverFactory.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolverFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; @@ -35,10 +34,8 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; * TODO you don't need the container in here with the active maps (jvz). * @since 3.0 */ -@Component( role = ConflictResolverFactory.class ) -public class DefaultConflictResolverFactory - implements ConflictResolverFactory, Contextualizable -{ +@Component(role = ConflictResolverFactory.class) +public class DefaultConflictResolverFactory implements ConflictResolverFactory, Contextualizable { // fields ----------------------------------------------------------------- /** @@ -50,19 +47,14 @@ public class DefaultConflictResolverFactory // ConflictResolverFactory methods ---------------------------------------- /* - * @see org.apache.maven.artifact.resolver.conflict.ConflictResolverFactory#getConflictResolver(java.lang.String) - */ + * @see org.apache.maven.artifact.resolver.conflict.ConflictResolverFactory#getConflictResolver(java.lang.String) + */ - public ConflictResolver getConflictResolver( String type ) - throws ConflictResolverNotFoundException - { - try - { - return (ConflictResolver) container.lookup( ConflictResolver.ROLE, type ); - } - catch ( ComponentLookupException exception ) - { - throw new ConflictResolverNotFoundException( "Cannot find conflict resolver of type: " + type ); + public ConflictResolver getConflictResolver(String type) throws ConflictResolverNotFoundException { + try { + return (ConflictResolver) container.lookup(ConflictResolver.ROLE, type); + } catch (ComponentLookupException exception) { + throw new ConflictResolverNotFoundException("Cannot find conflict resolver of type: " + type); } } @@ -72,9 +64,7 @@ public class DefaultConflictResolverFactory * @see org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable#contextualize(org.codehaus.plexus.context.Context) */ - public void contextualize( Context context ) - throws ContextException - { - container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); + public void contextualize(Context context) throws ContextException { + container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolver.java index 726e9a6db4..89d32c90bb 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.codehaus.plexus.component.annotations.Component; @@ -29,19 +28,16 @@ import org.codehaus.plexus.component.annotations.Component; * @author Mark Hobson * @since 3.0 */ -@Component( role = ConflictResolver.class, hint = "farthest" ) -public class FarthestConflictResolver - implements ConflictResolver -{ +@Component(role = ConflictResolver.class, hint = "farthest") +public class FarthestConflictResolver implements ConflictResolver { // ConflictResolver methods ----------------------------------------------- /* - * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, - * org.apache.maven.artifact.resolver.ResolutionNode) - */ + * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, + * org.apache.maven.artifact.resolver.ResolutionNode) + */ - public ResolutionNode resolveConflict( ResolutionNode node1, ResolutionNode node2 ) - { + public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) { return node1.getDepth() >= node2.getDepth() ? node1 : node2; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver.java index 338baed613..a265835eee 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.codehaus.plexus.component.annotations.Component; @@ -30,19 +29,16 @@ import org.codehaus.plexus.component.annotations.Component; * @author Mark Hobson * @since 3.0 */ -@Component( role = ConflictResolver.class, hint = "nearest" ) -public class NearestConflictResolver - implements ConflictResolver -{ +@Component(role = ConflictResolver.class, hint = "nearest") +public class NearestConflictResolver implements ConflictResolver { // ConflictResolver methods ----------------------------------------------- /* - * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, - * org.apache.maven.artifact.resolver.ResolutionNode) - */ + * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, + * org.apache.maven.artifact.resolver.ResolutionNode) + */ - public ResolutionNode resolveConflict( ResolutionNode node1, ResolutionNode node2 ) - { + public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) { return node1.getDepth() <= node2.getDepth() ? node1 : node2; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolver.java index e5bf55801e..cd4fac8221 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -32,28 +31,22 @@ import org.codehaus.plexus.component.annotations.Component; * @see ArtifactVersion#compareTo * @since 3.0 */ -@Component( role = ConflictResolver.class, hint = "newest" ) -public class NewestConflictResolver - implements ConflictResolver -{ +@Component(role = ConflictResolver.class, hint = "newest") +public class NewestConflictResolver implements ConflictResolver { // ConflictResolver methods ----------------------------------------------- /* - * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, - * org.apache.maven.artifact.resolver.ResolutionNode) - */ + * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, + * org.apache.maven.artifact.resolver.ResolutionNode) + */ - public ResolutionNode resolveConflict( ResolutionNode node1, ResolutionNode node2 ) - { - try - { + public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) { + try { ArtifactVersion version1 = node1.getArtifact().getSelectedVersion(); ArtifactVersion version2 = node2.getArtifact().getSelectedVersion(); - return version1.compareTo( version2 ) > 0 ? node1 : node2; - } - catch ( OverConstrainedVersionException exception ) - { + return version1.compareTo(version2) > 0 ? node1 : node2; + } catch (OverConstrainedVersionException exception) { // TODO log message or throw exception? return null; diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolver.java index d5e880c86a..eee4bde2bd 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -32,28 +31,22 @@ import org.codehaus.plexus.component.annotations.Component; * @see ArtifactVersion#compareTo * @since 3.0 */ -@Component( role = ConflictResolver.class, hint = "oldest" ) -public class OldestConflictResolver - implements ConflictResolver -{ +@Component(role = ConflictResolver.class, hint = "oldest") +public class OldestConflictResolver implements ConflictResolver { // ConflictResolver methods ----------------------------------------------- /* - * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, - * org.apache.maven.artifact.resolver.ResolutionNode) - */ + * @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode, + * org.apache.maven.artifact.resolver.ResolutionNode) + */ - public ResolutionNode resolveConflict( ResolutionNode node1, ResolutionNode node2 ) - { - try - { + public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) { + try { ArtifactVersion version1 = node1.getArtifact().getSelectedVersion(); ArtifactVersion version2 = node2.getArtifact().getSelectedVersion(); - return version1.compareTo( version2 ) <= 0 ? node1 : node2; - } - catch ( OverConstrainedVersionException exception ) - { + return version1.compareTo(version2) <= 0 ? node1 : node2; + } catch (OverConstrainedVersionException exception) { // TODO log message or throw exception? return null; diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/AbstractVersionTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/AbstractVersionTransformation.java index 1ce54580b9..1ef8a51a94 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/AbstractVersionTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/AbstractVersionTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.DefaultRepositoryRequest; @@ -44,92 +42,74 @@ import org.codehaus.plexus.logging.AbstractLogEnabled; * @author Brett Porter * TODO try and refactor to remove abstract methods - not particular happy about current design */ -public abstract class AbstractVersionTransformation - extends AbstractLogEnabled - implements ArtifactTransformation -{ +public abstract class AbstractVersionTransformation extends AbstractLogEnabled implements ArtifactTransformation { @Requirement protected RepositoryMetadataManager repositoryMetadataManager; @Requirement protected WagonManager wagonManager; - public void transformForResolve( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException - { + public void transformForResolve( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException { RepositoryRequest request = new DefaultRepositoryRequest(); - request.setLocalRepository( localRepository ); - request.setRemoteRepositories( remoteRepositories ); - transformForResolve( artifact, request ); + request.setLocalRepository(localRepository); + request.setRemoteRepositories(remoteRepositories); + transformForResolve(artifact, request); } - protected String resolveVersion( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws RepositoryMetadataResolutionException - { + protected String resolveVersion( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws RepositoryMetadataResolutionException { RepositoryRequest request = new DefaultRepositoryRequest(); - request.setLocalRepository( localRepository ); - request.setRemoteRepositories( remoteRepositories ); - return resolveVersion( artifact, request ); + request.setLocalRepository(localRepository); + request.setRemoteRepositories(remoteRepositories); + return resolveVersion(artifact, request); } - protected String resolveVersion( Artifact artifact, RepositoryRequest request ) - throws RepositoryMetadataResolutionException - { + protected String resolveVersion(Artifact artifact, RepositoryRequest request) + throws RepositoryMetadataResolutionException { RepositoryMetadata metadata; // Don't use snapshot metadata for LATEST (which isSnapshot returns true for) - if ( !artifact.isSnapshot() || Artifact.LATEST_VERSION.equals( artifact.getBaseVersion() ) ) - { - metadata = new ArtifactRepositoryMetadata( artifact ); - } - else - { - metadata = new SnapshotArtifactRepositoryMetadata( artifact ); + if (!artifact.isSnapshot() || Artifact.LATEST_VERSION.equals(artifact.getBaseVersion())) { + metadata = new ArtifactRepositoryMetadata(artifact); + } else { + metadata = new SnapshotArtifactRepositoryMetadata(artifact); } - repositoryMetadataManager.resolve( metadata, request ); + repositoryMetadataManager.resolve(metadata, request); - artifact.addMetadata( metadata ); + artifact.addMetadata(metadata); Metadata repoMetadata = metadata.getMetadata(); String version = null; - if ( repoMetadata != null && repoMetadata.getVersioning() != null ) - { - version = constructVersion( repoMetadata.getVersioning(), artifact.getBaseVersion() ); + if (repoMetadata != null && repoMetadata.getVersioning() != null) { + version = constructVersion(repoMetadata.getVersioning(), artifact.getBaseVersion()); } - if ( version == null ) - { + if (version == null) { // use the local copy, or if it doesn't exist - go to the remote repo for it version = artifact.getBaseVersion(); } // TODO also do this logging for other metadata? // TODO figure out way to avoid duplicated message - if ( getLogger().isDebugEnabled() ) - { - if ( !version.equals( artifact.getBaseVersion() ) ) - { + if (getLogger().isDebugEnabled()) { + if (!version.equals(artifact.getBaseVersion())) { String message = artifact.getArtifactId() + ": resolved to version " + version; - if ( artifact.getRepository() != null ) - { + if (artifact.getRepository() != null) { message += " from repository " + artifact.getRepository().getId(); - } - else - { + } else { message += " from local repository"; } - getLogger().debug( message ); - } - else - { + getLogger().debug(message); + } else { // Locally installed file is newer, don't use the resolved version - getLogger().debug( artifact.getArtifactId() + ": using locally installed snapshot" ); + getLogger().debug(artifact.getArtifactId() + ": using locally installed snapshot"); } } return version; } - protected abstract String constructVersion( Versioning versioning, String baseVersion ); + protected abstract String constructVersion(Versioning versioning, String baseVersion); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformation.java index 4d20391cf7..39739f1c2a 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.deployer.ArtifactDeploymentException; import org.apache.maven.artifact.installer.ArtifactInstallationException; @@ -32,8 +30,7 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionException; /** * @author Jason van Zyl */ -public interface ArtifactTransformation -{ +public interface ArtifactTransformation { String ROLE = ArtifactTransformation.class.getName(); /** @@ -43,8 +40,8 @@ public interface ArtifactTransformation * @param artifact Artifact to be transformed. * @param request the repositories to check */ - void transformForResolve( Artifact artifact, RepositoryRequest request ) - throws ArtifactResolutionException, ArtifactNotFoundException; + void transformForResolve(Artifact artifact, RepositoryRequest request) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Take in an artifact and return the transformed artifact for locating in the remote repository. If no @@ -54,10 +51,9 @@ public interface ArtifactTransformation * @param remoteRepositories the repositories to check * @param localRepository the local repository */ - void transformForResolve( Artifact artifact, - List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException; + void transformForResolve( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Take in an artifact and return the transformed artifact for locating in the local repository. If no @@ -66,9 +62,8 @@ public interface ArtifactTransformation * @param artifact Artifact to be transformed. * @param localRepository the local repository it will be stored in */ - void transformForInstall( Artifact artifact, - ArtifactRepository localRepository ) - throws ArtifactInstallationException; + void transformForInstall(Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException; /** * Take in an artifact and return the transformed artifact for distributing to remote repository. If no @@ -78,9 +73,7 @@ public interface ArtifactTransformation * @param remoteRepository the repository to deploy to * @param localRepository the local repository */ - void transformForDeployment( Artifact artifact, - ArtifactRepository remoteRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException; - + void transformForDeployment( + Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) + throws ArtifactDeploymentException; } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformationManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformationManager.java index de88de84cd..029497f069 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformationManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformationManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.deployer.ArtifactDeploymentException; import org.apache.maven.artifact.installer.ArtifactInstallationException; @@ -32,8 +30,7 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionException; /** * Manages multiple ArtifactTransformation instances and applies them in succession. */ -public interface ArtifactTransformationManager -{ +public interface ArtifactTransformationManager { String ROLE = ArtifactTransformationManager.class.getName(); /** @@ -43,8 +40,8 @@ public interface ArtifactTransformationManager * @param artifact Artifact to be transformed. * @param request the repositories to check */ - void transformForResolve( Artifact artifact, RepositoryRequest request ) - throws ArtifactResolutionException, ArtifactNotFoundException; + void transformForResolve(Artifact artifact, RepositoryRequest request) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Take in an artifact and return the transformed artifact for locating in the remote repository. If no @@ -54,9 +51,9 @@ public interface ArtifactTransformationManager * @param remoteRepositories the repositories to check * @param localRepository the local repository */ - void transformForResolve( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException; + void transformForResolve( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Take in an artifact and return the transformed artifact for locating in the local repository. If no @@ -65,8 +62,8 @@ public interface ArtifactTransformationManager * @param artifact Artifact to be transformed. * @param localRepository the local repository it will be stored in */ - void transformForInstall( Artifact artifact, ArtifactRepository localRepository ) - throws ArtifactInstallationException; + void transformForInstall(Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException; /** * Take in an artifact and return the transformed artifact for distributing to a remote repository. If no @@ -76,9 +73,9 @@ public interface ArtifactTransformationManager * @param remoteRepository the repository to deploy to * @param localRepository the local repository the metadata is stored in */ - void transformForDeployment( Artifact artifact, ArtifactRepository remoteRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException; + void transformForDeployment( + Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) + throws ArtifactDeploymentException; List getArtifactTransformations(); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/DefaultArtifactTransformationManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/DefaultArtifactTransformationManager.java index 024778de9a..d61b006b8e 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/DefaultArtifactTransformationManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/DefaultArtifactTransformationManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.deployer.ArtifactDeploymentException; import org.apache.maven.artifact.installer.ArtifactInstallationException; @@ -34,53 +32,44 @@ import org.codehaus.plexus.component.annotations.Requirement; /** * @author Jason van Zyl */ -@Component( role = ArtifactTransformationManager.class ) -public class DefaultArtifactTransformationManager - implements ArtifactTransformationManager -{ - @Requirement( role = ArtifactTransformation.class, hints = { "release", "latest", "snapshot" } ) +@Component(role = ArtifactTransformationManager.class) +public class DefaultArtifactTransformationManager implements ArtifactTransformationManager { + @Requirement( + role = ArtifactTransformation.class, + hints = {"release", "latest", "snapshot"}) private List artifactTransformations; - public void transformForResolve( Artifact artifact, RepositoryRequest request ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - for ( ArtifactTransformation transform : artifactTransformations ) - { - transform.transformForResolve( artifact, request ); + public void transformForResolve(Artifact artifact, RepositoryRequest request) + throws ArtifactResolutionException, ArtifactNotFoundException { + for (ArtifactTransformation transform : artifactTransformations) { + transform.transformForResolve(artifact, request); } } - public void transformForResolve( Artifact artifact, List remoteRepositories, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - for ( ArtifactTransformation transform : artifactTransformations ) - { - transform.transformForResolve( artifact, remoteRepositories, localRepository ); + public void transformForResolve( + Artifact artifact, List remoteRepositories, ArtifactRepository localRepository) + throws ArtifactResolutionException, ArtifactNotFoundException { + for (ArtifactTransformation transform : artifactTransformations) { + transform.transformForResolve(artifact, remoteRepositories, localRepository); } } - public void transformForInstall( Artifact artifact, ArtifactRepository localRepository ) - throws ArtifactInstallationException - { - for ( ArtifactTransformation transform : artifactTransformations ) - { - transform.transformForInstall( artifact, localRepository ); + public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) + throws ArtifactInstallationException { + for (ArtifactTransformation transform : artifactTransformations) { + transform.transformForInstall(artifact, localRepository); } } - public void transformForDeployment( Artifact artifact, ArtifactRepository remoteRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException - { - for ( ArtifactTransformation transform : artifactTransformations ) - { - transform.transformForDeployment( artifact, remoteRepository, localRepository ); + public void transformForDeployment( + Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) + throws ArtifactDeploymentException { + for (ArtifactTransformation transform : artifactTransformations) { + transform.transformForDeployment(artifact, remoteRepository, localRepository); } } - public List getArtifactTransformations() - { + public List getArtifactTransformations() { return artifactTransformations; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/LatestArtifactTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/LatestArtifactTransformation.java index 0bc89c19f0..2821a833fc 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/LatestArtifactTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/LatestArtifactTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -31,47 +30,36 @@ import org.codehaus.plexus.component.annotations.Component; /** * Describes a version transformation during artifact resolution - "latest" type */ -@Component( role = ArtifactTransformation.class, hint = "latest" ) -public class LatestArtifactTransformation - extends AbstractVersionTransformation -{ +@Component(role = ArtifactTransformation.class, hint = "latest") +public class LatestArtifactTransformation extends AbstractVersionTransformation { - public void transformForResolve( Artifact artifact, RepositoryRequest request ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - if ( Artifact.LATEST_VERSION.equals( artifact.getVersion() ) ) - { - try - { - String version = resolveVersion( artifact, request ); - if ( Artifact.LATEST_VERSION.equals( version ) ) - { - throw new ArtifactNotFoundException( "Unable to determine the latest version", artifact ); + public void transformForResolve(Artifact artifact, RepositoryRequest request) + throws ArtifactResolutionException, ArtifactNotFoundException { + if (Artifact.LATEST_VERSION.equals(artifact.getVersion())) { + try { + String version = resolveVersion(artifact, request); + if (Artifact.LATEST_VERSION.equals(version)) { + throw new ArtifactNotFoundException("Unable to determine the latest version", artifact); } - artifact.setBaseVersion( version ); - artifact.updateVersion( version, request.getLocalRepository() ); - } - catch ( RepositoryMetadataResolutionException e ) - { - throw new ArtifactResolutionException( e.getMessage(), artifact, e ); + artifact.setBaseVersion(version); + artifact.updateVersion(version, request.getLocalRepository()); + } catch (RepositoryMetadataResolutionException e) { + throw new ArtifactResolutionException(e.getMessage(), artifact, e); } } } - public void transformForInstall( Artifact artifact, ArtifactRepository localRepository ) - { + public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) { // metadata is added via addPluginArtifactMetadata } - public void transformForDeployment( Artifact artifact, ArtifactRepository remoteRepository, - ArtifactRepository localRepository ) - { + public void transformForDeployment( + Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) { // metadata is added via addPluginArtifactMetadata } - protected String constructVersion( Versioning versioning, String baseVersion ) - { + protected String constructVersion(Versioning versioning, String baseVersion) { return versioning.getLatest(); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ReleaseArtifactTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ReleaseArtifactTransformation.java index b1d2c7107a..81a6e072de 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ReleaseArtifactTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ReleaseArtifactTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -35,67 +34,54 @@ import org.codehaus.plexus.component.annotations.Component; * * @author Brett Porter */ -@Component( role = ArtifactTransformation.class, hint = "release" ) -public class ReleaseArtifactTransformation - extends AbstractVersionTransformation -{ +@Component(role = ArtifactTransformation.class, hint = "release") +public class ReleaseArtifactTransformation extends AbstractVersionTransformation { - public void transformForResolve( Artifact artifact, RepositoryRequest request ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - if ( Artifact.RELEASE_VERSION.equals( artifact.getVersion() ) ) - { - try - { - String version = resolveVersion( artifact, request ); + public void transformForResolve(Artifact artifact, RepositoryRequest request) + throws ArtifactResolutionException, ArtifactNotFoundException { + if (Artifact.RELEASE_VERSION.equals(artifact.getVersion())) { + try { + String version = resolveVersion(artifact, request); - if ( Artifact.RELEASE_VERSION.equals( version ) ) - { - throw new ArtifactNotFoundException( "Unable to determine the release version", artifact ); + if (Artifact.RELEASE_VERSION.equals(version)) { + throw new ArtifactNotFoundException("Unable to determine the release version", artifact); } - artifact.setBaseVersion( version ); - artifact.updateVersion( version, request.getLocalRepository() ); - } - catch ( RepositoryMetadataResolutionException e ) - { - throw new ArtifactResolutionException( e.getMessage(), artifact, e ); + artifact.setBaseVersion(version); + artifact.updateVersion(version, request.getLocalRepository()); + } catch (RepositoryMetadataResolutionException e) { + throw new ArtifactResolutionException(e.getMessage(), artifact, e); } } } - public void transformForInstall( Artifact artifact, ArtifactRepository localRepository ) - { - ArtifactMetadata metadata = createMetadata( artifact ); + public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) { + ArtifactMetadata metadata = createMetadata(artifact); - artifact.addMetadata( metadata ); + artifact.addMetadata(metadata); } - public void transformForDeployment( Artifact artifact, ArtifactRepository remoteRepository, - ArtifactRepository localRepository ) - { - ArtifactMetadata metadata = createMetadata( artifact ); + public void transformForDeployment( + Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) { + ArtifactMetadata metadata = createMetadata(artifact); - artifact.addMetadata( metadata ); + artifact.addMetadata(metadata); } - private ArtifactMetadata createMetadata( Artifact artifact ) - { + private ArtifactMetadata createMetadata(Artifact artifact) { Versioning versioning = new Versioning(); // TODO Should this be changed for MNG-6754 too? versioning.updateTimestamp(); - versioning.addVersion( artifact.getVersion() ); + versioning.addVersion(artifact.getVersion()); - if ( artifact.isRelease() ) - { - versioning.setRelease( artifact.getVersion() ); + if (artifact.isRelease()) { + versioning.setRelease(artifact.getVersion()); } - return new ArtifactRepositoryMetadata( artifact, versioning ); + return new ArtifactRepositoryMetadata(artifact, versioning); } - protected String constructVersion( Versioning versioning, String baseVersion ) - { + protected String constructVersion(Versioning versioning, String baseVersion) { return versioning.getRelease(); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/SnapshotTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/SnapshotTransformation.java index 1a79049b17..f5516e6dcb 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/SnapshotTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/SnapshotTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.transform; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.repository.legacy.resolver.transform; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.transform; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.deployer.ArtifactDeploymentException; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -43,132 +41,109 @@ import org.codehaus.plexus.util.StringUtils; * @author Brett Porter * @author Michal Maczka */ -@Component( role = ArtifactTransformation.class, hint = "snapshot" ) -public class SnapshotTransformation - extends AbstractVersionTransformation -{ +@Component(role = ArtifactTransformation.class, hint = "snapshot") +public class SnapshotTransformation extends AbstractVersionTransformation { private static final String DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT = "yyyyMMdd.HHmmss"; - private static final TimeZone DEFAULT_SNAPSHOT_TIME_ZONE = TimeZone.getTimeZone( "Etc/UTC" ); + private static final TimeZone DEFAULT_SNAPSHOT_TIME_ZONE = TimeZone.getTimeZone("Etc/UTC"); private String deploymentTimestamp; - public void transformForResolve( Artifact artifact, RepositoryRequest request ) - throws ArtifactResolutionException - { + public void transformForResolve(Artifact artifact, RepositoryRequest request) throws ArtifactResolutionException { // Only select snapshots that are unresolved (eg 1.0-SNAPSHOT, not 1.0-20050607.123456) - if ( artifact.isSnapshot() && artifact.getBaseVersion().equals( artifact.getVersion() ) ) - { - try - { - String version = resolveVersion( artifact, request ); - artifact.updateVersion( version, request.getLocalRepository() ); - } - catch ( RepositoryMetadataResolutionException e ) - { - throw new ArtifactResolutionException( e.getMessage(), artifact, e ); + if (artifact.isSnapshot() && artifact.getBaseVersion().equals(artifact.getVersion())) { + try { + String version = resolveVersion(artifact, request); + artifact.updateVersion(version, request.getLocalRepository()); + } catch (RepositoryMetadataResolutionException e) { + throw new ArtifactResolutionException(e.getMessage(), artifact, e); } } } - public void transformForInstall( Artifact artifact, ArtifactRepository localRepository ) - { - if ( artifact.isSnapshot() ) - { + public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) { + if (artifact.isSnapshot()) { Snapshot snapshot = new Snapshot(); - snapshot.setLocalCopy( true ); - RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata( artifact, snapshot ); + snapshot.setLocalCopy(true); + RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact, snapshot); - artifact.addMetadata( metadata ); + artifact.addMetadata(metadata); } } - public void transformForDeployment( Artifact artifact, ArtifactRepository remoteRepository, - ArtifactRepository localRepository ) - throws ArtifactDeploymentException - { - if ( artifact.isSnapshot() ) - { + public void transformForDeployment( + Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) + throws ArtifactDeploymentException { + if (artifact.isSnapshot()) { Snapshot snapshot = new Snapshot(); // TODO Should this be changed for MNG-6754 too? - snapshot.setTimestamp( getDeploymentTimestamp() ); + snapshot.setTimestamp(getDeploymentTimestamp()); // we update the build number anyway so that it doesn't get lost. It requires the timestamp to take effect - try - { - int buildNumber = resolveLatestSnapshotBuildNumber( artifact, localRepository, remoteRepository ); + try { + int buildNumber = resolveLatestSnapshotBuildNumber(artifact, localRepository, remoteRepository); - snapshot.setBuildNumber( buildNumber + 1 ); - } - catch ( RepositoryMetadataResolutionException e ) - { - throw new ArtifactDeploymentException( "Error retrieving previous build number for artifact '" - + artifact.getDependencyConflictId() + "': " + e.getMessage(), e ); + snapshot.setBuildNumber(buildNumber + 1); + } catch (RepositoryMetadataResolutionException e) { + throw new ArtifactDeploymentException( + "Error retrieving previous build number for artifact '" + artifact.getDependencyConflictId() + + "': " + e.getMessage(), + e); } - RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata( artifact, snapshot ); + RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact, snapshot); artifact.setResolvedVersion( - constructVersion( metadata.getMetadata().getVersioning(), artifact.getBaseVersion() ) ); + constructVersion(metadata.getMetadata().getVersioning(), artifact.getBaseVersion())); - artifact.addMetadata( metadata ); + artifact.addMetadata(metadata); } } - public String getDeploymentTimestamp() - { - if ( deploymentTimestamp == null ) - { - deploymentTimestamp = getUtcDateFormatter().format( new Date() ); + public String getDeploymentTimestamp() { + if (deploymentTimestamp == null) { + deploymentTimestamp = getUtcDateFormatter().format(new Date()); } return deploymentTimestamp; } - protected String constructVersion( Versioning versioning, String baseVersion ) - { + protected String constructVersion(Versioning versioning, String baseVersion) { String version = null; Snapshot snapshot = versioning.getSnapshot(); - if ( snapshot != null ) - { - if ( snapshot.getTimestamp() != null && snapshot.getBuildNumber() > 0 ) - { + if (snapshot != null) { + if (snapshot.getTimestamp() != null && snapshot.getBuildNumber() > 0) { String newVersion = snapshot.getTimestamp() + "-" + snapshot.getBuildNumber(); - version = StringUtils.replace( baseVersion, Artifact.SNAPSHOT_VERSION, newVersion ); - } - else - { + version = StringUtils.replace(baseVersion, Artifact.SNAPSHOT_VERSION, newVersion); + } else { version = baseVersion; } } return version; } - private int resolveLatestSnapshotBuildNumber( Artifact artifact, ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws RepositoryMetadataResolutionException - { - RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata( artifact ); + private int resolveLatestSnapshotBuildNumber( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataResolutionException { + RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact); - getLogger().info( "Retrieving previous build number from " + remoteRepository.getId() ); - repositoryMetadataManager.resolveAlways( metadata, localRepository, remoteRepository ); + getLogger().info("Retrieving previous build number from " + remoteRepository.getId()); + repositoryMetadataManager.resolveAlways(metadata, localRepository, remoteRepository); int buildNumber = 0; Metadata repoMetadata = metadata.getMetadata(); - if ( ( repoMetadata != null ) - && ( repoMetadata.getVersioning() != null && repoMetadata.getVersioning().getSnapshot() != null ) ) - { + if ((repoMetadata != null) + && (repoMetadata.getVersioning() != null + && repoMetadata.getVersioning().getSnapshot() != null)) { buildNumber = repoMetadata.getVersioning().getSnapshot().getBuildNumber(); } return buildNumber; } - public static DateFormat getUtcDateFormatter() - { - DateFormat utcDateFormatter = new SimpleDateFormat( DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT ); - utcDateFormatter.setCalendar( new GregorianCalendar() ); - utcDateFormatter.setTimeZone( DEFAULT_SNAPSHOT_TIME_ZONE ); + public static DateFormat getUtcDateFormatter() { + DateFormat utcDateFormatter = new SimpleDateFormat(DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT); + utcDateFormatter.setCalendar(new GregorianCalendar()); + utcDateFormatter.setTimeZone(DEFAULT_SNAPSHOT_TIME_ZONE); return utcDateFormatter; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/ArtifactMetadata.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/ArtifactMetadata.java index 8d03a31f6d..8742973fad 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/ArtifactMetadata.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/ArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.Collection; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactScopeEnum; @@ -29,12 +27,12 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * * @author Oleg Gusakov */ -public class ArtifactMetadata -{ +public class ArtifactMetadata { /** * standard glorified artifact coordinates */ protected String groupId; + protected String artifactId; protected String version; protected String type; @@ -64,67 +62,75 @@ public class ArtifactMetadata /** error message */ private String error; - //------------------------------------------------------------------ + // ------------------------------------------------------------------ /** * */ - public ArtifactMetadata( String name ) - { - if ( name == null ) - { + public ArtifactMetadata(String name) { + if (name == null) { return; } - int ind1 = name.indexOf( ':' ); - int ind2 = name.lastIndexOf( ':' ); + int ind1 = name.indexOf(':'); + int ind2 = name.lastIndexOf(':'); - if ( ind1 == -1 || ind2 == -1 ) - { + if (ind1 == -1 || ind2 == -1) { return; } - this.groupId = name.substring( 0, ind1 ); - if ( ind1 == ind2 ) - { - this.artifactId = name.substring( ind1 + 1 ); - } - else - { - this.artifactId = name.substring( ind1 + 1, ind2 ); - this.version = name.substring( ind2 + 1 ); + this.groupId = name.substring(0, ind1); + if (ind1 == ind2) { + this.artifactId = name.substring(ind1 + 1); + } else { + this.artifactId = name.substring(ind1 + 1, ind2); + this.version = name.substring(ind2 + 1); } } - public ArtifactMetadata( String groupId, String name, String version ) - { - this( groupId, name, version, null ); + public ArtifactMetadata(String groupId, String name, String version) { + this(groupId, name, version, null); } - public ArtifactMetadata( String groupId, String name, String version, String type ) - { - this( groupId, name, version, type, null ); + public ArtifactMetadata(String groupId, String name, String version, String type) { + this(groupId, name, version, type, null); } - public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope ) - { - this( groupId, name, version, type, artifactScope, null ); + public ArtifactMetadata(String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope) { + this(groupId, name, version, type, artifactScope, null); } - public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope, - String classifier ) - { - this( groupId, name, version, type, artifactScope, classifier, null ); + public ArtifactMetadata( + String groupId, + String name, + String version, + String type, + ArtifactScopeEnum artifactScope, + String classifier) { + this(groupId, name, version, type, artifactScope, classifier, null); } - public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope, - String classifier, String artifactUri ) - { - this( groupId, name, version, type, artifactScope, classifier, artifactUri, null, true, null ); + public ArtifactMetadata( + String groupId, + String name, + String version, + String type, + ArtifactScopeEnum artifactScope, + String classifier, + String artifactUri) { + this(groupId, name, version, type, artifactScope, classifier, artifactUri, null, true, null); } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactMetadata( String groupId, String name, String version, String type, ArtifactScopeEnum artifactScope, - String classifier, String artifactUri, String why, boolean resolved, String error ) - { + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactMetadata( + String groupId, + String name, + String version, + String type, + ArtifactScopeEnum artifactScope, + String classifier, + String artifactUri, + String why, + boolean resolved, + String error) { this.groupId = groupId; this.artifactId = name; this.version = version; @@ -137,17 +143,32 @@ public class ArtifactMetadata this.error = error; } - @SuppressWarnings( "checkstyle:parameternumber" ) - public ArtifactMetadata( String groupId, String name, String version, String type, String scopeString, - String classifier, String artifactUri, String why, boolean resolved, String error ) - { - this( groupId, name, version, type, - scopeString == null ? ArtifactScopeEnum.DEFAULT_SCOPE : ArtifactScopeEnum.valueOf( scopeString ), - classifier, artifactUri, why, resolved, error ); + @SuppressWarnings("checkstyle:parameternumber") + public ArtifactMetadata( + String groupId, + String name, + String version, + String type, + String scopeString, + String classifier, + String artifactUri, + String why, + boolean resolved, + String error) { + this( + groupId, + name, + version, + type, + scopeString == null ? ArtifactScopeEnum.DEFAULT_SCOPE : ArtifactScopeEnum.valueOf(scopeString), + classifier, + artifactUri, + why, + resolved, + error); } - public ArtifactMetadata( Artifact af ) - { + public ArtifactMetadata(Artifact af) { /* if ( af != null ) { @@ -155,190 +176,154 @@ public class ArtifactMetadata } */ } - //------------------------------------------------------------------ -// public void init( ArtifactMetadata af ) -// { -// setGroupId( af.getGroupId() ); -// setArtifactId( af.getArtifactId() ); -// setVersion( af.getVersion() ); -// setType( af.getType() ); -// setScope( af.getScope() ); -// setClassifier( af.getClassifier() ); -// //setUri( af.getDownloadUrl() ); -// -// this.resolved = af.isResolved(); -// } + // ------------------------------------------------------------------ + // public void init( ArtifactMetadata af ) + // { + // setGroupId( af.getGroupId() ); + // setArtifactId( af.getArtifactId() ); + // setVersion( af.getVersion() ); + // setType( af.getType() ); + // setScope( af.getScope() ); + // setClassifier( af.getClassifier() ); + // //setUri( af.getDownloadUrl() ); + // + // this.resolved = af.isResolved(); + // } @Override - public String toString() - { + public String toString() { return groupId + ":" + artifactId + ":" + version; } - public String toDomainString() - { + public String toDomainString() { return groupId + ":" + artifactId; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setArtifactId( String name ) - { + public void setArtifactId(String name) { this.artifactId = name; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public String getType() - { + public String getType() { return type; } - public String getCheckedType() - { + public String getCheckedType() { return type == null ? "jar" : type; } - public void setType( String type ) - { + public void setType(String type) { this.type = type; } - public ArtifactScopeEnum getArtifactScope() - { + public ArtifactScopeEnum getArtifactScope() { return artifactScope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : artifactScope; } - public void setArtifactScope( ArtifactScopeEnum artifactScope ) - { + public void setArtifactScope(ArtifactScopeEnum artifactScope) { this.artifactScope = artifactScope; } - public void setScope( String scope ) - { - this.artifactScope = scope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : ArtifactScopeEnum.valueOf( scope ); + public void setScope(String scope) { + this.artifactScope = scope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : ArtifactScopeEnum.valueOf(scope); } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public void setClassifier( String classifier ) - { + public void setClassifier(String classifier) { this.classifier = classifier; } - public boolean isResolved() - { + public boolean isResolved() { return resolved; } - public void setResolved( boolean resolved ) - { + public void setResolved(boolean resolved) { this.resolved = resolved; } - public String getUri() - { + public String getUri() { return uri; } - public void setUri( String uri ) - { + public void setUri(String uri) { this.uri = uri; } - public String getScope() - { + public String getScope() { return getArtifactScope().getScope(); } - public ArtifactScopeEnum getScopeAsEnum() - { + public ArtifactScopeEnum getScopeAsEnum() { return artifactScope == null ? ArtifactScopeEnum.DEFAULT_SCOPE : artifactScope; } - public boolean isArtifactExists() - { + public boolean isArtifactExists() { return artifactExists; } - public void setArtifactExists( boolean artifactExists ) - { + public void setArtifactExists(boolean artifactExists) { this.artifactExists = artifactExists; } - - public Collection getDependencies() - { + public Collection getDependencies() { return dependencies; } - public void setDependencies( Collection dependencies ) - { + public void setDependencies(Collection dependencies) { this.dependencies = dependencies; } - public String getArtifactUri() - { + public String getArtifactUri() { return artifactUri; } - public void setArtifactUri( String artifactUri ) - { + public void setArtifactUri(String artifactUri) { this.artifactUri = artifactUri; } - - public String getWhy() - { + public String getWhy() { return why; } - public void setWhy( String why ) - { + public void setWhy(String why) { this.why = why; } - public String getError() - { + public String getError() { return error; } - public void setError( String error ) - { + public void setError(String error) { this.error = error; } - public boolean isError() - { + public boolean isError() { return error == null; } - public String getDependencyConflictId() - { + public String getDependencyConflictId() { return groupId + ":" + artifactId; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathContainer.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathContainer.java index 0630b68589..6091e1a9f0 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathContainer.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathContainer.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.ArrayList; import java.util.Iterator; import java.util.List; - import org.apache.maven.artifact.ArtifactScopeEnum; /** @@ -31,112 +29,95 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * @author Oleg Gusakov * */ -public class ClasspathContainer -implements Iterable -{ +public class ClasspathContainer implements Iterable { private List classpath; private ArtifactScopeEnum scope; // ------------------------------------------------------------------------------------------- - public ClasspathContainer( ArtifactScopeEnum scope ) - { - this.scope = ArtifactScopeEnum.checkScope( scope ); + public ClasspathContainer(ArtifactScopeEnum scope) { + this.scope = ArtifactScopeEnum.checkScope(scope); } // ------------------------------------------------------------------------------------------- - public ClasspathContainer( List classpath, ArtifactScopeEnum scope ) - { - this( scope ); + public ClasspathContainer(List classpath, ArtifactScopeEnum scope) { + this(scope); this.classpath = classpath; } // ------------------------------------------------------------------------------------------- - public Iterator iterator() - { + public Iterator iterator() { return classpath == null ? null : classpath.iterator(); } // ------------------------------------------------------------------------------------------- - public ClasspathContainer add( ArtifactMetadata md ) - { - if ( classpath == null ) - { - classpath = new ArrayList<>( 16 ); + public ClasspathContainer add(ArtifactMetadata md) { + if (classpath == null) { + classpath = new ArrayList<>(16); } - classpath.add( md ); + classpath.add(md); return this; } // ------------------------------------------------------------------------------------------- - public List getClasspath() - { + public List getClasspath() { return classpath; } // ------------------------------------------------------------------------------------------- - public MetadataTreeNode getClasspathAsTree() - throws MetadataResolutionException - { - if ( classpath == null || classpath.size() < 1 ) - { + public MetadataTreeNode getClasspathAsTree() throws MetadataResolutionException { + if (classpath == null || classpath.size() < 1) { return null; } MetadataTreeNode tree = null; MetadataTreeNode parent = null; - for ( ArtifactMetadata md : classpath ) - { - MetadataTreeNode node = new MetadataTreeNode( md, parent, md.isResolved(), md.getArtifactScope() ); - if ( tree == null ) - { + for (ArtifactMetadata md : classpath) { + MetadataTreeNode node = new MetadataTreeNode(md, parent, md.isResolved(), md.getArtifactScope()); + if (tree == null) { tree = node; } - if ( parent != null ) - { - parent.setNChildren( 1 ); - parent.addChild( 0, node ); + if (parent != null) { + parent.setNChildren(1); + parent.addChild(0, node); } parent = node; - } return tree; } - public void setClasspath( List classpath ) - { + public void setClasspath(List classpath) { this.classpath = classpath; } - public ArtifactScopeEnum getScope() - { + public ArtifactScopeEnum getScope() { return scope; } - public void setScope( ArtifactScopeEnum scope ) - { + public void setScope(ArtifactScopeEnum scope) { this.scope = scope; } // ------------------------------------------------------------------------------------------- @Override - public String toString() - { - StringBuilder sb = new StringBuilder( 256 ); - sb.append( "[scope=" ).append( scope.getScope() ); - if ( classpath != null ) - { - for ( ArtifactMetadata md : classpath ) - { - sb.append( ": " ).append( md.toString() ).append( '{' ).append( md.getArtifactUri() ).append( '}' ); + public String toString() { + StringBuilder sb = new StringBuilder(256); + sb.append("[scope=").append(scope.getScope()); + if (classpath != null) { + for (ArtifactMetadata md : classpath) { + sb.append(": ") + .append(md.toString()) + .append('{') + .append(md.getArtifactUri()) + .append('}'); } } - sb.append( ']' ); + sb.append(']'); return sb.toString(); } // ------------------------------------------------------------------------------------------- diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathTransformation.java index 26d5f3ed98..ccc85f5037 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.ArtifactScopeEnum; @@ -27,8 +26,7 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * @author Oleg Gusakov * */ -public interface ClasspathTransformation -{ +public interface ClasspathTransformation { String ROLE = ClasspathTransformation.class.getName(); /** @@ -41,6 +39,6 @@ public interface ClasspathTransformation * @return Collection of metadata objects in the linked subgraph of the graph which * contains the graph.getEntry() vertice */ - ClasspathContainer transform( MetadataGraph dirtyGraph, ArtifactScopeEnum scope, boolean resolve ) - throws MetadataGraphTransformationException; + ClasspathContainer transform(MetadataGraph dirtyGraph, ArtifactScopeEnum scope, boolean resolve) + throws MetadataGraphTransformationException; } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultClasspathTransformation.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultClasspathTransformation.java index a2bac9ccac..87e0b1da5b 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultClasspathTransformation.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultClasspathTransformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.maven.artifact.ArtifactScopeEnum; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; @@ -33,61 +31,49 @@ import org.codehaus.plexus.component.annotations.Requirement; * @author Oleg Gusakov * */ -@Component( role = ClasspathTransformation.class ) -public class DefaultClasspathTransformation - implements ClasspathTransformation -{ +@Component(role = ClasspathTransformation.class) +public class DefaultClasspathTransformation implements ClasspathTransformation { @Requirement GraphConflictResolver conflictResolver; - //---------------------------------------------------------------------------------------------------- - public ClasspathContainer transform( MetadataGraph dirtyGraph, ArtifactScopeEnum scope, boolean resolve ) - throws MetadataGraphTransformationException - { - try - { - if ( dirtyGraph == null || dirtyGraph.isEmpty() ) - { + // ---------------------------------------------------------------------------------------------------- + public ClasspathContainer transform(MetadataGraph dirtyGraph, ArtifactScopeEnum scope, boolean resolve) + throws MetadataGraphTransformationException { + try { + if (dirtyGraph == null || dirtyGraph.isEmpty()) { return null; } - MetadataGraph cleanGraph = conflictResolver.resolveConflicts( dirtyGraph, scope ); + MetadataGraph cleanGraph = conflictResolver.resolveConflicts(dirtyGraph, scope); - if ( cleanGraph == null || cleanGraph.isEmpty() ) - { + if (cleanGraph == null || cleanGraph.isEmpty()) { return null; } - ClasspathContainer cpc = new ClasspathContainer( scope ); - if ( cleanGraph.isEmptyEdges() ) - { + ClasspathContainer cpc = new ClasspathContainer(scope); + if (cleanGraph.isEmptyEdges()) { // single entry in the classpath, populated from itself ArtifactMetadata amd = cleanGraph.getEntry().getMd(); - cpc.add( amd ); - } - else - { - ClasspathGraphVisitor v = new ClasspathGraphVisitor( cleanGraph, cpc ); + cpc.add(amd); + } else { + ClasspathGraphVisitor v = new ClasspathGraphVisitor(cleanGraph, cpc); MetadataGraphVertex entry = cleanGraph.getEntry(); // entry point - v.visit( entry ); + v.visit(entry); } return cpc; - } - catch ( GraphConflictResolutionException e ) - { - throw new MetadataGraphTransformationException( e ); + } catch (GraphConflictResolutionException e) { + throw new MetadataGraphTransformationException(e); } } - //=================================================================================================== + // =================================================================================================== /** * Helper class to traverse graph. Required to make the containing method thread-safe * and yet use class level data to lessen stack usage in recursion */ - private class ClasspathGraphVisitor - { + private class ClasspathGraphVisitor { MetadataGraph graph; ClasspathContainer cpc; @@ -95,79 +81,71 @@ public class DefaultClasspathTransformation List visited; // ----------------------------------------------------------------------- - protected ClasspathGraphVisitor( MetadataGraph cleanGraph, ClasspathContainer cpc ) - { + protected ClasspathGraphVisitor(MetadataGraph cleanGraph, ClasspathContainer cpc) { this.cpc = cpc; this.graph = cleanGraph; - visited = new ArrayList<>( cleanGraph.getVertices().size() ); + visited = new ArrayList<>(cleanGraph.getVertices().size()); } // ----------------------------------------------------------------------- - protected void visit( MetadataGraphVertex node ) // , String version, String artifactUri ) - { + protected void visit(MetadataGraphVertex node) // , String version, String artifactUri ) + { ArtifactMetadata md = node.getMd(); - if ( visited.contains( node ) ) - { + if (visited.contains(node)) { return; } - cpc.add( md ); -// -// TreeSet deps = new TreeSet( -// new Comparator() -// { -// public int compare( MetadataGraphEdge e1 -// , MetadataGraphEdge e2 -// ) -// { -// if( e1.getDepth() == e2.getDepth() ) -// { -// if( e2.getPomOrder() == e1.getPomOrder() ) -// return e1.getTarget().toString().compareTo(e2.getTarget().toString() ); -// -// return e2.getPomOrder() - e1.getPomOrder(); -// } -// -// return e2.getDepth() - e1.getDepth(); -// } -// } -// ); + cpc.add(md); + // + // TreeSet deps = new TreeSet( + // new Comparator() + // { + // public int compare( MetadataGraphEdge e1 + // , MetadataGraphEdge e2 + // ) + // { + // if( e1.getDepth() == e2.getDepth() ) + // { + // if( e2.getPomOrder() == e1.getPomOrder() ) + // return + // e1.getTarget().toString().compareTo(e2.getTarget().toString() ); + // + // return e2.getPomOrder() - e1.getPomOrder(); + // } + // + // return e2.getDepth() - e1.getDepth(); + // } + // } + // ); - List exits = graph.getExcidentEdges( node ); + List exits = graph.getExcidentEdges(node); - if ( exits != null && exits.size() > 0 ) - { - MetadataGraphEdge[] sortedExits = exits.toArray( new MetadataGraphEdge[0] ); - Arrays.sort( sortedExits, ( e1, e2 ) -> - { - if ( e1.getDepth() == e2.getDepth() ) - { - if ( e2.getPomOrder() == e1.getPomOrder() ) - { - return e1.getTarget().toString().compareTo( e2.getTarget().toString() ); + if (exits != null && exits.size() > 0) { + MetadataGraphEdge[] sortedExits = exits.toArray(new MetadataGraphEdge[0]); + Arrays.sort(sortedExits, (e1, e2) -> { + if (e1.getDepth() == e2.getDepth()) { + if (e2.getPomOrder() == e1.getPomOrder()) { + return e1.getTarget() + .toString() + .compareTo(e2.getTarget().toString()); } return e2.getPomOrder() - e1.getPomOrder(); } return e2.getDepth() - e1.getDepth(); - } ); + }); - for ( MetadataGraphEdge e : sortedExits ) - { + for (MetadataGraphEdge e : sortedExits) { MetadataGraphVertex targetNode = e.getTarget(); - targetNode.getMd().setArtifactScope( e.getScope() ); - targetNode.getMd().setWhy( e.getSource().getMd().toString() ); - visit( targetNode ); + targetNode.getMd().setArtifactScope(e.getScope()); + targetNode.getMd().setWhy(e.getSource().getMd().toString()); + visit(targetNode); } } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- + // ----------------------------------------------------------------------- + // ----------------------------------------------------------------------- } - //---------------------------------------------------------------------------------------------------- - //---------------------------------------------------------------------------------------------------- + // ---------------------------------------------------------------------------------------------------- + // ---------------------------------------------------------------------------------------------------- } - - - diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicy.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicy.java index bb7642272e..c897c0f7d8 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicy.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicy.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; @@ -28,46 +27,39 @@ import org.codehaus.plexus.component.annotations.Configuration; * @author Oleg Gusakov * */ -@Component( role = GraphConflictResolutionPolicy.class ) -public class DefaultGraphConflictResolutionPolicy - implements GraphConflictResolutionPolicy -{ +@Component(role = GraphConflictResolutionPolicy.class) +public class DefaultGraphConflictResolutionPolicy implements GraphConflictResolutionPolicy { /** * artifact, closer to the entry point, is selected */ - @Configuration( name = "closer-first", value = "true" ) + @Configuration(name = "closer-first", value = "true") private boolean closerFirst = true; /** * newer artifact is selected */ - @Configuration( name = "newer-first", value = "true" ) + @Configuration(name = "newer-first", value = "true") private boolean newerFirst = true; - public MetadataGraphEdge apply( MetadataGraphEdge e1, MetadataGraphEdge e2 ) - { + public MetadataGraphEdge apply(MetadataGraphEdge e1, MetadataGraphEdge e2) { int depth1 = e1.getDepth(); int depth2 = e2.getDepth(); - if ( depth1 == depth2 ) - { - ArtifactVersion v1 = new DefaultArtifactVersion( e1.getVersion() ); - ArtifactVersion v2 = new DefaultArtifactVersion( e2.getVersion() ); + if (depth1 == depth2) { + ArtifactVersion v1 = new DefaultArtifactVersion(e1.getVersion()); + ArtifactVersion v2 = new DefaultArtifactVersion(e2.getVersion()); - if ( newerFirst ) - { - return v1.compareTo( v2 ) > 0 ? e1 : e2; + if (newerFirst) { + return v1.compareTo(v2) > 0 ? e1 : e2; } - return v1.compareTo( v2 ) > 0 ? e2 : e1; + return v1.compareTo(v2) > 0 ? e2 : e1; } - if ( closerFirst ) - { + if (closerFirst) { return depth1 < depth2 ? e1 : e2; } return depth1 < depth2 ? e2 : e1; } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolver.java index 976fcb80b4..429635ca1a 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; - import org.apache.maven.artifact.ArtifactScopeEnum; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; @@ -32,190 +30,166 @@ import org.codehaus.plexus.component.annotations.Requirement; * * @author Oleg Gusakov */ -@Component( role = GraphConflictResolver.class ) -public class DefaultGraphConflictResolver - implements GraphConflictResolver -{ +@Component(role = GraphConflictResolver.class) +public class DefaultGraphConflictResolver implements GraphConflictResolver { /** * artifact, closer to the entry point, is selected */ - @Requirement( role = GraphConflictResolutionPolicy.class ) + @Requirement(role = GraphConflictResolutionPolicy.class) protected GraphConflictResolutionPolicy policy; // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- - public MetadataGraph resolveConflicts( MetadataGraph graph, ArtifactScopeEnum scope ) - throws GraphConflictResolutionException - { - if ( policy == null ) - { - throw new GraphConflictResolutionException( "no GraphConflictResolutionPolicy injected" ); + public MetadataGraph resolveConflicts(MetadataGraph graph, ArtifactScopeEnum scope) + throws GraphConflictResolutionException { + if (policy == null) { + throw new GraphConflictResolutionException("no GraphConflictResolutionPolicy injected"); } - if ( graph == null ) - { + if (graph == null) { return null; } final MetadataGraphVertex entry = graph.getEntry(); - if ( entry == null ) - { + if (entry == null) { return null; } - if ( graph.isEmpty() ) - { - throw new GraphConflictResolutionException( "graph with an entry, but not vertices do not exist" ); + if (graph.isEmpty()) { + throw new GraphConflictResolutionException("graph with an entry, but not vertices do not exist"); } - if ( graph.isEmptyEdges() ) - { + if (graph.isEmptyEdges()) { return null; // no edges - nothing to worry about } final TreeSet vertices = graph.getVertices(); - try - { + try { // edge case - single vertex graph - if ( vertices.size() == 1 ) - { - return new MetadataGraph( entry ); + if (vertices.size() == 1) { + return new MetadataGraph(entry); } - final ArtifactScopeEnum requestedScope = ArtifactScopeEnum.checkScope( scope ); + final ArtifactScopeEnum requestedScope = ArtifactScopeEnum.checkScope(scope); - MetadataGraph res = new MetadataGraph( vertices.size() ); - res.setVersionedVertices( false ); - res.setScopedVertices( false ); + MetadataGraph res = new MetadataGraph(vertices.size()); + res.setVersionedVertices(false); + res.setScopedVertices(false); - MetadataGraphVertex resEntry = res.addVertex( entry.getMd() ); - res.setEntry( resEntry ); + MetadataGraphVertex resEntry = res.addVertex(entry.getMd()); + res.setEntry(resEntry); - res.setScope( requestedScope ); + res.setScope(requestedScope); - for ( MetadataGraphVertex v : vertices ) - { - final List ins = graph.getIncidentEdges( v ); - final MetadataGraphEdge edge = cleanEdges( v, ins, requestedScope ); + for (MetadataGraphVertex v : vertices) { + final List ins = graph.getIncidentEdges(v); + final MetadataGraphEdge edge = cleanEdges(v, ins, requestedScope); - if ( edge == null ) - { // no edges - don't need this vertex anymore - if ( entry.equals( v ) ) - { // unless it's an entry point. + if (edge == null) { // no edges - don't need this vertex anymore + if (entry.equals(v)) { // unless it's an entry point. // currently processing the entry point - it should not have any entry incident edges - res.getEntry().getMd().setWhy( "This is a graph entry point. No links." ); - } - else - { + res.getEntry().getMd().setWhy("This is a graph entry point. No links."); + } else { // System.out.println("--->"+v.getMd().toDomainString() // +" has been terminated on this entry set\n-------------------\n" // +ins // +"\n-------------------\n" // ); } - } - else - { + } else { // System.out.println("+++>"+v.getMd().toDomainString()+" still has "+edge.toString() ); // fill in domain md with actual version data ArtifactMetadata md = v.getMd(); - ArtifactMetadata newMd = - new ArtifactMetadata( md.getGroupId(), md.getArtifactId(), edge.getVersion(), md.getType(), - md.getScopeAsEnum(), md.getClassifier(), edge.getArtifactUri(), - edge.getSource() == null ? "" : edge.getSource().getMd().toString(), - edge.isResolved(), edge.getTarget() == null ? null - : edge.getTarget().getMd().getError() ); - MetadataGraphVertex newV = res.addVertex( newMd ); - MetadataGraphVertex sourceV = res.addVertex( edge.getSource().getMd() ); + ArtifactMetadata newMd = new ArtifactMetadata( + md.getGroupId(), + md.getArtifactId(), + edge.getVersion(), + md.getType(), + md.getScopeAsEnum(), + md.getClassifier(), + edge.getArtifactUri(), + edge.getSource() == null + ? "" + : edge.getSource().getMd().toString(), + edge.isResolved(), + edge.getTarget() == null + ? null + : edge.getTarget().getMd().getError()); + MetadataGraphVertex newV = res.addVertex(newMd); + MetadataGraphVertex sourceV = res.addVertex(edge.getSource().getMd()); - res.addEdge( sourceV, newV, edge ); + res.addEdge(sourceV, newV, edge); } } // System.err.println("Original graph("+graph.getVertices().size()+"):\n"+graph.toString()); // System.err.println("Cleaned("+requestedScope+") graph("+res.getVertices().size()+"):\n"+res.toString()); // System.err.println("Linked("+requestedScope+") // subgraph("+linkedRes.getVertices().size()+"):\n"+linkedRes.toString()); - return findLinkedSubgraph( res ); - } - catch ( MetadataResolutionException e ) - { - throw new GraphConflictResolutionException( e ); + return findLinkedSubgraph(res); + } catch (MetadataResolutionException e) { + throw new GraphConflictResolutionException(e); } } // ------------------------------------------------------------------------------------- - private MetadataGraph findLinkedSubgraph( MetadataGraph g ) - { - if ( g.getVertices().size() == 1 ) - { + private MetadataGraph findLinkedSubgraph(MetadataGraph g) { + if (g.getVertices().size() == 1) { return g; } - List visited = new ArrayList<>( g.getVertices().size() ); - visit( g.getEntry(), visited, g ); + List visited = new ArrayList<>(g.getVertices().size()); + visit(g.getEntry(), visited, g); - List dropList = new ArrayList<>( g.getVertices().size() ); + List dropList = new ArrayList<>(g.getVertices().size()); // collect drop list - for ( MetadataGraphVertex v : g.getVertices() ) - { - if ( !visited.contains( v ) ) - { - dropList.add( v ); + for (MetadataGraphVertex v : g.getVertices()) { + if (!visited.contains(v)) { + dropList.add(v); } } - if ( dropList.size() < 1 ) - { + if (dropList.size() < 1) { return g; } // now - drop vertices TreeSet vertices = g.getVertices(); - for ( MetadataGraphVertex v : dropList ) - { - vertices.remove( v ); + for (MetadataGraphVertex v : dropList) { + vertices.remove(v); } return g; } // ------------------------------------------------------------------------------------- - private void visit( MetadataGraphVertex from, List visited, MetadataGraph graph ) - { - if ( visited.contains( from ) ) - { + private void visit(MetadataGraphVertex from, List visited, MetadataGraph graph) { + if (visited.contains(from)) { return; } - visited.add( from ); + visited.add(from); - List exitList = graph.getExcidentEdges( from ); + List exitList = graph.getExcidentEdges(from); // String s = "|---> "+from.getMd().toString()+" - "+(exitList == null ? -1 : exitList.size()) + " exit links"; - if ( exitList != null && exitList.size() > 0 ) - { - for ( MetadataGraphEdge e : graph.getExcidentEdges( from ) ) - { - visit( e.getTarget(), visited, graph ); + if (exitList != null && exitList.size() > 0) { + for (MetadataGraphEdge e : graph.getExcidentEdges(from)) { + visit(e.getTarget(), visited, graph); } } } // ------------------------------------------------------------------------------------- - private MetadataGraphEdge cleanEdges( MetadataGraphVertex v, List edges, - ArtifactScopeEnum scope ) - { - if ( edges == null || edges.isEmpty() ) - { + private MetadataGraphEdge cleanEdges( + MetadataGraphVertex v, List edges, ArtifactScopeEnum scope) { + if (edges == null || edges.isEmpty()) { return null; } - if ( edges.size() == 1 ) - { - MetadataGraphEdge e = edges.get( 0 ); - if ( scope.encloses( e.getScope() ) ) - { + if (edges.size() == 1) { + MetadataGraphEdge e = edges.get(0); + if (scope.encloses(e.getScope())) { return e; } @@ -224,20 +198,15 @@ public class DefaultGraphConflictResolver MetadataGraphEdge res = null; - for ( MetadataGraphEdge e : edges ) - { - if ( !scope.encloses( e.getScope() ) ) - { + for (MetadataGraphEdge e : edges) { + if (!scope.encloses(e.getScope())) { continue; } - if ( res == null ) - { + if (res == null) { res = e; - } - else - { - res = policy.apply( e, res ); + } else { + res = policy.apply(e, res); } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionException.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionException.java index 035904aa80..aaae936bad 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,34 +16,27 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; /** * * @author Oleg Gusakov * */ -public class GraphConflictResolutionException - extends Exception -{ +public class GraphConflictResolutionException extends Exception { private static final long serialVersionUID = 2677613140287940255L; - public GraphConflictResolutionException() - { + public GraphConflictResolutionException() {} + + public GraphConflictResolutionException(String message) { + super(message); } - public GraphConflictResolutionException( String message ) - { - super( message ); + public GraphConflictResolutionException(Throwable cause) { + super(cause); } - public GraphConflictResolutionException( Throwable cause ) - { - super( cause ); + public GraphConflictResolutionException(String message, Throwable cause) { + super(message, cause); } - - public GraphConflictResolutionException( String message, Throwable cause ) - { - super( message, cause ); - } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionPolicy.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionPolicy.java index 979d3831ff..ee7b3b134c 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionPolicy.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolutionPolicy.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; /** * MetadataGraph edge selection policy. Complements @@ -26,10 +25,8 @@ package org.apache.maven.repository.metadata; * @author Oleg Gusakov * */ - -public interface GraphConflictResolutionPolicy -{ +public interface GraphConflictResolutionPolicy { String ROLE = GraphConflictResolutionPolicy.class.getName(); - MetadataGraphEdge apply( MetadataGraphEdge e1, MetadataGraphEdge e2 ); + MetadataGraphEdge apply(MetadataGraphEdge e1, MetadataGraphEdge e2); } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java index ef70baa24c..ec4bc18251 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.ArtifactScopeEnum; @@ -27,8 +26,7 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * * @author Oleg Gusakov */ -public interface GraphConflictResolver -{ +public interface GraphConflictResolver { String ROLE = GraphConflictResolver.class.getName(); /** @@ -43,6 +41,6 @@ public interface GraphConflictResolver * * @since 3.0 */ - MetadataGraph resolveConflicts( MetadataGraph graph, ArtifactScopeEnum scope ) - throws GraphConflictResolutionException; + MetadataGraph resolveConflicts(MetadataGraph graph, ArtifactScopeEnum scope) + throws GraphConflictResolutionException; } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraph.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraph.java index c6ec04882e..0bb441de7f 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraph.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraph.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; - import org.apache.maven.artifact.ArtifactScopeEnum; /** @@ -33,17 +31,16 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * @author Oleg Gusakov * */ -public class MetadataGraph -{ +public class MetadataGraph { public static final int DEFAULT_VERTICES = 32; - public static final int DEFAULT_EDGES = 64; + public static final int DEFAULT_EDGES = 64; // flags to indicate the granularity of vertices private boolean versionedVertices = false; - private boolean scopedVertices = false; + private boolean scopedVertices = false; /** - * the entry point we started building the graph from - */ + * the entry point we started building the graph from + */ MetadataGraphVertex entry; // graph vertices @@ -53,6 +50,7 @@ public class MetadataGraph * incident and excident edges per node */ Map> incidentEdges; + Map> excidentEdges; /** @@ -61,44 +59,39 @@ public class MetadataGraph */ ArtifactScopeEnum scope; - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ /** * init graph */ - public MetadataGraph( int nVertices ) - { - init( nVertices, 2 * nVertices ); + public MetadataGraph(int nVertices) { + init(nVertices, 2 * nVertices); } - public MetadataGraph( int nVertices, int nEdges ) - { - init( nVertices, nEdges ); + + public MetadataGraph(int nVertices, int nEdges) { + init(nVertices, nEdges); } - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ /** * construct a single vertex */ - public MetadataGraph( MetadataGraphVertex entry ) - throws MetadataResolutionException - { - checkVertex( entry ); - checkVertices( 1 ); + public MetadataGraph(MetadataGraphVertex entry) throws MetadataResolutionException { + checkVertex(entry); + checkVertices(1); - entry.setCompareVersion( versionedVertices ); - entry.setCompareScope( scopedVertices ); + entry.setCompareVersion(versionedVertices); + entry.setCompareScope(scopedVertices); - vertices.add( entry ); + vertices.add(entry); this.entry = entry; } - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ /** * construct graph from a "dirty" tree */ - public MetadataGraph( MetadataTreeNode tree ) - throws MetadataResolutionException - { - this( tree, false, false ); + public MetadataGraph(MetadataTreeNode tree) throws MetadataResolutionException { + this(tree, false, false); } - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ /** * construct graph from a "dirty" tree * @@ -108,407 +101,334 @@ public class MetadataGraph * (different versions and/or scopes -> different nodes) * */ - public MetadataGraph( MetadataTreeNode tree, boolean versionedVertices, boolean scopedVertices ) - throws MetadataResolutionException - { - if ( tree == null ) - { - throw new MetadataResolutionException( "tree is null" ); + public MetadataGraph(MetadataTreeNode tree, boolean versionedVertices, boolean scopedVertices) + throws MetadataResolutionException { + if (tree == null) { + throw new MetadataResolutionException("tree is null"); } - setVersionedVertices( versionedVertices ); - setScopedVertices( scopedVertices ); + setVersionedVertices(versionedVertices); + setScopedVertices(scopedVertices); this.versionedVertices = scopedVertices || versionedVertices; this.scopedVertices = scopedVertices; - int count = countNodes( tree ); + int count = countNodes(tree); - init( count, count + ( count / 2 ) ); + init(count, count + (count / 2)); - processTreeNodes( null, tree, 0, 0 ); + processTreeNodes(null, tree, 0, 0); } - //------------------------------------------------------------------------ - private void processTreeNodes( MetadataGraphVertex parentVertex, MetadataTreeNode node, int depth, int pomOrder ) - throws MetadataResolutionException - { - if ( node == null ) - { + // ------------------------------------------------------------------------ + private void processTreeNodes(MetadataGraphVertex parentVertex, MetadataTreeNode node, int depth, int pomOrder) + throws MetadataResolutionException { + if (node == null) { return; } - MetadataGraphVertex vertex = new MetadataGraphVertex( node.md, versionedVertices, scopedVertices ); - if ( !vertices.contains( vertex ) ) - { - vertices.add( vertex ); + MetadataGraphVertex vertex = new MetadataGraphVertex(node.md, versionedVertices, scopedVertices); + if (!vertices.contains(vertex)) { + vertices.add(vertex); } - if ( parentVertex != null ) // then create the edge + if (parentVertex != null) // then create the edge { ArtifactMetadata md = node.getMd(); MetadataGraphEdge e = - new MetadataGraphEdge( md.version, md.resolved, md.artifactScope, md.artifactUri, depth, pomOrder ); - addEdge( parentVertex, vertex, e ); - } - else - { + new MetadataGraphEdge(md.version, md.resolved, md.artifactScope, md.artifactUri, depth, pomOrder); + addEdge(parentVertex, vertex, e); + } else { entry = vertex; } MetadataTreeNode[] kids = node.getChildren(); - if ( kids == null || kids.length < 1 ) - { + if (kids == null || kids.length < 1) { return; } - for ( int i = 0; i < kids.length; i++ ) - { + for (int i = 0; i < kids.length; i++) { MetadataTreeNode n = kids[i]; - processTreeNodes( vertex, n, depth + 1, i ); + processTreeNodes(vertex, n, depth + 1, i); } } - //------------------------------------------------------------------------ - public MetadataGraphVertex findVertex( ArtifactMetadata md ) - { - if ( md == null || vertices == null || vertices.size() < 1 ) - { + // ------------------------------------------------------------------------ + public MetadataGraphVertex findVertex(ArtifactMetadata md) { + if (md == null || vertices == null || vertices.size() < 1) { return null; } - MetadataGraphVertex v = new MetadataGraphVertex( md ); - v.setCompareVersion( versionedVertices ); - v.setCompareScope( scopedVertices ); + MetadataGraphVertex v = new MetadataGraphVertex(md); + v.setCompareVersion(versionedVertices); + v.setCompareScope(scopedVertices); - for ( MetadataGraphVertex gv : vertices ) - { - if ( gv.equals( v ) ) - { + for (MetadataGraphVertex gv : vertices) { + if (gv.equals(v)) { return gv; } } return null; } - //------------------------------------------------------------------------ - public MetadataGraphVertex addVertex( ArtifactMetadata md ) - { - if ( md == null ) - { + // ------------------------------------------------------------------------ + public MetadataGraphVertex addVertex(ArtifactMetadata md) { + if (md == null) { return null; } checkVertices(); - MetadataGraphVertex v = findVertex( md ); - if ( v != null ) - { + MetadataGraphVertex v = findVertex(md); + if (v != null) { return v; } - v = new MetadataGraphVertex( md ); + v = new MetadataGraphVertex(md); - v.setCompareVersion( versionedVertices ); - v.setCompareScope( scopedVertices ); + v.setCompareVersion(versionedVertices); + v.setCompareScope(scopedVertices); - vertices.add( v ); + vertices.add(v); return v; } - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ /** * init graph */ - private void init( int nVertices, int nEdges ) - { + private void init(int nVertices, int nEdges) { int nV = nVertices; - if ( nVertices < 1 ) - { + if (nVertices < 1) { nV = 1; } - checkVertices( nV ); + checkVertices(nV); int nE = nVertices; - if ( nEdges <= nV ) - { + if (nEdges <= nV) { nE = 2 * nE; } - checkEdges( nE ); + checkEdges(nE); } - private void checkVertices() - { - checkVertices( DEFAULT_VERTICES ); + private void checkVertices() { + checkVertices(DEFAULT_VERTICES); } - private void checkVertices( int nVertices ) - { - if ( vertices == null ) - { + private void checkVertices(int nVertices) { + if (vertices == null) { vertices = new TreeSet<>(); } } - private void checkEdges() - { + + private void checkEdges() { int count = DEFAULT_EDGES; - if ( vertices != null ) - { + if (vertices != null) { count = vertices.size() + vertices.size() / 2; } - checkEdges( count ); + checkEdges(count); } - private void checkEdges( int nEdges ) - { - if ( incidentEdges == null ) - { - incidentEdges = new HashMap<>( nEdges ); + + private void checkEdges(int nEdges) { + if (incidentEdges == null) { + incidentEdges = new HashMap<>(nEdges); } - if ( excidentEdges == null ) - { - excidentEdges = new HashMap<>( nEdges ); + if (excidentEdges == null) { + excidentEdges = new HashMap<>(nEdges); } } - //------------------------------------------------------------------------ - private static void checkVertex( MetadataGraphVertex v ) - throws MetadataResolutionException - { - if ( v == null ) - { - throw new MetadataResolutionException( "null vertex" ); + // ------------------------------------------------------------------------ + private static void checkVertex(MetadataGraphVertex v) throws MetadataResolutionException { + if (v == null) { + throw new MetadataResolutionException("null vertex"); } - if ( v.getMd() == null ) - { - throw new MetadataResolutionException( "vertex without metadata" ); + if (v.getMd() == null) { + throw new MetadataResolutionException("vertex without metadata"); } } - //------------------------------------------------------------------------ - private static void checkEdge( MetadataGraphEdge e ) - throws MetadataResolutionException - { - if ( e == null ) - { - throw new MetadataResolutionException( "badly formed edge" ); + // ------------------------------------------------------------------------ + private static void checkEdge(MetadataGraphEdge e) throws MetadataResolutionException { + if (e == null) { + throw new MetadataResolutionException("badly formed edge"); } } - //------------------------------------------------------------------------ - public List getEdgesBetween( MetadataGraphVertex vFrom, MetadataGraphVertex vTo ) - { - List edges = getIncidentEdges( vTo ); - if ( edges == null || edges.isEmpty() ) - { + // ------------------------------------------------------------------------ + public List getEdgesBetween(MetadataGraphVertex vFrom, MetadataGraphVertex vTo) { + List edges = getIncidentEdges(vTo); + if (edges == null || edges.isEmpty()) { return null; } - List res = new ArrayList<>( edges.size() ); + List res = new ArrayList<>(edges.size()); - for ( MetadataGraphEdge e : edges ) - { - if ( e.getSource().equals( vFrom ) ) - { - res.add( e ); + for (MetadataGraphEdge e : edges) { + if (e.getSource().equals(vFrom)) { + res.add(e); } } return res; } - //------------------------------------------------------------------------ - public MetadataGraph addEdge( MetadataGraphVertex vFrom, MetadataGraphVertex vTo, MetadataGraphEdge e ) - throws MetadataResolutionException - { - checkVertex( vFrom ); - checkVertex( vTo ); + // ------------------------------------------------------------------------ + public MetadataGraph addEdge(MetadataGraphVertex vFrom, MetadataGraphVertex vTo, MetadataGraphEdge e) + throws MetadataResolutionException { + checkVertex(vFrom); + checkVertex(vTo); checkVertices(); - checkEdge( e ); + checkEdge(e); checkEdges(); - e.setSource( vFrom ); - e.setTarget( vTo ); + e.setSource(vFrom); + e.setTarget(vTo); - vFrom.setCompareVersion( versionedVertices ); - vFrom.setCompareScope( scopedVertices ); + vFrom.setCompareVersion(versionedVertices); + vFrom.setCompareScope(scopedVertices); - List exList = excidentEdges.computeIfAbsent( vFrom, k -> new ArrayList<>() ); + List exList = excidentEdges.computeIfAbsent(vFrom, k -> new ArrayList<>()); - if ( !exList.contains( e ) ) - { - exList.add( e ); + if (!exList.contains(e)) { + exList.add(e); } - List inList = incidentEdges.computeIfAbsent( vTo, k -> new ArrayList<>() ); + List inList = incidentEdges.computeIfAbsent(vTo, k -> new ArrayList<>()); - if ( !inList.contains( e ) ) - { - inList.add( e ); + if (!inList.contains(e)) { + inList.add(e); } return this; } - //------------------------------------------------------------------------ - public MetadataGraph removeVertex( MetadataGraphVertex v ) - { - if ( vertices != null && v != null ) - { - vertices.remove( v ); + // ------------------------------------------------------------------------ + public MetadataGraph removeVertex(MetadataGraphVertex v) { + if (vertices != null && v != null) { + vertices.remove(v); } - if ( incidentEdges != null ) - { - incidentEdges.remove( v ); + if (incidentEdges != null) { + incidentEdges.remove(v); } - if ( excidentEdges != null ) - { - excidentEdges.remove( v ); + if (excidentEdges != null) { + excidentEdges.remove(v); } return this; - } - //------------------------------------------------------------------------ - private static int countNodes( MetadataTreeNode tree ) - { - if ( tree == null ) - { + // ------------------------------------------------------------------------ + private static int countNodes(MetadataTreeNode tree) { + if (tree == null) { return 0; } int count = 1; MetadataTreeNode[] kids = tree.getChildren(); - if ( kids == null || kids.length < 1 ) - { + if (kids == null || kids.length < 1) { return count; } - for ( MetadataTreeNode n : kids ) - { - count += countNodes( n ); + for (MetadataTreeNode n : kids) { + count += countNodes(n); } return count; } - //------------------------------------------------------------------------ - public MetadataGraphVertex getEntry() - { + // ------------------------------------------------------------------------ + public MetadataGraphVertex getEntry() { return entry; } - public void setEntry( MetadataGraphVertex entry ) - { + public void setEntry(MetadataGraphVertex entry) { this.entry = entry; } - public TreeSet getVertices() - { + public TreeSet getVertices() { return vertices; } - public List getIncidentEdges( MetadataGraphVertex vertex ) - { + public List getIncidentEdges(MetadataGraphVertex vertex) { checkEdges(); - return incidentEdges.get( vertex ); + return incidentEdges.get(vertex); } - public List getExcidentEdges( MetadataGraphVertex vertex ) - { + public List getExcidentEdges(MetadataGraphVertex vertex) { checkEdges(); - return excidentEdges.get( vertex ); + return excidentEdges.get(vertex); } - public boolean isVersionedVertices() - { + public boolean isVersionedVertices() { return versionedVertices; } - public void setVersionedVertices( boolean versionedVertices ) - { + public void setVersionedVertices(boolean versionedVertices) { this.versionedVertices = versionedVertices; } - public boolean isScopedVertices() - { + public boolean isScopedVertices() { return scopedVertices; } - public void setScopedVertices( boolean scopedVertices ) - { + public void setScopedVertices(boolean scopedVertices) { this.scopedVertices = scopedVertices; // scoped graph is versioned by definition - if ( scopedVertices ) - { + if (scopedVertices) { versionedVertices = true; } } - public ArtifactScopeEnum getScope() - { + public ArtifactScopeEnum getScope() { return scope; } - public void setScope( ArtifactScopeEnum scope ) - { + public void setScope(ArtifactScopeEnum scope) { this.scope = scope; } // ------------------------------------------------------------------------ - public boolean isEmpty() - { + public boolean isEmpty() { return entry == null || vertices == null || vertices.isEmpty(); } - //------------------------------------------------------------------------ - public boolean isEmptyEdges() - { + // ------------------------------------------------------------------------ + public boolean isEmptyEdges() { return isEmpty() || incidentEdges == null || incidentEdges.isEmpty(); } - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ @Override - public String toString() - { - StringBuilder sb = new StringBuilder( 512 ); - if ( isEmpty() ) - { + public String toString() { + StringBuilder sb = new StringBuilder(512); + if (isEmpty()) { return "empty"; } - for ( MetadataGraphVertex v : vertices ) - { - sb.append( "Vertex: " ).append( v.getMd().toString() ).append( '\n' ); - List ins = getIncidentEdges( v ); - if ( ins != null ) - { - for ( MetadataGraphEdge e : ins ) - { - sb.append( " from : " ).append( e.toString() ).append( '\n' ); + for (MetadataGraphVertex v : vertices) { + sb.append("Vertex: ").append(v.getMd().toString()).append('\n'); + List ins = getIncidentEdges(v); + if (ins != null) { + for (MetadataGraphEdge e : ins) { + sb.append(" from : ").append(e.toString()).append('\n'); } - } - else - { - sb.append( " no entries\n" ); + } else { + sb.append(" no entries\n"); } - List outs = getExcidentEdges( v ); - if ( outs != null ) - { - for ( MetadataGraphEdge e : outs ) - { - sb.append( " to : " ).append( e.toString() ).append( '\n' ); + List outs = getExcidentEdges(v); + if (outs != null) { + for (MetadataGraphEdge e : outs) { + sb.append(" to : ").append(e.toString()).append('\n'); } - } - else - { - sb.append( " no exit\n" ); + } else { + sb.append(" no exit\n"); } - sb.append( "-------------------------------------------------\n" ); + sb.append("-------------------------------------------------\n"); } - sb.append( "=============================================================\n" ); + sb.append("=============================================================\n"); return sb.toString(); } - //------------------------------------------------------------------------ - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphEdge.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphEdge.java index 16fe9bc07f..628216805a 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphEdge.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphEdge.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.ArtifactScopeEnum; @@ -28,15 +27,13 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * @author Oleg Gusakov * */ - -public class MetadataGraphEdge -{ - String version; +public class MetadataGraphEdge { + String version; ArtifactScopeEnum scope; - int depth = -1; - int pomOrder = -1; - boolean resolved = true; - String artifactUri; + int depth = -1; + int pomOrder = -1; + boolean resolved = true; + String artifactUri; /** * capturing where this link came from @@ -44,13 +41,13 @@ public class MetadataGraphEdge * * In the first implementation only source used for explanatory function */ - MetadataGraphVertex source; - MetadataGraphVertex target; + MetadataGraphVertex source; - //---------------------------------------------------------------------------- - public MetadataGraphEdge( String version, boolean resolved, ArtifactScopeEnum scope, String artifactUri, int depth, - int pomOrder ) - { + MetadataGraphVertex target; + + // ---------------------------------------------------------------------------- + public MetadataGraphEdge( + String version, boolean resolved, ArtifactScopeEnum scope, String artifactUri, int depth, int pomOrder) { super(); this.version = version; this.scope = scope; @@ -59,133 +56,112 @@ public class MetadataGraphEdge this.resolved = resolved; this.pomOrder = pomOrder; } - //---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- /** * helper for equals */ - private static boolean objectsEqual( Object o1, Object o2 ) - { - if ( o1 == null && o2 == null ) - { + private static boolean objectsEqual(Object o1, Object o2) { + if (o1 == null && o2 == null) { return true; } - if ( o1 == null || o2 == null ) - { + if (o1 == null || o2 == null) { return false; // as they are not both null } - return o1.equals( o2 ); + return o1.equals(o2); } - //---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- /** * used to eliminate exact duplicates in the edge list */ @Override - @SuppressWarnings( "checkstyle:equalshashcode" ) - public boolean equals( Object o ) - { - if ( o instanceof MetadataGraphEdge ) - { + @SuppressWarnings("checkstyle:equalshashcode") + public boolean equals(Object o) { + if (o instanceof MetadataGraphEdge) { MetadataGraphEdge e = (MetadataGraphEdge) o; - return objectsEqual( version, e.version ) - && ArtifactScopeEnum.checkScope( scope ).getScope(). - equals( ArtifactScopeEnum.checkScope( e.scope ).getScope() ) - && depth == e.depth; + return objectsEqual(version, e.version) + && ArtifactScopeEnum.checkScope(scope) + .getScope() + .equals(ArtifactScopeEnum.checkScope(e.scope).getScope()) + && depth == e.depth; } return false; } - //---------------------------------------------------------------------------- - public String getVersion() - { + // ---------------------------------------------------------------------------- + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public ArtifactScopeEnum getScope() - { + public ArtifactScopeEnum getScope() { return scope; } - public void setScope( ArtifactScopeEnum scope ) - { + public void setScope(ArtifactScopeEnum scope) { this.scope = scope; } - public int getDepth() - { + public int getDepth() { return depth; } - public void setDepth( int depth ) - { + public void setDepth(int depth) { this.depth = depth; } - public boolean isResolved() - { + public boolean isResolved() { return resolved; } - public void setResolved( boolean resolved ) - { + public void setResolved(boolean resolved) { this.resolved = resolved; } - public int getPomOrder() - { + public int getPomOrder() { return pomOrder; } - public void setPomOrder( int pomOrder ) - { + public void setPomOrder(int pomOrder) { this.pomOrder = pomOrder; } - public String getArtifactUri() - { + public String getArtifactUri() { return artifactUri; } - public void setArtifactUri( String artifactUri ) - { + public void setArtifactUri(String artifactUri) { this.artifactUri = artifactUri; } - public MetadataGraphVertex getSource() - { + public MetadataGraphVertex getSource() { return source; } - public void setSource( MetadataGraphVertex source ) - { + public void setSource(MetadataGraphVertex source) { this.source = source; } - public MetadataGraphVertex getTarget() - { + public MetadataGraphVertex getTarget() { return target; } - public void setTarget( MetadataGraphVertex target ) - { + public void setTarget(MetadataGraphVertex target) { this.target = target; } @Override - public String toString() - { + public String toString() { return "[ " + "FROM:(" - + ( source == null ? "no source" : ( source.md == null ? "no source MD" : source.md.toString() ) ) + ") " - + "TO:(" + ( target == null ? "no target" : ( target.md == null ? "no target MD" : target.md.toString() ) ) - + ") " + "version=" + version + ", scope=" + ( scope == null ? "null" : scope.getScope() ) + ", depth=" - + depth + "]"; + + (source == null ? "no source" : (source.md == null ? "no source MD" : source.md.toString())) + ") " + + "TO:(" + (target == null ? "no target" : (target.md == null ? "no target MD" : target.md.toString())) + + ") " + "version=" + version + ", scope=" + (scope == null ? "null" : scope.getScope()) + ", depth=" + + depth + "]"; } - //---------------------------------------------------------------------------- - //---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphTransformationException.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphTransformationException.java index 7861b48ede..cab32f403f 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphTransformationException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphTransformationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,33 +16,26 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; /** * @author Oleg Gusakov */ -public class MetadataGraphTransformationException - extends Exception -{ +public class MetadataGraphTransformationException extends Exception { private static final long serialVersionUID = -4029897098314019152L; - public MetadataGraphTransformationException() - { + public MetadataGraphTransformationException() {} + + public MetadataGraphTransformationException(String message) { + super(message); } - public MetadataGraphTransformationException( String message ) - { - super( message ); + public MetadataGraphTransformationException(Throwable cause) { + super(cause); } - public MetadataGraphTransformationException( Throwable cause ) - { - super( cause ); + public MetadataGraphTransformationException(String message, Throwable cause) { + super(message, cause); } - - public MetadataGraphTransformationException( String message, Throwable cause ) - { - super( message, cause ); - } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphVertex.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphVertex.java index f24c39555d..b59406e0ff 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphVertex.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphVertex.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.ArtifactScopeEnum; @@ -26,144 +25,113 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * * @author Oleg Gusakov */ -public class MetadataGraphVertex - implements Comparable -{ +public class MetadataGraphVertex implements Comparable { ArtifactMetadata md; // indications to use these in comparison private boolean compareVersion = false; - private boolean compareScope = false; + private boolean compareScope = false; - public MetadataGraphVertex( ArtifactMetadata md ) - { + public MetadataGraphVertex(ArtifactMetadata md) { super(); this.md = md; } - public MetadataGraphVertex( ArtifactMetadata md, boolean compareVersion, boolean compareScope ) - { - this( md ); + public MetadataGraphVertex(ArtifactMetadata md, boolean compareVersion, boolean compareScope) { + this(md); this.compareVersion = compareVersion; this.compareScope = compareScope; } - public ArtifactMetadata getMd() - { + public ArtifactMetadata getMd() { return md; } - public void setMd( ArtifactMetadata md ) - { + public void setMd(ArtifactMetadata md) { this.md = md; } // --------------------------------------------------------------------- - public boolean isCompareVersion() - { + public boolean isCompareVersion() { return compareVersion; } - public void setCompareVersion( boolean compareVersion ) - { + public void setCompareVersion(boolean compareVersion) { this.compareVersion = compareVersion; } - public boolean isCompareScope() - { + public boolean isCompareScope() { return compareScope; } - public void setCompareScope( boolean compareScope ) - { + public void setCompareScope(boolean compareScope) { this.compareScope = compareScope; } // --------------------------------------------------------------------- @Override - public String toString() - { - return "[" + ( md == null ? "no metadata" : md.toString() ) + "]"; + public String toString() { + return "[" + (md == null ? "no metadata" : md.toString()) + "]"; } // --------------------------------------------------------------------- - private static int compareStrings( String s1, String s2 ) - { - if ( s1 == null && s2 == null ) - { + private static int compareStrings(String s1, String s2) { + if (s1 == null && s2 == null) { return 0; } - if ( s1 == null /* && s2 != null */ ) - { + if (s1 == null /* && s2 != null */) { return -1; } - if ( /* s1 != null && */ s2 == null ) - { + if ( + /* s1 != null && */ s2 == null) { return 1; } - return s1.compareTo( s2 ); + return s1.compareTo(s2); } // --------------------------------------------------------------------- - public int compareTo( MetadataGraphVertex vertex ) - { - if ( vertex == null || vertex.getMd() == null ) - { + public int compareTo(MetadataGraphVertex vertex) { + if (vertex == null || vertex.getMd() == null) { return 1; } ArtifactMetadata vmd = vertex.getMd(); - if ( vmd == null ) - { - if ( md == null ) - { + if (vmd == null) { + if (md == null) { return 0; - } - else - { + } else { return 1; } } - int g = compareStrings( md.groupId, vmd.groupId ); + int g = compareStrings(md.groupId, vmd.groupId); - if ( g == 0 ) - { - int a = compareStrings( md.artifactId, vmd.artifactId ); - if ( a == 0 ) - { - if ( compareVersion ) - { - int v = compareStrings( md.version, vmd.version ); - if ( v == 0 ) - { - if ( compareScope ) - { - String s1 = ArtifactScopeEnum.checkScope( md.artifactScope ).getScope(); - String s2 = ArtifactScopeEnum.checkScope( vmd.artifactScope ).getScope(); - return s1.compareTo( s2 ); - } - else - { + if (g == 0) { + int a = compareStrings(md.artifactId, vmd.artifactId); + if (a == 0) { + if (compareVersion) { + int v = compareStrings(md.version, vmd.version); + if (v == 0) { + if (compareScope) { + String s1 = ArtifactScopeEnum.checkScope(md.artifactScope) + .getScope(); + String s2 = ArtifactScopeEnum.checkScope(vmd.artifactScope) + .getScope(); + return s1.compareTo(s2); + } else { return 0; } - } - else - { + } else { return v; } - } - else - { + } else { return 0; } - } - else - { + } else { return a; } } @@ -173,36 +141,30 @@ public class MetadataGraphVertex // --------------------------------------------------------------------- @Override - public boolean equals( Object vo ) - { - if ( !( vo instanceof MetadataGraphVertex ) ) - { + public boolean equals(Object vo) { + if (!(vo instanceof MetadataGraphVertex)) { return false; } - return compareTo( (MetadataGraphVertex) vo ) == 0; + return compareTo((MetadataGraphVertex) vo) == 0; } // --------------------------------------------------------------------- @Override - public int hashCode() - { - if ( md == null ) - { + public int hashCode() { + if (md == null) { return super.hashCode(); } - StringBuilder hashString = new StringBuilder( 128 ); - hashString.append( md.groupId ).append( '|' ); - hashString.append( md.artifactId ).append( '|' ); + StringBuilder hashString = new StringBuilder(128); + hashString.append(md.groupId).append('|'); + hashString.append(md.artifactId).append('|'); - if ( compareVersion ) - { - hashString.append( md.version ).append( '|' ); + if (compareVersion) { + hashString.append(md.version).append('|'); } - if ( compareScope ) - { - hashString.append( md.getArtifactScope() ).append( '|' ); + if (compareScope) { + hashString.append(md.getArtifactScope()).append('|'); } return hashString.toString().hashCode(); diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolution.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolution.java index 9a9130b2fa..9223992947 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolution.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolution.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.Collection; - import org.apache.maven.artifact.repository.ArtifactRepository; /** @@ -28,44 +26,37 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * @author Jason van Zyl * */ -public class MetadataResolution -{ +public class MetadataResolution { /** resolved MD */ private ArtifactMetadata artifactMetadata; /** repositories, added by this POM */ private Collection metadataRepositories; - //------------------------------------------------------------------- - public MetadataResolution( ArtifactMetadata artifactMetadata ) - { + // ------------------------------------------------------------------- + public MetadataResolution(ArtifactMetadata artifactMetadata) { this.artifactMetadata = artifactMetadata; } - //------------------------------------------------------------------- - public MetadataResolution( ArtifactMetadata artifactMetadata, Collection metadataRepositories ) - { - this( artifactMetadata ); + // ------------------------------------------------------------------- + public MetadataResolution(ArtifactMetadata artifactMetadata, Collection metadataRepositories) { + this(artifactMetadata); this.metadataRepositories = metadataRepositories; } - //------------------------------------------------------------------- - public Collection getMetadataRepositories() - { + // ------------------------------------------------------------------- + public Collection getMetadataRepositories() { return metadataRepositories; } - public void setMetadataRepositories( Collection metadataRepositories ) - { + public void setMetadataRepositories(Collection metadataRepositories) { this.metadataRepositories = metadataRepositories; } - //------------------------------------------------------------------- - public ArtifactMetadata getArtifactMetadata() - { + // ------------------------------------------------------------------- + public ArtifactMetadata getArtifactMetadata() { return artifactMetadata; } - public void setArtifactMetadata( ArtifactMetadata artifactMetadata ) - { + public void setArtifactMetadata(ArtifactMetadata artifactMetadata) { this.artifactMetadata = artifactMetadata; } - //------------------------------------------------------------------- - //------------------------------------------------------------------- + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionException.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionException.java index 149d2ac69b..5d9efbc21a 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,35 +16,29 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; /** * MetadataResolutionException */ -public class MetadataResolutionException - extends Exception -{ +public class MetadataResolutionException extends Exception { - public MetadataResolutionException() - { + public MetadataResolutionException() { // TODO Auto-generated constructor stub } - public MetadataResolutionException( String message ) - { - super( message ); + public MetadataResolutionException(String message) { + super(message); // TODO Auto-generated constructor stub } - public MetadataResolutionException( Throwable cause ) - { - super( cause ); + public MetadataResolutionException(Throwable cause) { + super(cause); // TODO Auto-generated constructor stub } - public MetadataResolutionException( String message, Throwable cause ) - { - super( message, cause ); + public MetadataResolutionException(String message, Throwable cause) { + super(message, cause); // TODO Auto-generated constructor stub } - } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequest.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequest.java index e1f6fe1ee8..163dce602d 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequest.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,62 +16,52 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.List; - import org.apache.maven.artifact.repository.ArtifactRepository; /** @author Oleg Gusakov */ -public class MetadataResolutionRequest -{ +public class MetadataResolutionRequest { protected ArtifactMetadata query; protected ArtifactRepository localRepository; protected List remoteRepositories; - //-------------------------------------------------------------------- - public MetadataResolutionRequest() - { - } + // -------------------------------------------------------------------- + public MetadataResolutionRequest() {} - //-------------------------------------------------------------------- - public MetadataResolutionRequest( ArtifactMetadata query, ArtifactRepository localRepository, - List remoteRepositories ) - { + // -------------------------------------------------------------------- + public MetadataResolutionRequest( + ArtifactMetadata query, ArtifactRepository localRepository, List remoteRepositories) { this.query = query; this.localRepository = localRepository; this.remoteRepositories = remoteRepositories; } - //-------------------------------------------------------------------- - public ArtifactMetadata getQuery() - { + // -------------------------------------------------------------------- + public ArtifactMetadata getQuery() { return query; } - public void setQuery( ArtifactMetadata query ) - { + public void setQuery(ArtifactMetadata query) { this.query = query; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } - public void setLocalRepository( ArtifactRepository localRepository ) - { + public void setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - public void setRemoteRepositories( List remoteRepositories ) - { + public void setRemoteRepositories(List remoteRepositories) { this.remoteRepositories = remoteRepositories; } - //-------------------------------------------------------------------- - //-------------------------------------------------------------------- + // -------------------------------------------------------------------- + // -------------------------------------------------------------------- } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequestTypeEnum.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequestTypeEnum.java index 31e3e9123a..0183ea66a2 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequestTypeEnum.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionRequestTypeEnum.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,31 +16,28 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; /** * MetadataResolutionRequestTypeEnum */ -public enum MetadataResolutionRequestTypeEnum -{ - tree( 1 ) - , graph( 2 ) - , classpathCompile( 3 ) - , classpathTest( 4 ) - , classpathRuntime( 5 ) - , versionedGraph( 6 ) - , scopedGraph( 7 ) - ; +public enum MetadataResolutionRequestTypeEnum { + tree(1), + graph(2), + classpathCompile(3), + classpathTest(4), + classpathRuntime(5), + versionedGraph(6), + scopedGraph(7); private int id; // Constructor - MetadataResolutionRequestTypeEnum( int id ) - { + MetadataResolutionRequestTypeEnum(int id) { this.id = id; } - int getId() - { + int getId() { return id; } } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionResult.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionResult.java index 0f35bd664f..516c9ae952 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionResult.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.ArtifactScopeEnum; import org.codehaus.plexus.PlexusContainer; @@ -29,8 +28,7 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti * * @author Oleg Gusakov */ -public class MetadataResolutionResult -{ +public class MetadataResolutionResult { MetadataTreeNode treeRoot; /** @@ -38,131 +36,100 @@ public class MetadataResolutionResult * explicit call of the initTreeProcessing() */ ClasspathTransformation classpathTransformation; + GraphConflictResolver conflictResolver; - //---------------------------------------------------------------------------- - public MetadataResolutionResult( ) - { - } - //---------------------------------------------------------------------------- - public MetadataResolutionResult( MetadataTreeNode root ) - { + // ---------------------------------------------------------------------------- + public MetadataResolutionResult() {} + // ---------------------------------------------------------------------------- + public MetadataResolutionResult(MetadataTreeNode root) { this.treeRoot = root; } - //---------------------------------------------------------------------------- - public MetadataTreeNode getTree() - { + // ---------------------------------------------------------------------------- + public MetadataTreeNode getTree() { return treeRoot; } - //---------------------------------------------------------------------------- - public void setTree( MetadataTreeNode root ) - { + // ---------------------------------------------------------------------------- + public void setTree(MetadataTreeNode root) { this.treeRoot = root; } - public void initTreeProcessing( PlexusContainer plexus ) - throws ComponentLookupException - { - classpathTransformation = plexus.lookup( ClasspathTransformation.class ); - conflictResolver = plexus.lookup( GraphConflictResolver.class ); + public void initTreeProcessing(PlexusContainer plexus) throws ComponentLookupException { + classpathTransformation = plexus.lookup(ClasspathTransformation.class); + conflictResolver = plexus.lookup(GraphConflictResolver.class); } - //---------------------------------------------------------------------------- - public MetadataGraph getGraph() - throws MetadataResolutionException - { - return treeRoot == null ? null : new MetadataGraph( treeRoot ); + // ---------------------------------------------------------------------------- + public MetadataGraph getGraph() throws MetadataResolutionException { + return treeRoot == null ? null : new MetadataGraph(treeRoot); } - //---------------------------------------------------------------------------- - public MetadataGraph getGraph( ArtifactScopeEnum scope ) - throws MetadataResolutionException, GraphConflictResolutionException - { - if ( treeRoot == null ) - { + // ---------------------------------------------------------------------------- + public MetadataGraph getGraph(ArtifactScopeEnum scope) + throws MetadataResolutionException, GraphConflictResolutionException { + if (treeRoot == null) { return null; } - if ( conflictResolver == null ) - { + if (conflictResolver == null) { return null; } - return conflictResolver.resolveConflicts( getGraph(), scope ); + return conflictResolver.resolveConflicts(getGraph(), scope); } - //---------------------------------------------------------------------------- - public MetadataGraph getGraph( MetadataResolutionRequestTypeEnum requestType ) - throws MetadataResolutionException, GraphConflictResolutionException - { - if ( requestType == null ) - { + // ---------------------------------------------------------------------------- + public MetadataGraph getGraph(MetadataResolutionRequestTypeEnum requestType) + throws MetadataResolutionException, GraphConflictResolutionException { + if (requestType == null) { return null; } - if ( treeRoot == null ) - { + if (treeRoot == null) { return null; } - if ( conflictResolver == null ) - { + if (conflictResolver == null) { return null; } - if ( requestType.equals( MetadataResolutionRequestTypeEnum.classpathCompile ) ) - { - return conflictResolver.resolveConflicts( getGraph(), ArtifactScopeEnum.compile ); - } - else if ( requestType.equals( MetadataResolutionRequestTypeEnum.classpathRuntime ) ) - { - return conflictResolver.resolveConflicts( getGraph(), ArtifactScopeEnum.runtime ); - } - else if ( requestType.equals( MetadataResolutionRequestTypeEnum.classpathTest ) ) - { - return conflictResolver.resolveConflicts( getGraph(), ArtifactScopeEnum.test ); - } - else if ( requestType.equals( MetadataResolutionRequestTypeEnum.graph ) ) - { + if (requestType.equals(MetadataResolutionRequestTypeEnum.classpathCompile)) { + return conflictResolver.resolveConflicts(getGraph(), ArtifactScopeEnum.compile); + } else if (requestType.equals(MetadataResolutionRequestTypeEnum.classpathRuntime)) { + return conflictResolver.resolveConflicts(getGraph(), ArtifactScopeEnum.runtime); + } else if (requestType.equals(MetadataResolutionRequestTypeEnum.classpathTest)) { + return conflictResolver.resolveConflicts(getGraph(), ArtifactScopeEnum.test); + } else if (requestType.equals(MetadataResolutionRequestTypeEnum.graph)) { return getGraph(); - } - else if ( requestType.equals( MetadataResolutionRequestTypeEnum.versionedGraph ) ) - { - return new MetadataGraph( getTree(), true, false ); - } - else if ( requestType.equals( MetadataResolutionRequestTypeEnum.scopedGraph ) ) - { - return new MetadataGraph( getTree(), true, true ); + } else if (requestType.equals(MetadataResolutionRequestTypeEnum.versionedGraph)) { + return new MetadataGraph(getTree(), true, false); + } else if (requestType.equals(MetadataResolutionRequestTypeEnum.scopedGraph)) { + return new MetadataGraph(getTree(), true, true); } return null; } - //---------------------------------------------------------------------------- - public ClasspathContainer getClasspath( ArtifactScopeEnum scope ) - throws MetadataGraphTransformationException, MetadataResolutionException - { - if ( classpathTransformation == null ) - { + // ---------------------------------------------------------------------------- + public ClasspathContainer getClasspath(ArtifactScopeEnum scope) + throws MetadataGraphTransformationException, MetadataResolutionException { + if (classpathTransformation == null) { return null; } MetadataGraph dirtyGraph = getGraph(); - if ( dirtyGraph == null ) - { + if (dirtyGraph == null) { return null; } - return classpathTransformation.transform( dirtyGraph, scope, false ); + return classpathTransformation.transform(dirtyGraph, scope, false); } - //---------------------------------------------------------------------------- - public MetadataTreeNode getClasspathTree( ArtifactScopeEnum scope ) - throws MetadataGraphTransformationException, MetadataResolutionException - { - ClasspathContainer cpc = getClasspath( scope ); - if ( cpc == null ) - { + // ---------------------------------------------------------------------------- + public MetadataTreeNode getClasspathTree(ArtifactScopeEnum scope) + throws MetadataGraphTransformationException, MetadataResolutionException { + ClasspathContainer cpc = getClasspath(scope); + if (cpc == null) { return null; } return cpc.getClasspathAsTree(); } - //---------------------------------------------------------------------------- - //---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- } diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataRetrievalException.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataRetrievalException.java index f5461d7166..0f679571fe 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataRetrievalException.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataRetrievalException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,42 +16,36 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; /** * Error while retrieving repository metadata from the repository. * * @author Jason van Zyl */ -public class MetadataRetrievalException - extends Exception -{ +public class MetadataRetrievalException extends Exception { private ArtifactMetadata artifact; - public MetadataRetrievalException( String message ) - { - this( message, null, null ); + public MetadataRetrievalException(String message) { + this(message, null, null); } - public MetadataRetrievalException( Throwable cause ) - { - this( null, cause, null ); + public MetadataRetrievalException(Throwable cause) { + this(null, cause, null); } - public MetadataRetrievalException( String message, Throwable cause ) - { - this( message, cause, null ); + public MetadataRetrievalException(String message, Throwable cause) { + this(message, cause, null); } - public MetadataRetrievalException( String message, Throwable cause, ArtifactMetadata artifact ) - { - super( message, cause ); + public MetadataRetrievalException(String message, Throwable cause, ArtifactMetadata artifact) { + super(message, cause); this.artifact = artifact; } - public ArtifactMetadata getArtifactMetadata() - { + public ArtifactMetadata getArtifactMetadata() { return artifact; } -} \ No newline at end of file +} diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataSource.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataSource.java index 3ca6ce84f5..69f14d970d 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataSource.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.List; - import org.apache.maven.artifact.repository.ArtifactRepository; /** @@ -29,11 +27,10 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * * @author Jason van Zyl */ -public interface MetadataSource -{ +public interface MetadataSource { String ROLE = MetadataSource.class.getName(); - MetadataResolution retrieve( ArtifactMetadata artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws MetadataRetrievalException; -} \ No newline at end of file + MetadataResolution retrieve( + ArtifactMetadata artifact, ArtifactRepository localRepository, List remoteRepositories) + throws MetadataRetrievalException; +} diff --git a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataTreeNode.java b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataTreeNode.java index dd720d3866..7006f748cf 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataTreeNode.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataTreeNode.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactScopeEnum; @@ -28,8 +27,7 @@ import org.apache.maven.artifact.ArtifactScopeEnum; * @author Oleg Gusakov * */ -public class MetadataTreeNode -{ +public class MetadataTreeNode { ArtifactMetadata md; // this node MetadataTreeNode parent; // papa @@ -39,110 +37,89 @@ public class MetadataTreeNode MetadataTreeNode[] children; // of cause - public int getNChildren() - { + public int getNChildren() { return nChildren; } - public void setNChildren( int children ) - { + public void setNChildren(int children) { nChildren = children; } - //------------------------------------------------------------------------ - public MetadataTreeNode() - { - } - //------------------------------------------------------------------------ - public MetadataTreeNode( ArtifactMetadata md, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope ) - { - if ( md != null ) - { - md.setArtifactScope( ArtifactScopeEnum.checkScope( scope ) ); - md.setResolved( resolved ); + // ------------------------------------------------------------------------ + public MetadataTreeNode() {} + // ------------------------------------------------------------------------ + public MetadataTreeNode(ArtifactMetadata md, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope) { + if (md != null) { + md.setArtifactScope(ArtifactScopeEnum.checkScope(scope)); + md.setResolved(resolved); } this.md = md; this.parent = parent; } - //------------------------------------------------------------------------ - public MetadataTreeNode( Artifact af, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope ) - { - this( new ArtifactMetadata( af ), parent, resolved, scope ); + // ------------------------------------------------------------------------ + public MetadataTreeNode(Artifact af, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope) { + this(new ArtifactMetadata(af), parent, resolved, scope); } // ------------------------------------------------------------------------ - public void addChild( int index, MetadataTreeNode kid ) - { - if ( kid == null ) - { + public void addChild(int index, MetadataTreeNode kid) { + if (kid == null) { return; } - if ( children == null ) - { + if (children == null) { children = new MetadataTreeNode[nChildren]; } children[index % nChildren] = kid; } - //------------------------------------------------------------------ + // ------------------------------------------------------------------ @Override - public String toString() - { + public String toString() { return md == null ? "no metadata" : md.toString(); } - //------------------------------------------------------------------ - public String graphHash() - throws MetadataResolutionException - { - if ( md == null ) - { - throw new MetadataResolutionException( "treenode without metadata, parent: " - + ( parent == null ? "null" : parent.toString() ) ); + // ------------------------------------------------------------------ + public String graphHash() throws MetadataResolutionException { + if (md == null) { + throw new MetadataResolutionException( + "treenode without metadata, parent: " + (parent == null ? "null" : parent.toString())); } return md.groupId + ":" + md.artifactId; } - //------------------------------------------------------------------------ - public boolean hasChildren() - { + // ------------------------------------------------------------------------ + public boolean hasChildren() { return children != null; } - //------------------------------------------------------------------------ - public ArtifactMetadata getMd() - { + // ------------------------------------------------------------------------ + public ArtifactMetadata getMd() { return md; } - public void setMd( ArtifactMetadata md ) - { + public void setMd(ArtifactMetadata md) { this.md = md; } - public MetadataTreeNode getParent() - { + public MetadataTreeNode getParent() { return parent; } - public void setParent( MetadataTreeNode parent ) - { + public void setParent(MetadataTreeNode parent) { this.parent = parent; } - public MetadataTreeNode[] getChildren() - { + public MetadataTreeNode[] getChildren() { return children; } - public void setChildren( MetadataTreeNode[] children ) - { + public void setChildren(MetadataTreeNode[] children) { this.children = children; } - //------------------------------------------------------------------------ - //------------------------------------------------------------------------ + // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumentationException.java b/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumentationException.java index d001562fa2..fad67888ba 100644 --- a/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumentationException.java +++ b/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumentationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.usability.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.usability.plugin; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.usability.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.usability.plugin; /** * ExpressionDocumentationException */ -public class ExpressionDocumentationException - extends Exception -{ +public class ExpressionDocumentationException extends Exception { static final long serialVersionUID = 1; - public ExpressionDocumentationException( String message, Throwable cause ) - { - super( message, cause ); + public ExpressionDocumentationException(String message, Throwable cause) { + super(message, cause); } - public ExpressionDocumentationException( String message ) - { - super( message ); + public ExpressionDocumentationException(String message) { + super(message); } - } diff --git a/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java b/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java index f4e7bf928e..00e104c805 100644 --- a/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java +++ b/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java @@ -1,5 +1,3 @@ -package org.apache.maven.usability.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.usability.plugin; * "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 + * 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 @@ -18,10 +16,7 @@ package org.apache.maven.usability.plugin; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.usability.plugin.io.xpp3.ParamdocXpp3Reader; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +package org.apache.maven.usability.plugin; import java.io.BufferedReader; import java.io.File; @@ -34,54 +29,42 @@ import java.net.URLClassLoader; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.maven.usability.plugin.io.xpp3.ParamdocXpp3Reader; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * ExpressionDocumenter */ -public class ExpressionDocumenter -{ +public class ExpressionDocumenter { - private static final String[] EXPRESSION_ROOTS = - { - "project", "settings", "session", "plugin", "rootless" - }; + private static final String[] EXPRESSION_ROOTS = {"project", "settings", "session", "plugin", "rootless"}; private static final String EXPRESSION_DOCO_ROOTPATH = "META-INF/maven/plugin-expressions/"; private static Map expressionDocumentation; - public static Map load() - throws ExpressionDocumentationException - { - if ( expressionDocumentation == null ) - { + public static Map load() throws ExpressionDocumentationException { + if (expressionDocumentation == null) { expressionDocumentation = new HashMap<>(); ClassLoader docLoader = initializeDocLoader(); - for ( String root : EXPRESSION_ROOTS ) - { - try ( InputStream docStream = docLoader.getResourceAsStream( - EXPRESSION_DOCO_ROOTPATH + root + ".paramdoc.xml" ) ) - { - if ( docStream != null ) - { - Map doco = parseExpressionDocumentation( docStream ); + for (String root : EXPRESSION_ROOTS) { + try (InputStream docStream = + docLoader.getResourceAsStream(EXPRESSION_DOCO_ROOTPATH + root + ".paramdoc.xml")) { + if (docStream != null) { + Map doco = parseExpressionDocumentation(docStream); - expressionDocumentation.putAll( doco ); + expressionDocumentation.putAll(doco); } - } - catch ( IOException e ) - { + } catch (IOException e) { throw new ExpressionDocumentationException( - "Failed to read documentation for expression root: " + root, e ); - } - catch ( XmlPullParserException e ) - { + "Failed to read documentation for expression root: " + root, e); + } catch (XmlPullParserException e) { throw new ExpressionDocumentationException( - "Failed to parse documentation for expression root: " + root, e ); + "Failed to parse documentation for expression root: " + root, e); } - } } @@ -114,63 +97,50 @@ public class ExpressionDocumenter * @throws IOException * @throws XmlPullParserException */ - private static Map parseExpressionDocumentation( InputStream docStream ) - throws IOException, XmlPullParserException - { - Reader reader = new BufferedReader( ReaderFactory.newXmlReader( docStream ) ); + private static Map parseExpressionDocumentation(InputStream docStream) + throws IOException, XmlPullParserException { + Reader reader = new BufferedReader(ReaderFactory.newXmlReader(docStream)); ParamdocXpp3Reader paramdocReader = new ParamdocXpp3Reader(); - ExpressionDocumentation documentation = paramdocReader.read( reader, true ); + ExpressionDocumentation documentation = paramdocReader.read(reader, true); List expressions = documentation.getExpressions(); Map bySyntax = new HashMap<>(); - if ( expressions != null && !expressions.isEmpty() ) - { - for ( Expression expression : expressions ) - { - bySyntax.put( expression.getSyntax(), expression ); + if (expressions != null && !expressions.isEmpty()) { + for (Expression expression : expressions) { + bySyntax.put(expression.getSyntax(), expression); } } return bySyntax; } - private static ClassLoader initializeDocLoader() - throws ExpressionDocumentationException - { - String myResourcePath = ExpressionDocumenter.class.getName().replace( '.', '/' ) + ".class"; + private static ClassLoader initializeDocLoader() throws ExpressionDocumentationException { + String myResourcePath = ExpressionDocumenter.class.getName().replace('.', '/') + ".class"; - URL myResource = ExpressionDocumenter.class.getClassLoader().getResource( myResourcePath ); + URL myResource = ExpressionDocumenter.class.getClassLoader().getResource(myResourcePath); assert myResource != null : "The resource is this class itself loaded by its own classloader and must exist"; String myClasspathEntry = myResource.getPath(); - myClasspathEntry = myClasspathEntry.substring( 0, myClasspathEntry.length() - ( myResourcePath.length() + 2 ) ); + myClasspathEntry = myClasspathEntry.substring(0, myClasspathEntry.length() - (myResourcePath.length() + 2)); - if ( myClasspathEntry.startsWith( "file:" ) ) - { - myClasspathEntry = myClasspathEntry.substring( "file:".length() ); + if (myClasspathEntry.startsWith("file:")) { + myClasspathEntry = myClasspathEntry.substring("file:".length()); } URL docResource; - try - { - docResource = new File( myClasspathEntry ).toURL(); - } - catch ( MalformedURLException e ) - { + try { + docResource = new File(myClasspathEntry).toURL(); + } catch (MalformedURLException e) { throw new ExpressionDocumentationException( - "Cannot construct expression documentation classpath" + " resource base.", e ); + "Cannot construct expression documentation classpath" + " resource base.", e); } - return new URLClassLoader( new URL[] - { - docResource - } ); + return new URLClassLoader(new URL[] {docResource}); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java b/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java index 735c6499f2..9607560b2c 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,11 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; + +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileOutputStream; @@ -28,11 +31,8 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; - -import org.codehaus.plexus.testing.PlexusTest; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -43,6 +43,7 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.LegacySupport; import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.collection.DependencyGraphTransformer; @@ -67,16 +68,12 @@ import org.eclipse.aether.util.graph.traverser.FatArtifactTraverser; import org.eclipse.aether.util.repository.SimpleArtifactDescriptorPolicy; import org.junit.jupiter.api.BeforeEach; -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * @author Jason van Zyl */ @PlexusTest -public abstract class AbstractArtifactComponentTestCase //extends PlexusTestCase -{ +public abstract class AbstractArtifactComponentTestCase // extends PlexusTestCase + { @Inject protected ArtifactFactory artifactFactory; @@ -86,7 +83,8 @@ public abstract class AbstractArtifactComponentTestCase //extends PlexusTestCase @Inject LegacySupport legacySupport; - @Inject @Named( "default" ) + @Inject + @Named("default") ArtifactRepositoryLayout repoLayout; @Inject @@ -97,14 +95,12 @@ public abstract class AbstractArtifactComponentTestCase //extends PlexusTestCase } @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { RepositorySystemSession repoSession = initRepoSession(); - MavenSession session = new MavenSession( getContainer(), repoSession, new DefaultMavenExecutionRequest(), - new DefaultMavenExecutionResult() ); + MavenSession session = new MavenSession( + getContainer(), repoSession, new DefaultMavenExecutionRequest(), new DefaultMavenExecutionResult()); - legacySupport.setSession( session ); + legacySupport.setSession(session); } protected abstract String component(); @@ -114,112 +110,96 @@ public abstract class AbstractArtifactComponentTestCase //extends PlexusTestCase * * @throws Exception */ - protected ArtifactRepository badLocalRepository() - throws Exception - { + protected ArtifactRepository badLocalRepository() throws Exception { String path = "target/test-repositories/" + component() + "/bad-local-repository"; - File f = new File( getBasedir(), path ); + File f = new File(getBasedir(), path); f.createNewFile(); - return artifactRepositoryFactory.createArtifactRepository( "test", "file://" + f.getPath(), repoLayout, null, - null ); + return artifactRepositoryFactory.createArtifactRepository( + "test", "file://" + f.getPath(), repoLayout, null, null); } - protected String getRepositoryLayout() - { + protected String getRepositoryLayout() { return "default"; } - protected ArtifactRepository localRepository() - throws Exception - { + protected ArtifactRepository localRepository() throws Exception { String path = "target/test-repositories/" + component() + "/local-repository"; - File f = new File( getBasedir(), path ); + File f = new File(getBasedir(), path); - return artifactRepositoryFactory.createArtifactRepository( "local", "file://" + f.getPath(), repoLayout, null, - null ); + return artifactRepositoryFactory.createArtifactRepository( + "local", "file://" + f.getPath(), repoLayout, null, null); } - protected ArtifactRepository remoteRepository() - throws Exception - { + protected ArtifactRepository remoteRepository() throws Exception { String path = "target/test-repositories/" + component() + "/remote-repository"; - File f = new File( getBasedir(), path ); + File f = new File(getBasedir(), path); - return artifactRepositoryFactory.createArtifactRepository( "test", "file://" + f.getPath(), repoLayout, - new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + return artifactRepositoryFactory.createArtifactRepository( + "test", + "file://" + f.getPath(), + repoLayout, + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - protected ArtifactRepository badRemoteRepository() - throws Exception - { - return artifactRepositoryFactory.createArtifactRepository( "test", "http://foo.bar/repository", repoLayout, - null, null ); + protected ArtifactRepository badRemoteRepository() throws Exception { + return artifactRepositoryFactory.createArtifactRepository( + "test", "http://foo.bar/repository", repoLayout, null, null); } - protected void assertRemoteArtifactPresent( Artifact artifact ) - throws Exception - { + protected void assertRemoteArtifactPresent(Artifact artifact) throws Exception { ArtifactRepository remoteRepo = remoteRepository(); - String path = remoteRepo.pathOf( artifact ); + String path = remoteRepo.pathOf(artifact); - File file = new File( remoteRepo.getBasedir(), path ); + File file = new File(remoteRepo.getBasedir(), path); - assertTrue( file.exists(), "Remote artifact " + file + " should be present." ); + assertTrue(file.exists(), "Remote artifact " + file + " should be present."); } - protected void assertLocalArtifactPresent( Artifact artifact ) - throws Exception - { + protected void assertLocalArtifactPresent(Artifact artifact) throws Exception { ArtifactRepository localRepo = localRepository(); - String path = localRepo.pathOf( artifact ); + String path = localRepo.pathOf(artifact); - File file = new File( localRepo.getBasedir(), path ); + File file = new File(localRepo.getBasedir(), path); - assertTrue( file.exists(), "Local artifact " + file + " should be present." ); + assertTrue(file.exists(), "Local artifact " + file + " should be present."); } - protected void assertRemoteArtifactNotPresent( Artifact artifact ) - throws Exception - { + protected void assertRemoteArtifactNotPresent(Artifact artifact) throws Exception { ArtifactRepository remoteRepo = remoteRepository(); - String path = remoteRepo.pathOf( artifact ); + String path = remoteRepo.pathOf(artifact); - File file = new File( remoteRepo.getBasedir(), path ); + File file = new File(remoteRepo.getBasedir(), path); - assertFalse( file.exists(), "Remote artifact " + file + " should not be present." ); + assertFalse(file.exists(), "Remote artifact " + file + " should not be present."); } - protected void assertLocalArtifactNotPresent( Artifact artifact ) - throws Exception - { + protected void assertLocalArtifactNotPresent(Artifact artifact) throws Exception { ArtifactRepository localRepo = localRepository(); - String path = localRepo.pathOf( artifact ); + String path = localRepo.pathOf(artifact); - File file = new File( localRepo.getBasedir(), path ); + File file = new File(localRepo.getBasedir(), path); - assertFalse( file.exists(), "Local artifact " + file + " should not be present." ); + assertFalse(file.exists(), "Local artifact " + file + " should not be present."); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - protected List remoteRepositories() - throws Exception - { + protected List remoteRepositories() throws Exception { List remoteRepositories = new ArrayList<>(); - remoteRepositories.add( remoteRepository() ); + remoteRepositories.add(remoteRepository()); return remoteRepositories; } @@ -228,148 +208,119 @@ public abstract class AbstractArtifactComponentTestCase //extends PlexusTestCase // Test artifact generation for unit tests // ---------------------------------------------------------------------- - protected Artifact createLocalArtifact( String artifactId, String version ) - throws Exception - { - Artifact artifact = createArtifact( artifactId, version ); + protected Artifact createLocalArtifact(String artifactId, String version) throws Exception { + Artifact artifact = createArtifact(artifactId, version); - createArtifact( artifact, localRepository() ); + createArtifact(artifact, localRepository()); return artifact; } - protected Artifact createRemoteArtifact( String artifactId, String version ) - throws Exception - { - Artifact artifact = createArtifact( artifactId, version ); + protected Artifact createRemoteArtifact(String artifactId, String version) throws Exception { + Artifact artifact = createArtifact(artifactId, version); - createArtifact( artifact, remoteRepository() ); + createArtifact(artifact, remoteRepository()); return artifact; } - protected void createLocalArtifact( Artifact artifact ) - throws Exception - { - createArtifact( artifact, localRepository() ); + protected void createLocalArtifact(Artifact artifact) throws Exception { + createArtifact(artifact, localRepository()); } - protected void createRemoteArtifact( Artifact artifact ) - throws Exception - { - createArtifact( artifact, remoteRepository() ); + protected void createRemoteArtifact(Artifact artifact) throws Exception { + createArtifact(artifact, remoteRepository()); } - protected void createArtifact( Artifact artifact, ArtifactRepository repository ) - throws Exception - { - String path = repository.pathOf( artifact ); + protected void createArtifact(Artifact artifact, ArtifactRepository repository) throws Exception { + String path = repository.pathOf(artifact); - File artifactFile = new File( repository.getBasedir(), path ); + File artifactFile = new File(repository.getBasedir(), path); - if ( !artifactFile.getParentFile().exists() ) - { + if (!artifactFile.getParentFile().exists()) { artifactFile.getParentFile().mkdirs(); } - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( artifactFile ), StandardCharsets.ISO_8859_1) ) - { - writer.write( artifact.getId() ); + try (Writer writer = new OutputStreamWriter(new FileOutputStream(artifactFile), StandardCharsets.ISO_8859_1)) { + writer.write(artifact.getId()); } - MessageDigest md = MessageDigest.getInstance( "MD5" ); - md.update( artifact.getId().getBytes() ); + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(artifact.getId().getBytes()); byte[] digest = md.digest(); - String md5path = repository.pathOf( artifact ) + ".md5"; - File md5artifactFile = new File( repository.getBasedir(), md5path ); - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( md5artifactFile ), StandardCharsets.ISO_8859_1) ) - { - writer.append( printHexBinary( digest ) ); + String md5path = repository.pathOf(artifact) + ".md5"; + File md5artifactFile = new File(repository.getBasedir(), md5path); + try (Writer writer = + new OutputStreamWriter(new FileOutputStream(md5artifactFile), StandardCharsets.ISO_8859_1)) { + writer.append(printHexBinary(digest)); } } - protected Artifact createArtifact( String artifactId, String version ) - throws Exception - { - return createArtifact( artifactId, version, "jar" ); + protected Artifact createArtifact(String artifactId, String version) throws Exception { + return createArtifact(artifactId, version, "jar"); } - protected Artifact createArtifact( String artifactId, String version, String type ) - throws Exception - { - return createArtifact( "org.apache.maven", artifactId, version, type ); + protected Artifact createArtifact(String artifactId, String version, String type) throws Exception { + return createArtifact("org.apache.maven", artifactId, version, type); } - protected Artifact createArtifact( String groupId, String artifactId, String version, String type ) - throws Exception - { - Artifact a = artifactFactory.createBuildArtifact( groupId, artifactId, version, type ); + protected Artifact createArtifact(String groupId, String artifactId, String version, String type) throws Exception { + Artifact a = artifactFactory.createBuildArtifact(groupId, artifactId, version, type); return a; } - protected void deleteLocalArtifact( Artifact artifact ) - throws Exception - { - deleteArtifact( artifact, localRepository() ); + protected void deleteLocalArtifact(Artifact artifact) throws Exception { + deleteArtifact(artifact, localRepository()); } - protected void deleteArtifact( Artifact artifact, ArtifactRepository repository ) - throws Exception - { - String path = repository.pathOf( artifact ); + protected void deleteArtifact(Artifact artifact, ArtifactRepository repository) throws Exception { + String path = repository.pathOf(artifact); - File artifactFile = new File( repository.getBasedir(), path ); + File artifactFile = new File(repository.getBasedir(), path); - if ( artifactFile.exists() ) - { - if ( !artifactFile.delete() ) - { - throw new IOException( "Failure while attempting to delete artifact " + artifactFile ); + if (artifactFile.exists()) { + if (!artifactFile.delete()) { + throw new IOException("Failure while attempting to delete artifact " + artifactFile); } } } - protected RepositorySystemSession initRepoSession() - throws Exception - { + protected RepositorySystemSession initRepoSession() throws Exception { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - session.setArtifactDescriptorPolicy( new SimpleArtifactDescriptorPolicy( true, true ) ); + session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(true, true)); DependencyTraverser depTraverser = new FatArtifactTraverser(); - session.setDependencyTraverser( depTraverser ); + session.setDependencyTraverser(depTraverser); DependencyManager depManager = new ClassicDependencyManager(); - session.setDependencyManager( depManager ); + session.setDependencyManager(depManager); - DependencySelector depFilter = new AndDependencySelector( new ScopeDependencySelector( "test", "provided" ), - new OptionalDependencySelector(), - new ExclusionDependencySelector() ); - session.setDependencySelector( depFilter ); + DependencySelector depFilter = new AndDependencySelector( + new ScopeDependencySelector("test", "provided"), + new OptionalDependencySelector(), + new ExclusionDependencySelector()); + session.setDependencySelector(depFilter); - DependencyGraphTransformer transformer = - new ConflictResolver( new NearestVersionSelector(), new JavaScopeSelector(), - new SimpleOptionalitySelector(), new JavaScopeDeriver() ); - transformer = new ChainedDependencyGraphTransformer( transformer, new JavaDependencyContextRefiner() ); - session.setDependencyGraphTransformer( transformer ); + DependencyGraphTransformer transformer = new ConflictResolver( + new NearestVersionSelector(), new JavaScopeSelector(), + new SimpleOptionalitySelector(), new JavaScopeDeriver()); + transformer = new ChainedDependencyGraphTransformer(transformer, new JavaDependencyContextRefiner()); + session.setDependencyGraphTransformer(transformer); - LocalRepository localRepo = new LocalRepository( localRepository().getBasedir() ); - session.setLocalRepositoryManager( - new SimpleLocalRepositoryManagerFactory().newInstance( session, localRepo ) ); + LocalRepository localRepo = new LocalRepository(localRepository().getBasedir()); + session.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepo)); return session; } private static final char[] hexCode = "0123456789ABCDEF".toCharArray(); - private static final String printHexBinary( byte[] data ) - { - StringBuilder r = new StringBuilder( data.length * 2 ); - for ( byte b : data ) - { - r.append( hexCode[( b >> 4 ) & 0xF] ); - r.append( hexCode[( b & 0xF )] ); + private static final String printHexBinary(byte[] data) { + StringBuilder r = new StringBuilder(data.length * 2); + for (byte b : data) { + r.append(hexCode[(b >> 4) & 0xF]); + r.append(hexCode[(b & 0xF)]); } return r.toString(); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/deployer/ArtifactDeployerTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/deployer/ArtifactDeployerTest.java index 3f33fa1281..a9fa595cee 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/deployer/ArtifactDeployerTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/deployer/ArtifactDeployerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.deployer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.deployer; * "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 + * 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 @@ -18,9 +16,15 @@ package org.apache.maven.artifact.deployer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.deployer; + +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; import java.io.File; - +import javax.inject.Inject; import org.apache.maven.artifact.AbstractArtifactComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -29,56 +33,41 @@ import org.apache.maven.session.scope.internal.SessionScope; import org.codehaus.plexus.util.FileUtils; import org.junit.jupiter.api.Test; -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -import javax.inject.Inject; - /** * @author Jason van Zyl */ -public class ArtifactDeployerTest - extends AbstractArtifactComponentTestCase -{ +public class ArtifactDeployerTest extends AbstractArtifactComponentTestCase { @Inject private ArtifactDeployer artifactDeployer; @Inject private SessionScope sessionScope; - protected String component() - { + protected String component() { return "deployer"; } @Test - public void testArtifactInstallation() - throws Exception - { + public void testArtifactInstallation() throws Exception { sessionScope.enter(); - try - { + try { sessionScope.seed(MavenSession.class, mock(MavenSession.class)); - String artifactBasedir = new File( getBasedir(), "src/test/resources/artifact-install" ).getAbsolutePath(); + String artifactBasedir = new File(getBasedir(), "src/test/resources/artifact-install").getAbsolutePath(); - Artifact artifact = createArtifact( "artifact", "1.0" ); + Artifact artifact = createArtifact("artifact", "1.0"); - File file = new File( artifactBasedir, "artifact-1.0.jar" ); - assertEquals( "dummy", FileUtils.fileRead( file, "UTF-8" ).trim() ); + File file = new File(artifactBasedir, "artifact-1.0.jar"); + assertEquals("dummy", FileUtils.fileRead(file, "UTF-8").trim()); - artifactDeployer.deploy( file, artifact, remoteRepository(), localRepository() ); + artifactDeployer.deploy(file, artifact, remoteRepository(), localRepository()); ArtifactRepository remoteRepository = remoteRepository(); - File deployedFile = new File( remoteRepository.getBasedir(), remoteRepository.pathOf( artifact ) ); - assertTrue( deployedFile.exists() ); - assertEquals( "dummy", FileUtils.fileRead( deployedFile, "UTF-8" ).trim() ); - } - finally - { + File deployedFile = new File(remoteRepository.getBasedir(), remoteRepository.pathOf(artifact)); + assertTrue(deployedFile.exists()); + assertEquals("dummy", FileUtils.fileRead(deployedFile, "UTF-8").trim()); + } finally { sessionScope.exit(); } } -} \ No newline at end of file +} diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/deployer/SimpleArtifactMetadataSource.java b/maven-compat/src/test/java/org/apache/maven/artifact/deployer/SimpleArtifactMetadataSource.java index 5864f1b9a6..c658eb4246 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/deployer/SimpleArtifactMetadataSource.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/deployer/SimpleArtifactMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.deployer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.deployer; * "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 + * 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 @@ -18,10 +16,12 @@ package org.apache.maven.artifact.deployer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.deployer; import java.util.Collections; import java.util.List; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -30,37 +30,26 @@ import org.apache.maven.repository.legacy.metadata.ArtifactMetadataSource; import org.apache.maven.repository.legacy.metadata.MetadataResolutionRequest; import org.apache.maven.repository.legacy.metadata.ResolutionGroup; -import javax.inject.Named; -import javax.inject.Singleton; - /** @author Jason van Zyl */ -@Named( "classpath" ) +@Named("classpath") @Singleton -public class SimpleArtifactMetadataSource - implements ArtifactMetadataSource -{ - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - { - throw new UnsupportedOperationException( "Cannot retrieve metadata in this test case" ); +public class SimpleArtifactMetadataSource implements ArtifactMetadataSource { + public ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) { + throw new UnsupportedOperationException("Cannot retrieve metadata in this test case"); } - public List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - { - return Collections.singletonList( new DefaultArtifactVersion( "10.1.3" ) ); + public List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) { + return Collections.singletonList(new DefaultArtifactVersion("10.1.3")); } - public List retrieveAvailableVersionsFromDeploymentRepository( Artifact artifact, - ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - { - return Collections.singletonList( new DefaultArtifactVersion( "10.1.3" ) ); + public List retrieveAvailableVersionsFromDeploymentRepository( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) { + return Collections.singletonList(new DefaultArtifactVersion("10.1.3")); } - public ResolutionGroup retrieve( MetadataResolutionRequest request ) - { - return retrieve( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public ResolutionGroup retrieve(MetadataResolutionRequest request) { + return retrieve(request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/factory/DefaultArtifactFactoryTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/factory/DefaultArtifactFactoryTest.java index d124894d6d..e0b841d851 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/factory/DefaultArtifactFactoryTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/factory/DefaultArtifactFactoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.factory; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.factory; * "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 + * 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 @@ -18,39 +16,53 @@ package org.apache.maven.artifact.factory; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; - -import org.codehaus.plexus.testing.PlexusTest; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.versioning.VersionRange; -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.factory; import static org.junit.jupiter.api.Assertions.assertEquals; +import javax.inject.Inject; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.versioning.VersionRange; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.Test; + @PlexusTest -public class DefaultArtifactFactoryTest -{ +public class DefaultArtifactFactoryTest { @Inject ArtifactFactory factory; @Test - public void testPropagationOfSystemScopeRegardlessOfInheritedScope() - { - Artifact artifact = factory.createDependencyArtifact( "test-grp", "test-artifact", VersionRange.createFromVersion("1.0"), "type", null, "system", "provided" ); - Artifact artifact2 = factory.createDependencyArtifact( "test-grp", "test-artifact-2", VersionRange.createFromVersion("1.0"), "type", null, "system", "test" ); - Artifact artifact3 = factory.createDependencyArtifact( "test-grp", "test-artifact-3", VersionRange.createFromVersion("1.0"), "type", null, "system", "runtime" ); - Artifact artifact4 = factory.createDependencyArtifact( "test-grp", "test-artifact-4", VersionRange.createFromVersion("1.0"), "type", null, "system", "compile" ); + public void testPropagationOfSystemScopeRegardlessOfInheritedScope() { + Artifact artifact = factory.createDependencyArtifact( + "test-grp", "test-artifact", VersionRange.createFromVersion("1.0"), "type", null, "system", "provided"); + Artifact artifact2 = factory.createDependencyArtifact( + "test-grp", "test-artifact-2", VersionRange.createFromVersion("1.0"), "type", null, "system", "test"); + Artifact artifact3 = factory.createDependencyArtifact( + "test-grp", + "test-artifact-3", + VersionRange.createFromVersion("1.0"), + "type", + null, + "system", + "runtime"); + Artifact artifact4 = factory.createDependencyArtifact( + "test-grp", + "test-artifact-4", + VersionRange.createFromVersion("1.0"), + "type", + null, + "system", + "compile"); // this one should never happen in practice... - Artifact artifact5 = factory.createDependencyArtifact( "test-grp", "test-artifact-5", VersionRange.createFromVersion("1.0"), "type", null, "system", "system" ); + Artifact artifact5 = factory.createDependencyArtifact( + "test-grp", "test-artifact-5", VersionRange.createFromVersion("1.0"), "type", null, "system", "system"); - assertEquals( "system", artifact.getScope() ); - assertEquals( "system", artifact2.getScope() ); - assertEquals( "system", artifact3.getScope() ); - assertEquals( "system", artifact4.getScope() ); - assertEquals( "system", artifact5.getScope() ); + assertEquals("system", artifact.getScope()); + assertEquals("system", artifact2.getScope()); + assertEquals("system", artifact3.getScope()); + assertEquals("system", artifact4.getScope()); + assertEquals("system", artifact5.getScope()); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/installer/ArtifactInstallerTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/installer/ArtifactInstallerTest.java index afa276106b..124df752ef 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/installer/ArtifactInstallerTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/installer/ArtifactInstallerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.installer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.installer; * "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 + * 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 @@ -18,59 +16,50 @@ package org.apache.maven.artifact.installer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.installer; + +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.mockito.Mockito.mock; import java.io.File; - +import javax.inject.Inject; import org.apache.maven.artifact.AbstractArtifactComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.session.scope.internal.SessionScope; import org.junit.jupiter.api.Test; -import javax.inject.Inject; - -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.mockito.Mockito.mock; - /** * @author Jason van Zyl */ -public class ArtifactInstallerTest - extends AbstractArtifactComponentTestCase -{ +public class ArtifactInstallerTest extends AbstractArtifactComponentTestCase { @Inject private ArtifactInstaller artifactInstaller; @Inject private SessionScope sessionScope; - protected String component() - { + protected String component() { return "installer"; } @Test - public void testArtifactInstallation() - throws Exception - { + public void testArtifactInstallation() throws Exception { sessionScope.enter(); - try - { + try { sessionScope.seed(MavenSession.class, mock(MavenSession.class)); - String artifactBasedir = new File( getBasedir(), "src/test/resources/artifact-install" ).getAbsolutePath(); + String artifactBasedir = new File(getBasedir(), "src/test/resources/artifact-install").getAbsolutePath(); - Artifact artifact = createArtifact( "artifact", "1.0" ); + Artifact artifact = createArtifact("artifact", "1.0"); - File source = new File( artifactBasedir, "artifact-1.0.jar" ); + File source = new File(artifactBasedir, "artifact-1.0.jar"); - artifactInstaller.install( source, artifact, localRepository() ); + artifactInstaller.install(source, artifact, localRepository()); - assertLocalArtifactPresent( artifact ); - } - finally - { + assertLocalArtifactPresent(artifact); + } finally { sessionScope.exit(); } } -} \ No newline at end of file +} diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/metadata/TestMetadataSource.java b/maven-compat/src/test/java/org/apache/maven/artifact/metadata/TestMetadataSource.java index f1973f9e60..feae22a6e4 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/metadata/TestMetadataSource.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/metadata/TestMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,88 +16,73 @@ package org.apache.maven.artifact.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.metadata; import java.util.HashSet; import java.util.List; import java.util.Set; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.repository.legacy.metadata.MetadataResolutionRequest; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -@Named( "test" ) +@Named("test") @Singleton -public class TestMetadataSource - implements ArtifactMetadataSource -{ +public class TestMetadataSource implements ArtifactMetadataSource { @Inject private ArtifactFactory factory; - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { + public ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { Set dependencies = new HashSet<>(); - if ( "g".equals( artifact.getArtifactId() ) ) - { + if ("g".equals(artifact.getArtifactId())) { Artifact a = null; - try - { - a = factory.createBuildArtifact( "org.apache.maven", "h", "1.0", "jar" ); - dependencies.add( a ); - } - catch ( Exception e ) - { - throw new ArtifactMetadataRetrievalException( "Error retrieving metadata", e, a ); + try { + a = factory.createBuildArtifact("org.apache.maven", "h", "1.0", "jar"); + dependencies.add(a); + } catch (Exception e) { + throw new ArtifactMetadataRetrievalException("Error retrieving metadata", e, a); } } - if ( "i".equals( artifact.getArtifactId() ) ) - { + if ("i".equals(artifact.getArtifactId())) { Artifact a = null; - try - { - a = factory.createBuildArtifact( "org.apache.maven", "j", "1.0-SNAPSHOT", "jar" ); - dependencies.add( a ); - } - catch ( Exception e ) - { - throw new ArtifactMetadataRetrievalException( "Error retrieving metadata", e, a ); + try { + a = factory.createBuildArtifact("org.apache.maven", "j", "1.0-SNAPSHOT", "jar"); + dependencies.add(a); + } catch (Exception e) { + throw new ArtifactMetadataRetrievalException("Error retrieving metadata", e, a); } } - - return new ResolutionGroup( artifact, dependencies, remoteRepositories ); + return new ResolutionGroup(artifact, dependencies, remoteRepositories); } - public List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { - throw new UnsupportedOperationException( "Cannot get available versions in this test case" ); + public List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { + throw new UnsupportedOperationException("Cannot get available versions in this test case"); } - public List retrieveAvailableVersionsFromDeploymentRepository( Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws ArtifactMetadataRetrievalException - { - throw new UnsupportedOperationException( "Cannot get available versions in this test case" ); + public List retrieveAvailableVersionsFromDeploymentRepository( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws ArtifactMetadataRetrievalException { + throw new UnsupportedOperationException("Cannot get available versions in this test case"); } - public ResolutionGroup retrieve( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { - return retrieve( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public ResolutionGroup retrieve(MetadataResolutionRequest request) throws ArtifactMetadataRetrievalException { + return retrieve(request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } - public List retrieveAvailableVersions( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { - return retrieveAvailableVersions( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public List retrieveAvailableVersions(MetadataResolutionRequest request) + throws ArtifactMetadataRetrievalException { + return retrieveAvailableVersions( + request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/repository/MavenArtifactRepositoryTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/repository/MavenArtifactRepositoryTest.java index 4e7b5dc8c1..fde9f90b1b 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/repository/MavenArtifactRepositoryTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/repository/MavenArtifactRepositoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,45 +16,40 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ - - -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.repository; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -public class MavenArtifactRepositoryTest -{ - private static class MavenArtifactRepositorySubclass extends MavenArtifactRepository - { +import org.junit.jupiter.api.Test; + +public class MavenArtifactRepositoryTest { + private static class MavenArtifactRepositorySubclass extends MavenArtifactRepository { String id; - public MavenArtifactRepositorySubclass(String id) - { + public MavenArtifactRepositorySubclass(String id) { this.id = id; } @Override - public String getId() - { + public String getId() { return id; } } @Test - public void testHashCodeEquals() - { - MavenArtifactRepositorySubclass r1 = new MavenArtifactRepositorySubclass( "foo" ); - MavenArtifactRepositorySubclass r2 = new MavenArtifactRepositorySubclass( "foo" ); - MavenArtifactRepositorySubclass r3 = new MavenArtifactRepositorySubclass( "bar" ); + public void testHashCodeEquals() { + MavenArtifactRepositorySubclass r1 = new MavenArtifactRepositorySubclass("foo"); + MavenArtifactRepositorySubclass r2 = new MavenArtifactRepositorySubclass("foo"); + MavenArtifactRepositorySubclass r3 = new MavenArtifactRepositorySubclass("bar"); - assertTrue( r1.hashCode() == r2.hashCode() ); - assertFalse( r1.hashCode() == r3.hashCode() ); + assertTrue(r1.hashCode() == r2.hashCode()); + assertFalse(r1.hashCode() == r3.hashCode()); - assertTrue( r1.equals( r2 ) ); - assertTrue( r2.equals( r1 ) ); + assertTrue(r1.equals(r2)); + assertTrue(r2.equals(r1)); - assertFalse( r1.equals( r3 ) ); - assertFalse( r3.equals( r1 ) ); + assertFalse(r1.equals(r3)); + assertFalse(r3.equals(r1)); } } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolutionExceptionTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolutionExceptionTest.java index e6b0e567a2..edf3410a9c 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolutionExceptionTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolutionExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,26 +16,24 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Test the artifact resolution exception message * * @author Mauro Talevi */ -public class ArtifactResolutionExceptionTest -{ +public class ArtifactResolutionExceptionTest { private static final String LS = System.lineSeparator(); @Test - public void testMissingArtifactMessageFormat() - { + public void testMissingArtifactMessageFormat() { String message = "Missing artifact"; String indentation = " "; String groupId = "aGroupId"; @@ -46,9 +42,8 @@ public class ArtifactResolutionExceptionTest String type = "jar"; String classifier = "aClassifier"; String downloadUrl = "http://somewhere.com/download"; - List path = Arrays.asList( "dependency1", "dependency2" ); - String expected = - "Missing artifact" + LS + LS + " Try downloading the file manually from: " + LS + List path = Arrays.asList("dependency1", "dependency2"); + String expected = "Missing artifact" + LS + LS + " Try downloading the file manually from: " + LS + " http://somewhere.com/download" + LS + LS + " Then, install it using the command: " + LS + " mvn install:install-file -DgroupId=aGroupId -DartifactId=anArtifactId -Dversion=aVersion " + "-Dclassifier=aClassifier -Dpackaging=jar -Dfile=/path/to/file" + LS + LS @@ -57,10 +52,8 @@ public class ArtifactResolutionExceptionTest + " -Dversion=aVersion -Dclassifier=aClassifier -Dpackaging=jar -Dfile=/path/to/file" + " -Durl=[url] -DrepositoryId=[id]" + LS + LS + " Path to dependency: " + LS + " \t1) dependency1" + LS + " \t2) dependency2" + LS + LS; - String actual = - AbstractArtifactResolutionException.constructMissingArtifactMessage( message, indentation, groupId, - artifactId, version, type, classifier, - downloadUrl, path ); - assertEquals( expected, actual ); + String actual = AbstractArtifactResolutionException.constructMissingArtifactMessage( + message, indentation, groupId, artifactId, version, type, classifier, downloadUrl, path); + assertEquals(expected, actual); } } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolverTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolverTest.java index 9a3934ea9c..68c8c9955b 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/ArtifactResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,11 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collections; @@ -26,7 +29,7 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - +import javax.inject.Inject; import org.apache.maven.artifact.AbstractArtifactComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; @@ -37,12 +40,6 @@ import org.apache.maven.repository.legacy.metadata.MetadataResolutionRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javax.inject.Inject; - // It would be cool if there was a hook that I could use to set up a test environment. // I want to set up a local/remote repositories for testing but I don't want to have // to change them when I change the layout of the repositories. So I want to generate @@ -52,9 +49,7 @@ import javax.inject.Inject; /** * @author Jason van Zyl */ -public class ArtifactResolverTest - extends AbstractArtifactComponentTestCase -{ +public class ArtifactResolverTest extends AbstractArtifactComponentTestCase { @Inject private ArtifactResolver artifactResolver; @@ -62,216 +57,193 @@ public class ArtifactResolverTest @BeforeEach @Override - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - projectArtifact = createLocalArtifact( "project", "3.0" ); + projectArtifact = createLocalArtifact("project", "3.0"); } @Override - protected String component() - { + protected String component() { return "resolver"; } @Test - public void testResolutionOfASingleArtifactWhereTheArtifactIsPresentInTheLocalRepository() - throws Exception - { - Artifact a = createLocalArtifact( "a", "1.0" ); + public void testResolutionOfASingleArtifactWhereTheArtifactIsPresentInTheLocalRepository() throws Exception { + Artifact a = createLocalArtifact("a", "1.0"); - artifactResolver.resolve( a, remoteRepositories(), localRepository() ); + artifactResolver.resolve(a, remoteRepositories(), localRepository()); - assertLocalArtifactPresent( a ); + assertLocalArtifactPresent(a); } @Test - public void testResolutionOfASingleArtifactWhereTheArtifactIsNotPresentLocallyAndMustBeRetrievedFromTheRemoteRepository() - throws Exception - { - Artifact b = createRemoteArtifact( "b", "1.0-SNAPSHOT" ); - deleteLocalArtifact( b ); - artifactResolver.resolve( b, remoteRepositories(), localRepository() ); - assertLocalArtifactPresent( b ); + public void + testResolutionOfASingleArtifactWhereTheArtifactIsNotPresentLocallyAndMustBeRetrievedFromTheRemoteRepository() + throws Exception { + Artifact b = createRemoteArtifact("b", "1.0-SNAPSHOT"); + deleteLocalArtifact(b); + artifactResolver.resolve(b, remoteRepositories(), localRepository()); + assertLocalArtifactPresent(b); } @Override - protected Artifact createArtifact( String groupId, String artifactId, String version, String type ) - throws Exception - { + protected Artifact createArtifact(String groupId, String artifactId, String version, String type) throws Exception { // for the anonymous classes - return super.createArtifact( groupId, artifactId, version, type ); + return super.createArtifact(groupId, artifactId, version, type); } @Test - public void testTransitiveResolutionWhereAllArtifactsArePresentInTheLocalRepository() - throws Exception - { - Artifact g = createLocalArtifact( "g", "1.0" ); + public void testTransitiveResolutionWhereAllArtifactsArePresentInTheLocalRepository() throws Exception { + Artifact g = createLocalArtifact("g", "1.0"); - Artifact h = createLocalArtifact( "h", "1.0" ); + Artifact h = createLocalArtifact("h", "1.0"); - ArtifactResolutionResult result = artifactResolver.resolveTransitively( Collections.singleton( g ), projectArtifact, remoteRepositories(), localRepository(), null ); + ArtifactResolutionResult result = artifactResolver.resolveTransitively( + Collections.singleton(g), projectArtifact, remoteRepositories(), localRepository(), null); - printErrors( result ); + printErrors(result); - assertEquals( 2, result.getArtifacts().size() ); + assertEquals(2, result.getArtifacts().size()); - assertTrue( result.getArtifacts().contains( g ) ); + assertTrue(result.getArtifacts().contains(g)); - assertTrue( result.getArtifacts().contains( h ) ); + assertTrue(result.getArtifacts().contains(h)); - assertLocalArtifactPresent( g ); + assertLocalArtifactPresent(g); - assertLocalArtifactPresent( h ); + assertLocalArtifactPresent(h); } @Test - public void testTransitiveResolutionWhereAllArtifactsAreNotPresentInTheLocalRepositoryAndMustBeRetrievedFromTheRemoteRepository() - throws Exception - { - Artifact i = createRemoteArtifact( "i", "1.0-SNAPSHOT" ); - deleteLocalArtifact( i ); + public void + testTransitiveResolutionWhereAllArtifactsAreNotPresentInTheLocalRepositoryAndMustBeRetrievedFromTheRemoteRepository() + throws Exception { + Artifact i = createRemoteArtifact("i", "1.0-SNAPSHOT"); + deleteLocalArtifact(i); - Artifact j = createRemoteArtifact( "j", "1.0-SNAPSHOT" ); - deleteLocalArtifact( j ); + Artifact j = createRemoteArtifact("j", "1.0-SNAPSHOT"); + deleteLocalArtifact(j); - ArtifactResolutionResult result = artifactResolver.resolveTransitively( Collections.singleton( i ), projectArtifact, remoteRepositories(), localRepository(), null ); + ArtifactResolutionResult result = artifactResolver.resolveTransitively( + Collections.singleton(i), projectArtifact, remoteRepositories(), localRepository(), null); - printErrors( result ); + printErrors(result); - assertEquals( 2, result.getArtifacts().size() ); + assertEquals(2, result.getArtifacts().size()); - assertTrue( result.getArtifacts().contains( i ) ); + assertTrue(result.getArtifacts().contains(i)); - assertTrue( result.getArtifacts().contains( j ) ); + assertTrue(result.getArtifacts().contains(j)); - assertLocalArtifactPresent( i ); + assertLocalArtifactPresent(i); - assertLocalArtifactPresent( j ); + assertLocalArtifactPresent(j); } @Test - public void testResolutionFailureWhenArtifactNotPresentInRemoteRepository() - throws Exception - { - Artifact k = createArtifact( "k", "1.0" ); + public void testResolutionFailureWhenArtifactNotPresentInRemoteRepository() throws Exception { + Artifact k = createArtifact("k", "1.0"); assertThrows( ArtifactNotFoundException.class, - () -> artifactResolver.resolve( k, remoteRepositories(), localRepository() ), - "Resolution succeeded when it should have failed" ); + () -> artifactResolver.resolve(k, remoteRepositories(), localRepository()), + "Resolution succeeded when it should have failed"); } @Test - public void testResolutionOfAnArtifactWhereOneRemoteRepositoryIsBadButOneIsGood() - throws Exception - { - Artifact l = createRemoteArtifact( "l", "1.0-SNAPSHOT" ); - deleteLocalArtifact( l ); + public void testResolutionOfAnArtifactWhereOneRemoteRepositoryIsBadButOneIsGood() throws Exception { + Artifact l = createRemoteArtifact("l", "1.0-SNAPSHOT"); + deleteLocalArtifact(l); List repositories = new ArrayList<>(); - repositories.add( remoteRepository() ); - repositories.add( badRemoteRepository() ); + repositories.add(remoteRepository()); + repositories.add(badRemoteRepository()); - artifactResolver.resolve( l, repositories, localRepository() ); + artifactResolver.resolve(l, repositories, localRepository()); - assertLocalArtifactPresent( l ); + assertLocalArtifactPresent(l); } @Test - public void testTransitiveResolutionOrder() - throws Exception - { - Artifact m = createLocalArtifact( "m", "1.0" ); + public void testTransitiveResolutionOrder() throws Exception { + Artifact m = createLocalArtifact("m", "1.0"); - Artifact n = createLocalArtifact( "n", "1.0" ); + Artifact n = createLocalArtifact("n", "1.0"); - ArtifactMetadataSource mds = new ArtifactMetadataSource() - { - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - { + ArtifactMetadataSource mds = new ArtifactMetadataSource() { + public ResolutionGroup retrieve( + Artifact artifact, + ArtifactRepository localRepository, + List remoteRepositories) { Set dependencies = new HashSet<>(); - return new ResolutionGroup( artifact, dependencies, remoteRepositories ); + return new ResolutionGroup(artifact, dependencies, remoteRepositories); } - public List retrieveAvailableVersions( Artifact artifact, - ArtifactRepository localRepository, - List remoteRepositories ) - { - throw new UnsupportedOperationException( "Cannot get available versions in this test case" ); + public List retrieveAvailableVersions( + Artifact artifact, + ArtifactRepository localRepository, + List remoteRepositories) { + throw new UnsupportedOperationException("Cannot get available versions in this test case"); } public List retrieveAvailableVersionsFromDeploymentRepository( - Artifact artifact, - ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - { - throw new UnsupportedOperationException( "Cannot get available versions in this test case" ); + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) { + throw new UnsupportedOperationException("Cannot get available versions in this test case"); } - public ResolutionGroup retrieve( MetadataResolutionRequest request ) - { - return retrieve( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public ResolutionGroup retrieve(MetadataResolutionRequest request) { + return retrieve(request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } - public List retrieveAvailableVersions( MetadataResolutionRequest request ) - { - return retrieveAvailableVersions( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public List retrieveAvailableVersions(MetadataResolutionRequest request) { + return retrieveAvailableVersions( + request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } }; ArtifactResolutionResult result = null; Set set = new LinkedHashSet<>(); - set.add( n ); - set.add( m ); + set.add(n); + set.add(m); - result = - artifactResolver.resolveTransitively( set, projectArtifact, remoteRepositories(), localRepository(), mds ); + result = artifactResolver.resolveTransitively( + set, projectArtifact, remoteRepositories(), localRepository(), mds); - printErrors( result ); + printErrors(result); Iterator i = result.getArtifacts().iterator(); - assertEquals( n, i.next(), "n should be first" ); - assertEquals( m, i.next(), "m should be second" ); + assertEquals(n, i.next(), "n should be first"); + assertEquals(m, i.next(), "m should be second"); // inverse order set = new LinkedHashSet<>(); - set.add( m ); - set.add( n ); + set.add(m); + set.add(n); - result = - artifactResolver.resolveTransitively( set, projectArtifact, remoteRepositories(), localRepository(), mds ); + result = artifactResolver.resolveTransitively( + set, projectArtifact, remoteRepositories(), localRepository(), mds); - printErrors( result ); + printErrors(result); i = result.getArtifacts().iterator(); - assertEquals( m, i.next(), "m should be first" ); - assertEquals( n, i.next(), "n should be second" ); + assertEquals(m, i.next(), "m should be first"); + assertEquals(n, i.next(), "n should be second"); } - private void printErrors( ArtifactResolutionResult result ) - { - if ( result.hasMissingArtifacts() ) - { - for ( Artifact artifact : result.getMissingArtifacts() ) - { - System.err.println( "Missing: " + artifact ); + private void printErrors(ArtifactResolutionResult result) { + if (result.hasMissingArtifacts()) { + for (Artifact artifact : result.getMissingArtifacts()) { + System.err.println("Missing: " + artifact); } } - if ( result.hasExceptions() ) - { - for ( Exception e : result.getExceptions() ) - { + if (result.hasExceptions()) { + for (Exception e : result.getExceptions()) { e.printStackTrace(); } } } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/DefaultArtifactResolverTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/DefaultArtifactResolverTest.java index 30458d5933..8eb2f2164b 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/DefaultArtifactResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/DefaultArtifactResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,22 +16,19 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; + +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; - +import javax.inject.Inject; import org.apache.maven.artifact.AbstractArtifactComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.DefaultArtifactResolver.DaemonThreadCreator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javax.inject.Inject; - -public class DefaultArtifactResolverTest - extends AbstractArtifactComponentTestCase -{ +public class DefaultArtifactResolverTest extends AbstractArtifactComponentTestCase { @Inject private ArtifactResolver artifactResolver; @@ -41,44 +36,36 @@ public class DefaultArtifactResolverTest @BeforeEach @Override - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - projectArtifact = createLocalArtifact( "project", "3.0" ); + projectArtifact = createLocalArtifact("project", "3.0"); } @Override - protected String component() - { + protected String component() { return "resolver"; } @Test - public void testMNG4738() - throws Exception - { - Artifact g = createLocalArtifact( "g", "1.0" ); - createLocalArtifact( "h", "1.0" ); - artifactResolver.resolveTransitively( Collections.singleton( g ), projectArtifact, remoteRepositories(), - localRepository(), null ); + public void testMNG4738() throws Exception { + Artifact g = createLocalArtifact("g", "1.0"); + createLocalArtifact("h", "1.0"); + artifactResolver.resolveTransitively( + Collections.singleton(g), projectArtifact, remoteRepositories(), localRepository(), null); // we want to see all top-level thread groups ThreadGroup tg = Thread.currentThread().getThreadGroup(); - while ( tg.getParent() == null ) - { + while (tg.getParent() == null) { tg = tg.getParent(); } ThreadGroup[] tgList = new ThreadGroup[tg.activeGroupCount()]; - tg.enumerate( tgList ); + tg.enumerate(tgList); boolean seen = false; - for ( ThreadGroup aTgList : tgList ) - { - if ( !aTgList.getName().equals( DaemonThreadCreator.THREADGROUP_NAME ) ) - { + for (ThreadGroup aTgList : tgList) { + if (!aTgList.getName().equals(DaemonThreadCreator.THREADGROUP_NAME)) { continue; } @@ -86,24 +73,20 @@ public class DefaultArtifactResolverTest tg = aTgList; Thread[] ts = new Thread[tg.activeCount()]; - tg.enumerate( ts ); + tg.enumerate(ts); - for ( Thread active : ts ) - { + for (Thread active : ts) { String name = active.getName(); boolean daemon = active.isDaemon(); - assertTrue( daemon, name + " is no daemon Thread." ); + assertTrue(daemon, name + " is no daemon Thread."); } - } - assertTrue( seen, "Could not find ThreadGroup: " + DaemonThreadCreator.THREADGROUP_NAME ); + assertTrue(seen, "Could not find ThreadGroup: " + DaemonThreadCreator.THREADGROUP_NAME); } @Test - public void testLookup() - throws Exception - { - ArtifactResolver resolver = getContainer().lookup( ArtifactResolver.class, "default" ); + public void testLookup() throws Exception { + ArtifactResolver resolver = getContainer().lookup(ArtifactResolver.class, "default"); } } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestFileWagon.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestFileWagon.java index 4e24fe8532..36c169cfd8 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestFileWagon.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestFileWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.io.File; import java.io.InputStream; - import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; import org.apache.maven.wagon.authorization.AuthorizationException; @@ -32,63 +30,45 @@ import org.apache.maven.wagon.resource.Resource; /** * Wagon used for test cases that annotate some methods. Note that this is not a thread-safe implementation. */ -public class TestFileWagon - extends FileWagon -{ +public class TestFileWagon extends FileWagon { private TestTransferListener testTransferListener; private boolean insideGet; - protected void getTransfer( Resource resource, - File destination, - InputStream input, - boolean closeInput, - int maxSize ) - throws TransferFailedException - { - addTransfer( "getTransfer " + resource.getName() ); - super.getTransfer( resource, destination, input, closeInput, maxSize ); + protected void getTransfer(Resource resource, File destination, InputStream input, boolean closeInput, int maxSize) + throws TransferFailedException { + addTransfer("getTransfer " + resource.getName()); + super.getTransfer(resource, destination, input, closeInput, maxSize); } - public void get( String resourceName, File destination ) - throws TransferFailedException, - ResourceDoesNotExistException, - AuthorizationException - { - addTransfer( "get " + resourceName ); + public void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + addTransfer("get " + resourceName); insideGet = true; - super.get( resourceName, destination ); + super.get(resourceName, destination); insideGet = false; } - private void addTransfer( String resourceName ) - { - if ( testTransferListener != null ) - { - testTransferListener.addTransfer( resourceName ); + private void addTransfer(String resourceName) { + if (testTransferListener != null) { + testTransferListener.addTransfer(resourceName); } } - public boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, - ResourceDoesNotExistException, - AuthorizationException - { - if ( !insideGet ) - { - addTransfer( "getIfNewer " + resourceName ); + public boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + if (!insideGet) { + addTransfer("getIfNewer " + resourceName); } - return super.getIfNewer( resourceName, destination, timestamp ); + return super.getIfNewer(resourceName, destination, timestamp); } - public void addTransferListener( TransferListener listener ) - { - if ( listener instanceof TestTransferListener ) - { + public void addTransferListener(TransferListener listener) { + if (listener instanceof TestTransferListener) { testTransferListener = (TestTransferListener) listener; } - super.addTransferListener( listener ); + super.addTransferListener(listener); } } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestTransferListener.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestTransferListener.java index 82ee63e958..2201ecbe8d 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestTransferListener.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/TestTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,26 +16,21 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.ArrayList; import java.util.List; - import org.apache.maven.wagon.observers.AbstractTransferListener; -public class TestTransferListener - extends AbstractTransferListener -{ +public class TestTransferListener extends AbstractTransferListener { private final List transfers = new ArrayList<>(); - public List getTransfers() - { + public List getTransfers() { return transfers; } - public void addTransfer( String name ) - { - transfers.add( name ); + public void addTransfer(String name) { + transfers.add(name); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilterTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilterTest.java index 96a8882232..862b11f0f3 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilterTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,41 +16,37 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.resolver.filter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + /** * Tests {@link AndArtifactFilter}. * * @author Benjamin Bentmann */ -public class AndArtifactFilterTest -{ +public class AndArtifactFilterTest { - private ArtifactFilter newSubFilter() - { + private ArtifactFilter newSubFilter() { return artifact -> false; } @Test - public void testEquals() - { + public void testEquals() { AndArtifactFilter filter1 = new AndArtifactFilter(); - AndArtifactFilter filter2 = new AndArtifactFilter( Arrays.asList( newSubFilter() ) ); + AndArtifactFilter filter2 = new AndArtifactFilter(Arrays.asList(newSubFilter())); - assertFalse( filter1.equals( null ) ); - assertTrue( filter1.equals( filter1 ) ); - assertEquals( filter1.hashCode(), filter1.hashCode() ); + assertFalse(filter1.equals(null)); + assertTrue(filter1.equals(filter1)); + assertEquals(filter1.hashCode(), filter1.hashCode()); - assertFalse( filter1.equals( filter2 ) ); - assertFalse( filter2.equals( filter1 ) ); + assertFalse(filter1.equals(filter2)); + assertFalse(filter2.equals(filter1)); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/FilterHashEqualsTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/FilterHashEqualsTest.java index 6c3df9e900..bcf61ec275 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/FilterHashEqualsTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/FilterHashEqualsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,35 +16,33 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; + +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * @author Igor Fedorenko */ -public class FilterHashEqualsTest -{ +public class FilterHashEqualsTest { @Test - public void testIncludesExcludesArtifactFilter() - { - List patterns = Arrays.asList( "c", "d", "e" ); + public void testIncludesExcludesArtifactFilter() { + List patterns = Arrays.asList("c", "d", "e"); - IncludesArtifactFilter f1 = new IncludesArtifactFilter( patterns ); + IncludesArtifactFilter f1 = new IncludesArtifactFilter(patterns); - IncludesArtifactFilter f2 = new IncludesArtifactFilter( patterns ); + IncludesArtifactFilter f2 = new IncludesArtifactFilter(patterns); - assertTrue( f1.equals(f2) ); - assertTrue( f2.equals(f1) ); - assertTrue( f1.hashCode() == f2.hashCode() ); + assertTrue(f1.equals(f2)); + assertTrue(f2.equals(f1)); + assertTrue(f1.hashCode() == f2.hashCode()); - IncludesArtifactFilter f3 = new IncludesArtifactFilter( Arrays.asList( "d", "c", "e" ) ); - assertTrue( f1.equals( f3 ) ); - assertTrue( f1.hashCode() == f3.hashCode() ); + IncludesArtifactFilter f3 = new IncludesArtifactFilter(Arrays.asList("d", "c", "e")); + assertTrue(f1.equals(f3)); + assertTrue(f1.hashCode() == f3.hashCode()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilterTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilterTest.java index 65d9caa2b2..de4cdaf4d9 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilterTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,41 +16,37 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.resolver.filter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + /** * Tests {@link OrArtifactFilter}. * * @author Benjamin Bentmann */ -public class OrArtifactFilterTest -{ +public class OrArtifactFilterTest { - private ArtifactFilter newSubFilter() - { + private ArtifactFilter newSubFilter() { return artifact -> false; } @Test - public void testEquals() - { + public void testEquals() { OrArtifactFilter filter1 = new OrArtifactFilter(); - OrArtifactFilter filter2 = new OrArtifactFilter( Arrays.asList( newSubFilter() ) ); + OrArtifactFilter filter2 = new OrArtifactFilter(Arrays.asList(newSubFilter())); - assertFalse( filter1.equals( null ) ); - assertTrue( filter1.equals( filter1 ) ); - assertEquals( filter1.hashCode(), filter1.hashCode() ); + assertFalse(filter1.equals(null)); + assertTrue(filter1.equals(filter1)); + assertEquals(filter1.hashCode(), filter1.hashCode()); - assertFalse( filter1.equals( filter2 ) ); - assertFalse( filter2.equals( filter1 ) ); + assertFalse(filter1.equals(filter2)); + assertFalse(filter2.equals(filter1)); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilterTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilterTest.java index 914ff99bcb..72fecbc418 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilterTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,85 +16,78 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Tests {@link ScopeArtifactFilter}. * * @author Benjamin Bentmann */ -public class ScopeArtifactFilterTest -{ +public class ScopeArtifactFilterTest { - private Artifact newArtifact( String scope ) - { - return new DefaultArtifact( "g", "a", "1.0", scope, "jar", "", null ); + private Artifact newArtifact(String scope) { + return new DefaultArtifact("g", "a", "1.0", scope, "jar", "", null); } @Test - public void testInclude_Compile() - { - ScopeArtifactFilter filter = new ScopeArtifactFilter( Artifact.SCOPE_COMPILE ); + public void testInclude_Compile() { + ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_COMPILE ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_SYSTEM ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_PROVIDED ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_RUNTIME ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_TEST ) ) ); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_COMPILE))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_SYSTEM))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_PROVIDED))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_RUNTIME))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_TEST))); } @Test - public void testInclude_CompilePlusRuntime() - { - ScopeArtifactFilter filter = new ScopeArtifactFilter( Artifact.SCOPE_COMPILE_PLUS_RUNTIME ); + public void testInclude_CompilePlusRuntime() { + ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE_PLUS_RUNTIME); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_COMPILE ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_SYSTEM ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_PROVIDED ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_RUNTIME ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_TEST ) ) ); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_COMPILE))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_SYSTEM))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_PROVIDED))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_RUNTIME))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_TEST))); } @Test - public void testInclude_Runtime() - { - ScopeArtifactFilter filter = new ScopeArtifactFilter( Artifact.SCOPE_RUNTIME ); + public void testInclude_Runtime() { + ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_COMPILE ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_SYSTEM ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_PROVIDED ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_RUNTIME ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_TEST ) ) ); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_COMPILE))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_SYSTEM))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_PROVIDED))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_RUNTIME))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_TEST))); } @Test - public void testInclude_RuntimePlusSystem() - { - ScopeArtifactFilter filter = new ScopeArtifactFilter( Artifact.SCOPE_RUNTIME_PLUS_SYSTEM ); + public void testInclude_RuntimePlusSystem() { + ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME_PLUS_SYSTEM); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_COMPILE ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_SYSTEM ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_PROVIDED ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_RUNTIME ) ) ); - assertFalse( filter.include( newArtifact( Artifact.SCOPE_TEST ) ) ); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_COMPILE))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_SYSTEM))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_PROVIDED))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_RUNTIME))); + assertFalse(filter.include(newArtifact(Artifact.SCOPE_TEST))); } @Test - public void testInclude_Test() - { - ScopeArtifactFilter filter = new ScopeArtifactFilter( Artifact.SCOPE_TEST ); + public void testInclude_Test() { + ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_TEST); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_COMPILE ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_SYSTEM ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_PROVIDED ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_RUNTIME ) ) ); - assertTrue( filter.include( newArtifact( Artifact.SCOPE_TEST ) ) ); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_COMPILE))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_SYSTEM))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_PROVIDED))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_RUNTIME))); + assertTrue(filter.include(newArtifact(Artifact.SCOPE_TEST))); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/testutils/TestFileManager.java b/maven-compat/src/test/java/org/apache/maven/artifact/testutils/TestFileManager.java index 558b5a5ca3..7907a1a8a7 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/testutils/TestFileManager.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/testutils/TestFileManager.java @@ -1,59 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.artifact.testutils; -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; - import org.codehaus.plexus.util.FileUtils; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +public class TestFileManager { -public class TestFileManager -{ - - public static final String TEMP_DIR_PATH = System.getProperty( "java.io.tmpdir" ); + public static final String TEMP_DIR_PATH = System.getProperty("java.io.tmpdir"); private List filesToDelete = new ArrayList<>(); @@ -67,83 +45,65 @@ public class TestFileManager private boolean warnAboutCleanup = false; - public TestFileManager( String baseFilename, String fileSuffix ) - { + public TestFileManager(String baseFilename, String fileSuffix) { this.baseFilename = baseFilename; this.fileSuffix = fileSuffix; initializeCleanupMonitoring(); } - private void initializeCleanupMonitoring() - { + private void initializeCleanupMonitoring() { callerInfo = new NullPointerException().getStackTrace()[2]; Runnable warning = this::maybeWarnAboutCleanUp; - cleanupWarning = new Thread( warning ); + cleanupWarning = new Thread(warning); - Runtime.getRuntime().addShutdownHook( cleanupWarning ); + Runtime.getRuntime().addShutdownHook(cleanupWarning); } - private void maybeWarnAboutCleanUp() - { - if ( warnAboutCleanup ) - { - System.out.println( "[WARNING] TestFileManager from: " + callerInfo.getClassName() + " not cleaned up!" ); + private void maybeWarnAboutCleanUp() { + if (warnAboutCleanup) { + System.out.println("[WARNING] TestFileManager from: " + callerInfo.getClassName() + " not cleaned up!"); } } - public void markForDeletion( File toDelete ) - { - filesToDelete.add( toDelete ); + public void markForDeletion(File toDelete) { + filesToDelete.add(toDelete); warnAboutCleanup = true; } - public synchronized File createTempDir() - { - try - { - Thread.sleep( 20 ); - } - catch ( InterruptedException e ) - { + public synchronized File createTempDir() { + try { + Thread.sleep(20); + } catch (InterruptedException e) { // ignore } - File dir = new File( TEMP_DIR_PATH, baseFilename + System.currentTimeMillis() ); + File dir = new File(TEMP_DIR_PATH, baseFilename + System.currentTimeMillis()); dir.mkdirs(); - markForDeletion( dir ); + markForDeletion(dir); return dir; } - public synchronized File createTempFile() - throws IOException - { - File tempFile = File.createTempFile( baseFilename, fileSuffix ); + public synchronized File createTempFile() throws IOException { + File tempFile = File.createTempFile(baseFilename, fileSuffix); tempFile.deleteOnExit(); - markForDeletion( tempFile ); + markForDeletion(tempFile); return tempFile; } - public void cleanUp() - throws IOException - { - for ( Iterator it = filesToDelete.iterator(); it.hasNext(); ) - { + public void cleanUp() throws IOException { + for (Iterator it = filesToDelete.iterator(); it.hasNext(); ) { File file = (File) it.next(); - if ( file.exists() ) - { - if ( file.isDirectory() ) - { - FileUtils.deleteDirectory( file ); - } - else - { + if (file.exists()) { + if (file.isDirectory()) { + FileUtils.deleteDirectory(file); + } else { file.delete(); } } @@ -154,65 +114,50 @@ public class TestFileManager warnAboutCleanup = false; } - public void assertFileExistence( File dir, String filename, boolean shouldExist ) - { - File file = new File( dir, filename ); + public void assertFileExistence(File dir, String filename, boolean shouldExist) { + File file = new File(dir, filename); - if ( shouldExist ) - { - assertTrue( file.exists() ); - } - else - { - assertFalse( file.exists() ); + if (shouldExist) { + assertTrue(file.exists()); + } else { + assertFalse(file.exists()); } } - public void assertFileContents( File dir, String filename, String contentsTest, String encoding ) - throws IOException - { - assertFileExistence( dir, filename, true ); + public void assertFileContents(File dir, String filename, String contentsTest, String encoding) throws IOException { + assertFileExistence(dir, filename, true); - File file = new File( dir, filename ); + File file = new File(dir, filename); - String contents = FileUtils.fileRead( file, encoding ); + String contents = FileUtils.fileRead(file, encoding); - assertEquals( contentsTest, contents ); + assertEquals(contentsTest, contents); } - public File createFile( File dir, String filename, String contents, String encoding ) - throws IOException - { - File file = new File( dir, filename ); + public File createFile(File dir, String filename, String contents, String encoding) throws IOException { + File file = new File(dir, filename); file.getParentFile().mkdirs(); - FileUtils.fileWrite( file.getPath(), encoding, contents ); + FileUtils.fileWrite(file.getPath(), encoding, contents); - markForDeletion( file ); + markForDeletion(file); return file; } - public String getFileContents( File file, String encoding ) - throws IOException - { - return FileUtils.fileRead( file, encoding ); + public String getFileContents(File file, String encoding) throws IOException { + return FileUtils.fileRead(file, encoding); } - protected void finalize() - throws Throwable - { + protected void finalize() throws Throwable { maybeWarnAboutCleanUp(); super.finalize(); } - public File createFile( String filename, String content, String encoding ) - throws IOException - { + public File createFile(String filename, String content, String encoding) throws IOException { File dir = createTempDir(); - return createFile( dir, filename, content, encoding ); + return createFile(dir, filename, content, encoding); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/transform/TransformationManagerTest.java b/maven-compat/src/test/java/org/apache/maven/artifact/transform/TransformationManagerTest.java index 68a7522d5f..888572972c 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/transform/TransformationManagerTest.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/transform/TransformationManagerTest.java @@ -1,22 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.artifact.transform; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.repository.legacy.resolver.transform.ArtifactTransformation; import org.apache.maven.repository.legacy.resolver.transform.ArtifactTransformationManager; import org.apache.maven.repository.legacy.resolver.transform.LatestArtifactTransformation; @@ -25,30 +31,28 @@ import org.apache.maven.repository.legacy.resolver.transform.SnapshotTransformat import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javax.inject.Inject; - /** @author Jason van Zyl */ @PlexusTest -public class TransformationManagerTest -{ +public class TransformationManagerTest { @Inject ArtifactTransformationManager tm; @Test - public void testTransformationManager() - { + public void testTransformationManager() { List tms = tm.getArtifactTransformations(); - assertEquals( 3, tms.size() ); + assertEquals(3, tms.size()); - assertTrue( tms.get(0) instanceof ReleaseArtifactTransformation, "We expected the release transformation and got " + tms.get(0) ); + assertTrue( + tms.get(0) instanceof ReleaseArtifactTransformation, + "We expected the release transformation and got " + tms.get(0)); - assertTrue( tms.get(1) instanceof LatestArtifactTransformation, "We expected the latest transformation and got " + tms.get(1) ); + assertTrue( + tms.get(1) instanceof LatestArtifactTransformation, + "We expected the latest transformation and got " + tms.get(1)); - assertTrue( tms.get(2) instanceof SnapshotTransformation, "We expected the snapshot transformation and got " + tms.get(2) ); + assertTrue( + tms.get(2) instanceof SnapshotTransformation, + "We expected the snapshot transformation and got " + tms.get(2)); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/profiles/manager/DefaultProfileManagerTest.java b/maven-compat/src/test/java/org/apache/maven/profiles/manager/DefaultProfileManagerTest.java index bcb50a1ad2..cc619413fe 100644 --- a/maven-compat/src/test/java/org/apache/maven/profiles/manager/DefaultProfileManagerTest.java +++ b/maven-compat/src/test/java/org/apache/maven/profiles/manager/DefaultProfileManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.profiles.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.profiles.manager; * "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 + * 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 @@ -18,28 +16,26 @@ package org.apache.maven.profiles.manager; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.profiles.manager; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.List; import java.util.Properties; - import javax.inject.Inject; - -import org.codehaus.plexus.testing.PlexusTest; import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationProperty; import org.apache.maven.model.Profile; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - @PlexusTest -public class DefaultProfileManagerTest -{ +public class DefaultProfileManagerTest { @Inject PlexusContainer container; @@ -49,175 +45,162 @@ public class DefaultProfileManagerTest } @Test - public void testShouldActivateDefaultProfile() - throws Exception - { + public void testShouldActivateDefaultProfile() throws Exception { Profile notActivated = new Profile(); - notActivated.setId( "notActivated" ); + notActivated.setId("notActivated"); Activation nonActivation = new Activation(); - nonActivation.setJdk( "19.2" ); + nonActivation.setJdk("19.2"); - notActivated.setActivation( nonActivation ); + notActivated.setActivation(nonActivation); Profile defaultActivated = new Profile(); - defaultActivated.setId( "defaultActivated" ); + defaultActivated.setId("defaultActivated"); Activation defaultActivation = new Activation(); - defaultActivation.setActiveByDefault( true ); + defaultActivation.setActiveByDefault(true); - defaultActivated.setActivation( defaultActivation ); + defaultActivated.setActivation(defaultActivation); Properties props = System.getProperties(); - ProfileManager profileManager = new DefaultProfileManager( getContainer(), props ); + ProfileManager profileManager = new DefaultProfileManager(getContainer(), props); - profileManager.addProfile( notActivated ); - profileManager.addProfile( defaultActivated ); + profileManager.addProfile(notActivated); + profileManager.addProfile(defaultActivated); List active = profileManager.getActiveProfiles(); - assertNotNull( active ); - assertEquals( 1, active.size() ); - assertEquals( "defaultActivated", ( (Profile) active.get( 0 ) ).getId() ); + assertNotNull(active); + assertEquals(1, active.size()); + assertEquals("defaultActivated", ((Profile) active.get(0)).getId()); } @Test - public void testShouldNotActivateDefaultProfile() - throws Exception - { + public void testShouldNotActivateDefaultProfile() throws Exception { Profile syspropActivated = new Profile(); - syspropActivated.setId( "syspropActivated" ); + syspropActivated.setId("syspropActivated"); Activation syspropActivation = new Activation(); ActivationProperty syspropProperty = new ActivationProperty(); - syspropProperty.setName( "java.version" ); + syspropProperty.setName("java.version"); - syspropActivation.setProperty( syspropProperty ); + syspropActivation.setProperty(syspropProperty); - syspropActivated.setActivation( syspropActivation ); + syspropActivated.setActivation(syspropActivation); Profile defaultActivated = new Profile(); - defaultActivated.setId( "defaultActivated" ); + defaultActivated.setId("defaultActivated"); Activation defaultActivation = new Activation(); - defaultActivation.setActiveByDefault( true ); + defaultActivation.setActiveByDefault(true); - defaultActivated.setActivation( defaultActivation ); + defaultActivated.setActivation(defaultActivation); Properties props = System.getProperties(); - ProfileManager profileManager = new DefaultProfileManager( getContainer(), props ); + ProfileManager profileManager = new DefaultProfileManager(getContainer(), props); - profileManager.addProfile( syspropActivated ); - profileManager.addProfile( defaultActivated ); + profileManager.addProfile(syspropActivated); + profileManager.addProfile(defaultActivated); List active = profileManager.getActiveProfiles(); - assertNotNull( active ); - assertEquals( 1, active.size() ); - assertEquals( "syspropActivated", ( (Profile) active.get( 0 ) ).getId() ); + assertNotNull(active); + assertEquals(1, active.size()); + assertEquals("syspropActivated", ((Profile) active.get(0)).getId()); } - @Test - public void testShouldNotActivateReversalOfPresentSystemProperty() - throws Exception - { + public void testShouldNotActivateReversalOfPresentSystemProperty() throws Exception { Profile syspropActivated = new Profile(); - syspropActivated.setId( "syspropActivated" ); + syspropActivated.setId("syspropActivated"); Activation syspropActivation = new Activation(); ActivationProperty syspropProperty = new ActivationProperty(); - syspropProperty.setName( "!java.version" ); + syspropProperty.setName("!java.version"); - syspropActivation.setProperty( syspropProperty ); + syspropActivation.setProperty(syspropProperty); - syspropActivated.setActivation( syspropActivation ); + syspropActivated.setActivation(syspropActivation); Properties props = System.getProperties(); - ProfileManager profileManager = new DefaultProfileManager( getContainer(), props ); + ProfileManager profileManager = new DefaultProfileManager(getContainer(), props); - profileManager.addProfile( syspropActivated ); + profileManager.addProfile(syspropActivated); List active = profileManager.getActiveProfiles(); - assertNotNull( active ); - assertEquals( 0, active.size() ); + assertNotNull(active); + assertEquals(0, active.size()); } @Test - public void testShouldOverrideAndActivateInactiveProfile() - throws Exception - { + public void testShouldOverrideAndActivateInactiveProfile() throws Exception { Profile syspropActivated = new Profile(); - syspropActivated.setId( "syspropActivated" ); + syspropActivated.setId("syspropActivated"); Activation syspropActivation = new Activation(); ActivationProperty syspropProperty = new ActivationProperty(); - syspropProperty.setName( "!java.version" ); + syspropProperty.setName("!java.version"); - syspropActivation.setProperty( syspropProperty ); + syspropActivation.setProperty(syspropProperty); - syspropActivated.setActivation( syspropActivation ); + syspropActivated.setActivation(syspropActivation); Properties props = System.getProperties(); - ProfileManager profileManager = new DefaultProfileManager( getContainer(), props ); + ProfileManager profileManager = new DefaultProfileManager(getContainer(), props); - profileManager.addProfile( syspropActivated ); + profileManager.addProfile(syspropActivated); - profileManager.explicitlyActivate( "syspropActivated" ); + profileManager.explicitlyActivate("syspropActivated"); List active = profileManager.getActiveProfiles(); - assertNotNull( active ); - assertEquals( 1, active.size() ); - assertEquals( "syspropActivated", ( (Profile) active.get( 0 ) ).getId() ); + assertNotNull(active); + assertEquals(1, active.size()); + assertEquals("syspropActivated", ((Profile) active.get(0)).getId()); } @Test - public void testShouldOverrideAndDeactivateActiveProfile() - throws Exception - { + public void testShouldOverrideAndDeactivateActiveProfile() throws Exception { Profile syspropActivated = new Profile(); - syspropActivated.setId( "syspropActivated" ); + syspropActivated.setId("syspropActivated"); Activation syspropActivation = new Activation(); ActivationProperty syspropProperty = new ActivationProperty(); - syspropProperty.setName( "java.version" ); + syspropProperty.setName("java.version"); - syspropActivation.setProperty( syspropProperty ); + syspropActivation.setProperty(syspropProperty); - syspropActivated.setActivation( syspropActivation ); + syspropActivated.setActivation(syspropActivation); Properties props = System.getProperties(); - ProfileManager profileManager = new DefaultProfileManager( getContainer(), props ); + ProfileManager profileManager = new DefaultProfileManager(getContainer(), props); - profileManager.addProfile( syspropActivated ); + profileManager.addProfile(syspropActivated); - profileManager.explicitlyDeactivate( "syspropActivated" ); + profileManager.explicitlyDeactivate("syspropActivated"); List active = profileManager.getActiveProfiles(); - assertNotNull( active ); - assertEquals( 0, active.size() ); + assertNotNull(active); + assertEquals(0, active.size()); } @Test @Disabled - public void testOsActivationProfile() - throws Exception - { + public void testOsActivationProfile() throws Exception { /* Profile osActivated = new Profile(); osActivated.setId( "os-profile" ); @@ -245,5 +228,4 @@ public class DefaultProfileManagerTest assertEquals( 1, active.size() ); */ } - } diff --git a/maven-compat/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java b/maven-compat/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java index 482a5b4730..5f524489ee 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java +++ b/maven-compat/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java @@ -1,19 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.project; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.FileNotFoundException; @@ -21,10 +26,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; - import javax.inject.Inject; - -import org.codehaus.plexus.testing.PlexusTest; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.model.building.ModelBuildingException; @@ -32,17 +34,15 @@ import org.apache.maven.model.building.ModelProblem; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.eclipse.aether.DefaultRepositorySystemSession; import org.junit.jupiter.api.BeforeEach; -import static org.junit.jupiter.api.Assertions.fail; - /** * @author Jason van Zyl */ @PlexusTest -public abstract class AbstractMavenProjectTestCase -{ +public abstract class AbstractMavenProjectTestCase { protected ProjectBuilder projectBuilder; @Inject @@ -56,22 +56,16 @@ public abstract class AbstractMavenProjectTestCase } @BeforeEach - public void setUp() - throws Exception - { - if ( getContainer().hasComponent( ProjectBuilder.class, "test" ) ) - { - projectBuilder = getContainer().lookup( ProjectBuilder.class, "test" ); - } - else - { + public void setUp() throws Exception { + if (getContainer().hasComponent(ProjectBuilder.class, "test")) { + projectBuilder = getContainer().lookup(ProjectBuilder.class, "test"); + } else { // default over to the main project builder... - projectBuilder = getContainer().lookup( ProjectBuilder.class ); + projectBuilder = getContainer().lookup(ProjectBuilder.class); } } - protected ProjectBuilder getProjectBuilder() - { + protected ProjectBuilder getProjectBuilder() { return projectBuilder; } @@ -79,35 +73,29 @@ public abstract class AbstractMavenProjectTestCase // Local repository // ---------------------------------------------------------------------- - protected File getLocalRepositoryPath() - throws FileNotFoundException, URISyntaxException - { - File markerFile = getFileForClasspathResource( "local-repo/marker.txt" ); + protected File getLocalRepositoryPath() throws FileNotFoundException, URISyntaxException { + File markerFile = getFileForClasspathResource("local-repo/marker.txt"); return markerFile.getAbsoluteFile().getParentFile(); } - protected static File getFileForClasspathResource( String resource ) - throws FileNotFoundException - { + protected static File getFileForClasspathResource(String resource) throws FileNotFoundException { ClassLoader cloader = Thread.currentThread().getContextClassLoader(); - URL resourceUrl = cloader.getResource( resource ); + URL resourceUrl = cloader.getResource(resource); - if ( resourceUrl == null ) - { - throw new FileNotFoundException( "Unable to find: " + resource ); + if (resourceUrl == null) { + throw new FileNotFoundException("Unable to find: " + resource); } - return new File( URI.create( resourceUrl.toString().replaceAll( " ", "%20" ) ) ); + return new File(URI.create(resourceUrl.toString().replaceAll(" ", "%20"))); } - protected ArtifactRepository getLocalRepository() - throws Exception - { - ArtifactRepositoryLayout repoLayout = getContainer().lookup( ArtifactRepositoryLayout.class ); + protected ArtifactRepository getLocalRepository() throws Exception { + ArtifactRepositoryLayout repoLayout = getContainer().lookup(ArtifactRepositoryLayout.class); - ArtifactRepository r = repositorySystem.createArtifactRepository( "local", "file://" + getLocalRepositoryPath().getAbsolutePath(), repoLayout, null, null ); + ArtifactRepository r = repositorySystem.createArtifactRepository( + "local", "file://" + getLocalRepositoryPath().getAbsolutePath(), repoLayout, null, null); return r; } @@ -116,54 +104,43 @@ public abstract class AbstractMavenProjectTestCase // Project building // ---------------------------------------------------------------------- - protected MavenProject getProjectWithDependencies( File pom ) - throws Exception - { + protected MavenProject getProjectWithDependencies(File pom) throws Exception { ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setLocalRepository( getLocalRepository() ); - configuration.setRemoteRepositories( Arrays.asList( new ArtifactRepository[] {} ) ); - configuration.setProcessPlugins( false ); - configuration.setResolveDependencies( true ); - initRepoSession( configuration ); + configuration.setLocalRepository(getLocalRepository()); + configuration.setRemoteRepositories(Arrays.asList(new ArtifactRepository[] {})); + configuration.setProcessPlugins(false); + configuration.setResolveDependencies(true); + initRepoSession(configuration); - try - { - return projectBuilder.build( pom, configuration ).getProject(); - } - catch ( Exception e ) - { + try { + return projectBuilder.build(pom, configuration).getProject(); + } catch (Exception e) { Throwable cause = e.getCause(); - if ( cause instanceof ModelBuildingException ) - { + if (cause instanceof ModelBuildingException) { String message = "In: " + pom + "\n\n"; - for ( ModelProblem problem : ( (ModelBuildingException) cause ).getProblems() ) - { + for (ModelProblem problem : ((ModelBuildingException) cause).getProblems()) { message += problem + "\n"; } - System.out.println( message ); - fail( message ); + System.out.println(message); + fail(message); } throw e; } } - protected MavenProject getProject( File pom ) - throws Exception - { + protected MavenProject getProject(File pom) throws Exception { ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setLocalRepository( getLocalRepository() ); - initRepoSession( configuration ); + configuration.setLocalRepository(getLocalRepository()); + initRepoSession(configuration); - return projectBuilder.build( pom, configuration ).getProject(); + return projectBuilder.build(pom, configuration).getProject(); } - protected void initRepoSession( ProjectBuildingRequest request ) - { - File localRepo = new File( request.getLocalRepository().getBasedir() ); + protected void initRepoSession(ProjectBuildingRequest request) { + File localRepo = new File(request.getLocalRepository().getBasedir()); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - session.setLocalRepositoryManager( new LegacyLocalRepositoryManager( localRepo ) ); - request.setRepositorySession( session ); + session.setLocalRepositoryManager(new LegacyLocalRepositoryManager(localRepo)); + request.setRepositorySession(session); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/project/ClasspathArtifactResolver.java b/maven-compat/src/test/java/org/apache/maven/project/ClasspathArtifactResolver.java index f4813593f8..cb98d394de 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/ClasspathArtifactResolver.java +++ b/maven-compat/src/test/java/org/apache/maven/project/ClasspathArtifactResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,15 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; - +import javax.inject.Named; +import javax.inject.Singleton; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.impl.ArtifactResolver; @@ -33,60 +33,44 @@ import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.transfer.ArtifactNotFoundException; -import javax.inject.Named; -import javax.inject.Singleton; - /** * @author Benjamin Bentmann */ -@Named( "classpath" ) +@Named("classpath") @Singleton -public class ClasspathArtifactResolver - implements ArtifactResolver -{ +public class ClasspathArtifactResolver implements ArtifactResolver { - public List resolveArtifacts( RepositorySystemSession session, - Collection requests ) - throws ArtifactResolutionException - { + public List resolveArtifacts( + RepositorySystemSession session, Collection requests) + throws ArtifactResolutionException { List results = new ArrayList<>(); - for ( ArtifactRequest request : requests ) - { - ArtifactResult result = new ArtifactResult( request ); - results.add( result ); + for (ArtifactRequest request : requests) { + ArtifactResult result = new ArtifactResult(request); + results.add(result); Artifact artifact = request.getArtifact(); - if ( "maven-test".equals( artifact.getGroupId() ) ) - { - String scope = artifact.getArtifactId().substring( "scope-".length() ); + if ("maven-test".equals(artifact.getGroupId())) { + String scope = artifact.getArtifactId().substring("scope-".length()); - try - { - artifact = - artifact.setFile( ProjectClasspathTest.getFileForClasspathResource( ProjectClasspathTest.dir - + "transitive-" + scope + "-dep.xml" ) ); - result.setArtifact( artifact ); + try { + artifact = artifact.setFile(ProjectClasspathTest.getFileForClasspathResource( + ProjectClasspathTest.dir + "transitive-" + scope + "-dep.xml")); + result.setArtifact(artifact); + } catch (FileNotFoundException e) { + throw new IllegalStateException("Missing test POM for " + artifact); } - catch ( FileNotFoundException e ) - { - throw new IllegalStateException( "Missing test POM for " + artifact ); - } - } - else - { - result.addException( new ArtifactNotFoundException( artifact, null ) ); - throw new ArtifactResolutionException( results ); + } else { + result.addException(new ArtifactNotFoundException(artifact, null)); + throw new ArtifactResolutionException(results); } } return results; } - public ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request ) - throws ArtifactResolutionException - { - return resolveArtifacts( session, Collections.singleton( request ) ).get( 0 ); + public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) + throws ArtifactResolutionException { + return resolveArtifacts(session, Collections.singleton(request)).get(0); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java b/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java index 21c7349762..6a8e6c5060 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java +++ b/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.DefaultLifecycles; import org.apache.maven.lifecycle.LifecycleExecutor; @@ -38,73 +36,57 @@ import org.apache.maven.plugin.MojoExecution; * * @author Benjamin Bentmann */ -public class EmptyLifecycleExecutor - implements LifecycleExecutor -{ +public class EmptyLifecycleExecutor implements LifecycleExecutor { - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, String... tasks ) - { - return new MavenExecutionPlan( null, new DefaultLifecycles() ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, String... tasks) { + return new MavenExecutionPlan(null, new DefaultLifecycles()); } - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, boolean setup, String... tasks ) - { - return new MavenExecutionPlan( null, new DefaultLifecycles() ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, boolean setup, String... tasks) { + return new MavenExecutionPlan(null, new DefaultLifecycles()); } - public void execute( MavenSession session ) - { - } + public void execute(MavenSession session) {} - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { Set plugins; // NOTE: The upper-case packaging name is intentional, that's a special hinting mode used for certain tests - if ( "JAR".equals( packaging ) ) - { + if ("JAR".equals(packaging)) { plugins = new LinkedHashSet<>(); - plugins.add( newPlugin( "maven-compiler-plugin", "compile", "testCompile" ) ); - plugins.add( newPlugin( "maven-resources-plugin", "resources", "testResources" ) ); - plugins.add( newPlugin( "maven-surefire-plugin", "test" ) ); - plugins.add( newPlugin( "maven-jar-plugin", "jar" ) ); - plugins.add( newPlugin( "maven-install-plugin", "install" ) ); - plugins.add( newPlugin( "maven-deploy-plugin", "deploy" ) ); - } - else - { + plugins.add(newPlugin("maven-compiler-plugin", "compile", "testCompile")); + plugins.add(newPlugin("maven-resources-plugin", "resources", "testResources")); + plugins.add(newPlugin("maven-surefire-plugin", "test")); + plugins.add(newPlugin("maven-jar-plugin", "jar")); + plugins.add(newPlugin("maven-install-plugin", "install")); + plugins.add(newPlugin("maven-deploy-plugin", "deploy")); + } else { plugins = Collections.emptySet(); } return plugins; } - private Plugin newPlugin( String artifactId, String... goals ) - { + private Plugin newPlugin(String artifactId, String... goals) { Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.plugins" ); - plugin.setArtifactId( artifactId ); + plugin.setGroupId("org.apache.maven.plugins"); + plugin.setArtifactId(artifactId); - for ( String goal : goals ) - { + for (String goal : goals) { PluginExecution pluginExecution = new PluginExecution(); - pluginExecution.setId( "default-" + goal ); - pluginExecution.addGoal( goal ); - plugin.addExecution( pluginExecution ); + pluginExecution.setId("default-" + goal); + pluginExecution.addGoal(goal); + plugin.addExecution(pluginExecution); } return plugin; } - public void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - { - } + public void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) {} - public List executeForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - { + public List executeForkedExecutions(MojoExecution mojoExecution, MavenSession session) { return Collections.emptyList(); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecyclePluginAnalyzer.java b/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecyclePluginAnalyzer.java index 672e07b35e..88686024c3 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecyclePluginAnalyzer.java +++ b/maven-compat/src/test/java/org/apache/maven/project/EmptyLifecyclePluginAnalyzer.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -30,49 +28,40 @@ import org.apache.maven.model.PluginExecution; /** * @author Benjamin Bentmann */ -public class EmptyLifecyclePluginAnalyzer - implements LifeCyclePluginAnalyzer -{ - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { +public class EmptyLifecyclePluginAnalyzer implements LifeCyclePluginAnalyzer { + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { Set plugins; // NOTE: The upper-case packaging name is intentional, that's a special hinting mode used for certain tests - if ( "JAR".equals( packaging ) ) - { + if ("JAR".equals(packaging)) { plugins = new LinkedHashSet<>(); - plugins.add( newPlugin( "maven-compiler-plugin", "compile", "testCompile" ) ); - plugins.add( newPlugin( "maven-resources-plugin", "resources", "testResources" ) ); - plugins.add( newPlugin( "maven-surefire-plugin", "test" ) ); - plugins.add( newPlugin( "maven-jar-plugin", "jar" ) ); - plugins.add( newPlugin( "maven-install-plugin", "install" ) ); - plugins.add( newPlugin( "maven-deploy-plugin", "deploy" ) ); - } - else - { + plugins.add(newPlugin("maven-compiler-plugin", "compile", "testCompile")); + plugins.add(newPlugin("maven-resources-plugin", "resources", "testResources")); + plugins.add(newPlugin("maven-surefire-plugin", "test")); + plugins.add(newPlugin("maven-jar-plugin", "jar")); + plugins.add(newPlugin("maven-install-plugin", "install")); + plugins.add(newPlugin("maven-deploy-plugin", "deploy")); + } else { plugins = Collections.emptySet(); } return plugins; } - private Plugin newPlugin( String artifactId, String... goals ) - { + private Plugin newPlugin(String artifactId, String... goals) { Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.plugins" ); - plugin.setArtifactId( artifactId ); + plugin.setGroupId("org.apache.maven.plugins"); + plugin.setArtifactId(artifactId); - for ( String goal : goals ) - { + for (String goal : goals) { PluginExecution pluginExecution = new PluginExecution(); - pluginExecution.setId( "default-" + goal ); - pluginExecution.addGoal( goal ); - plugin.addExecution( pluginExecution ); + pluginExecution.setId("default-" + goal); + pluginExecution.addGoal(goal); + plugin.addExecution(pluginExecution); } return plugin; } - } diff --git a/maven-compat/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java b/maven-compat/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java index c919cdf776..e105e2cbd5 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java +++ b/maven-compat/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; @@ -37,124 +35,102 @@ import org.eclipse.aether.repository.RemoteRepository; /** * @author Benjamin Bentmann */ -public class LegacyLocalRepositoryManager - implements LocalRepositoryManager -{ +public class LegacyLocalRepositoryManager implements LocalRepositoryManager { private final LocalRepository repository; - public LegacyLocalRepositoryManager( File basedir ) - { - this.repository = new LocalRepository( basedir.getAbsoluteFile(), "legacy" ); + public LegacyLocalRepositoryManager(File basedir) { + this.repository = new LocalRepository(basedir.getAbsoluteFile(), "legacy"); } - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return repository; } - public String getPathForLocalArtifact( Artifact artifact ) - { - StringBuilder path = new StringBuilder( 128 ); + public String getPathForLocalArtifact(Artifact artifact) { + StringBuilder path = new StringBuilder(128); - path.append( artifact.getGroupId() ).append( '/' ); + path.append(artifact.getGroupId()).append('/'); - path.append( artifact.getExtension() ).append( "s/" ); + path.append(artifact.getExtension()).append("s/"); - path.append( artifact.getArtifactId() ).append( '-' ).append( artifact.getVersion() ); + path.append(artifact.getArtifactId()).append('-').append(artifact.getVersion()); - if ( artifact.getClassifier().length() > 0 ) - { - path.append( '-' ).append( artifact.getClassifier() ); + if (artifact.getClassifier().length() > 0) { + path.append('-').append(artifact.getClassifier()); } - path.append( '.' ).append( artifact.getExtension() ); + path.append('.').append(artifact.getExtension()); return path.toString(); } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { - return getPathForLocalArtifact( artifact ); + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { + return getPathForLocalArtifact(artifact); } - public String getPathForLocalMetadata( Metadata metadata ) - { - return getPath( metadata, "local" ); + public String getPathForLocalMetadata(Metadata metadata) { + return getPath(metadata, "local"); } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { - return getPath( metadata, getRepositoryKey( repository, context ) ); + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { + return getPath(metadata, getRepositoryKey(repository, context)); } - String getRepositoryKey( RemoteRepository repository, String context ) - { + String getRepositoryKey(RemoteRepository repository, String context) { return repository.getId(); } - private String getPath( Metadata metadata, String repositoryKey ) - { - StringBuilder path = new StringBuilder( 128 ); + private String getPath(Metadata metadata, String repositoryKey) { + StringBuilder path = new StringBuilder(128); - if ( metadata.getGroupId().length() > 0 ) - { - path.append( metadata.getGroupId().replace( '.', '/' ) ).append( '/' ); + if (metadata.getGroupId().length() > 0) { + path.append(metadata.getGroupId().replace('.', '/')).append('/'); - if ( metadata.getArtifactId().length() > 0 ) - { - path.append( metadata.getArtifactId() ).append( '/' ); + if (metadata.getArtifactId().length() > 0) { + path.append(metadata.getArtifactId()).append('/'); - if ( metadata.getVersion().length() > 0 ) - { - path.append( metadata.getVersion() ).append( '/' ); + if (metadata.getVersion().length() > 0) { + path.append(metadata.getVersion()).append('/'); } } } - path.append( insertRepositoryKey( metadata.getType(), repositoryKey ) ); + path.append(insertRepositoryKey(metadata.getType(), repositoryKey)); return path.toString(); } - private String insertRepositoryKey( String filename, String repositoryKey ) - { + private String insertRepositoryKey(String filename, String repositoryKey) { String result; - int idx = filename.indexOf( '.' ); - if ( idx < 0 ) - { + int idx = filename.indexOf('.'); + if (idx < 0) { result = filename + '-' + repositoryKey; - } - else - { - result = filename.substring( 0, idx ) + '-' + repositoryKey + filename.substring( idx ); + } else { + result = filename.substring(0, idx) + '-' + repositoryKey + filename.substring(idx); } return result; } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { - String path = getPathForLocalArtifact( request.getArtifact() ); - File file = new File( getRepository().getBasedir(), path ); + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { + String path = getPathForLocalArtifact(request.getArtifact()); + File file = new File(getRepository().getBasedir(), path); - LocalArtifactResult result = new LocalArtifactResult( request ); - if ( file.isFile() ) - { - result.setFile( file ); - result.setAvailable( true ); + LocalArtifactResult result = new LocalArtifactResult(request); + if (file.isFile()) { + result.setFile(file); + result.setAvailable(true); } return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { // noop } - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - LocalMetadataResult result = new LocalMetadataResult( request ); + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + LocalMetadataResult result = new LocalMetadataResult(request); String path; @@ -162,31 +138,25 @@ public class LegacyLocalRepositoryManager String context = request.getContext(); RemoteRepository remote = request.getRepository(); - if ( remote != null ) - { - path = getPathForRemoteMetadata( metadata, remote, context ); - } - else - { - path = getPathForLocalMetadata( metadata ); + if (remote != null) { + path = getPathForRemoteMetadata(metadata, remote, context); + } else { + path = getPathForLocalMetadata(metadata); } - File file = new File( getRepository().getBasedir(), path ); - if ( file.isFile() ) - { - result.setFile( file ); + File file = new File(getRepository().getBasedir(), path); + if (file.isFile()) { + result.setFile(file); } return result; } - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { + public void add(RepositorySystemSession session, LocalMetadataRegistration request) { // noop } - public String toString() - { - return String.valueOf( getRepository() ); + public String toString() { + return String.valueOf(getRepository()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/ProjectClasspathTest.java b/maven-compat/src/test/java/org/apache/maven/project/ProjectClasspathTest.java index ad4531c645..2e42f584e3 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/ProjectClasspathTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/ProjectClasspathTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,10 +16,14 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.File; import java.lang.reflect.Field; - import org.apache.maven.artifact.Artifact; import org.apache.maven.repository.internal.DefaultArtifactDescriptorReader; import org.eclipse.aether.impl.ArtifactDescriptorReader; @@ -29,122 +31,107 @@ import org.eclipse.aether.impl.ArtifactResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -public class ProjectClasspathTest - extends AbstractMavenProjectTestCase -{ +public class ProjectClasspathTest extends AbstractMavenProjectTestCase { static final String dir = "projects/scope/"; @Override @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - ArtifactResolver resolver = getContainer().lookup( ArtifactResolver.class, "classpath" ); - DefaultArtifactDescriptorReader pomReader = (DefaultArtifactDescriptorReader) getContainer().lookup(ArtifactDescriptorReader.class); - Field field = DefaultArtifactDescriptorReader.class.getDeclaredField( "artifactResolver" ); - field.setAccessible( true ); - field.set( pomReader, resolver ); + ArtifactResolver resolver = getContainer().lookup(ArtifactResolver.class, "classpath"); + DefaultArtifactDescriptorReader pomReader = + (DefaultArtifactDescriptorReader) getContainer().lookup(ArtifactDescriptorReader.class); + Field field = DefaultArtifactDescriptorReader.class.getDeclaredField("artifactResolver"); + field.setAccessible(true); + field.set(pomReader, resolver); - projectBuilder = getContainer().lookup( ProjectBuilder.class, "classpath" ); + projectBuilder = getContainer().lookup(ProjectBuilder.class, "classpath"); } @Test - public void testProjectClasspath() - throws Exception - { - File f = getFileForClasspathResource( dir + "project-with-scoped-dependencies.xml" ); + public void testProjectClasspath() throws Exception { + File f = getFileForClasspathResource(dir + "project-with-scoped-dependencies.xml"); - MavenProject project = getProjectWithDependencies( f ); + MavenProject project = getProjectWithDependencies(f); Artifact artifact; - assertNotNull( project, "Test project can't be null!" ); + assertNotNull(project, "Test project can't be null!"); - checkArtifactIdScope( project, "provided", "provided" ); - checkArtifactIdScope( project, "test", "test" ); - checkArtifactIdScope( project, "compile", "compile" ); - checkArtifactIdScope( project, "runtime", "runtime" ); - checkArtifactIdScope( project, "default", "compile" ); + checkArtifactIdScope(project, "provided", "provided"); + checkArtifactIdScope(project, "test", "test"); + checkArtifactIdScope(project, "compile", "compile"); + checkArtifactIdScope(project, "runtime", "runtime"); + checkArtifactIdScope(project, "default", "compile"); // check all transitive deps of a test dependency are test, except test and provided which is skipped - artifact = getArtifact( project, "maven-test-test", "scope-provided" ); - assertNull( artifact, "Check no provided dependencies are transitive" ); - artifact = getArtifact( project, "maven-test-test", "scope-test" ); - assertNull( artifact, "Check no test dependencies are transitive" ); + artifact = getArtifact(project, "maven-test-test", "scope-provided"); + assertNull(artifact, "Check no provided dependencies are transitive"); + artifact = getArtifact(project, "maven-test-test", "scope-test"); + assertNull(artifact, "Check no test dependencies are transitive"); - artifact = getArtifact( project, "maven-test-test", "scope-compile" ); - assertNotNull( artifact ); + artifact = getArtifact(project, "maven-test-test", "scope-compile"); + assertNotNull(artifact); - System.out.println( "a = " + artifact ); - System.out.println( "b = " + artifact.getScope() ); - assertEquals( "test", artifact.getScope(), "Check scope" ); - artifact = getArtifact( project, "maven-test-test", "scope-default" ); - assertEquals( "test", artifact.getScope(), "Check scope" ); - artifact = getArtifact( project, "maven-test-test", "scope-runtime" ); - assertEquals( "test", artifact.getScope(), "Check scope" ); + System.out.println("a = " + artifact); + System.out.println("b = " + artifact.getScope()); + assertEquals("test", artifact.getScope(), "Check scope"); + artifact = getArtifact(project, "maven-test-test", "scope-default"); + assertEquals("test", artifact.getScope(), "Check scope"); + artifact = getArtifact(project, "maven-test-test", "scope-runtime"); + assertEquals("test", artifact.getScope(), "Check scope"); // check all transitive deps of a provided dependency are provided scope, except for test - checkGroupIdScope( project, "provided", "maven-test-provided" ); - artifact = getArtifact( project, "maven-test-provided", "scope-runtime" ); - assertEquals( "provided", artifact.getScope(), "Check scope" ); + checkGroupIdScope(project, "provided", "maven-test-provided"); + artifact = getArtifact(project, "maven-test-provided", "scope-runtime"); + assertEquals("provided", artifact.getScope(), "Check scope"); // check all transitive deps of a runtime dependency are runtime scope, except for test - checkGroupIdScope( project, "runtime", "maven-test-runtime" ); - artifact = getArtifact( project, "maven-test-runtime", "scope-runtime" ); - assertEquals( "runtime", artifact.getScope(), "Check scope" ); + checkGroupIdScope(project, "runtime", "maven-test-runtime"); + artifact = getArtifact(project, "maven-test-runtime", "scope-runtime"); + assertEquals("runtime", artifact.getScope(), "Check scope"); // check all transitive deps of a compile dependency are compile scope, except for runtime and test - checkGroupIdScope( project, "compile", "maven-test-compile" ); - artifact = getArtifact( project, "maven-test-compile", "scope-runtime" ); - assertEquals( "runtime", artifact.getScope(), "Check scope" ); + checkGroupIdScope(project, "compile", "maven-test-compile"); + artifact = getArtifact(project, "maven-test-compile", "scope-runtime"); + assertEquals("runtime", artifact.getScope(), "Check scope"); // check all transitive deps of a default dependency are compile scope, except for runtime and test - checkGroupIdScope( project, "compile", "maven-test-default" ); - artifact = getArtifact( project, "maven-test-default", "scope-runtime" ); - assertEquals( "runtime", artifact.getScope(), "Check scope" ); + checkGroupIdScope(project, "compile", "maven-test-default"); + artifact = getArtifact(project, "maven-test-default", "scope-runtime"); + assertEquals("runtime", artifact.getScope(), "Check scope"); } - private void checkGroupIdScope( MavenProject project, String scopeValue, String groupId ) - { + private void checkGroupIdScope(MavenProject project, String scopeValue, String groupId) { Artifact artifact; - artifact = getArtifact( project, groupId, "scope-compile" ); - assertEquals( scopeValue, artifact.getScope(), "Check scope" ); - artifact = getArtifact( project, groupId, "scope-test" ); - assertNull( artifact, "Check test dependency is not transitive" ); - artifact = getArtifact( project, groupId, "scope-provided" ); - assertNull( artifact, "Check provided dependency is not transitive" ); - artifact = getArtifact( project, groupId, "scope-default" ); - assertEquals( scopeValue, artifact.getScope(), "Check scope" ); + artifact = getArtifact(project, groupId, "scope-compile"); + assertEquals(scopeValue, artifact.getScope(), "Check scope"); + artifact = getArtifact(project, groupId, "scope-test"); + assertNull(artifact, "Check test dependency is not transitive"); + artifact = getArtifact(project, groupId, "scope-provided"); + assertNull(artifact, "Check provided dependency is not transitive"); + artifact = getArtifact(project, groupId, "scope-default"); + assertEquals(scopeValue, artifact.getScope(), "Check scope"); } - private void checkArtifactIdScope( MavenProject project, String scope, String scopeValue ) - { + private void checkArtifactIdScope(MavenProject project, String scope, String scopeValue) { String artifactId = "scope-" + scope; - Artifact artifact = getArtifact( project, "maven-test", artifactId ); - assertNotNull( artifact ); - assertEquals( scopeValue, artifact.getScope(), "Check scope" ); + Artifact artifact = getArtifact(project, "maven-test", artifactId); + assertNotNull(artifact); + assertEquals(scopeValue, artifact.getScope(), "Check scope"); } - private Artifact getArtifact( MavenProject project, String groupId, String artifactId ) - { - System.out.println( "[ Looking for " + groupId + ":" + artifactId + " ]" ); - for ( Artifact a : project.getArtifacts() ) - { - System.out.println( a.toString() ); - if ( artifactId.equals( a.getArtifactId() ) && a.getGroupId().equals( groupId ) ) - { - System.out.println( "RETURN" ); + private Artifact getArtifact(MavenProject project, String groupId, String artifactId) { + System.out.println("[ Looking for " + groupId + ":" + artifactId + " ]"); + for (Artifact a : project.getArtifacts()) { + System.out.println(a.toString()); + if (artifactId.equals(a.getArtifactId()) && a.getGroupId().equals(groupId)) { + System.out.println("RETURN"); return a; } } - System.out.println( "Return null" ); + System.out.println("Return null"); return null; } - } diff --git a/maven-compat/src/test/java/org/apache/maven/project/TestArtifactResolver.java b/maven-compat/src/test/java/org/apache/maven/project/TestArtifactResolver.java index 94b30dbb98..52465152de 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/TestArtifactResolver.java +++ b/maven-compat/src/test/java/org/apache/maven/project/TestArtifactResolver.java @@ -1,36 +1,36 @@ -package org.apache.maven.project; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - -import org.apache.maven.artifact.metadata.ArtifactMetadataSource; -import org.apache.maven.artifact.resolver.DefaultArtifactResolver; +package org.apache.maven.project; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.resolver.DefaultArtifactResolver; -@Named( "classpath" ) +@Named("classpath") @Singleton -public class TestArtifactResolver - extends DefaultArtifactResolver -{ +public class TestArtifactResolver extends DefaultArtifactResolver { private ArtifactMetadataSource source; @Inject - public TestArtifactResolver(final @Named( "classpath" ) ArtifactMetadataSource source) { + public TestArtifactResolver(final @Named("classpath") ArtifactMetadataSource source) { this.source = source; } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/TestMavenRepositorySystem.java b/maven-compat/src/test/java/org/apache/maven/project/TestMavenRepositorySystem.java index f3b342d9cb..1b423c2525 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/TestMavenRepositorySystem.java +++ b/maven-compat/src/test/java/org/apache/maven/project/TestMavenRepositorySystem.java @@ -1,32 +1,32 @@ -package org.apache.maven.project; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - -import org.apache.maven.artifact.resolver.ArtifactResolver; -import org.apache.maven.repository.legacy.LegacyRepositorySystem; +package org.apache.maven.project; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.maven.repository.legacy.LegacyRepositorySystem; -@Named( "classpath" ) +@Named("classpath") @Singleton -public class TestMavenRepositorySystem - extends LegacyRepositorySystem -{ +public class TestMavenRepositorySystem extends LegacyRepositorySystem { @Inject private ArtifactResolver artifactResolver; } diff --git a/maven-compat/src/test/java/org/apache/maven/project/TestProjectBuilder.java b/maven-compat/src/test/java/org/apache/maven/project/TestProjectBuilder.java index a92cd57681..2cabebe66a 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/TestProjectBuilder.java +++ b/maven-compat/src/test/java/org/apache/maven/project/TestProjectBuilder.java @@ -1,23 +1,28 @@ -package org.apache.maven.project; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.Collections; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.bridge.MavenRepositorySystem; import org.apache.maven.model.building.ModelBuilder; @@ -26,35 +31,37 @@ import org.apache.maven.repository.internal.ModelCacheFactory; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.impl.RemoteRepositoryManager; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -@Named( "classpath" ) +@Named("classpath") @Singleton -public class TestProjectBuilder - extends DefaultProjectBuilder -{ +public class TestProjectBuilder extends DefaultProjectBuilder { @Inject public TestProjectBuilder( - ModelBuilder modelBuilder, ModelProcessor modelProcessor, - ProjectBuildingHelper projectBuildingHelper, MavenRepositorySystem repositorySystem, - RepositorySystem repoSystem, RemoteRepositoryManager repositoryManager, - ProjectDependenciesResolver dependencyResolver, ModelCacheFactory modelCacheFactory ) - { - super( modelBuilder, modelProcessor, projectBuildingHelper, repositorySystem, repoSystem, - repositoryManager, dependencyResolver, modelCacheFactory ); + ModelBuilder modelBuilder, + ModelProcessor modelProcessor, + ProjectBuildingHelper projectBuildingHelper, + MavenRepositorySystem repositorySystem, + RepositorySystem repoSystem, + RemoteRepositoryManager repositoryManager, + ProjectDependenciesResolver dependencyResolver, + ModelCacheFactory modelCacheFactory) { + super( + modelBuilder, + modelProcessor, + projectBuildingHelper, + repositorySystem, + repoSystem, + repositoryManager, + dependencyResolver, + modelCacheFactory); } @Override - public ProjectBuildingResult build( File pomFile, ProjectBuildingRequest configuration ) - throws ProjectBuildingException - { - ProjectBuildingResult result = super.build( pomFile, configuration ); + public ProjectBuildingResult build(File pomFile, ProjectBuildingRequest configuration) + throws ProjectBuildingException { + ProjectBuildingResult result = super.build(pomFile, configuration); - result.getProject().setRemoteArtifactRepositories( Collections. emptyList() ); + result.getProject().setRemoteArtifactRepositories(Collections.emptyList()); return result; } - -} \ No newline at end of file +} diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/AbstractProjectInheritanceTestCase.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/AbstractProjectInheritanceTestCase.java index af3655f826..9b843e9df5 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/AbstractProjectInheritanceTestCase.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/AbstractProjectInheritanceTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance; * "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 + * 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 @@ -18,42 +16,36 @@ package org.apache.maven.project.inheritance; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; - -import org.apache.maven.project.AbstractMavenProjectTestCase; +package org.apache.maven.project.inheritance; import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; +import java.io.File; +import org.apache.maven.project.AbstractMavenProjectTestCase; + /** * @author Jason van Zyl */ -public abstract class AbstractProjectInheritanceTestCase - extends AbstractMavenProjectTestCase -{ - protected String getTestSeries() - { +public abstract class AbstractProjectInheritanceTestCase extends AbstractMavenProjectTestCase { + protected String getTestSeries() { String className = getClass().getPackage().getName(); - return className.substring( className.lastIndexOf( '.' ) + 1 ); + return className.substring(className.lastIndexOf('.') + 1); } - protected File projectFile( String name ) - { - return projectFile( "maven", name ); + protected File projectFile(String name) { + return projectFile("maven", name); } - protected File projectFile( String groupId, String artifactId ) - { - return new File( getLocalRepositoryPath(), "/" + groupId + "/poms/" + artifactId + "-1.0.pom" ); + protected File projectFile(String groupId, String artifactId) { + return new File(getLocalRepositoryPath(), "/" + groupId + "/poms/" + artifactId + "-1.0.pom"); } // ---------------------------------------------------------------------- // The local repository for this category of tests // ---------------------------------------------------------------------- - protected File getLocalRepositoryPath() - { - return getTestFile("src/test/resources/inheritance-repo/" + getTestSeries() ); + protected File getLocalRepositoryPath() { + return getTestFile("src/test/resources/inheritance-repo/" + getTestSeries()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t00/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t00/ProjectInheritanceTest.java index 0300d56670..eb0dd8a676 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t00/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t00/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t00; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t00; * "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 + * 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 @@ -18,13 +16,14 @@ package org.apache.maven.project.inheritance.t00; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance.t00; + +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.maven.project.MavenProject; import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * A test which demonstrates maven's recursive inheritance where * a distinct value is taken from each parent contributing to @@ -36,9 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * * @author Jason van Zyl */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p4 inherits from p3 @@ -54,43 +51,41 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testProjectInheritance() - throws Exception - { - MavenProject p4 = getProject( projectFile( "p4" ) ); + public void testProjectInheritance() throws Exception { + MavenProject p4 = getProject(projectFile("p4")); - assertEquals( "p4", p4.getName() ); + assertEquals("p4", p4.getName()); // ---------------------------------------------------------------------- // Value inherited from p3 // ---------------------------------------------------------------------- - assertEquals( "2000", p4.getInceptionYear() ); + assertEquals("2000", p4.getInceptionYear()); // ---------------------------------------------------------------------- // Value taken from p2 // ---------------------------------------------------------------------- - assertEquals( "mailing-list", p4.getMailingLists().get( 0 ).getName() ); + assertEquals("mailing-list", p4.getMailingLists().get(0).getName()); // ---------------------------------------------------------------------- // Value taken from p1 // ---------------------------------------------------------------------- - assertEquals( "scm-url/p2/p3/p4", p4.getScm().getUrl() ); + assertEquals("scm-url/p2/p3/p4", p4.getScm().getUrl()); // ---------------------------------------------------------------------- // Value taken from p4 // ---------------------------------------------------------------------- - assertEquals( "Codehaus", p4.getOrganization().getName() ); + assertEquals("Codehaus", p4.getOrganization().getName()); // ---------------------------------------------------------------------- // Value taken from super model // ---------------------------------------------------------------------- - assertEquals( "4.0.0", p4.getModelVersion() ); + assertEquals("4.0.0", p4.getModelVersion()); - assertEquals( "4.0.0", p4.getModelVersion() ); + assertEquals("4.0.0", p4.getModelVersion()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t01/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t01/ProjectInheritanceTest.java index 8f8199e9c1..e339609f20 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t01/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t01/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t01; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t01; * "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 + * 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 @@ -18,13 +16,14 @@ package org.apache.maven.project.inheritance.t01; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance.t01; + +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.maven.project.MavenProject; import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * A test which demonstrates maven's recursive inheritance where * we are testing to make sure that elements stated in a model are @@ -32,9 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * * @author Jason van Zyl */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p4 inherits from p3 @@ -50,47 +47,45 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testProjectInheritance() - throws Exception - { + public void testProjectInheritance() throws Exception { // ---------------------------------------------------------------------- // Check p0 value for org name // ---------------------------------------------------------------------- - MavenProject p0 = getProject( projectFile( "maven.t01", "p0" ) ); + MavenProject p0 = getProject(projectFile("maven.t01", "p0")); - assertEquals( "p0-org", p0.getOrganization().getName() ); + assertEquals("p0-org", p0.getOrganization().getName()); // ---------------------------------------------------------------------- // Check p1 value for org name // ---------------------------------------------------------------------- - MavenProject p1 = getProject( projectFile( "maven.t01", "p1" ) ); + MavenProject p1 = getProject(projectFile("maven.t01", "p1")); - assertEquals( "p1-org", p1.getOrganization().getName() ); + assertEquals("p1-org", p1.getOrganization().getName()); // ---------------------------------------------------------------------- // Check p2 value for org name // ---------------------------------------------------------------------- - MavenProject p2 = getProject( projectFile( "maven.t01", "p2" ) ); + MavenProject p2 = getProject(projectFile("maven.t01", "p2")); - assertEquals( "p2-org", p2.getOrganization().getName() ); + assertEquals("p2-org", p2.getOrganization().getName()); // ---------------------------------------------------------------------- // Check p2 value for org name // ---------------------------------------------------------------------- - MavenProject p3 = getProject( projectFile( "maven.t01", "p3" ) ); + MavenProject p3 = getProject(projectFile("maven.t01", "p3")); - assertEquals( "p3-org", p3.getOrganization().getName() ); + assertEquals("p3-org", p3.getOrganization().getName()); // ---------------------------------------------------------------------- // Check p4 value for org name // ---------------------------------------------------------------------- - MavenProject p4 = getProject( projectFile( "maven.t01", "p4" ) ); + MavenProject p4 = getProject(projectFile("maven.t01", "p4")); - assertEquals( "p4-org", p4.getOrganization().getName() ); + assertEquals("p4-org", p4.getOrganization().getName()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t02/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t02/ProjectInheritanceTest.java index adacaf8606..cec5d8eafa 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t02/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t02/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t02; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t02; * "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 + * 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 @@ -18,12 +16,16 @@ package org.apache.maven.project.inheritance.t02; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance.t02; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -31,10 +33,6 @@ import org.apache.maven.project.MavenProject; import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * A test which demonstrates maven's recursive inheritance where * a distinct value is taken from each parent contributing to @@ -46,9 +44,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * * @author Jason van Zyl */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p4 inherits from p3 @@ -64,61 +60,59 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testProjectInheritance() - throws Exception - { + public void testProjectInheritance() throws Exception { File localRepo = getLocalRepositoryPath(); - System.out.println( "Local repository is at: " + localRepo.getAbsolutePath() ); + System.out.println("Local repository is at: " + localRepo.getAbsolutePath()); - File pom0 = new File( localRepo, "p0/pom.xml" ); - File pom1 = new File( pom0.getParentFile(), "p1/pom.xml" ); - File pom2 = new File( pom1.getParentFile(), "p2/pom.xml" ); - File pom3 = new File( pom2.getParentFile(), "p3/pom.xml" ); - File pom4 = new File( pom3.getParentFile(), "p4/pom.xml" ); - File pom5 = new File( pom4.getParentFile(), "p5/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); + File pom1 = new File(pom0.getParentFile(), "p1/pom.xml"); + File pom2 = new File(pom1.getParentFile(), "p2/pom.xml"); + File pom3 = new File(pom2.getParentFile(), "p3/pom.xml"); + File pom4 = new File(pom3.getParentFile(), "p4/pom.xml"); + File pom5 = new File(pom4.getParentFile(), "p5/pom.xml"); - System.out.println( "Location of project-4's POM: " + pom4.getPath() ); + System.out.println("Location of project-4's POM: " + pom4.getPath()); // load everything... - MavenProject project0 = getProject( pom0 ); - MavenProject project1 = getProject( pom1 ); - MavenProject project2 = getProject( pom2 ); - MavenProject project3 = getProject( pom3 ); - MavenProject project4 = getProject( pom4 ); - MavenProject project5 = getProject( pom5 ); + MavenProject project0 = getProject(pom0); + MavenProject project1 = getProject(pom1); + MavenProject project2 = getProject(pom2); + MavenProject project3 = getProject(pom3); + MavenProject project4 = getProject(pom4); + MavenProject project5 = getProject(pom5); - assertEquals( "p4", project4.getName() ); + assertEquals("p4", project4.getName()); // ---------------------------------------------------------------------- // Value inherited from p3 // ---------------------------------------------------------------------- - assertEquals( "2000", project4.getInceptionYear() ); + assertEquals("2000", project4.getInceptionYear()); // ---------------------------------------------------------------------- // Value taken from p2 // ---------------------------------------------------------------------- - assertEquals( "mailing-list", project4.getMailingLists().get( 0 ).getName() ); + assertEquals("mailing-list", project4.getMailingLists().get(0).getName()); // ---------------------------------------------------------------------- // Value taken from p1 // ---------------------------------------------------------------------- - assertEquals( "scm-url/p2/p3/p4", project4.getScm().getUrl() ); + assertEquals("scm-url/p2/p3/p4", project4.getScm().getUrl()); // ---------------------------------------------------------------------- // Value taken from p4 // ---------------------------------------------------------------------- - assertEquals( "Codehaus", project4.getOrganization().getName() ); + assertEquals("Codehaus", project4.getOrganization().getName()); // ---------------------------------------------------------------------- // Value taken from super model // ---------------------------------------------------------------------- - assertEquals( "4.0.0", project4.getModelVersion() ); + assertEquals("4.0.0", project4.getModelVersion()); Build build = project4.getBuild(); List plugins = build.getPlugins(); @@ -128,39 +122,37 @@ public class ProjectInheritanceTest String testPluginArtifactId = "maven-compiler-plugin"; // this is the plugin we're looking for. - validPluginCounts.put( testPluginArtifactId, 0 ); + validPluginCounts.put(testPluginArtifactId, 0); // these are injected if -DperformRelease=true - validPluginCounts.put( "maven-deploy-plugin", 0 ); - validPluginCounts.put( "maven-javadoc-plugin", 0 ); - validPluginCounts.put( "maven-source-plugin", 0 ); + validPluginCounts.put("maven-deploy-plugin", 0); + validPluginCounts.put("maven-javadoc-plugin", 0); + validPluginCounts.put("maven-source-plugin", 0); Plugin testPlugin = null; - for ( Plugin plugin : plugins ) - { + for (Plugin plugin : plugins) { String pluginArtifactId = plugin.getArtifactId(); - assertTrue( validPluginCounts.containsKey( pluginArtifactId ), "Illegal plugin found: " + pluginArtifactId ); + assertTrue(validPluginCounts.containsKey(pluginArtifactId), "Illegal plugin found: " + pluginArtifactId); - if ( pluginArtifactId.equals( testPluginArtifactId ) ) - { + if (pluginArtifactId.equals(testPluginArtifactId)) { testPlugin = plugin; } - Integer count = validPluginCounts.get( pluginArtifactId ); + Integer count = validPluginCounts.get(pluginArtifactId); - assertEquals( 0, (int) count, "Multiple copies of plugin: " + pluginArtifactId + " found in POM." ); + assertEquals(0, (int) count, "Multiple copies of plugin: " + pluginArtifactId + " found in POM."); count = count + 1; - validPluginCounts.put( pluginArtifactId, count ); + validPluginCounts.put(pluginArtifactId, count); } - assertNotNull( testPlugin ); + assertNotNull(testPlugin); List executions = testPlugin.getExecutions(); - assertEquals( 1, executions.size() ); + assertEquals(1, executions.size()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t03/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t03/ProjectInheritanceTest.java index ca8565a66d..4485561a7c 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t03/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t03/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t03; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t03; * "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 + * 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 @@ -18,15 +16,15 @@ package org.apache.maven.project.inheritance.t03; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance.t03; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; - import org.apache.maven.project.MavenProject; import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * A test which demonstrates maven's recursive inheritance where * a distinct value is taken from each parent contributing to @@ -38,9 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * * @author Jason van Zyl */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -53,20 +49,18 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testProjectInheritance() - throws Exception - { + public void testProjectInheritance() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load everything... - MavenProject project0 = getProject( pom0 ); - MavenProject project1 = getProject( pom1 ); + MavenProject project0 = getProject(pom0); + MavenProject project1 = getProject(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t04/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t04/ProjectInheritanceTest.java index 34a31d5e21..1cb8c505c2 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t04/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t04/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t04; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t04; * "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 + * 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 @@ -18,19 +16,19 @@ package org.apache.maven.project.inheritance.t04; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t04; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * Verifies the version of a dependency listed in a parent's * dependencyManagement section is chosen over another version of the same @@ -38,9 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * * @author Patrick Schneider */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -57,35 +53,28 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagementOverridesTransitiveDependencyVersion() - throws Exception - { + public void testDependencyManagementOverridesTransitiveDependencyVersion() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load the child project, which inherits from p0... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); Set set = project1.getArtifacts(); - assertNotNull( set, "No artifacts" ); - assertTrue( set.size() > 0, "No Artifacts" ); - assertTrue( set.size() == 3, "Set size should be 3, is " + set.size() ); + assertNotNull(set, "No artifacts"); + assertTrue(set.size() > 0, "No Artifacts"); + assertTrue(set.size() == 3, "Set size should be 3, is " + set.size()); - for ( Object aSet : set ) - { + for (Object aSet : set) { Artifact artifact = (Artifact) aSet; - System.out.println( - "Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + " Optional=" + ( - artifact.isOptional() - ? "true" - : "false" ) ); - assertTrue( artifact.getVersion().equals( "1.0" ), - "Incorrect version for " + artifact.getDependencyConflictId() ); + System.out.println("Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + + " Optional=" + (artifact.isOptional() ? "true" : "false")); + assertTrue( + artifact.getVersion().equals("1.0"), "Incorrect version for " + artifact.getDependencyConflictId()); } - } -} \ No newline at end of file +} diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t05/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t05/ProjectInheritanceTest.java index 8af4a2fdf7..14c8f2cfcc 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t05/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t05/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t05; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t05; * "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 + * 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 @@ -18,27 +16,25 @@ package org.apache.maven.project.inheritance.t05; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t05; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * A test which demonstrates maven's dependency management * * @author Ralph Goers */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -51,34 +47,29 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagement() - throws Exception - { + public void testDependencyManagement() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load everything... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); Set set = project1.getArtifacts(); - assertNotNull( set, "No artifacts" ); - assertTrue( set.size() > 0, "No Artifacts" ); + assertNotNull(set, "No artifacts"); + assertTrue(set.size() > 0, "No Artifacts"); - for ( Object aSet : set ) - { + for (Object aSet : set) { Artifact artifact = (Artifact) aSet; - System.out.println( - "Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + " Scope: " - + artifact.getScope() ); - assertTrue( artifact.getVersion().equals( "1.0" ), - "Incorrect version for " + artifact.getDependencyConflictId() ); + System.out.println("Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + + " Scope: " + artifact.getScope()); + assertTrue( + artifact.getVersion().equals("1.0"), "Incorrect version for " + artifact.getDependencyConflictId()); } - } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t06/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t06/ProjectInheritanceTest.java index bc37066a05..149c3a7d75 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t06/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t06/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t06; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t06; * "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 + * 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 @@ -18,28 +16,26 @@ package org.apache.maven.project.inheritance.t06; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Iterator; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t06; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Iterator; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * A test which demonstrates maven's dependency management * * @author Ralph Goers */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -52,35 +48,31 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagement() - throws Exception - { + public void testDependencyManagement() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load everything... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); Set set = project1.getArtifacts(); - assertNotNull( set, "No artifacts" ); - assertTrue( set.size() > 0, "No Artifacts" ); + assertNotNull(set, "No artifacts"); + assertTrue(set.size() > 0, "No Artifacts"); Iterator iter = set.iterator(); - assertTrue( set.size() == 4, "Set size should be 4, is " + set.size() ); + assertTrue(set.size() == 4, "Set size should be 4, is " + set.size()); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = (Artifact) iter.next(); - System.out.println( "Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() - + " Optional=" + ( artifact.isOptional() ? "true" : "false" ) ); - assertTrue( artifact.getVersion().equals( "1.0" ), - "Incorrect version for " + artifact.getDependencyConflictId() ); + System.out.println("Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + + " Optional=" + (artifact.isOptional() ? "true" : "false")); + assertTrue( + artifact.getVersion().equals("1.0"), "Incorrect version for " + artifact.getDependencyConflictId()); } - } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t07/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t07/ProjectInheritanceTest.java index 87b07d3a80..732e4f9659 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t07/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t07/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t07; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t07; * "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 + * 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 @@ -18,28 +16,26 @@ package org.apache.maven.project.inheritance.t07; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t07; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * A test which demonstrates maven's dependency management * * @author Jason van Zyl */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -52,37 +48,31 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagement() - throws Exception - { + public void testDependencyManagement() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load everything... - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); System.out.println("Project " + project1.getId() + " " + project1); Set set = project1.getArtifacts(); - assertNotNull( set, "No artifacts" ); - assertTrue( set.size() > 0, "No Artifacts" ); - assertTrue( set.size() == 3, "Set size should be 3, is " + set.size() ); + assertNotNull(set, "No artifacts"); + assertTrue(set.size() > 0, "No Artifacts"); + assertTrue(set.size() == 3, "Set size should be 3, is " + set.size()); - for ( Object aSet : set ) - { + for (Object aSet : set) { Artifact artifact = (Artifact) aSet; - assertFalse( artifact.getArtifactId().equals( "t07-d" ) ); - System.out.println( - "Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + " Optional=" + ( - artifact.isOptional() - ? "true" - : "false" ) ); - assertTrue( artifact.getVersion().equals( "1.0" ), - "Incorrect version for " + artifact.getDependencyConflictId() ); + assertFalse(artifact.getArtifactId().equals("t07-d")); + System.out.println("Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + + " Optional=" + (artifact.isOptional() ? "true" : "false")); + assertTrue( + artifact.getVersion().equals("1.0"), "Incorrect version for " + artifact.getDependencyConflictId()); } } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t08/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t08/ProjectInheritanceTest.java index c4562dc67e..830889fc5a 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t08/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t08/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t08; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t08; * "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 + * 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 @@ -18,28 +16,26 @@ package org.apache.maven.project.inheritance.t08; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Iterator; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t08; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Iterator; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * A test which demonstrates maven's dependency management * * @author Ralph Goers */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -52,35 +48,32 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagement() - throws Exception - { + public void testDependencyManagement() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load everything... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); - System.out.println( "Project " + project1.getId() + " " + project1 ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); + System.out.println("Project " + project1.getId() + " " + project1); Set set = project1.getArtifacts(); - assertNotNull( set, "No artifacts" ); - assertTrue( set.size() > 0, "No Artifacts" ); + assertNotNull(set, "No artifacts"); + assertTrue(set.size() > 0, "No Artifacts"); Iterator iter = set.iterator(); - assertTrue( set.size() == 4, "Set size should be 4, is " + set.size() ); + assertTrue(set.size() == 4, "Set size should be 4, is " + set.size()); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { Artifact artifact = (Artifact) iter.next(); - System.out.println( "Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() - + " Optional=" + ( artifact.isOptional() ? "true" : "false" ) ); - assertTrue( artifact.getVersion().equals( "1.0" ), "Incorrect version for " + artifact.getDependencyConflictId() ); + System.out.println("Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + + " Optional=" + (artifact.isOptional() ? "true" : "false")); + assertTrue( + artifact.getVersion().equals("1.0"), "Incorrect version for " + artifact.getDependencyConflictId()); } - } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t09/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t09/ProjectInheritanceTest.java index dcc4e8bf7e..ac59e99a1e 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t09/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t09/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t09; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t09; * "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 + * 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 @@ -18,27 +16,26 @@ package org.apache.maven.project.inheritance.t09; * specific language governing permissions and limitations * under the License. */ -import java.io.File; -import java.util.Map; - -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t09; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Map; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * Verifies exclusions listed in dependencyManagement are valid for * transitive dependencies. * * @author Patrick Schneider */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -63,30 +60,28 @@ public class ProjectInheritanceTest * a & b only. */ @Test - public void testDependencyManagementExclusionsExcludeTransitively() - throws Exception - { + public void testDependencyManagementExclusionsExcludeTransitively() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load the child project, which inherits from p0... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertNotNull( project1.getParent(), "Parent is null" ); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertNotNull(project1.getParent(), "Parent is null"); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); Map map = project1.getArtifactMap(); - assertNotNull( map, "No artifacts" ); - assertTrue( map.size() > 0, "No Artifacts" ); - assertTrue( map.size() == 2, "Set size should be 2, is " + map.size() ); + assertNotNull(map, "No artifacts"); + assertTrue(map.size() > 0, "No Artifacts"); + assertTrue(map.size() == 2, "Set size should be 2, is " + map.size()); - assertTrue( map.containsKey( "maven-test:t09-a" ), "maven-test:t09-a is not in the project" ); - assertTrue( map.containsKey( "maven-test:t09-b" ), "maven-test:t09-b is not in the project" ); - assertFalse( map.containsKey( "maven-test:t09-c" ), "maven-test:t09-c is in the project" ); + assertTrue(map.containsKey("maven-test:t09-a"), "maven-test:t09-a is not in the project"); + assertTrue(map.containsKey("maven-test:t09-b"), "maven-test:t09-b is not in the project"); + assertFalse(map.containsKey("maven-test:t09-c"), "maven-test:t09-c is in the project"); } /** @@ -100,28 +95,26 @@ public class ProjectInheritanceTest * @throws Exception */ @Test - public void testDependencyManagementExclusionDoesNotOverrideGloballyForTransitives() - throws Exception - { + public void testDependencyManagementExclusionDoesNotOverrideGloballyForTransitives() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom2 = new File( pom0Basedir, "p2/pom.xml" ); + File pom2 = new File(pom0Basedir, "p2/pom.xml"); // load the child project, which inherits from p0... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project2 = getProjectWithDependencies( pom2 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project2 = getProjectWithDependencies(pom2); - assertEquals( pom0Basedir, project2.getParent().getBasedir() ); + assertEquals(pom0Basedir, project2.getParent().getBasedir()); Map map = project2.getArtifactMap(); - assertNotNull( map, "No artifacts" ); - assertTrue( map.size() > 0, "No Artifacts" ); - assertTrue( map.size() == 4, "Set size should be 4, is " + map.size() ); + assertNotNull(map, "No artifacts"); + assertTrue(map.size() > 0, "No Artifacts"); + assertTrue(map.size() == 4, "Set size should be 4, is " + map.size()); - assertTrue( map.containsKey( "maven-test:t09-a" ), "maven-test:t09-a is not in the project" ); - assertTrue( map.containsKey( "maven-test:t09-b" ), "maven-test:t09-b is not in the project" ); - assertTrue( map.containsKey( "maven-test:t09-c" ), "maven-test:t09-c is not in the project" ); - assertTrue( map.containsKey( "maven-test:t09-d" ), "maven-test:t09-d is not in the project" ); + assertTrue(map.containsKey("maven-test:t09-a"), "maven-test:t09-a is not in the project"); + assertTrue(map.containsKey("maven-test:t09-b"), "maven-test:t09-b is not in the project"); + assertTrue(map.containsKey("maven-test:t09-c"), "maven-test:t09-c is not in the project"); + assertTrue(map.containsKey("maven-test:t09-d"), "maven-test:t09-d is not in the project"); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t10/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t10/ProjectInheritanceTest.java index b1e74087ba..a750730e5d 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t10/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t10/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t10; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t10; * "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 + * 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 @@ -18,19 +16,19 @@ package org.apache.maven.project.inheritance.t10; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Map; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t10; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.Map; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * Verifies scope inheritance of direct and transitive dependencies. * @@ -43,9 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * * @author Patrick Schneider */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -58,43 +54,40 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagementOverridesTransitiveDependencyVersion() - throws Exception - { + public void testDependencyManagementOverridesTransitiveDependencyVersion() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load the child project, which inherits from p0... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); System.out.println("Project " + project1.getId() + " " + project1); Map map = project1.getArtifactMap(); - assertNotNull( map, "No artifacts" ); - assertTrue( map.size() > 0, "No Artifacts" ); - assertTrue( map.size() == 3, "Set size should be 3, is " + map.size() ); + assertNotNull(map, "No artifacts"); + assertTrue(map.size() > 0, "No Artifacts"); + assertTrue(map.size() == 3, "Set size should be 3, is " + map.size()); Artifact a = (Artifact) map.get("maven-test:t10-a"); Artifact b = (Artifact) map.get("maven-test:t10-b"); Artifact c = (Artifact) map.get("maven-test:t10-c"); - assertNotNull( a ); - assertNotNull( b ); - assertNotNull( c ); + assertNotNull(a); + assertNotNull(b); + assertNotNull(c); // inherited from depMgmt System.out.println(a.getScope()); - assertTrue( a.getScope().equals("test"), "Incorrect scope for " + a.getDependencyConflictId() ); + assertTrue(a.getScope().equals("test"), "Incorrect scope for " + a.getDependencyConflictId()); // transitive dep, overridden b depMgmt - assertTrue( b.getScope().equals("runtime"), "Incorrect scope for " + b.getDependencyConflictId() ); + assertTrue(b.getScope().equals("runtime"), "Incorrect scope for " + b.getDependencyConflictId()); // direct dep, overrides depMgmt - assertTrue( c.getScope().equals("runtime"), "Incorrect scope for " + c.getDependencyConflictId() ); - + assertTrue(c.getScope().equals("runtime"), "Incorrect scope for " + c.getDependencyConflictId()); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t11/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t11/ProjectInheritanceTest.java index 3f21d5e0ad..f595ab880b 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t11/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t11/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t11; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t11; * "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 + * 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 @@ -18,25 +16,23 @@ package org.apache.maven.project.inheritance.t11; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; - -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t11; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import java.io.File; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * Verifies scope of root project is preserved regardless of parent dependency management. * * @author Patrick Schneider * @see MNG-2919 */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -49,21 +45,20 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testDependencyManagementDoesNotOverrideScopeOfCurrentArtifact() - throws Exception - { + public void testDependencyManagementDoesNotOverrideScopeOfCurrentArtifact() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load the child project, which inherits from p0... - MavenProject project0 = getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + MavenProject project0 = getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); - assertEquals( pom0Basedir, project1.getParent().getBasedir() ); - assertNull( project1.getArtifact().getScope(), - "dependencyManagement has overwritten the scope of the currently building child project" ); + assertEquals(pom0Basedir, project1.getParent().getBasedir()); + assertNull( + project1.getArtifact().getScope(), + "dependencyManagement has overwritten the scope of the currently building child project"); } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12/ProjectInheritanceTest.java index 25adce8402..9fc1dc21eb 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t12; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t12; * "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 + * 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 @@ -18,26 +16,23 @@ package org.apache.maven.project.inheritance.t12; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.Map; -import java.util.stream.Collectors; - -import org.apache.maven.model.Plugin; -import org.apache.maven.model.PluginExecution; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; -import org.junit.jupiter.api.Test; +package org.apache.maven.project.inheritance.t12; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import java.io.File; +import java.util.Map; +import org.apache.maven.model.Plugin; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; +import org.junit.jupiter.api.Test; + /** * Verifies that plugin execution sections in the parent POM that have * inherit == false are not inherited to the child POM. */ -public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -50,24 +45,24 @@ public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase // ---------------------------------------------------------------------- @Test - public void testFalsePluginExecutionInheritValue() throws Exception - { + public void testFalsePluginExecutionInheritValue() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "p1/pom.xml"); - getProjectWithDependencies( pom0 ); - MavenProject project1 = getProjectWithDependencies( pom1 ); + getProjectWithDependencies(pom0); + MavenProject project1 = getProjectWithDependencies(pom1); Map pluginMap = project1.getBuild().getPluginsAsMap(); - Plugin compilerPlugin = (Plugin) pluginMap.get( "org.apache.maven.plugins:maven-compiler-plugin" ); + Plugin compilerPlugin = (Plugin) pluginMap.get("org.apache.maven.plugins:maven-compiler-plugin"); - assertNotNull( compilerPlugin ); + assertNotNull(compilerPlugin); Map executionMap = compilerPlugin.getExecutionsAsMap(); - assertNull( executionMap.get( "test" ), - "Plugin execution: 'test' should NOT exist in the compiler plugin specification for the child project!" ); + assertNull( + executionMap.get("test"), + "Plugin execution: 'test' should NOT exist in the compiler plugin specification for the child project!"); } -} \ No newline at end of file +} diff --git a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12scm/ProjectInheritanceTest.java b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12scm/ProjectInheritanceTest.java index 82aee6c70f..889778bc8a 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12scm/ProjectInheritanceTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/inheritance/t12scm/ProjectInheritanceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.inheritance.t12scm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.inheritance.t12scm; * "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 + * 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 @@ -18,23 +16,21 @@ package org.apache.maven.project.inheritance.t12scm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.inheritance.t12scm; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; - import org.apache.maven.project.MavenProject; import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Verifies SCM inheritance uses modules statement from parent. * * @author jdcasey */ -public class ProjectInheritanceTest - extends AbstractProjectInheritanceTestCase -{ +public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 @@ -47,84 +43,80 @@ public class ProjectInheritanceTest // ---------------------------------------------------------------------- @Test - public void testScmInfoCalculatedCorrectlyOnParentAndChildRead() - throws Exception - { + public void testScmInfoCalculatedCorrectlyOnParentAndChildRead() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom0 = new File( localRepo, "p0/pom.xml" ); + File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); - File pom1 = new File( pom0Basedir, "modules/p1/pom.xml" ); + File pom1 = new File(pom0Basedir, "modules/p1/pom.xml"); // load the child project, which inherits from p0... - MavenProject project0 = getProject( pom0 ); - MavenProject project1 = getProject( pom1 ); + MavenProject project0 = getProject(pom0); + MavenProject project1 = getProject(pom1); - System.out.println( "\n\n" ); - System.out.println( "Parent SCM URL is: " + project0.getScm().getUrl() ); - System.out.println( "Child SCM URL is: " + project1.getScm().getUrl() ); + System.out.println("\n\n"); + System.out.println("Parent SCM URL is: " + project0.getScm().getUrl()); + System.out.println("Child SCM URL is: " + project1.getScm().getUrl()); System.out.println(); - System.out.println( "Parent SCM connection is: " + project0.getScm().getConnection() ); - System.out.println( "Child SCM connection is: " + project1.getScm().getConnection() ); + System.out.println("Parent SCM connection is: " + project0.getScm().getConnection()); + System.out.println("Child SCM connection is: " + project1.getScm().getConnection()); System.out.println(); - System.out.println( "Parent SCM developer connection is: " - + project0.getScm().getDeveloperConnection() ); - System.out.println( "Child SCM developer connection is: " - + project1.getScm().getDeveloperConnection() ); + System.out.println( + "Parent SCM developer connection is: " + project0.getScm().getDeveloperConnection()); + System.out.println( + "Child SCM developer connection is: " + project1.getScm().getDeveloperConnection()); - assertEquals( project1.getScm().getUrl(), project0.getScm().getUrl() + "/modules/p1" ); - assertEquals( project1.getScm().getConnection(), project0.getScm().getConnection() - + "/modules/p1" ); - assertEquals( project1.getScm().getDeveloperConnection(), project0.getScm() - .getDeveloperConnection() - + "/modules/p1" ); + assertEquals(project1.getScm().getUrl(), project0.getScm().getUrl() + "/modules/p1"); + assertEquals(project1.getScm().getConnection(), project0.getScm().getConnection() + "/modules/p1"); + assertEquals( + project1.getScm().getDeveloperConnection(), project0.getScm().getDeveloperConnection() + "/modules/p1"); } @Test - public void testScmInfoCalculatedCorrectlyOnChildOnlyRead() - throws Exception - { + public void testScmInfoCalculatedCorrectlyOnChildOnlyRead() throws Exception { File localRepo = getLocalRepositoryPath(); - File pom1 = new File( localRepo, "p0/modules/p1/pom.xml" ); + File pom1 = new File(localRepo, "p0/modules/p1/pom.xml"); // load the child project, which inherits from p0... - MavenProject project1 = getProject( pom1 ); + MavenProject project1 = getProject(pom1); - System.out.println( "\n\n" ); - System.out.println( "Child SCM URL is: " + project1.getScm().getUrl() ); - System.out.println( "Child SCM connection is: " + project1.getScm().getConnection() ); - System.out.println( "Child SCM developer connection is: " - + project1.getScm().getDeveloperConnection() ); + System.out.println("\n\n"); + System.out.println("Child SCM URL is: " + project1.getScm().getUrl()); + System.out.println("Child SCM connection is: " + project1.getScm().getConnection()); + System.out.println( + "Child SCM developer connection is: " + project1.getScm().getDeveloperConnection()); - assertEquals( "http://host/viewer?path=/p0/modules/p1", project1.getScm().getUrl() ); - assertEquals( "scm:svn:http://host/p0/modules/p1", project1.getScm().getConnection() ); - assertEquals( "scm:svn:https://host/p0/modules/p1", project1.getScm().getDeveloperConnection() ); + assertEquals("http://host/viewer?path=/p0/modules/p1", project1.getScm().getUrl()); + assertEquals("scm:svn:http://host/p0/modules/p1", project1.getScm().getConnection()); + assertEquals("scm:svn:https://host/p0/modules/p1", project1.getScm().getDeveloperConnection()); } -// public void testScmInfoCalculatedCorrectlyOnChildReadFromLocalRepository() -// throws Exception -// { -// File localRepo = getLocalRepositoryPath(); -// -// ArtifactFactory factory = (ArtifactFactory) lookup( ArtifactFactory.class ); -// Artifact artifact = factory.createProjectArtifact( "maven", "p1", "1.0" ); -// -// ArtifactRepositoryFactory repoFactory = (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.class ); -// ArtifactRepository localArtifactRepo = repoFactory.createLocalRepository( localRepo ); -// -// MavenProject project1 = getProjectBuilder().buildFromRepository( artifact, Collections.EMPTY_LIST, localArtifactRepo ); -// -// System.out.println( "\n\n" ); -// System.out.println( "Child SCM URL is: " + project1.getScm().getUrl() ); -// System.out.println( "Child SCM connection is: " + project1.getScm().getConnection() ); -// System.out.println( "Child SCM developer connection is: " -// + project1.getScm().getDeveloperConnection() ); -// -// assertEquals( project1.getScm().getUrl(), "http://host/viewer?path=/p0/modules/p1" ); -// assertEquals( project1.getScm().getConnection(), "scm:svn:http://host/p0/modules/p1" ); -// assertEquals( project1.getScm().getDeveloperConnection(), -// "scm:svn:https://host/p0/modules/p1" ); -// } + // public void testScmInfoCalculatedCorrectlyOnChildReadFromLocalRepository() + // throws Exception + // { + // File localRepo = getLocalRepositoryPath(); + // + // ArtifactFactory factory = (ArtifactFactory) lookup( ArtifactFactory.class ); + // Artifact artifact = factory.createProjectArtifact( "maven", "p1", "1.0" ); + // + // ArtifactRepositoryFactory repoFactory = (ArtifactRepositoryFactory) lookup( + // ArtifactRepositoryFactory.class ); + // ArtifactRepository localArtifactRepo = repoFactory.createLocalRepository( localRepo ); + // + // MavenProject project1 = getProjectBuilder().buildFromRepository( artifact, Collections.EMPTY_LIST, + // localArtifactRepo ); + // + // System.out.println( "\n\n" ); + // System.out.println( "Child SCM URL is: " + project1.getScm().getUrl() ); + // System.out.println( "Child SCM connection is: " + project1.getScm().getConnection() ); + // System.out.println( "Child SCM developer connection is: " + // + project1.getScm().getDeveloperConnection() ); + // + // assertEquals( project1.getScm().getUrl(), "http://host/viewer?path=/p0/modules/p1" ); + // assertEquals( project1.getScm().getConnection(), "scm:svn:http://host/p0/modules/p1" ); + // assertEquals( project1.getScm().getDeveloperConnection(), + // "scm:svn:https://host/p0/modules/p1" ); + // } } diff --git a/maven-compat/src/test/java/org/apache/maven/project/path/DefaultPathTranslatorTest.java b/maven-compat/src/test/java/org/apache/maven/project/path/DefaultPathTranslatorTest.java index 022ccd5592..1224a90be3 100644 --- a/maven-compat/src/test/java/org/apache/maven/project/path/DefaultPathTranslatorTest.java +++ b/maven-compat/src/test/java/org/apache/maven/project/path/DefaultPathTranslatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.path; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.path; * "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 + * 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 @@ -18,44 +16,40 @@ package org.apache.maven.project.path; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; - -import org.junit.jupiter.api.Test; +package org.apache.maven.project.path; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings( "deprecation" ) -public class DefaultPathTranslatorTest -{ + +import java.io.File; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") +public class DefaultPathTranslatorTest { @Test - public void testAlignToBasedirWhereBasedirExpressionIsTheCompleteValue() - { - File basedir = new File( System.getProperty( "java.io.tmpdir" ), "test" ).getAbsoluteFile(); + public void testAlignToBasedirWhereBasedirExpressionIsTheCompleteValue() { + File basedir = new File(System.getProperty("java.io.tmpdir"), "test").getAbsoluteFile(); - String aligned = new DefaultPathTranslator().alignToBaseDirectory( "${basedir}", basedir ); + String aligned = new DefaultPathTranslator().alignToBaseDirectory("${basedir}", basedir); - assertEquals( basedir.getAbsolutePath(), aligned ); + assertEquals(basedir.getAbsolutePath(), aligned); } @Test - public void testAlignToBasedirWhereBasedirExpressionIsTheValuePrefix() - { - File basedir = new File( System.getProperty( "java.io.tmpdir" ), "test" ).getAbsoluteFile(); + public void testAlignToBasedirWhereBasedirExpressionIsTheValuePrefix() { + File basedir = new File(System.getProperty("java.io.tmpdir"), "test").getAbsoluteFile(); - String aligned = new DefaultPathTranslator().alignToBaseDirectory( "${basedir}/dir", basedir ); + String aligned = new DefaultPathTranslator().alignToBaseDirectory("${basedir}/dir", basedir); - assertEquals( new File( basedir, "dir" ).getAbsolutePath(), aligned ); + assertEquals(new File(basedir, "dir").getAbsolutePath(), aligned); } @Test - public void testUnalignToBasedirWherePathEqualsBasedir() - { - File basedir = new File( System.getProperty( "java.io.tmpdir" ), "test" ).getAbsoluteFile(); + public void testUnalignToBasedirWherePathEqualsBasedir() { + File basedir = new File(System.getProperty("java.io.tmpdir"), "test").getAbsoluteFile(); - String unaligned = new DefaultPathTranslator().unalignFromBaseDirectory( basedir.getAbsolutePath(), basedir ); + String unaligned = new DefaultPathTranslator().unalignFromBaseDirectory(basedir.getAbsolutePath(), basedir); - assertEquals( ".", unaligned ); + assertEquals(".", unaligned); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/DefaultMirrorSelectorTest.java b/maven-compat/src/test/java/org/apache/maven/repository/DefaultMirrorSelectorTest.java index 97687e3207..6b70b8cc2c 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/DefaultMirrorSelectorTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/DefaultMirrorSelectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository; * "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 + * 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 @@ -18,20 +16,19 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; + +import static org.junit.jupiter.api.Assertions.assertFalse; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.DefaultArtifactRepository; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertFalse; - -public class DefaultMirrorSelectorTest -{ +public class DefaultMirrorSelectorTest { @Test - public void testMirrorWithMirrorOfPatternContainingANegationIsNotSelected() - { - ArtifactRepository repository = new DefaultArtifactRepository( "snapshots.repo", "http://whatever", null ); + public void testMirrorWithMirrorOfPatternContainingANegationIsNotSelected() { + ArtifactRepository repository = new DefaultArtifactRepository("snapshots.repo", "http://whatever", null); String pattern = "external:*, !snapshots.repo"; - assertFalse( DefaultMirrorSelector.matchPattern( repository, pattern ) ); + assertFalse(DefaultMirrorSelector.matchPattern(repository, pattern)); } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/LegacyRepositorySystemTest.java b/maven-compat/src/test/java/org/apache/maven/repository/LegacyRepositorySystemTest.java index f68a9961fb..0cf0ba8b21 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/LegacyRepositorySystemTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/LegacyRepositorySystemTest.java @@ -1,24 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.repository; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.util.Arrays; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; @@ -32,161 +40,146 @@ import org.apache.maven.model.Repository; import org.apache.maven.model.RepositoryPolicy; import org.apache.maven.plugin.LegacySupport; import org.apache.maven.repository.legacy.LegacyRepositorySystem; -import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; import org.junit.jupiter.api.Test; -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javax.inject.Inject; - /** * Tests {@link LegacyRepositorySystem}. * * @author Benjamin Bentmann */ @PlexusTest -public class LegacyRepositorySystemTest -{ +public class LegacyRepositorySystemTest { @Inject private RepositorySystem repositorySystem; + @Inject private ResolutionErrorHandler resolutionErrorHandler; + @Inject private PlexusContainer container; - protected List getRemoteRepositories() - throws Exception - { - File repoDir = new File( getBasedir(), "src/test/remote-repo" ).getAbsoluteFile(); + protected List getRemoteRepositories() throws Exception { + File repoDir = new File(getBasedir(), "src/test/remote-repo").getAbsoluteFile(); RepositoryPolicy policy = new RepositoryPolicy(); - policy.setEnabled( true ); - policy.setChecksumPolicy( "ignore" ); - policy.setUpdatePolicy( "always" ); + policy.setEnabled(true); + policy.setChecksumPolicy("ignore"); + policy.setUpdatePolicy("always"); Repository repository = new Repository(); - repository.setId( RepositorySystem.DEFAULT_REMOTE_REPO_ID ); - repository.setUrl( "file://" + repoDir.toURI().getPath() ); - repository.setReleases( policy ); - repository.setSnapshots( policy ); + repository.setId(RepositorySystem.DEFAULT_REMOTE_REPO_ID); + repository.setUrl("file://" + repoDir.toURI().getPath()); + repository.setReleases(policy); + repository.setSnapshots(policy); - return Arrays.asList( repositorySystem.buildArtifactRepository( repository ) ); + return Arrays.asList(repositorySystem.buildArtifactRepository(repository)); } - protected ArtifactRepository getLocalRepository() - throws Exception - { - File repoDir = new File( getBasedir(), "target/local-repo" ).getAbsoluteFile(); + protected ArtifactRepository getLocalRepository() throws Exception { + File repoDir = new File(getBasedir(), "target/local-repo").getAbsoluteFile(); - return repositorySystem.createLocalRepository( repoDir ); + return repositorySystem.createLocalRepository(repoDir); } @Test - public void testThatASystemScopedDependencyIsNotResolvedFromRepositories() - throws Exception - { + public void testThatASystemScopedDependencyIsNotResolvedFromRepositories() throws Exception { // // We should get a whole slew of dependencies resolving this artifact transitively // Dependency d = new Dependency(); - d.setGroupId( "org.apache.maven.its" ); - d.setArtifactId( "b" ); - d.setVersion( "0.1" ); - d.setScope( Artifact.SCOPE_COMPILE ); - Artifact artifact = repositorySystem.createDependencyArtifact( d ); + d.setGroupId("org.apache.maven.its"); + d.setArtifactId("b"); + d.setVersion("0.1"); + d.setScope(Artifact.SCOPE_COMPILE); + Artifact artifact = repositorySystem.createDependencyArtifact(d); ArtifactResolutionRequest request = new ArtifactResolutionRequest() - .setArtifact( artifact ) - .setResolveRoot( true ) - .setResolveTransitively( true ) - .setRemoteRepositories( getRemoteRepositories() ) - .setLocalRepository( getLocalRepository() ); + .setArtifact(artifact) + .setResolveRoot(true) + .setResolveTransitively(true) + .setRemoteRepositories(getRemoteRepositories()) + .setLocalRepository(getLocalRepository()); DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - LocalRepository localRepo = new LocalRepository( request.getLocalRepository().getBasedir() ); - session.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( session, localRepo ) ); - LegacySupport legacySupport = container.lookup( LegacySupport.class ); - legacySupport.setSession( new MavenSession( container, session, new DefaultMavenExecutionRequest(), - new DefaultMavenExecutionResult() ) ); + LocalRepository localRepo = + new LocalRepository(request.getLocalRepository().getBasedir()); + session.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepo)); + LegacySupport legacySupport = container.lookup(LegacySupport.class); + legacySupport.setSession(new MavenSession( + container, session, new DefaultMavenExecutionRequest(), new DefaultMavenExecutionResult())); - ArtifactResolutionResult result = repositorySystem.resolve( request ); - resolutionErrorHandler.throwErrors( request, result ); - assertEquals( 2, result.getArtifacts().size() ); + ArtifactResolutionResult result = repositorySystem.resolve(request); + resolutionErrorHandler.throwErrors(request, result); + assertEquals(2, result.getArtifacts().size()); // // System scoped version which should // - d.setScope( Artifact.SCOPE_SYSTEM ); - File file = new File( getBasedir(), "src/test/repository-system/maven-core-2.1.0.jar" ); - assertTrue( file.exists() ); - d.setSystemPath( file.getCanonicalPath() ); + d.setScope(Artifact.SCOPE_SYSTEM); + File file = new File(getBasedir(), "src/test/repository-system/maven-core-2.1.0.jar"); + assertTrue(file.exists()); + d.setSystemPath(file.getCanonicalPath()); - artifact = repositorySystem.createDependencyArtifact( d ); + artifact = repositorySystem.createDependencyArtifact(d); // - // The request has not set any local or remote repositories as the system scoped dependency being resolved should only + // The request has not set any local or remote repositories as the system scoped dependency being resolved + // should only // give us the dependency off the disk and nothing more. // request = new ArtifactResolutionRequest() - .setArtifact( artifact ) - .setResolveRoot( true ) - .setResolveTransitively( true ); + .setArtifact(artifact) + .setResolveRoot(true) + .setResolveTransitively(true); - result = repositorySystem.resolve( request ); - resolutionErrorHandler.throwErrors( request, result ); - assertEquals( 1, result.getArtifacts().size() ); + result = repositorySystem.resolve(request); + resolutionErrorHandler.throwErrors(request, result); + assertEquals(1, result.getArtifacts().size()); // // Put in a bogus file to make sure missing files cause the resolution to fail. // - file = new File( getBasedir(), "src/test/repository-system/maven-monkey-2.1.0.jar" ); - assertFalse( file.exists() ); - d.setSystemPath( file.getCanonicalPath() ); - artifact = repositorySystem.createDependencyArtifact( d ); + file = new File(getBasedir(), "src/test/repository-system/maven-monkey-2.1.0.jar"); + assertFalse(file.exists()); + d.setSystemPath(file.getCanonicalPath()); + artifact = repositorySystem.createDependencyArtifact(d); // - // The request has not set any local or remote repositories as the system scoped dependency being resolved should only + // The request has not set any local or remote repositories as the system scoped dependency being resolved + // should only // give us the dependency off the disk and nothing more. // request = new ArtifactResolutionRequest() - .setArtifact( artifact ) - .setResolveRoot( true ) - .setResolveTransitively( true ); + .setArtifact(artifact) + .setResolveRoot(true) + .setResolveTransitively(true); - try - { - result = repositorySystem.resolve( request ); - resolutionErrorHandler.throwErrors( request, result ); - } - catch( Exception e ) - { - assertTrue( result.hasMissingArtifacts() ); + try { + result = repositorySystem.resolve(request); + resolutionErrorHandler.throwErrors(request, result); + } catch (Exception e) { + assertTrue(result.hasMissingArtifacts()); } } @Test - public void testLocalRepositoryBasedir() - throws Exception - { - File localRepoDir = new File( "" ).getAbsoluteFile(); + public void testLocalRepositoryBasedir() throws Exception { + File localRepoDir = new File("").getAbsoluteFile(); - ArtifactRepository localRepo = repositorySystem.createLocalRepository( localRepoDir ); + ArtifactRepository localRepo = repositorySystem.createLocalRepository(localRepoDir); String basedir = localRepo.getBasedir(); - assertFalse( basedir.endsWith( "/" ) ); - assertFalse( basedir.endsWith( "\\" ) ); + assertFalse(basedir.endsWith("/")); + assertFalse(basedir.endsWith("\\")); - assertEquals( localRepoDir, new File( basedir ) ); + assertEquals(localRepoDir, new File(basedir)); - assertEquals( localRepoDir.getPath(), basedir ); + assertEquals(localRepoDir.getPath(), basedir); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/MirrorProcessorTest.java b/maven-compat/src/test/java/org/apache/maven/repository/MirrorProcessorTest.java index 9e8ab4e271..6bb6ffff51 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/MirrorProcessorTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/MirrorProcessorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository; * "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 + * 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 @@ -18,27 +16,25 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ - -import java.util.Arrays; -import java.util.List; - -import org.codehaus.plexus.testing.PlexusTest; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; -import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; -import org.apache.maven.settings.Mirror; -import org.junit.jupiter.api.Test; +package org.apache.maven.repository; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Arrays; +import java.util.List; import javax.inject.Inject; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; +import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; +import org.apache.maven.settings.Mirror; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.Test; @PlexusTest -public class MirrorProcessorTest -{ +public class MirrorProcessorTest { @Inject private DefaultMirrorSelector mirrorSelector; @@ -46,176 +42,168 @@ public class MirrorProcessorTest private ArtifactRepositoryFactory repositorySystem; @Test - public void testExternalURL() - { - assertTrue( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://somehost" ) ) ); - assertTrue( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://somehost:9090/somepath" ) ) ); - assertTrue( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "ftp://somehost" ) ) ); - assertTrue( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://192.168.101.1" ) ) ); - assertTrue( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://" ) ) ); + public void testExternalURL() { + assertTrue(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://somehost"))); + assertTrue(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://somehost:9090/somepath"))); + assertTrue(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "ftp://somehost"))); + assertTrue(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://192.168.101.1"))); + assertTrue(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://"))); // these are local - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://localhost:8080" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://127.0.0.1:9090" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "file://localhost/somepath" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "file://localhost/D:/somepath" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://localhost" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "http://127.0.0.1" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "file:///somepath" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "file://D:/somepath" ) ) ); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://localhost:8080"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://127.0.0.1:9090"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "file://localhost/somepath"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "file://localhost/D:/somepath"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://localhost"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "http://127.0.0.1"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "file:///somepath"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "file://D:/somepath"))); // not a proper url so returns false; - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "192.168.101.1" ) ) ); - assertFalse( DefaultMirrorSelector.isExternalRepo( getRepo( "foo", "" ) ) ); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", "192.168.101.1"))); + assertFalse(DefaultMirrorSelector.isExternalRepo(getRepo("foo", ""))); } @Test - public void testMirrorLookup() - { - Mirror mirrorA = newMirror( "a", "a", "http://a" ); - Mirror mirrorB = newMirror( "b", "b", "http://b" ); + public void testMirrorLookup() { + Mirror mirrorA = newMirror("a", "a", "http://a"); + Mirror mirrorB = newMirror("b", "b", "http://b"); - List mirrors = Arrays.asList( mirrorA, mirrorB ); + List mirrors = Arrays.asList(mirrorA, mirrorB); - assertSame( mirrorA, mirrorSelector.getMirror( getRepo( "a", "http://a.a" ), mirrors ) ); + assertSame(mirrorA, mirrorSelector.getMirror(getRepo("a", "http://a.a"), mirrors)); - assertSame( mirrorB, mirrorSelector.getMirror( getRepo( "b", "http://a.a" ), mirrors ) ); + assertSame(mirrorB, mirrorSelector.getMirror(getRepo("b", "http://a.a"), mirrors)); - assertNull( mirrorSelector.getMirror( getRepo( "c", "http://c.c" ), mirrors ) ); + assertNull(mirrorSelector.getMirror(getRepo("c", "http://c.c"), mirrors)); } @Test - public void testMirrorWildcardLookup() - { - Mirror mirrorA = newMirror( "a", "a", "http://a" ); - Mirror mirrorB = newMirror( "b", "b", "http://b" ); - Mirror mirrorC = newMirror( "c", "*", "http://wildcard" ); + public void testMirrorWildcardLookup() { + Mirror mirrorA = newMirror("a", "a", "http://a"); + Mirror mirrorB = newMirror("b", "b", "http://b"); + Mirror mirrorC = newMirror("c", "*", "http://wildcard"); - List mirrors = Arrays.asList( mirrorA, mirrorB, mirrorC ); + List mirrors = Arrays.asList(mirrorA, mirrorB, mirrorC); - assertSame( mirrorA, mirrorSelector.getMirror( getRepo( "a", "http://a.a" ), mirrors ) ); + assertSame(mirrorA, mirrorSelector.getMirror(getRepo("a", "http://a.a"), mirrors)); - assertSame( mirrorB, mirrorSelector.getMirror( getRepo( "b", "http://a.a" ), mirrors ) ); + assertSame(mirrorB, mirrorSelector.getMirror(getRepo("b", "http://a.a"), mirrors)); - assertSame( mirrorC, mirrorSelector.getMirror( getRepo( "c", "http://c.c" ), mirrors ) ); + assertSame(mirrorC, mirrorSelector.getMirror(getRepo("c", "http://c.c"), mirrors)); } @Test - public void testMirrorStopOnFirstMatch() - { + public void testMirrorStopOnFirstMatch() { // exact matches win first - Mirror mirrorA2 = newMirror( "a2", "a,b", "http://a2" ); - Mirror mirrorA = newMirror( "a", "a", "http://a" ); + Mirror mirrorA2 = newMirror("a2", "a,b", "http://a2"); + Mirror mirrorA = newMirror("a", "a", "http://a"); // make sure repeated entries are skipped - Mirror mirrorA3 = newMirror( "a", "a", "http://a3" ); + Mirror mirrorA3 = newMirror("a", "a", "http://a3"); - Mirror mirrorB = newMirror( "b", "b", "http://b" ); - Mirror mirrorC = newMirror( "c", "d,e", "http://de" ); - Mirror mirrorC2 = newMirror( "c", "*", "http://wildcard" ); - Mirror mirrorC3 = newMirror( "c", "e,f", "http://ef" ); + Mirror mirrorB = newMirror("b", "b", "http://b"); + Mirror mirrorC = newMirror("c", "d,e", "http://de"); + Mirror mirrorC2 = newMirror("c", "*", "http://wildcard"); + Mirror mirrorC3 = newMirror("c", "e,f", "http://ef"); - List mirrors = Arrays.asList( mirrorA2, mirrorA, mirrorA3, mirrorB, mirrorC, mirrorC2, mirrorC3 ); + List mirrors = Arrays.asList(mirrorA2, mirrorA, mirrorA3, mirrorB, mirrorC, mirrorC2, mirrorC3); - assertSame( mirrorA, mirrorSelector.getMirror( getRepo( "a", "http://a.a" ), mirrors ) ); + assertSame(mirrorA, mirrorSelector.getMirror(getRepo("a", "http://a.a"), mirrors)); - assertSame( mirrorB, mirrorSelector.getMirror( getRepo( "b", "http://a.a" ), mirrors ) ); + assertSame(mirrorB, mirrorSelector.getMirror(getRepo("b", "http://a.a"), mirrors)); - assertSame( mirrorC2, mirrorSelector.getMirror( getRepo( "c", "http://c.c" ), mirrors ) ); + assertSame(mirrorC2, mirrorSelector.getMirror(getRepo("c", "http://c.c"), mirrors)); - assertSame( mirrorC, mirrorSelector.getMirror( getRepo( "d", "http://d" ), mirrors ) ); + assertSame(mirrorC, mirrorSelector.getMirror(getRepo("d", "http://d"), mirrors)); - assertSame( mirrorC, mirrorSelector.getMirror( getRepo( "e", "http://e" ), mirrors ) ); + assertSame(mirrorC, mirrorSelector.getMirror(getRepo("e", "http://e"), mirrors)); - assertSame( mirrorC2, mirrorSelector.getMirror( getRepo( "f", "http://f" ), mirrors ) ); + assertSame(mirrorC2, mirrorSelector.getMirror(getRepo("f", "http://f"), mirrors)); } @Test - public void testPatterns() - { - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*," ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), ",*," ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*," ) ); + public void testPatterns() { + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "*")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "*,")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), ",*,")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "*,")); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "a" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "a," ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), ",a," ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "a," ) ); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "a")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "a,")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), ",a,")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "a,")); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "b" ), "a" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "b" ), "a," ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "b" ), ",a" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "b" ), ",a," ) ); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("b"), "a")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("b"), "a,")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("b"), ",a")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("b"), ",a,")); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "a,b" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "b" ), "a,b" ) ); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "a,b")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("b"), "a,b")); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "c" ), "a,b" ) ); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("c"), "a,b")); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*,b" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*,!b" ) ); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "*")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "*,b")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a"), "*,!b")); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "*,!a" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "a" ), "!a,*" ) ); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("a"), "*,!a")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("a"), "!a,*")); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "c" ), "*,!a" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "c" ), "!a,*" ) ); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("c"), "*,!a")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("c"), "!a,*")); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "c" ), "!a,!c" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "d" ), "!a,!c*" ) ); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("c"), "!a,!c")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("d"), "!a,!c*")); } @Test - public void testPatternsWithExternal() - { - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a", "http://localhost" ), "*" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "a", "http://localhost" ), "external:*" ) ); + public void testPatternsWithExternal() { + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a", "http://localhost"), "*")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("a", "http://localhost"), "external:*")); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a", "http://localhost" ), "external:*,a" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "a", "http://localhost" ), "external:*,!a" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "a", "http://localhost" ), "a,external:*" ) ); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "a", "http://localhost" ), "!a,external:*" ) ); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a", "http://localhost"), "external:*,a")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("a", "http://localhost"), "external:*,!a")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("a", "http://localhost"), "a,external:*")); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("a", "http://localhost"), "!a,external:*")); - assertFalse( DefaultMirrorSelector.matchPattern( getRepo( "c", "http://localhost" ), "!a,external:*" ) ); - assertTrue( DefaultMirrorSelector.matchPattern( getRepo( "c", "http://somehost" ), "!a,external:*" ) ); + assertFalse(DefaultMirrorSelector.matchPattern(getRepo("c", "http://localhost"), "!a,external:*")); + assertTrue(DefaultMirrorSelector.matchPattern(getRepo("c", "http://somehost"), "!a,external:*")); } @Test - public void testLayoutPattern() - { - assertTrue( DefaultMirrorSelector.matchesLayout( "default", null ) ); - assertTrue( DefaultMirrorSelector.matchesLayout( "default", "" ) ); - assertTrue( DefaultMirrorSelector.matchesLayout( "default", "*" ) ); + public void testLayoutPattern() { + assertTrue(DefaultMirrorSelector.matchesLayout("default", null)); + assertTrue(DefaultMirrorSelector.matchesLayout("default", "")); + assertTrue(DefaultMirrorSelector.matchesLayout("default", "*")); - assertTrue( DefaultMirrorSelector.matchesLayout( "default", "default" ) ); - assertFalse( DefaultMirrorSelector.matchesLayout( "default", "legacy" ) ); + assertTrue(DefaultMirrorSelector.matchesLayout("default", "default")); + assertFalse(DefaultMirrorSelector.matchesLayout("default", "legacy")); - assertTrue( DefaultMirrorSelector.matchesLayout( "default", "legacy,default" ) ); - assertTrue( DefaultMirrorSelector.matchesLayout( "default", "default,legacy" ) ); + assertTrue(DefaultMirrorSelector.matchesLayout("default", "legacy,default")); + assertTrue(DefaultMirrorSelector.matchesLayout("default", "default,legacy")); - assertFalse( DefaultMirrorSelector.matchesLayout( "default", "legacy,!default" ) ); - assertFalse( DefaultMirrorSelector.matchesLayout( "default", "!default,legacy" ) ); + assertFalse(DefaultMirrorSelector.matchesLayout("default", "legacy,!default")); + assertFalse(DefaultMirrorSelector.matchesLayout("default", "!default,legacy")); - assertFalse( DefaultMirrorSelector.matchesLayout( "default", "*,!default" ) ); - assertFalse( DefaultMirrorSelector.matchesLayout( "default", "!default,*" ) ); + assertFalse(DefaultMirrorSelector.matchesLayout("default", "*,!default")); + assertFalse(DefaultMirrorSelector.matchesLayout("default", "!default,*")); } @Test - public void testMirrorLayoutConsideredForMatching() - { - ArtifactRepository repo = getRepo( "a" ); + public void testMirrorLayoutConsideredForMatching() { + ArtifactRepository repo = getRepo("a"); - Mirror mirrorA = newMirror( "a", "a", null, "http://a" ); - Mirror mirrorB = newMirror( "b", "a", "p2", "http://b" ); + Mirror mirrorA = newMirror("a", "a", null, "http://a"); + Mirror mirrorB = newMirror("b", "a", "p2", "http://b"); - Mirror mirrorC = newMirror( "c", "*", null, "http://c" ); - Mirror mirrorD = newMirror( "d", "*", "p2", "http://d" ); + Mirror mirrorC = newMirror("c", "*", null, "http://c"); + Mirror mirrorD = newMirror("d", "*", "p2", "http://d"); - assertSame( mirrorA, mirrorSelector.getMirror( repo, Arrays.asList( mirrorA ) ) ); - assertNull( mirrorSelector.getMirror( repo, Arrays.asList( mirrorB ) ) ); + assertSame(mirrorA, mirrorSelector.getMirror(repo, Arrays.asList(mirrorA))); + assertNull(mirrorSelector.getMirror(repo, Arrays.asList(mirrorB))); - assertSame( mirrorC, mirrorSelector.getMirror( repo, Arrays.asList( mirrorC ) ) ); - assertNull( mirrorSelector.getMirror( repo, Arrays.asList( mirrorD ) ) ); + assertSame(mirrorC, mirrorSelector.getMirror(repo, Arrays.asList(mirrorC))); + assertNull(mirrorSelector.getMirror(repo, Arrays.asList(mirrorD))); } /** @@ -225,9 +213,8 @@ public class MirrorProcessorTest * @param url * @return */ - private ArtifactRepository getRepo( String id, String url ) - { - return repositorySystem.createArtifactRepository( id, url, new DefaultRepositoryLayout(), null, null ); + private ArtifactRepository getRepo(String id, String url) { + return repositorySystem.createArtifactRepository(id, url, new DefaultRepositoryLayout(), null, null); } /** @@ -236,26 +223,22 @@ public class MirrorProcessorTest * @param id * @return */ - private ArtifactRepository getRepo( String id ) - { - return getRepo( id, "http://something" ); + private ArtifactRepository getRepo(String id) { + return getRepo(id, "http://something"); } - private Mirror newMirror( String id, String mirrorOf, String url ) - { - return newMirror( id, mirrorOf, null, url ); + private Mirror newMirror(String id, String mirrorOf, String url) { + return newMirror(id, mirrorOf, null, url); } - private Mirror newMirror( String id, String mirrorOf, String layouts, String url ) - { + private Mirror newMirror(String id, String mirrorOf, String layouts, String url) { Mirror mirror = new Mirror(); - mirror.setId( id ); - mirror.setMirrorOf( mirrorOf ); - mirror.setMirrorOfLayouts( layouts ); - mirror.setUrl( url ); + mirror.setId(id); + mirror.setMirrorOf(mirrorOf); + mirror.setMirrorOfLayouts(layouts); + mirror.setUrl(url); return mirror; } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManagerTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManagerTest.java index 85041ee435..c82bc13b5b 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManagerTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,11 +16,16 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; - import javax.inject.Inject; - import org.apache.maven.artifact.AbstractArtifactComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; @@ -34,15 +37,7 @@ import org.codehaus.plexus.logging.console.ConsoleLogger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class DefaultUpdateCheckManagerTest - extends AbstractArtifactComponentTestCase -{ +public class DefaultUpdateCheckManagerTest extends AbstractArtifactComponentTestCase { @Inject private ArtifactFactory artifactFactory; @@ -50,209 +45,196 @@ public class DefaultUpdateCheckManagerTest DefaultUpdateCheckManager updateCheckManager; @Override - protected String component() - { + protected String component() { return "updateCheckManager"; } @BeforeEach @Override - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - updateCheckManager = new DefaultUpdateCheckManager( new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ) ); + updateCheckManager = new DefaultUpdateCheckManager(new ConsoleLogger(Logger.LEVEL_DEBUG, "test")); } @Test - public void testArtifact() throws Exception - { + public void testArtifact() throws Exception { ArtifactRepository remoteRepository = remoteRepository(); ArtifactRepository localRepository = localRepository(); - Artifact a = createArtifact( "a", "0.0.1-SNAPSHOT" ); - File file = new File( localRepository.getBasedir(), - localRepository.pathOf( a ) ); + Artifact a = createArtifact("a", "0.0.1-SNAPSHOT"); + File file = new File(localRepository.getBasedir(), localRepository.pathOf(a)); file.delete(); - a.setFile( file ); + a.setFile(file); - File touchFile = updateCheckManager.getTouchfile( a ); + File touchFile = updateCheckManager.getTouchfile(a); touchFile.delete(); - assertTrue( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertTrue(updateCheckManager.isUpdateRequired(a, remoteRepository)); file.getParentFile().mkdirs(); file.createNewFile(); - updateCheckManager.touch( a, remoteRepository, null ); + updateCheckManager.touch(a, remoteRepository, null); - assertFalse( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertFalse(updateCheckManager.isUpdateRequired(a, remoteRepository)); - assertNull( updateCheckManager.readLastUpdated( touchFile, - updateCheckManager.getRepositoryKey( remoteRepository ) ) ); + assertNull( + updateCheckManager.readLastUpdated(touchFile, updateCheckManager.getRepositoryKey(remoteRepository))); - assertFalse( updateCheckManager.getTouchfile( a ).exists() ); + assertFalse(updateCheckManager.getTouchfile(a).exists()); } @Test - public void testMissingArtifact() - throws Exception - { + public void testMissingArtifact() throws Exception { ArtifactRepository remoteRepository = remoteRepository(); ArtifactRepository localRepository = localRepository(); - Artifact a = createArtifact( "a", "0.0.1-SNAPSHOT" ); - File file = new File( localRepository.getBasedir(), - localRepository.pathOf( a ) ); + Artifact a = createArtifact("a", "0.0.1-SNAPSHOT"); + File file = new File(localRepository.getBasedir(), localRepository.pathOf(a)); file.delete(); - a.setFile( file ); + a.setFile(file); - File touchFile = updateCheckManager.getTouchfile( a ); + File touchFile = updateCheckManager.getTouchfile(a); touchFile.delete(); - assertTrue( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertTrue(updateCheckManager.isUpdateRequired(a, remoteRepository)); - updateCheckManager.touch( a, remoteRepository, null ); + updateCheckManager.touch(a, remoteRepository, null); - assertFalse( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertFalse(updateCheckManager.isUpdateRequired(a, remoteRepository)); - assertFalse( file.exists() ); - assertNotNull( updateCheckManager.readLastUpdated( touchFile, - updateCheckManager.getRepositoryKey( remoteRepository ) ) ); + assertFalse(file.exists()); + assertNotNull( + updateCheckManager.readLastUpdated(touchFile, updateCheckManager.getRepositoryKey(remoteRepository))); } @Test - public void testPom() throws Exception - { + public void testPom() throws Exception { ArtifactRepository remoteRepository = remoteRepository(); ArtifactRepository localRepository = localRepository(); - Artifact a = createArtifact( "a", "0.0.1", "pom" ); - File file = new File( localRepository.getBasedir(), - localRepository.pathOf( a ) ); + Artifact a = createArtifact("a", "0.0.1", "pom"); + File file = new File(localRepository.getBasedir(), localRepository.pathOf(a)); file.delete(); - a.setFile( file ); + a.setFile(file); - File touchFile = updateCheckManager.getTouchfile( a ); + File touchFile = updateCheckManager.getTouchfile(a); touchFile.delete(); - assertTrue( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertTrue(updateCheckManager.isUpdateRequired(a, remoteRepository)); file.getParentFile().mkdirs(); file.createNewFile(); - updateCheckManager.touch( a, remoteRepository, null ); + updateCheckManager.touch(a, remoteRepository, null); - assertFalse( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertFalse(updateCheckManager.isUpdateRequired(a, remoteRepository)); - assertNull( updateCheckManager.readLastUpdated( touchFile, - updateCheckManager.getRepositoryKey( remoteRepository ) ) ); + assertNull( + updateCheckManager.readLastUpdated(touchFile, updateCheckManager.getRepositoryKey(remoteRepository))); - assertFalse( updateCheckManager.getTouchfile( a ).exists() ); + assertFalse(updateCheckManager.getTouchfile(a).exists()); } @Test - public void testMissingPom() - throws Exception - { + public void testMissingPom() throws Exception { ArtifactRepository remoteRepository = remoteRepository(); ArtifactRepository localRepository = localRepository(); - Artifact a = createArtifact( "a", "0.0.1", "pom" ); - File file = new File( localRepository.getBasedir(), - localRepository.pathOf( a ) ); + Artifact a = createArtifact("a", "0.0.1", "pom"); + File file = new File(localRepository.getBasedir(), localRepository.pathOf(a)); file.delete(); - a.setFile( file ); + a.setFile(file); - File touchFile = updateCheckManager.getTouchfile( a ); + File touchFile = updateCheckManager.getTouchfile(a); touchFile.delete(); - assertTrue( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertTrue(updateCheckManager.isUpdateRequired(a, remoteRepository)); - updateCheckManager.touch( a, remoteRepository, null ); + updateCheckManager.touch(a, remoteRepository, null); - assertFalse( updateCheckManager.isUpdateRequired( a, remoteRepository ) ); + assertFalse(updateCheckManager.isUpdateRequired(a, remoteRepository)); - assertFalse( file.exists() ); - assertNotNull( updateCheckManager.readLastUpdated( touchFile, - updateCheckManager.getRepositoryKey( remoteRepository ) ) ); + assertFalse(file.exists()); + assertNotNull( + updateCheckManager.readLastUpdated(touchFile, updateCheckManager.getRepositoryKey(remoteRepository))); } @Test - public void testMetadata() throws Exception - { + public void testMetadata() throws Exception { ArtifactRepository remoteRepository = remoteRepository(); ArtifactRepository localRepository = localRepository(); - Artifact a = createRemoteArtifact( "a", "0.0.1-SNAPSHOT" ); - RepositoryMetadata metadata = new ArtifactRepositoryMetadata( a ); + Artifact a = createRemoteArtifact("a", "0.0.1-SNAPSHOT"); + RepositoryMetadata metadata = new ArtifactRepositoryMetadata(a); - File file = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( metadata, localRepository ) ); + File file = new File( + localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(metadata, localRepository)); file.delete(); - File touchFile = updateCheckManager.getTouchfile( metadata, file ); + File touchFile = updateCheckManager.getTouchfile(metadata, file); touchFile.delete(); - assertTrue( updateCheckManager.isUpdateRequired( metadata, remoteRepository, file ) ); + assertTrue(updateCheckManager.isUpdateRequired(metadata, remoteRepository, file)); file.getParentFile().mkdirs(); file.createNewFile(); - updateCheckManager.touch( metadata, remoteRepository, file ); + updateCheckManager.touch(metadata, remoteRepository, file); - assertFalse( updateCheckManager.isUpdateRequired( metadata, remoteRepository, file ) ); + assertFalse(updateCheckManager.isUpdateRequired(metadata, remoteRepository, file)); - assertNotNull( updateCheckManager.readLastUpdated( touchFile, updateCheckManager.getMetadataKey( remoteRepository, file ) ) ); + assertNotNull(updateCheckManager.readLastUpdated( + touchFile, updateCheckManager.getMetadataKey(remoteRepository, file))); } @Test - public void testMissingMetadata() throws Exception - { + public void testMissingMetadata() throws Exception { ArtifactRepository remoteRepository = remoteRepository(); ArtifactRepository localRepository = localRepository(); - Artifact a = createRemoteArtifact( "a", "0.0.1-SNAPSHOT" ); - RepositoryMetadata metadata = new ArtifactRepositoryMetadata( a ); + Artifact a = createRemoteArtifact("a", "0.0.1-SNAPSHOT"); + RepositoryMetadata metadata = new ArtifactRepositoryMetadata(a); - File file = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( metadata, localRepository ) ); + File file = new File( + localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(metadata, localRepository)); file.delete(); - File touchFile = updateCheckManager.getTouchfile( metadata, file ); + File touchFile = updateCheckManager.getTouchfile(metadata, file); touchFile.delete(); - assertTrue( updateCheckManager.isUpdateRequired( metadata, remoteRepository, file ) ); + assertTrue(updateCheckManager.isUpdateRequired(metadata, remoteRepository, file)); - updateCheckManager.touch( metadata, remoteRepository, file ); + updateCheckManager.touch(metadata, remoteRepository, file); - assertFalse( updateCheckManager.isUpdateRequired( metadata, remoteRepository, file ) ); + assertFalse(updateCheckManager.isUpdateRequired(metadata, remoteRepository, file)); - assertNotNull( updateCheckManager.readLastUpdated( touchFile, updateCheckManager.getMetadataKey( remoteRepository, file ) ) ); + assertNotNull(updateCheckManager.readLastUpdated( + touchFile, updateCheckManager.getMetadataKey(remoteRepository, file))); } @Test - public void testArtifactTouchFileName() throws Exception - { + public void testArtifactTouchFileName() throws Exception { ArtifactRepository localRepository = localRepository(); - Artifact a = artifactFactory.createArtifactWithClassifier( "groupId", "a", "0.0.1-SNAPSHOT", "jar", null ); - File file = new File( localRepository.getBasedir(), - localRepository.pathOf( a ) ); - a.setFile( file ); + Artifact a = artifactFactory.createArtifactWithClassifier("groupId", "a", "0.0.1-SNAPSHOT", "jar", null); + File file = new File(localRepository.getBasedir(), localRepository.pathOf(a)); + a.setFile(file); - assertEquals( "a-0.0.1-SNAPSHOT.jar.lastUpdated", updateCheckManager.getTouchfile( a ).getName() ); + assertEquals( + "a-0.0.1-SNAPSHOT.jar.lastUpdated", + updateCheckManager.getTouchfile(a).getName()); - a = artifactFactory.createArtifactWithClassifier( "groupId", "a", "0.0.1-SNAPSHOT", "jar", "classifier" ); - file = new File( localRepository.getBasedir(), - localRepository.pathOf( a ) ); - a.setFile( file ); + a = artifactFactory.createArtifactWithClassifier("groupId", "a", "0.0.1-SNAPSHOT", "jar", "classifier"); + file = new File(localRepository.getBasedir(), localRepository.pathOf(a)); + a.setFile(file); - assertEquals( "a-0.0.1-SNAPSHOT-classifier.jar.lastUpdated", updateCheckManager.getTouchfile( a ).getName() ); + assertEquals( + "a-0.0.1-SNAPSHOT-classifier.jar.lastUpdated", + updateCheckManager.getTouchfile(a).getName()); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultWagonManagerTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultWagonManagerTest.java index 14961c10d2..5e1e2a85e0 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultWagonManagerTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/DefaultWagonManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,12 +16,21 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; + +import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.factory.ArtifactFactory; @@ -34,7 +41,6 @@ import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; -import org.codehaus.plexus.testing.PlexusTest; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; import org.apache.maven.wagon.UnsupportedProtocolException; @@ -43,26 +49,16 @@ import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; import org.apache.maven.wagon.observers.AbstractTransferListener; import org.apache.maven.wagon.observers.Debug; +import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.util.FileUtils; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javax.inject.Inject; - /** * @author Michal Maczka */ @PlexusTest -public class DefaultWagonManagerTest -{ +public class DefaultWagonManagerTest { @Inject private WagonManager wagonManager; @@ -75,120 +71,107 @@ public class DefaultWagonManagerTest private ArtifactRepositoryFactory artifactRepositoryFactory; @Test - public void testUnnecessaryRepositoryLookup() - throws Exception - { - Artifact artifact = createTestPomArtifact( "target/test-data/get-missing-pom" ); + public void testUnnecessaryRepositoryLookup() throws Exception { + Artifact artifact = createTestPomArtifact("target/test-data/get-missing-pom"); List repos = new ArrayList<>(); - repos.add( artifactRepositoryFactory.createArtifactRepository( "repo1", "string://url1", - new ArtifactRepositoryLayoutStub(), null, null ) ); - repos.add( artifactRepositoryFactory.createArtifactRepository( "repo2", "string://url2", - new ArtifactRepositoryLayoutStub(), null, null ) ); + repos.add(artifactRepositoryFactory.createArtifactRepository( + "repo1", "string://url1", new ArtifactRepositoryLayoutStub(), null, null)); + repos.add(artifactRepositoryFactory.createArtifactRepository( + "repo2", "string://url2", new ArtifactRepositoryLayoutStub(), null, null)); - StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" ); - wagon.addExpectedContent( repos.get( 0 ).getLayout().pathOf( artifact ), "expected" ); - wagon.addExpectedContent( repos.get( 0 ).getLayout().pathOf( artifact ) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac" ); - wagon.addExpectedContent( repos.get( 1 ).getLayout().pathOf( artifact ), "expected" ); - wagon.addExpectedContent( repos.get( 1 ).getLayout().pathOf( artifact ) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac" ); + StringWagon wagon = (StringWagon) wagonManager.getWagon("string"); + wagon.addExpectedContent(repos.get(0).getLayout().pathOf(artifact), "expected"); + wagon.addExpectedContent( + repos.get(0).getLayout().pathOf(artifact) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac"); + wagon.addExpectedContent(repos.get(1).getLayout().pathOf(artifact), "expected"); + wagon.addExpectedContent( + repos.get(1).getLayout().pathOf(artifact) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac"); - - class TransferListener - extends AbstractTransferListener - { + class TransferListener extends AbstractTransferListener { public List events = new ArrayList<>(); @Override - public void transferInitiated( TransferEvent transferEvent ) - { - events.add( transferEvent ); + public void transferInitiated(TransferEvent transferEvent) { + events.add(transferEvent); } } TransferListener listener = new TransferListener(); - wagonManager.getArtifact( artifact, repos, listener, false ); - assertEquals( 1, listener.events.size() ); + wagonManager.getArtifact(artifact, repos, listener, false); + assertEquals(1, listener.events.size()); } @Test - public void testGetMissingJar() throws TransferFailedException, UnsupportedProtocolException, IOException - { - Artifact artifact = createTestArtifact( "target/test-data/get-missing-jar", "jar" ); + public void testGetMissingJar() throws TransferFailedException, UnsupportedProtocolException, IOException { + Artifact artifact = createTestArtifact("target/test-data/get-missing-jar", "jar"); ArtifactRepository repo = createStringRepo(); - assertThrows( ResourceDoesNotExistException.class, - () -> wagonManager.getArtifact( artifact, repo, null, false ) ); + assertThrows(ResourceDoesNotExistException.class, () -> wagonManager.getArtifact(artifact, repo, null, false)); - assertFalse( artifact.getFile().exists() ); + assertFalse(artifact.getFile().exists()); } @Test - public void testGetMissingJarForced() throws TransferFailedException, UnsupportedProtocolException, IOException - { - Artifact artifact = createTestArtifact( "target/test-data/get-missing-jar", "jar" ); + public void testGetMissingJarForced() throws TransferFailedException, UnsupportedProtocolException, IOException { + Artifact artifact = createTestArtifact("target/test-data/get-missing-jar", "jar"); ArtifactRepository repo = createStringRepo(); - assertThrows( ResourceDoesNotExistException.class, - () -> wagonManager.getArtifact( artifact, repo, null, true ) ); + assertThrows(ResourceDoesNotExistException.class, () -> wagonManager.getArtifact(artifact, repo, null, true)); - assertFalse( artifact.getFile().exists() ); + assertFalse(artifact.getFile().exists()); } @Test public void testGetRemoteJar() - throws TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException, IOException - { - Artifact artifact = createTestArtifact( "target/test-data/get-remote-jar", "jar" ); + throws TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException, IOException { + Artifact artifact = createTestArtifact("target/test-data/get-remote-jar", "jar"); ArtifactRepository repo = createStringRepo(); - StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" ); - wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" ); - wagon.addExpectedContent( repo.getLayout().pathOf( artifact ) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac" ); + StringWagon wagon = (StringWagon) wagonManager.getWagon("string"); + wagon.addExpectedContent(repo.getLayout().pathOf(artifact), "expected"); + wagon.addExpectedContent(repo.getLayout().pathOf(artifact) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac"); - wagonManager.getArtifact( artifact, repo, null, false ); + wagonManager.getArtifact(artifact, repo, null, false); - assertTrue( artifact.getFile().exists() ); - assertEquals( "expected", FileUtils.fileRead( artifact.getFile(), "UTF-8" ) ); + assertTrue(artifact.getFile().exists()); + assertEquals("expected", FileUtils.fileRead(artifact.getFile(), "UTF-8")); } - private Artifact createTestPomArtifact( String directory ) - throws IOException - { - File testData = getTestFile( directory ); - FileUtils.deleteDirectory( testData ); + private Artifact createTestPomArtifact(String directory) throws IOException { + File testData = getTestFile(directory); + FileUtils.deleteDirectory(testData); testData.mkdirs(); - Artifact artifact = artifactFactory.createProjectArtifact( "test", "test", "1.0" ); - artifact.setFile( new File( testData, "test-1.0.pom" ) ); - assertFalse( artifact.getFile().exists() ); + Artifact artifact = artifactFactory.createProjectArtifact("test", "test", "1.0"); + artifact.setFile(new File(testData, "test-1.0.pom")); + assertFalse(artifact.getFile().exists()); return artifact; } - private Artifact createTestArtifact( String directory, String type ) - throws IOException - { - return createTestArtifact( directory, "1.0", type ); + private Artifact createTestArtifact(String directory, String type) throws IOException { + return createTestArtifact(directory, "1.0", type); } - private Artifact createTestArtifact( String directory, String version, String type ) - throws IOException - { - File testData = getTestFile( directory ); - FileUtils.deleteDirectory( testData ); + private Artifact createTestArtifact(String directory, String version, String type) throws IOException { + File testData = getTestFile(directory); + FileUtils.deleteDirectory(testData); testData.mkdirs(); - Artifact artifact = artifactFactory.createBuildArtifact( "test", "test", version, type ); - artifact.setFile( new File( testData, "test-" + version + "." + artifact.getArtifactHandler().getExtension() ) ); - assertFalse( artifact.getFile().exists() ); + Artifact artifact = artifactFactory.createBuildArtifact("test", "test", version, type); + artifact.setFile(new File( + testData, + "test-" + version + "." + artifact.getArtifactHandler().getExtension())); + assertFalse(artifact.getFile().exists()); return artifact; } - private ArtifactRepository createStringRepo() - { - return artifactRepositoryFactory.createArtifactRepository( "id", "string://url", new ArtifactRepositoryLayoutStub(), null, null ); + private ArtifactRepository createStringRepo() { + return artifactRepositoryFactory.createArtifactRepository( + "id", "string://url", new ArtifactRepositoryLayoutStub(), null, null); } /** @@ -198,9 +181,8 @@ public class DefaultWagonManagerTest * @param url * @return */ - private ArtifactRepository getRepo( String id, String url ) - { - return artifactRepositoryFactory.createArtifactRepository( id, url, new DefaultRepositoryLayout(), null, null ); + private ArtifactRepository getRepo(String id, String url) { + return artifactRepositoryFactory.createArtifactRepository(id, url, new DefaultRepositoryLayout(), null, null); } /** @@ -209,55 +191,54 @@ public class DefaultWagonManagerTest * @param id * @return */ - private ArtifactRepository getRepo( String id ) - { - return getRepo( id, "http://something" ); + private ArtifactRepository getRepo(String id) { + return getRepo(id, "http://something"); } @Test - public void testDefaultWagonManager() - throws Exception - { - assertWagon( "a" ); + public void testDefaultWagonManager() throws Exception { + assertWagon("a"); - assertWagon( "b" ); + assertWagon("b"); - assertWagon( "c" ); + assertWagon("c"); - assertWagon( "string" ); + assertWagon("string"); - assertThrows( UnsupportedProtocolException.class, () -> assertWagon( "d" ) ); + assertThrows(UnsupportedProtocolException.class, () -> assertWagon("d")); } /** * Check that transfer listeners are properly removed after getArtifact and putArtifact */ @Test - public void testWagonTransferListenerRemovedAfterGetArtifactAndPutArtifact() - throws Exception - { - Artifact artifact = createTestArtifact( "target/test-data/transfer-listener", "jar" ); + public void testWagonTransferListenerRemovedAfterGetArtifactAndPutArtifact() throws Exception { + Artifact artifact = createTestArtifact("target/test-data/transfer-listener", "jar"); ArtifactRepository repo = createStringRepo(); - StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" ); - wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" ); - wagon.addExpectedContent( repo.getLayout().pathOf( artifact ) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac" ); + StringWagon wagon = (StringWagon) wagonManager.getWagon("string"); + wagon.addExpectedContent(repo.getLayout().pathOf(artifact), "expected"); + wagon.addExpectedContent(repo.getLayout().pathOf(artifact) + ".md5", "cd26d9e10ce691cc69aa2b90dcebbdac"); /* getArtifact */ - assertFalse( wagon.getTransferEventSupport().hasTransferListener( transferListener ), - "Transfer listener is registered before test" ); - wagonManager.getArtifact( artifact, repo, transferListener, false ); - assertFalse( wagon.getTransferEventSupport().hasTransferListener( transferListener ), - "Transfer listener still registered after getArtifact" ); + assertFalse( + wagon.getTransferEventSupport().hasTransferListener(transferListener), + "Transfer listener is registered before test"); + wagonManager.getArtifact(artifact, repo, transferListener, false); + assertFalse( + wagon.getTransferEventSupport().hasTransferListener(transferListener), + "Transfer listener still registered after getArtifact"); /* putArtifact */ - File sampleFile = getTestFile( "target/test-file" ); - FileUtils.fileWrite( sampleFile.getAbsolutePath(), "sample file" ); + File sampleFile = getTestFile("target/test-file"); + FileUtils.fileWrite(sampleFile.getAbsolutePath(), "sample file"); - assertFalse( wagon.getTransferEventSupport().hasTransferListener( transferListener ), - "Transfer listener is registered before test" ); - wagonManager.putArtifact( sampleFile, artifact, repo, transferListener ); - assertFalse( wagon.getTransferEventSupport().hasTransferListener( transferListener ), - "Transfer listener still registered after putArtifact" ); + assertFalse( + wagon.getTransferEventSupport().hasTransferListener(transferListener), + "Transfer listener is registered before test"); + wagonManager.putArtifact(sampleFile, artifact, repo, transferListener); + assertFalse( + wagon.getTransferEventSupport().hasTransferListener(transferListener), + "Transfer listener still registered after putArtifact"); } /** @@ -265,99 +246,93 @@ public class DefaultWagonManagerTest */ @Disabled @Test - public void testChecksumVerification() - throws Exception - { - ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy( true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL ); + public void testChecksumVerification() throws Exception { + ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy( + true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL); - ArtifactRepository repo = artifactRepositoryFactory.createArtifactRepository( "id", "string://url", new ArtifactRepositoryLayoutStub(), policy, policy ); + ArtifactRepository repo = artifactRepositoryFactory.createArtifactRepository( + "id", "string://url", new ArtifactRepositoryLayoutStub(), policy, policy); - Artifact artifact = - new DefaultArtifact( "sample.group", "sample-art", VersionRange.createFromVersion( "1.0" ), "scope", - "jar", "classifier", null ); - artifact.setFile( getTestFile( "target/sample-art" ) ); + Artifact artifact = new DefaultArtifact( + "sample.group", + "sample-art", + VersionRange.createFromVersion("1.0"), + "scope", + "jar", + "classifier", + null); + artifact.setFile(getTestFile("target/sample-art")); - StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" ); + StringWagon wagon = (StringWagon) wagonManager.getWagon("string"); wagon.clearExpectedContent(); - wagon.addExpectedContent( "path", "lower-case-checksum" ); - wagon.addExpectedContent( "path.sha1", "2a25dc564a3b34f68237fc849066cbc7bb7a36a1" ); - wagonManager.getArtifact( artifact, repo, null, false ); + wagon.addExpectedContent("path", "lower-case-checksum"); + wagon.addExpectedContent("path.sha1", "2a25dc564a3b34f68237fc849066cbc7bb7a36a1"); + wagonManager.getArtifact(artifact, repo, null, false); wagon.clearExpectedContent(); - wagon.addExpectedContent( "path", "upper-case-checksum" ); - wagon.addExpectedContent( "path.sha1", "B7BB97D7D0B9244398D9B47296907F73313663E6" ); - wagonManager.getArtifact( artifact, repo, null, false ); + wagon.addExpectedContent("path", "upper-case-checksum"); + wagon.addExpectedContent("path.sha1", "B7BB97D7D0B9244398D9B47296907F73313663E6"); + wagonManager.getArtifact(artifact, repo, null, false); wagon.clearExpectedContent(); - wagon.addExpectedContent( "path", "expected-failure" ); - wagon.addExpectedContent( "path.sha1", "b7bb97d7d0b9244398d9b47296907f73313663e6" ); - assertThrows( - ChecksumFailedException.class, () -> - wagonManager.getArtifact( artifact, repo, null, false ), - "Checksum verification did not fail" ); - - wagon.clearExpectedContent(); - wagon.addExpectedContent( "path", "lower-case-checksum" ); - wagon.addExpectedContent( "path.md5", "50b2cf50a103a965efac62b983035cac" ); - wagonManager.getArtifact( artifact, repo, null, false ); - - wagon.clearExpectedContent(); - wagon.addExpectedContent( "path", "upper-case-checksum" ); - wagon.addExpectedContent( "path.md5", "842F568FCCFEB7E534DC72133D42FFDC" ); - wagonManager.getArtifact( artifact, repo, null, false ); - - wagon.clearExpectedContent(); - wagon.addExpectedContent( "path", "expected-failure" ); - wagon.addExpectedContent( "path.md5", "b7bb97d7d0b9244398d9b47296907f73313663e6" ); + wagon.addExpectedContent("path", "expected-failure"); + wagon.addExpectedContent("path.sha1", "b7bb97d7d0b9244398d9b47296907f73313663e6"); assertThrows( ChecksumFailedException.class, - () -> wagonManager.getArtifact( artifact, repo, null, false ), - "Checksum verification did not fail" ); + () -> wagonManager.getArtifact(artifact, repo, null, false), + "Checksum verification did not fail"); + + wagon.clearExpectedContent(); + wagon.addExpectedContent("path", "lower-case-checksum"); + wagon.addExpectedContent("path.md5", "50b2cf50a103a965efac62b983035cac"); + wagonManager.getArtifact(artifact, repo, null, false); + + wagon.clearExpectedContent(); + wagon.addExpectedContent("path", "upper-case-checksum"); + wagon.addExpectedContent("path.md5", "842F568FCCFEB7E534DC72133D42FFDC"); + wagonManager.getArtifact(artifact, repo, null, false); + + wagon.clearExpectedContent(); + wagon.addExpectedContent("path", "expected-failure"); + wagon.addExpectedContent("path.md5", "b7bb97d7d0b9244398d9b47296907f73313663e6"); + assertThrows( + ChecksumFailedException.class, + () -> wagonManager.getArtifact(artifact, repo, null, false), + "Checksum verification did not fail"); } @Test - public void testPerLookupInstantiation() - throws Exception - { + public void testPerLookupInstantiation() throws Exception { String protocol = "perlookup"; - Wagon one = wagonManager.getWagon( protocol ); - Wagon two = wagonManager.getWagon( protocol ); + Wagon one = wagonManager.getWagon(protocol); + Wagon two = wagonManager.getWagon(protocol); - assertNotSame( one, two ); + assertNotSame(one, two); } - private void assertWagon( String protocol ) - throws Exception - { - Wagon wagon = wagonManager.getWagon( protocol ); + private void assertWagon(String protocol) throws Exception { + Wagon wagon = wagonManager.getWagon(protocol); - assertNotNull( wagon, "Check wagon, protocol=" + protocol ); + assertNotNull(wagon, "Check wagon, protocol=" + protocol); } - private final class ArtifactRepositoryLayoutStub - implements ArtifactRepositoryLayout - { - public String getId() - { + private final class ArtifactRepositoryLayoutStub implements ArtifactRepositoryLayout { + public String getId() { return "test"; } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata metadata ) - { + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) { return "path"; } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { return "path"; } - public String pathOf( Artifact artifact ) - { + public String pathOf(Artifact artifact) { return "path"; } } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/LegacyRepositorySystemTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/LegacyRepositorySystemTest.java index ab93995043..b983db1f90 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/LegacyRepositorySystemTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/LegacyRepositorySystemTest.java @@ -1,23 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.repository.legacy; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.util.Arrays; - +import javax.inject.Inject; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.Authentication; import org.apache.maven.repository.RepositorySystem; @@ -25,46 +31,36 @@ import org.apache.maven.settings.Server; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import javax.inject.Inject; - /** * Tests {@link LegacyRepositorySystem}. * * @author Benjamin Bentmann */ @PlexusTest -public class LegacyRepositorySystemTest -{ +public class LegacyRepositorySystemTest { @Inject private RepositorySystem repositorySystem; @Test - public void testThatLocalRepositoryWithSpacesIsProperlyHandled() - throws Exception - { - File basedir = new File( "target/spacy path" ).getAbsoluteFile(); - ArtifactRepository repo = repositorySystem.createLocalRepository( basedir ); - assertEquals( basedir, new File( repo.getBasedir() ) ); + public void testThatLocalRepositoryWithSpacesIsProperlyHandled() throws Exception { + File basedir = new File("target/spacy path").getAbsoluteFile(); + ArtifactRepository repo = repositorySystem.createLocalRepository(basedir); + assertEquals(basedir, new File(repo.getBasedir())); } @Test - public void testAuthenticationHandling() - { + public void testAuthenticationHandling() { Server server = new Server(); - server.setId( "repository" ); - server.setUsername( "jason" ); - server.setPassword( "abc123" ); + server.setId("repository"); + server.setUsername("jason"); + server.setPassword("abc123"); ArtifactRepository repository = - repositorySystem.createArtifactRepository( "repository", "http://foo", null, null, null ); - repositorySystem.injectAuthentication( Arrays.asList( repository ), Arrays.asList( server ) ); + repositorySystem.createArtifactRepository("repository", "http://foo", null, null, null); + repositorySystem.injectAuthentication(Arrays.asList(repository), Arrays.asList(server)); Authentication authentication = repository.getAuthentication(); - assertNotNull( authentication ); - assertEquals( "jason", authentication.getUsername() ); - assertEquals( "abc123", authentication.getPassword() ); + assertNotNull(authentication); + assertEquals("jason", authentication.getUsername()); + assertEquals("abc123", authentication.getPassword()); } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/PerLookupWagon.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/PerLookupWagon.java index 26a68b41ca..9d4b5d3e0d 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/PerLookupWagon.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/PerLookupWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,20 +16,17 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import javax.inject.Named; /** * Wagon with per-lookup instantiation strategy. */ -@Named( "perlookup" ) -public class PerLookupWagon - extends WagonMock -{ +@Named("perlookup") +public class PerLookupWagon extends WagonMock { - public String[] getSupportedProtocols() - { - return new String[] { "perlookup" }; + public String[] getSupportedProtocols() { + return new String[] {"perlookup"}; } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/StringWagon.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/StringWagon.java index 00be1626dc..7955bb7aed 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/StringWagon.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/StringWagon.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,13 +16,15 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.InputData; import org.apache.maven.wagon.OutputData; @@ -35,68 +35,48 @@ import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.resource.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -@Named( "string" ) +@Named("string") @Singleton -public class StringWagon - extends StreamWagon -{ +public class StringWagon extends StreamWagon { private Map expectedContent = new HashMap<>(); - public void addExpectedContent( String resourceName, String expectedContent ) - { - this.expectedContent.put( resourceName, expectedContent ); + public void addExpectedContent(String resourceName, String expectedContent) { + this.expectedContent.put(resourceName, expectedContent); } - public String[] getSupportedProtocols() - { - return new String[] { "string" }; + public String[] getSupportedProtocols() { + return new String[] {"string"}; } @Override - public void closeConnection() - throws ConnectionException - { - } + public void closeConnection() throws ConnectionException {} @Override - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + public void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = inputData.getResource(); - String content = expectedContent.get( resource.getName() ); + String content = expectedContent.get(resource.getName()); - if ( content != null ) - { - resource.setContentLength( content.length() ); - resource.setLastModified( System.currentTimeMillis() ); + if (content != null) { + resource.setContentLength(content.length()); + resource.setLastModified(System.currentTimeMillis()); - inputData.setInputStream( new ByteArrayInputStream( content.getBytes( StandardCharsets.UTF_8 ) ) ); - } - else - { - throw new ResourceDoesNotExistException( "No content provided for " + resource.getName() ); + inputData.setInputStream(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))); + } else { + throw new ResourceDoesNotExistException("No content provided for " + resource.getName()); } } @Override - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - outputData.setOutputStream( new ByteArrayOutputStream() ); + public void fillOutputData(OutputData outputData) throws TransferFailedException { + outputData.setOutputStream(new ByteArrayOutputStream()); } @Override - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - } + protected void openConnectionInternal() throws ConnectionException, AuthenticationException {} - public void clearExpectedContent() - { + public void clearExpectedContent() { expectedContent.clear(); } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonA.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonA.java index dbab864767..949c3fd642 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonA.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonA.java @@ -1,4 +1,3 @@ -package org.apache.maven.repository.legacy; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -17,6 +16,8 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; + import javax.inject.Named; import javax.inject.Singleton; @@ -26,13 +27,10 @@ import javax.inject.Singleton; * @author Carlos Sanchez * @author Jason van Zyl */ -@Named( "a" ) +@Named("a") @Singleton -public class WagonA - extends WagonMock -{ - public String[] getSupportedProtocols() - { - return new String[]{ "a" }; +public class WagonA extends WagonMock { + public String[] getSupportedProtocols() { + return new String[] {"a"}; } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonB.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonB.java index c08381113c..db488723e2 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonB.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonB.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import javax.inject.Named; import javax.inject.Singleton; @@ -28,13 +27,10 @@ import javax.inject.Singleton; * @author Carlos Sanchez * @author Jason van Zyl */ -@Named( "b" ) +@Named("b") @Singleton -public class WagonB - extends WagonMock -{ - public String[] getSupportedProtocols() - { - return new String[]{ "b1", "b2" }; +public class WagonB extends WagonMock { + public String[] getSupportedProtocols() { + return new String[] {"b1", "b2"}; } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonC.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonC.java index 29aa1de016..9192621f5c 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonC.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonC.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import javax.inject.Named; import javax.inject.Singleton; @@ -28,13 +27,10 @@ import javax.inject.Singleton; * @author Carlos Sanchez * @author Jason van Zyl */ -@Named( "c" ) +@Named("c") @Singleton -public class WagonC - extends WagonMock -{ - public String[] getSupportedProtocols() - { - return new String[]{ "c" }; +public class WagonC extends WagonMock { + public String[] getSupportedProtocols() { + return new String[] {"c"}; } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonMock.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonMock.java index c5163609b0..f5f66a2b06 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonMock.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/WagonMock.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy; import org.apache.maven.wagon.providers.file.FileWagon; @@ -26,9 +25,7 @@ import org.apache.maven.wagon.providers.file.FileWagon; * * @author Carlos Sanchez */ -public class WagonMock - extends FileWagon -{ +public class WagonMock extends FileWagon { /** * A field that can be configured in the Wagon @@ -37,14 +34,11 @@ public class WagonMock */ private String configurableField = null; - public void setConfigurableField( String configurableField ) - { + public void setConfigurableField(String configurableField) { this.configurableField = configurableField; } - public String getConfigurableField() - { + public String getConfigurableField() { return configurableField; } - } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/DefaultArtifactCollectorTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/DefaultArtifactCollectorTest.java index 56018d39b2..bd1f570ef1 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/DefaultArtifactCollectorTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/DefaultArtifactCollectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver; * "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 + * 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 @@ -18,6 +16,12 @@ package org.apache.maven.repository.legacy.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -28,9 +32,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; @@ -54,19 +56,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Test the default artifact collector. * * @author Brett Porter */ @PlexusTest -public class DefaultArtifactCollectorTest -{ +public class DefaultArtifactCollectorTest { @Inject private LegacyArtifactCollector artifactCollector; @@ -80,628 +76,602 @@ public class DefaultArtifactCollectorTest private static final String GROUP_ID = "test"; @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { source = new Source(); - projectArtifact = createArtifactSpec( "project", "1.0", null ); + projectArtifact = createArtifactSpec("project", "1.0", null); } @Test @Disabled("works, but we don't fail on cycles presently") public void testCircularDependencyNotIncludingCurrentProject() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - b.addDependency( "a", "1.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + b.addDependency("a", "1.0"); assertThrows( CyclicDependencyException.class, - () -> collect( a ), - "Should have failed on cyclic dependency not involving project" ); + () -> collect(a), + "Should have failed on cyclic dependency not involving project"); } @Test @Disabled("works, but we don't fail on cycles presently") public void testCircularDependencyIncludingCurrentProject() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - b.addDependency( "project", "1.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + b.addDependency("project", "1.0"); assertThrows( CyclicDependencyException.class, - () -> collect( a ), - "Should have failed on cyclic dependency not involving project" ); + () -> collect(a), + "Should have failed on cyclic dependency not involving project"); } @Test - public void testResolveWithFilter() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - ArtifactSpec c = a.addDependency( "c", "3.0" ); + public void testResolveWithFilter() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + ArtifactSpec c = a.addDependency("c", "3.0"); - b.addDependency( "c", "2.0" ); - ArtifactSpec d = b.addDependency( "d", "4.0" ); + b.addDependency("c", "2.0"); + ArtifactSpec d = b.addDependency("d", "4.0"); - ArtifactResolutionResult res = collect( a ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, c.artifact, d.artifact } ), res.getArtifacts(), - "Check artifact list" ); + ArtifactResolutionResult res = collect(a); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, c.artifact, d.artifact}), + res.getArtifacts(), + "Check artifact list"); - ArtifactFilter filter = new ExclusionSetFilter( new String[] { "b" } ); - res = collect( a, filter ); - assertEquals( createSet( new Object[] { a.artifact, c.artifact } ), res.getArtifacts(), "Check artifact list" ); + ArtifactFilter filter = new ExclusionSetFilter(new String[] {"b"}); + res = collect(a, filter); + assertEquals(createSet(new Object[] {a.artifact, c.artifact}), res.getArtifacts(), "Check artifact list"); } @Test public void testResolveCorrectDependenciesWhenDifferentDependenciesOnNearest() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - ArtifactSpec c2 = b.addDependency( "c", "2.0" ); - c2.addDependency( "d", "1.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + ArtifactSpec c2 = b.addDependency("c", "2.0"); + c2.addDependency("d", "1.0"); - ArtifactSpec e = createArtifactSpec( "e", "1.0" ); - ArtifactSpec c1 = e.addDependency( "c", "1.0" ); - ArtifactSpec f = c1.addDependency( "f", "1.0" ); + ArtifactSpec e = createArtifactSpec("e", "1.0"); + ArtifactSpec c1 = e.addDependency("c", "1.0"); + ArtifactSpec f = c1.addDependency("f", "1.0"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, e.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, e.artifact, c1.artifact, f.artifact } ), - res.getArtifacts(), "Check artifact list" ); - assertEquals( "1.0", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, e.artifact})); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, e.artifact, c1.artifact, f.artifact}), + res.getArtifacts(), + "Check artifact list"); + assertEquals("1.0", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test @Disabled public void testResolveCorrectDependenciesWhenDifferentDependenciesOnNewest() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { + throws ArtifactResolutionException, InvalidVersionSpecificationException { // TODO use newest conflict resolver - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - ArtifactSpec c2 = b.addDependency( "c", "2.0" ); - ArtifactSpec d = c2.addDependency( "d", "1.0" ); + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + ArtifactSpec c2 = b.addDependency("c", "2.0"); + ArtifactSpec d = c2.addDependency("d", "1.0"); - ArtifactSpec e = createArtifactSpec( "e", "1.0" ); - ArtifactSpec c1 = e.addDependency( "c", "1.0" ); - c1.addDependency( "f", "1.0" ); + ArtifactSpec e = createArtifactSpec("e", "1.0"); + ArtifactSpec c1 = e.addDependency("c", "1.0"); + c1.addDependency("f", "1.0"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, e.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, e.artifact, c2.artifact, d.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "2.0", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, e.artifact})); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, e.artifact, c2.artifact, d.artifact}), + res.getArtifacts(), + "Check artifact list"); + assertEquals("2.0", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test @Disabled public void testResolveCorrectDependenciesWhenDifferentDependenciesOnNewestVersionReplaced() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { + throws ArtifactResolutionException, InvalidVersionSpecificationException { // TODO use newest conflict resolver - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b1 = a.addDependency( "b", "1.0" ); - ArtifactSpec c = a.addDependency( "c", "1.0" ); - ArtifactSpec d2 = b1.addDependency( "d", "2.0" ); - d2.addDependency( "h", "1.0" ); - ArtifactSpec d1 = c.addDependency( "d", "1.0" ); - ArtifactSpec b2 = c.addDependency( "b", "2.0" ); - ArtifactSpec e = b2.addDependency( "e", "1.0" ); - ArtifactSpec g = d1.addDependency( "g", "1.0" ); + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b1 = a.addDependency("b", "1.0"); + ArtifactSpec c = a.addDependency("c", "1.0"); + ArtifactSpec d2 = b1.addDependency("d", "2.0"); + d2.addDependency("h", "1.0"); + ArtifactSpec d1 = c.addDependency("d", "1.0"); + ArtifactSpec b2 = c.addDependency("b", "2.0"); + ArtifactSpec e = b2.addDependency("e", "1.0"); + ArtifactSpec g = d1.addDependency("g", "1.0"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact } ) ); - Object[] artifacts = new Object[] { a.artifact, c.artifact, d1.artifact, b2.artifact, e.artifact, g.artifact }; - assertEquals( createSet( artifacts ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "1.0", getArtifact( "d", res.getArtifacts() ).getVersion(), "Check version" ); - assertEquals( "2.0", getArtifact( "b", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact})); + Object[] artifacts = new Object[] {a.artifact, c.artifact, d1.artifact, b2.artifact, e.artifact, g.artifact}; + assertEquals(createSet(artifacts), res.getArtifacts(), "Check artifact list"); + assertEquals("1.0", getArtifact("d", res.getArtifacts()).getVersion(), "Check version"); + assertEquals("2.0", getArtifact("b", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testResolveNearestNewestIsNearest() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - ArtifactSpec c = a.addDependency( "c", "3.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + ArtifactSpec c = a.addDependency("c", "3.0"); - b.addDependency( "c", "2.0" ); + b.addDependency("c", "2.0"); - ArtifactResolutionResult res = collect( a ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, c.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "3.0", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(a); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, c.artifact}), + res.getArtifacts(), + "Check artifact list"); + assertEquals("3.0", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testResolveNearestOldestIsNearest() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - ArtifactSpec c = a.addDependency( "c", "2.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + ArtifactSpec c = a.addDependency("c", "2.0"); - b.addDependency( "c", "3.0" ); + b.addDependency("c", "3.0"); - ArtifactResolutionResult res = collect( a ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, c.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "2.0", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(a); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, c.artifact}), + res.getArtifacts(), + "Check artifact list"); + assertEquals("2.0", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testResolveLocalNewestIsLocal() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - a.addDependency( "b", "2.0" ); - ArtifactSpec b = createArtifactSpec( "b", "3.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + a.addDependency("b", "2.0"); + ArtifactSpec b = createArtifactSpec("b", "3.0"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "3.0", getArtifact( "b", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); + assertEquals("3.0", getArtifact("b", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testResolveLocalOldestIsLocal() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - a.addDependency( "b", "3.0" ); - ArtifactSpec b = createArtifactSpec( "b", "2.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + a.addDependency("b", "3.0"); + ArtifactSpec b = createArtifactSpec("b", "2.0"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "2.0", getArtifact( "b", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); + assertEquals("2.0", getArtifact("b", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testResolveLocalWithNewerVersionButLesserScope() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "commons-logging", "1.0" ); - a.addDependency( "junit", "3.7" ); - ArtifactSpec b = createArtifactSpec( "junit", "3.8.1", Artifact.SCOPE_TEST ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("commons-logging", "1.0"); + a.addDependency("junit", "3.7"); + ArtifactSpec b = createArtifactSpec("junit", "3.8.1", Artifact.SCOPE_TEST); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "3.8.1", getArtifact( "junit", res.getArtifacts() ).getVersion(), "Check version" ); - assertEquals( Artifact.SCOPE_TEST, getArtifact( "junit", res.getArtifacts() ).getScope(), "Check artifactScope" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); + assertEquals("3.8.1", getArtifact("junit", res.getArtifacts()).getVersion(), "Check version"); + assertEquals( + Artifact.SCOPE_TEST, getArtifact("junit", res.getArtifacts()).getScope(), "Check artifactScope"); } @Test public void testResolveLocalWithNewerVersionButLesserScopeResolvedFirst() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec b = createArtifactSpec( "junit", "3.8.1", Artifact.SCOPE_TEST ); - ArtifactSpec a = createArtifactSpec( "commons-logging", "1.0" ); - a.addDependency( "junit", "3.7" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec b = createArtifactSpec("junit", "3.8.1", Artifact.SCOPE_TEST); + ArtifactSpec a = createArtifactSpec("commons-logging", "1.0"); + a.addDependency("junit", "3.7"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "3.8.1", getArtifact( "junit", res.getArtifacts() ).getVersion(), "Check version" ); - assertEquals( Artifact.SCOPE_TEST, getArtifact( "junit", res.getArtifacts() ).getScope(), "Check artifactScope" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); + assertEquals("3.8.1", getArtifact("junit", res.getArtifacts()).getVersion(), "Check version"); + assertEquals( + Artifact.SCOPE_TEST, getArtifact("junit", res.getArtifacts()).getScope(), "Check artifactScope"); } @Test public void testResolveNearestWithRanges() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - ArtifactSpec c = a.addDependency( "c", "2.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + ArtifactSpec c = a.addDependency("c", "2.0"); - b.addDependency( "c", "[1.0,3.0]" ); + b.addDependency("c", "[1.0,3.0]"); - ArtifactResolutionResult res = collect( a ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, c.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "2.0", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(a); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, c.artifact}), + res.getArtifacts(), + "Check artifact list"); + assertEquals("2.0", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testResolveRangeWithManagedVersion() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "[1.0,3.0]" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "[1.0,3.0]"); - ArtifactSpec managedB = createArtifactSpec( "b", "5.0" ); + ArtifactSpec managedB = createArtifactSpec("b", "5.0"); - ArtifactResolutionResult res = collect( a, managedB.artifact ); - assertEquals( createSet( new Object[] { a.artifact, managedB.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "5.0", getArtifact( "b", res.getArtifacts() ).getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(a, managedB.artifact); + assertEquals( + createSet(new Object[] {a.artifact, managedB.artifact}), res.getArtifacts(), "Check artifact list"); + assertEquals("5.0", getArtifact("b", res.getArtifacts()).getVersion(), "Check version"); } @Test - public void testCompatibleRanges() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - a.addDependency( "c", "[2.0,2.5]" ); - b.addDependency( "c", "[1.0,3.0]" ); - ArtifactSpec c = createArtifactSpec( "c", "2.5" ); + public void testCompatibleRanges() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + a.addDependency("c", "[2.0,2.5]"); + b.addDependency("c", "[1.0,3.0]"); + ArtifactSpec c = createArtifactSpec("c", "2.5"); - ArtifactResolutionResult res = collect( a ); + ArtifactResolutionResult res = collect(a); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, c.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "2.5", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, c.artifact}), + res.getArtifacts(), + "Check artifact list"); + assertEquals("2.5", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test - public void testIncompatibleRanges() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - a.addDependency( "c", "[2.4,3.0]" ); + public void testIncompatibleRanges() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + a.addDependency("c", "[2.4,3.0]"); - b.addDependency( "c", "[1.0,2.0]" ); + b.addDependency("c", "[1.0,2.0]"); - ArtifactResolutionResult res = collect( a ); + ArtifactResolutionResult res = collect(a); - assertTrue( res.hasVersionRangeViolations() ); + assertTrue(res.hasVersionRangeViolations()); } @Test public void testUnboundedRangeWhenVersionUnavailable() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = a.addDependency( "b", "1.0" ); - a.addDependency( "c", "[2.0,]" ); - b.addDependency( "c", "[1.0,]" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = a.addDependency("b", "1.0"); + a.addDependency("c", "[2.0,]"); + b.addDependency("c", "[1.0,]"); - ArtifactResolutionResult res = collect( a ); + ArtifactResolutionResult res = collect(a); - assertTrue( res.hasVersionRangeViolations() ); + assertTrue(res.hasVersionRangeViolations()); } @Test public void testUnboundedRangeBelowLastRelease() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - createArtifactSpec( "c", "1.5" ); - ArtifactSpec c = createArtifactSpec( "c", "2.0" ); - createArtifactSpec( "c", "1.1" ); - a.addDependency( "c", "[1.0,)" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + createArtifactSpec("c", "1.5"); + ArtifactSpec c = createArtifactSpec("c", "2.0"); + createArtifactSpec("c", "1.1"); + a.addDependency("c", "[1.0,)"); - ArtifactResolutionResult res = collect( a ); + ArtifactResolutionResult res = collect(a); - assertEquals( createSet( new Object[] { a.artifact, c.artifact } ), res.getArtifacts(), "Check artifact list" ); - assertEquals( "2.0", getArtifact( "c", res.getArtifacts() ).getVersion(), "Check version" ); + assertEquals(createSet(new Object[] {a.artifact, c.artifact}), res.getArtifacts(), "Check artifact list"); + assertEquals("2.0", getArtifact("c", res.getArtifacts()).getVersion(), "Check version"); } @Test public void testUnboundedRangeAboveLastRelease() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - createArtifactSpec( "c", "2.0" ); - a.addDependency( "c", "[10.0,)" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + createArtifactSpec("c", "2.0"); + a.addDependency("c", "[10.0,)"); - ArtifactResolutionResult res = collect( a ); + ArtifactResolutionResult res = collect(a); - assertTrue( res.hasVersionRangeViolations() ); + assertTrue(res.hasVersionRangeViolations()); } @Test - public void testResolveManagedVersion() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - a.addDependency( "b", "3.0", Artifact.SCOPE_RUNTIME ); + public void testResolveManagedVersion() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + a.addDependency("b", "3.0", Artifact.SCOPE_RUNTIME); - Artifact managedVersion = createArtifactSpec( "b", "5.0" ).artifact; - Artifact modifiedB = createArtifactSpec( "b", "5.0", Artifact.SCOPE_RUNTIME ).artifact; + Artifact managedVersion = createArtifactSpec("b", "5.0").artifact; + Artifact modifiedB = createArtifactSpec("b", "5.0", Artifact.SCOPE_RUNTIME).artifact; - ArtifactResolutionResult res = collect( a, managedVersion ); - assertEquals( createSet( new Object[] { a.artifact, modifiedB } ), res.getArtifacts(), "Check artifact list" ); + ArtifactResolutionResult res = collect(a, managedVersion); + assertEquals(createSet(new Object[] {a.artifact, modifiedB}), res.getArtifacts(), "Check artifact list"); } @Test public void testCollectChangesVersionOfOriginatingArtifactIfInDependencyManagementHasDifferentVersion() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); Artifact artifact = projectArtifact.artifact; - Artifact managedVersion = createArtifactSpec( artifact.getArtifactId(), "2.0" ).artifact; + Artifact managedVersion = createArtifactSpec(artifact.getArtifactId(), "2.0").artifact; - ArtifactResolutionResult result = collect( a, managedVersion ); + ArtifactResolutionResult result = collect(a, managedVersion); - assertEquals( "1.0", artifact.getVersion(), "collect has modified version in originating artifact" ); + assertEquals("1.0", artifact.getVersion(), "collect has modified version in originating artifact"); Artifact resolvedArtifact = result.getArtifacts().iterator().next(); - assertEquals( "1.0", resolvedArtifact.getVersion(), "Resolved version don't match original artifact version" ); + assertEquals("1.0", resolvedArtifact.getVersion(), "Resolved version don't match original artifact version"); } @Test public void testResolveCompileScopeOverTestScope() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec c = createArtifactSpec( "c", "3.0", Artifact.SCOPE_TEST ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec c = createArtifactSpec("c", "3.0", Artifact.SCOPE_TEST); - a.addDependency( "c", "2.0", Artifact.SCOPE_COMPILE ); + a.addDependency("c", "2.0", Artifact.SCOPE_COMPILE); - Artifact modifiedC = createArtifactSpec( "c", "3.0", Artifact.SCOPE_COMPILE ).artifact; + Artifact modifiedC = createArtifactSpec("c", "3.0", Artifact.SCOPE_COMPILE).artifact; - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, c.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, modifiedC } ), res.getArtifacts(), "Check artifact list" ); - Artifact artifact = getArtifact( "c", res.getArtifacts() ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, c.artifact})); + assertEquals(createSet(new Object[] {a.artifact, modifiedC}), res.getArtifacts(), "Check artifact list"); + Artifact artifact = getArtifact("c", res.getArtifacts()); // local wins now, and irrelevant if not local as test/provided aren't transitive // assertEquals( Artifact.SCOPE_COMPILE, artifact.getArtifactScope(), "Check artifactScope" ); - assertEquals( Artifact.SCOPE_TEST, artifact.getScope(), "Check artifactScope" ); + assertEquals(Artifact.SCOPE_TEST, artifact.getScope(), "Check artifactScope"); } @Test public void testResolveRuntimeScopeOverTestScope() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec c = createArtifactSpec( "c", "3.0", Artifact.SCOPE_TEST ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec c = createArtifactSpec("c", "3.0", Artifact.SCOPE_TEST); - a.addDependency( "c", "2.0", Artifact.SCOPE_RUNTIME ); + a.addDependency("c", "2.0", Artifact.SCOPE_RUNTIME); - Artifact modifiedC = createArtifactSpec( "c", "3.0", Artifact.SCOPE_RUNTIME ).artifact; + Artifact modifiedC = createArtifactSpec("c", "3.0", Artifact.SCOPE_RUNTIME).artifact; - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, c.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, modifiedC } ), res.getArtifacts(), "Check artifact list" ); - Artifact artifact = getArtifact( "c", res.getArtifacts() ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, c.artifact})); + assertEquals(createSet(new Object[] {a.artifact, modifiedC}), res.getArtifacts(), "Check artifact list"); + Artifact artifact = getArtifact("c", res.getArtifacts()); // local wins now, and irrelevant if not local as test/provided aren't transitive // assertEquals( Artifact.SCOPE_RUNTIME, artifact.getArtifactScope(), "Check artifactScope" ); - assertEquals( Artifact.SCOPE_TEST, artifact.getScope(), "Check artifactScope" ); + assertEquals(Artifact.SCOPE_TEST, artifact.getScope(), "Check artifactScope"); } @Test public void testResolveCompileScopeOverRuntimeScope() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec root = createArtifactSpec( "root", "1.0" ); - ArtifactSpec a = root.addDependency( "a", "1.0" ); - root.addDependency( "c", "3.0", Artifact.SCOPE_RUNTIME ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec root = createArtifactSpec("root", "1.0"); + ArtifactSpec a = root.addDependency("a", "1.0"); + root.addDependency("c", "3.0", Artifact.SCOPE_RUNTIME); - a.addDependency( "c", "2.0", Artifact.SCOPE_COMPILE ); + a.addDependency("c", "2.0", Artifact.SCOPE_COMPILE); - Artifact modifiedC = createArtifactSpec( "c", "3.0", Artifact.SCOPE_COMPILE ).artifact; + Artifact modifiedC = createArtifactSpec("c", "3.0", Artifact.SCOPE_COMPILE).artifact; - ArtifactResolutionResult res = collect( createSet( new Object[] { root.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, root.artifact, modifiedC } ), res.getArtifacts(), "Check artifact list" ); - Artifact artifact = getArtifact( "c", res.getArtifacts() ); - assertEquals( Artifact.SCOPE_COMPILE, artifact.getScope(), "Check artifactScope" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {root.artifact})); + assertEquals( + createSet(new Object[] {a.artifact, root.artifact, modifiedC}), + res.getArtifacts(), + "Check artifact list"); + Artifact artifact = getArtifact("c", res.getArtifacts()); + assertEquals(Artifact.SCOPE_COMPILE, artifact.getScope(), "Check artifactScope"); } @Test public void testResolveCompileScopeOverProvidedScope() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec c = createArtifactSpec( "c", "3.0", Artifact.SCOPE_PROVIDED ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec c = createArtifactSpec("c", "3.0", Artifact.SCOPE_PROVIDED); - a.addDependency( "c", "2.0", Artifact.SCOPE_COMPILE ); + a.addDependency("c", "2.0", Artifact.SCOPE_COMPILE); - Artifact modifiedC = createArtifactSpec( "c", "3.0", Artifact.SCOPE_COMPILE ).artifact; + Artifact modifiedC = createArtifactSpec("c", "3.0", Artifact.SCOPE_COMPILE).artifact; - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, c.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, modifiedC } ), res.getArtifacts(), "Check artifact list" ); - Artifact artifact = getArtifact( "c", res.getArtifacts() ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, c.artifact})); + assertEquals(createSet(new Object[] {a.artifact, modifiedC}), res.getArtifacts(), "Check artifact list"); + Artifact artifact = getArtifact("c", res.getArtifacts()); // local wins now, and irrelevant if not local as test/provided aren't transitive // assertEquals( Artifact.SCOPE_COMPILE, artifact.getArtifactScope(), "Check artifactScope" ); - assertEquals( Artifact.SCOPE_PROVIDED, artifact.getScope(), "Check artifactScope" ); + assertEquals(Artifact.SCOPE_PROVIDED, artifact.getScope(), "Check artifactScope"); } @Test public void testResolveRuntimeScopeOverProvidedScope() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec c = createArtifactSpec( "c", "3.0", Artifact.SCOPE_PROVIDED ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec c = createArtifactSpec("c", "3.0", Artifact.SCOPE_PROVIDED); - a.addDependency( "c", "2.0", Artifact.SCOPE_RUNTIME ); + a.addDependency("c", "2.0", Artifact.SCOPE_RUNTIME); - Artifact modifiedC = createArtifactSpec( "c", "3.0", Artifact.SCOPE_RUNTIME ).artifact; + Artifact modifiedC = createArtifactSpec("c", "3.0", Artifact.SCOPE_RUNTIME).artifact; - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, c.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, modifiedC } ), res.getArtifacts(), "Check artifact list" ); - Artifact artifact = getArtifact( "c", res.getArtifacts() ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, c.artifact})); + assertEquals(createSet(new Object[] {a.artifact, modifiedC}), res.getArtifacts(), "Check artifact list"); + Artifact artifact = getArtifact("c", res.getArtifacts()); // local wins now, and irrelevant if not local as test/provided aren't transitive // assertEquals( Artifact.SCOPE_RUNTIME, artifact.getArtifactScope(), "Check artifactScope" ); - assertEquals( Artifact.SCOPE_PROVIDED, artifact.getScope(), "Check artifactScope" ); + assertEquals(Artifact.SCOPE_PROVIDED, artifact.getScope(), "Check artifactScope"); } @Test public void testProvidedScopeNotTransitive() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0", Artifact.SCOPE_PROVIDED ); - ArtifactSpec b = createArtifactSpec( "b", "1.0" ); - b.addDependency( "c", "3.0", Artifact.SCOPE_PROVIDED ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0", Artifact.SCOPE_PROVIDED); + ArtifactSpec b = createArtifactSpec("b", "1.0"); + b.addDependency("c", "3.0", Artifact.SCOPE_PROVIDED); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); } @Test - public void testOptionalNotTransitive() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = createArtifactSpec( "b", "1.0" ); - b.addDependency( "c", "3.0", true ); + public void testOptionalNotTransitive() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = createArtifactSpec("b", "1.0"); + b.addDependency("c", "3.0", true); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); } @Test - public void testOptionalIncludedAtRoot() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); + public void testOptionalIncludedAtRoot() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); - ArtifactSpec b = createArtifactSpec( "b", "1.0", true ); + ArtifactSpec b = createArtifactSpec("b", "1.0", true); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); } @Test - public void testScopeUpdate() - throws InvalidVersionSpecificationException, ArtifactResolutionException - { + public void testScopeUpdate() throws InvalidVersionSpecificationException, ArtifactResolutionException { /* farthest = compile */ - checkScopeUpdate( Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_COMPILE, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_COMPILE, Artifact.SCOPE_TEST, Artifact.SCOPE_COMPILE ); + checkScopeUpdate(Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_COMPILE, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_COMPILE, Artifact.SCOPE_TEST, Artifact.SCOPE_COMPILE); /* farthest = provided */ - checkScopeUpdate( Artifact.SCOPE_PROVIDED, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED ); - checkScopeUpdate( Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME ); - checkScopeUpdate( Artifact.SCOPE_PROVIDED, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM ); - checkScopeUpdate( Artifact.SCOPE_PROVIDED, Artifact.SCOPE_TEST, Artifact.SCOPE_TEST ); + checkScopeUpdate(Artifact.SCOPE_PROVIDED, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED); + checkScopeUpdate(Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME); + checkScopeUpdate(Artifact.SCOPE_PROVIDED, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM); + checkScopeUpdate(Artifact.SCOPE_PROVIDED, Artifact.SCOPE_TEST, Artifact.SCOPE_TEST); /* farthest = runtime */ - checkScopeUpdate( Artifact.SCOPE_RUNTIME, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_RUNTIME, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME ); - checkScopeUpdate( Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME ); - checkScopeUpdate( Artifact.SCOPE_RUNTIME, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM ); - checkScopeUpdate( Artifact.SCOPE_RUNTIME, Artifact.SCOPE_TEST, Artifact.SCOPE_RUNTIME ); + checkScopeUpdate(Artifact.SCOPE_RUNTIME, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_RUNTIME, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME); + checkScopeUpdate(Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME); + checkScopeUpdate(Artifact.SCOPE_RUNTIME, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM); + checkScopeUpdate(Artifact.SCOPE_RUNTIME, Artifact.SCOPE_TEST, Artifact.SCOPE_RUNTIME); /* farthest = system */ - checkScopeUpdate( Artifact.SCOPE_SYSTEM, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED ); - checkScopeUpdate( Artifact.SCOPE_SYSTEM, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME ); - checkScopeUpdate( Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM ); - checkScopeUpdate( Artifact.SCOPE_SYSTEM, Artifact.SCOPE_TEST, Artifact.SCOPE_TEST ); + checkScopeUpdate(Artifact.SCOPE_SYSTEM, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED); + checkScopeUpdate(Artifact.SCOPE_SYSTEM, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME); + checkScopeUpdate(Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM); + checkScopeUpdate(Artifact.SCOPE_SYSTEM, Artifact.SCOPE_TEST, Artifact.SCOPE_TEST); /* farthest = test */ - checkScopeUpdate( Artifact.SCOPE_TEST, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE ); - checkScopeUpdate( Artifact.SCOPE_TEST, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED ); - checkScopeUpdate( Artifact.SCOPE_TEST, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME ); - checkScopeUpdate( Artifact.SCOPE_TEST, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM ); - checkScopeUpdate( Artifact.SCOPE_TEST, Artifact.SCOPE_TEST, Artifact.SCOPE_TEST ); + checkScopeUpdate(Artifact.SCOPE_TEST, Artifact.SCOPE_COMPILE, Artifact.SCOPE_COMPILE); + checkScopeUpdate(Artifact.SCOPE_TEST, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_PROVIDED); + checkScopeUpdate(Artifact.SCOPE_TEST, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_RUNTIME); + checkScopeUpdate(Artifact.SCOPE_TEST, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_SYSTEM); + checkScopeUpdate(Artifact.SCOPE_TEST, Artifact.SCOPE_TEST, Artifact.SCOPE_TEST); } - private void checkScopeUpdate( String farthestScope, String nearestScope, String expectedScope ) - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - checkScopeUpdateDirect( farthestScope, nearestScope, expectedScope ); - checkScopeUpdateTransitively( farthestScope, nearestScope, expectedScope ); + private void checkScopeUpdate(String farthestScope, String nearestScope, String expectedScope) + throws ArtifactResolutionException, InvalidVersionSpecificationException { + checkScopeUpdateDirect(farthestScope, nearestScope, expectedScope); + checkScopeUpdateTransitively(farthestScope, nearestScope, expectedScope); } - private void checkScopeUpdateTransitively( String farthestScope, String nearestScope, String expectedScope ) - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = createArtifactSpec( "b", "1.0", nearestScope ); - ArtifactSpec c = createArtifactSpec( "c", "1.0" ); - a.addDependency( c ); - ArtifactSpec dNearest = createArtifactSpec( "d", "2.0" ); - b.addDependency( dNearest ); - ArtifactSpec dFarthest = createArtifactSpec( "d", "3.0", farthestScope ); - c.addDependency( dFarthest ); + private void checkScopeUpdateTransitively(String farthestScope, String nearestScope, String expectedScope) + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = createArtifactSpec("b", "1.0", nearestScope); + ArtifactSpec c = createArtifactSpec("c", "1.0"); + a.addDependency(c); + ArtifactSpec dNearest = createArtifactSpec("d", "2.0"); + b.addDependency(dNearest); + ArtifactSpec dFarthest = createArtifactSpec("d", "3.0", farthestScope); + c.addDependency(dFarthest); /* system and provided dependencies are not transitive */ - if ( !Artifact.SCOPE_SYSTEM.equals( nearestScope ) && !Artifact.SCOPE_PROVIDED.equals( nearestScope ) ) - { - checkScopeUpdate( a, b, expectedScope, "2.0" ); + if (!Artifact.SCOPE_SYSTEM.equals(nearestScope) && !Artifact.SCOPE_PROVIDED.equals(nearestScope)) { + checkScopeUpdate(a, b, expectedScope, "2.0"); } } - private void checkScopeUpdateDirect( String farthestScope, String nearestScope, String expectedScope ) - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = createArtifactSpec( "b", "1.0" ); - ArtifactSpec c = createArtifactSpec( "c", "1.0" ); - a.addDependency( c ); - ArtifactSpec dNearest = createArtifactSpec( "d", "2.0", nearestScope ); - b.addDependency( dNearest ); - ArtifactSpec dFarthest = createArtifactSpec( "d", "3.0", farthestScope ); - c.addDependency( dFarthest ); + private void checkScopeUpdateDirect(String farthestScope, String nearestScope, String expectedScope) + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = createArtifactSpec("b", "1.0"); + ArtifactSpec c = createArtifactSpec("c", "1.0"); + a.addDependency(c); + ArtifactSpec dNearest = createArtifactSpec("d", "2.0", nearestScope); + b.addDependency(dNearest); + ArtifactSpec dFarthest = createArtifactSpec("d", "3.0", farthestScope); + c.addDependency(dFarthest); - checkScopeUpdate( a, b, expectedScope, "2.0" ); + checkScopeUpdate(a, b, expectedScope, "2.0"); } - private void checkScopeUpdate( ArtifactSpec a, ArtifactSpec b, String expectedScope, String expectedVersion ) - throws ArtifactResolutionException, InvalidVersionSpecificationException - { + private void checkScopeUpdate(ArtifactSpec a, ArtifactSpec b, String expectedScope, String expectedVersion) + throws ArtifactResolutionException, InvalidVersionSpecificationException { ScopeArtifactFilter filter; - if ( Artifact.SCOPE_PROVIDED.equals( expectedScope ) ) - { - filter = new ScopeArtifactFilter( Artifact.SCOPE_COMPILE ); - } - else if ( Artifact.SCOPE_SYSTEM.equals( expectedScope ) ) - { - filter = new ScopeArtifactFilter( Artifact.SCOPE_COMPILE ); - } - else - { - filter = new ScopeArtifactFilter( expectedScope ); + if (Artifact.SCOPE_PROVIDED.equals(expectedScope)) { + filter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE); + } else if (Artifact.SCOPE_SYSTEM.equals(expectedScope)) { + filter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE); + } else { + filter = new ScopeArtifactFilter(expectedScope); } - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ), filter ); - Artifact artifact = getArtifact( "d", res.getArtifacts() ); - assertNotNull( artifact, "MNG-1895 Dependency was not added to resolution" ); - assertEquals( expectedScope, artifact.getScope(), "Check artifactScope" ); - assertEquals( expectedVersion, artifact.getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact}), filter); + Artifact artifact = getArtifact("d", res.getArtifacts()); + assertNotNull(artifact, "MNG-1895 Dependency was not added to resolution"); + assertEquals(expectedScope, artifact.getScope(), "Check artifactScope"); + assertEquals(expectedVersion, artifact.getVersion(), "Check version"); - ArtifactSpec d = createArtifactSpec( "d", "1.0" ); - res = collect( createSet( new Object[] { a.artifact, b.artifact, d.artifact } ), filter ); - artifact = getArtifact( "d", res.getArtifacts() ); - assertNotNull( artifact, "MNG-1895 Dependency was not added to resolution" ); - assertEquals( d.artifact.getScope(), artifact.getScope(), "Check artifactScope" ); - assertEquals( "1.0", artifact.getVersion(), "Check version" ); + ArtifactSpec d = createArtifactSpec("d", "1.0"); + res = collect(createSet(new Object[] {a.artifact, b.artifact, d.artifact}), filter); + artifact = getArtifact("d", res.getArtifacts()); + assertNotNull(artifact, "MNG-1895 Dependency was not added to resolution"); + assertEquals(d.artifact.getScope(), artifact.getScope(), "Check artifactScope"); + assertEquals("1.0", artifact.getVersion(), "Check version"); } @Test @Disabled public void testOptionalNotTransitiveButVersionIsInfluential() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - ArtifactSpec b = createArtifactSpec( "b", "1.0" ); - b.addDependency( "c", "3.0", true ); - ArtifactSpec d = a.addDependency( "d", "1.0" ); - ArtifactSpec e = d.addDependency( "e", "1.0" ); - e.addDependency( "c", "2.0" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + ArtifactSpec b = createArtifactSpec("b", "1.0"); + b.addDependency("c", "3.0", true); + ArtifactSpec d = a.addDependency("d", "1.0"); + ArtifactSpec e = d.addDependency("e", "1.0"); + e.addDependency("c", "2.0"); - ArtifactSpec c = createArtifactSpec( "c", "3.0" ); + ArtifactSpec c = createArtifactSpec("c", "3.0"); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact, c.artifact, d.artifact, e.artifact } ), res.getArtifacts(), "Check artifact list" ); - Artifact artifact = getArtifact( "c", res.getArtifacts() ); - assertEquals( "3.0", artifact.getVersion(), "Check version" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals( + createSet(new Object[] {a.artifact, b.artifact, c.artifact, d.artifact, e.artifact}), + res.getArtifacts(), + "Check artifact list"); + Artifact artifact = getArtifact("c", res.getArtifacts()); + assertEquals("3.0", artifact.getVersion(), "Check version"); } @Test - public void testTestScopeNotTransitive() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0", Artifact.SCOPE_TEST ); - ArtifactSpec b = createArtifactSpec( "b", "1.0" ); - b.addDependency( "c", "3.0", Artifact.SCOPE_TEST ); + public void testTestScopeNotTransitive() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0", Artifact.SCOPE_TEST); + ArtifactSpec b = createArtifactSpec("b", "1.0"); + b.addDependency("c", "3.0", Artifact.SCOPE_TEST); - ArtifactResolutionResult res = collect( createSet( new Object[] { a.artifact, b.artifact } ) ); - assertEquals( createSet( new Object[] { a.artifact, b.artifact } ), res.getArtifacts(), "Check artifact list" ); + ArtifactResolutionResult res = collect(createSet(new Object[] {a.artifact, b.artifact})); + assertEquals(createSet(new Object[] {a.artifact, b.artifact}), res.getArtifacts(), "Check artifact list"); } @Test - public void testSnapshotNotIncluded() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - a.addDependency( "b", "[1.0,)" ); - createArtifactSpec( "b", "1.0-SNAPSHOT" ); + public void testSnapshotNotIncluded() throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + a.addDependency("b", "[1.0,)"); + createArtifactSpec("b", "1.0-SNAPSHOT"); - ArtifactResolutionResult res = collect( a ); + ArtifactResolutionResult res = collect(a); - assertTrue( res.hasVersionRangeViolations() ); + assertTrue(res.hasVersionRangeViolations()); /* * try { ArtifactResolutionResult res = collect( a ); fail( "Expected b not to resolve: " + res ); } catch ( @@ -713,280 +683,257 @@ public class DefaultArtifactCollectorTest @Test @Disabled("that one does not work") public void testOverConstrainedVersionException() - throws ArtifactResolutionException, InvalidVersionSpecificationException - { - ArtifactSpec a = createArtifactSpec( "a", "1.0" ); - a.addDependency( "b", "[1.0, 2.0)" ); - a.addDependency( "c", "[3.3.0,4.0.0)" ); + throws ArtifactResolutionException, InvalidVersionSpecificationException { + ArtifactSpec a = createArtifactSpec("a", "1.0"); + a.addDependency("b", "[1.0, 2.0)"); + a.addDependency("c", "[3.3.0,4.0.0)"); - ArtifactSpec b = createArtifactSpec( "b", "1.0.0" ); - b.addDependency( "c", "3.3.0-v3346" ); + ArtifactSpec b = createArtifactSpec("b", "1.0.0"); + b.addDependency("c", "3.3.0-v3346"); - ArtifactSpec c = createArtifactSpec( "c", "3.2.1-v3235e" ); + ArtifactSpec c = createArtifactSpec("c", "3.2.1-v3235e"); OverConstrainedVersionException e = assertThrows( - OverConstrainedVersionException.class, - () -> collect( createSet( new Object[] { a.artifact } ) ) ); - assertTrue( e.getMessage().contains( "[3.2.1-v3235e, 3.3.0-v3346]" ), "Versions unordered" ); - assertTrue( e.getMessage().contains( "Path to dependency:" ), "DependencyTrail unresolved" ); + OverConstrainedVersionException.class, () -> collect(createSet(new Object[] {a.artifact}))); + assertTrue(e.getMessage().contains("[3.2.1-v3235e, 3.3.0-v3346]"), "Versions unordered"); + assertTrue(e.getMessage().contains("Path to dependency:"), "DependencyTrail unresolved"); } - private Artifact getArtifact( String id, Set artifacts ) - { - for ( Object artifact : artifacts ) - { + private Artifact getArtifact(String id, Set artifacts) { + for (Object artifact : artifacts) { Artifact a = (Artifact) artifact; - if ( a.getArtifactId().equals( id ) && a.getGroupId().equals( GROUP_ID ) ) - { + if (a.getArtifactId().equals(id) && a.getGroupId().equals(GROUP_ID)) { return a; } } return null; } - private ArtifactResolutionResult collect( Set artifacts ) - throws ArtifactResolutionException - { - return collect( artifacts, null ); + private ArtifactResolutionResult collect(Set artifacts) throws ArtifactResolutionException { + return collect(artifacts, null); } - private ArtifactResolutionResult collect( Set artifacts, ArtifactFilter filter ) - throws ArtifactResolutionException - { - return artifactCollector.collect( artifacts, projectArtifact.artifact, null, null, null, source, filter, - Collections.emptyList(), null ); + private ArtifactResolutionResult collect(Set artifacts, ArtifactFilter filter) + throws ArtifactResolutionException { + return artifactCollector.collect( + artifacts, projectArtifact.artifact, null, null, null, source, filter, Collections.emptyList(), null); } - private ArtifactResolutionResult collect( ArtifactSpec a ) - throws ArtifactResolutionException - { - return artifactCollector.collect( Collections.singleton( a.artifact ), projectArtifact.artifact, null, null, - null, source, null, Collections.emptyList(), null ); + private ArtifactResolutionResult collect(ArtifactSpec a) throws ArtifactResolutionException { + return artifactCollector.collect( + Collections.singleton(a.artifact), + projectArtifact.artifact, + null, + null, + null, + source, + null, + Collections.emptyList(), + null); } - private ArtifactResolutionResult collect( ArtifactSpec a, ArtifactFilter filter ) - throws ArtifactResolutionException - { - return artifactCollector.collect( Collections.singleton( a.artifact ), projectArtifact.artifact, null, null, - null, source, filter, Collections.emptyList(), null ); + private ArtifactResolutionResult collect(ArtifactSpec a, ArtifactFilter filter) throws ArtifactResolutionException { + return artifactCollector.collect( + Collections.singleton(a.artifact), + projectArtifact.artifact, + null, + null, + null, + source, + filter, + Collections.emptyList(), + null); } - private ArtifactResolutionResult collect( ArtifactSpec a, Artifact managedVersion ) - throws ArtifactResolutionException - { - Map managedVersions = Collections.singletonMap( managedVersion.getDependencyConflictId(), managedVersion ); - return artifactCollector.collect( Collections.singleton( a.artifact ), projectArtifact.artifact, - managedVersions, null, null, source, null, Collections.emptyList(), null ); + private ArtifactResolutionResult collect(ArtifactSpec a, Artifact managedVersion) + throws ArtifactResolutionException { + Map managedVersions = + Collections.singletonMap(managedVersion.getDependencyConflictId(), managedVersion); + return artifactCollector.collect( + Collections.singleton(a.artifact), + projectArtifact.artifact, + managedVersions, + null, + null, + source, + null, + Collections.emptyList(), + null); } - private ArtifactSpec createArtifactSpec( String id, String version ) - throws InvalidVersionSpecificationException - { - return createArtifactSpec( id, version, Artifact.SCOPE_COMPILE ); + private ArtifactSpec createArtifactSpec(String id, String version) throws InvalidVersionSpecificationException { + return createArtifactSpec(id, version, Artifact.SCOPE_COMPILE); } - private ArtifactSpec createArtifactSpec( String id, String version, boolean optional ) - throws InvalidVersionSpecificationException - { - return createArtifactSpec( id, version, Artifact.SCOPE_COMPILE, null, optional ); + private ArtifactSpec createArtifactSpec(String id, String version, boolean optional) + throws InvalidVersionSpecificationException { + return createArtifactSpec(id, version, Artifact.SCOPE_COMPILE, null, optional); } - private ArtifactSpec createArtifactSpec( String id, String version, String scope ) - throws InvalidVersionSpecificationException - { - return createArtifactSpec( id, version, scope, null, false ); + private ArtifactSpec createArtifactSpec(String id, String version, String scope) + throws InvalidVersionSpecificationException { + return createArtifactSpec(id, version, scope, null, false); } - private ArtifactSpec createArtifactSpec( String id, String version, String scope, String inheritedScope, - boolean optional ) - throws InvalidVersionSpecificationException - { - VersionRange versionRange = VersionRange.createFromVersionSpec( version ); - Artifact artifact = - artifactFactory.createDependencyArtifact( GROUP_ID, id, versionRange, "jar", null, scope, inheritedScope, - optional ); + private ArtifactSpec createArtifactSpec( + String id, String version, String scope, String inheritedScope, boolean optional) + throws InvalidVersionSpecificationException { + VersionRange versionRange = VersionRange.createFromVersionSpec(version); + Artifact artifact = artifactFactory.createDependencyArtifact( + GROUP_ID, id, versionRange, "jar", null, scope, inheritedScope, optional); ArtifactSpec spec = null; - if ( artifact != null ) - { + if (artifact != null) { spec = new ArtifactSpec(); spec.artifact = artifact; - source.addArtifact( spec ); + source.addArtifact(spec); } return spec; } - @SuppressWarnings( "unchecked" ) - private static Set createSet( Object[] x ) - { - return new LinkedHashSet( Arrays.asList( x ) ); + @SuppressWarnings("unchecked") + private static Set createSet(Object[] x) { + return new LinkedHashSet(Arrays.asList(x)); } - private class ArtifactSpec - { + private class ArtifactSpec { private Artifact artifact; private Set dependencies = new HashSet<>(); - public ArtifactSpec addDependency( String id, String version ) - throws InvalidVersionSpecificationException - { - return addDependency( id, version, Artifact.SCOPE_COMPILE ); + public ArtifactSpec addDependency(String id, String version) throws InvalidVersionSpecificationException { + return addDependency(id, version, Artifact.SCOPE_COMPILE); } - public ArtifactSpec addDependency( String id, String version, String scope ) - throws InvalidVersionSpecificationException - { - return addDependency( id, version, scope, false ); + public ArtifactSpec addDependency(String id, String version, String scope) + throws InvalidVersionSpecificationException { + return addDependency(id, version, scope, false); } - private ArtifactSpec addDependency( ArtifactSpec dep ) - throws InvalidVersionSpecificationException - { - if ( dep != null ) - { - dependencies.add( dep.artifact ); + private ArtifactSpec addDependency(ArtifactSpec dep) throws InvalidVersionSpecificationException { + if (dep != null) { + dependencies.add(dep.artifact); } return dep; } - private ArtifactSpec addDependency( String id, String version, String scope, boolean optional ) - throws InvalidVersionSpecificationException - { - ArtifactSpec dep = createArtifactSpec( id, version, scope, artifact.getScope(), optional ); - return addDependency( dep ); + private ArtifactSpec addDependency(String id, String version, String scope, boolean optional) + throws InvalidVersionSpecificationException { + ArtifactSpec dep = createArtifactSpec(id, version, scope, artifact.getScope(), optional); + return addDependency(dep); } - public ArtifactSpec addDependency( String id, String version, boolean optional ) - throws InvalidVersionSpecificationException - { - return addDependency( id, version, Artifact.SCOPE_COMPILE, optional ); + public ArtifactSpec addDependency(String id, String version, boolean optional) + throws InvalidVersionSpecificationException { + return addDependency(id, version, Artifact.SCOPE_COMPILE, optional); } } - private class Source - implements ArtifactMetadataSource - { + private class Source implements ArtifactMetadataSource { private Map artifacts = new HashMap<>(); private Map> versions = new HashMap<>(); - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { - String key = getKey( artifact ); + public ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { + String key = getKey(artifact); - ArtifactSpec a = (ArtifactSpec) artifacts.get( key ); - try - { - return new ResolutionGroup( artifact, createArtifacts( artifactFactory, a.dependencies, - artifact.getScope(), - artifact.getDependencyFilter() ), - Collections.emptyList() ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new ArtifactMetadataRetrievalException( "Invalid version creating artifacts", e, artifact ); + ArtifactSpec a = (ArtifactSpec) artifacts.get(key); + try { + return new ResolutionGroup( + artifact, + createArtifacts( + artifactFactory, a.dependencies, artifact.getScope(), artifact.getDependencyFilter()), + Collections.emptyList()); + } catch (InvalidVersionSpecificationException e) { + throw new ArtifactMetadataRetrievalException("Invalid version creating artifacts", e, artifact); } } - private String getKey( Artifact artifact ) - { + private String getKey(Artifact artifact) { return artifact.getDependencyConflictId(); } - private Set createArtifacts( ArtifactFactory artifactFactory, Set dependencies, String inheritedScope, - ArtifactFilter dependencyFilter ) - throws InvalidVersionSpecificationException - { + private Set createArtifacts( + ArtifactFactory artifactFactory, + Set dependencies, + String inheritedScope, + ArtifactFilter dependencyFilter) + throws InvalidVersionSpecificationException { Set projectArtifacts = new HashSet<>(); - for ( Artifact d : dependencies ) - { + for (Artifact d : dependencies) { VersionRange versionRange; - if ( d.getVersionRange() != null ) - { + if (d.getVersionRange() != null) { versionRange = d.getVersionRange(); - } - else - { - versionRange = VersionRange.createFromVersionSpec( d.getVersion() ); + } else { + versionRange = VersionRange.createFromVersionSpec(d.getVersion()); } Artifact artifact; - if ( d.getScope().equals( Artifact.SCOPE_TEST ) || d.getScope().equals( Artifact.SCOPE_PROVIDED ) ) - { + if (d.getScope().equals(Artifact.SCOPE_TEST) || d.getScope().equals(Artifact.SCOPE_PROVIDED)) { /* don't call createDependencyArtifact as it'll ignore test and provided scopes */ - artifact = - artifactFactory.createArtifact( d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getScope(), - d.getType() ); - } - else - { - artifact = - artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, - d.getType(), d.getClassifier(), d.getScope(), - inheritedScope, d.isOptional() ); + artifact = artifactFactory.createArtifact( + d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getScope(), d.getType()); + } else { + artifact = artifactFactory.createDependencyArtifact( + d.getGroupId(), + d.getArtifactId(), + versionRange, + d.getType(), + d.getClassifier(), + d.getScope(), + inheritedScope, + d.isOptional()); } - if ( artifact != null && ( dependencyFilter == null || dependencyFilter.include( artifact ) ) ) - { - artifact.setDependencyFilter( dependencyFilter ); + if (artifact != null && (dependencyFilter == null || dependencyFilter.include(artifact))) { + artifact.setDependencyFilter(dependencyFilter); - projectArtifacts.add( artifact ); + projectArtifacts.add(artifact); } } return projectArtifacts; } - public void addArtifact( ArtifactSpec spec ) - { - artifacts.put( getKey( spec.artifact ), spec ); + public void addArtifact(ArtifactSpec spec) { + artifacts.put(getKey(spec.artifact), spec); String key = spec.artifact.getDependencyConflictId(); - List artifactVersions = versions.computeIfAbsent( key, k -> new ArrayList<>() ); - if ( spec.artifact.getVersion() != null ) - { - artifactVersions.add( new DefaultArtifactVersion( spec.artifact.getVersion() ) ); + List artifactVersions = versions.computeIfAbsent(key, k -> new ArrayList<>()); + if (spec.artifact.getVersion() != null) { + artifactVersions.add(new DefaultArtifactVersion(spec.artifact.getVersion())); } } - public List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { - return retrieveAvailableVersions( artifact ); + public List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { + return retrieveAvailableVersions(artifact); } public List retrieveAvailableVersionsFromDeploymentRepository( - Artifact artifact, - ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws ArtifactMetadataRetrievalException - { - return retrieveAvailableVersions( artifact ); + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws ArtifactMetadataRetrievalException { + return retrieveAvailableVersions(artifact); } - private List retrieveAvailableVersions( Artifact artifact ) - { - List artifactVersions = versions.get( artifact.getDependencyConflictId() ); - if ( artifactVersions == null ) - { + private List retrieveAvailableVersions(Artifact artifact) { + List artifactVersions = versions.get(artifact.getDependencyConflictId()); + if (artifactVersions == null) { artifactVersions = Collections.emptyList(); } return artifactVersions; } - public ResolutionGroup retrieve( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { - return retrieve( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public ResolutionGroup retrieve(MetadataResolutionRequest request) throws ArtifactMetadataRetrievalException { + return retrieve(request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } - public List retrieveAvailableVersions( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { - return retrieveAvailableVersions( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public List retrieveAvailableVersions(MetadataResolutionRequest request) + throws ArtifactMetadataRetrievalException { + return retrieveAvailableVersions( + request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/AbstractConflictResolverTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/AbstractConflictResolverTest.java index 178933996e..2982e99922 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/AbstractConflictResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/AbstractConflictResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,32 +16,30 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Collections; - +import javax.inject.Inject; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ResolutionNode; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; -import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.BeforeEach; -import javax.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * Provides a basis for testing conflict resolvers. * * @author Mark Hobson */ @PlexusTest -public abstract class AbstractConflictResolverTest -{ +public abstract class AbstractConflictResolverTest { // constants -------------------------------------------------------------- private static final String GROUP_ID = "test"; @@ -68,9 +64,7 @@ public abstract class AbstractConflictResolverTest // constructors ----------------------------------------------------------- - public AbstractConflictResolverTest( String roleHint ) - throws Exception - { + public AbstractConflictResolverTest(String roleHint) throws Exception { this.roleHint = roleHint; } @@ -80,58 +74,50 @@ public abstract class AbstractConflictResolverTest * @see junit.framework.TestCase#setUp() */ @BeforeEach - public void setUp() - throws Exception - { - conflictResolver = (ConflictResolver) container.lookup( ConflictResolver.ROLE, roleHint ); + public void setUp() throws Exception { + conflictResolver = (ConflictResolver) container.lookup(ConflictResolver.ROLE, roleHint); - a1 = createArtifact( "a", "1.0" ); - a2 = createArtifact( "a", "2.0" ); - b1 = createArtifact( "b", "1.0" ); + a1 = createArtifact("a", "1.0"); + a2 = createArtifact("a", "2.0"); + b1 = createArtifact("b", "1.0"); } // protected methods ------------------------------------------------------ - protected ConflictResolver getConflictResolver() - { + protected ConflictResolver getConflictResolver() { return conflictResolver; } - protected void assertResolveConflict( ResolutionNode expectedNode, ResolutionNode actualNode1, ResolutionNode actualNode2 ) - { - ResolutionNode resolvedNode = getConflictResolver().resolveConflict( actualNode1, actualNode2 ); + protected void assertResolveConflict( + ResolutionNode expectedNode, ResolutionNode actualNode1, ResolutionNode actualNode2) { + ResolutionNode resolvedNode = getConflictResolver().resolveConflict(actualNode1, actualNode2); - assertNotNull( resolvedNode, "Expected resolvable" ); - assertEquals( expectedNode, resolvedNode, "Resolution node" ); + assertNotNull(resolvedNode, "Expected resolvable"); + assertEquals(expectedNode, resolvedNode, "Resolution node"); } - protected Artifact createArtifact( String id, String version ) throws InvalidVersionSpecificationException - { - return createArtifact( id, version, Artifact.SCOPE_COMPILE ); + protected Artifact createArtifact(String id, String version) throws InvalidVersionSpecificationException { + return createArtifact(id, version, Artifact.SCOPE_COMPILE); } - protected Artifact createArtifact( String id, String version, String scope ) - throws InvalidVersionSpecificationException - { - return createArtifact( id, version, scope, null, false ); + protected Artifact createArtifact(String id, String version, String scope) + throws InvalidVersionSpecificationException { + return createArtifact(id, version, scope, null, false); } - protected Artifact createArtifact( String id, String version, String scope, String inheritedScope, boolean optional ) - throws InvalidVersionSpecificationException - { - VersionRange versionRange = VersionRange.createFromVersionSpec( version ); + protected Artifact createArtifact(String id, String version, String scope, String inheritedScope, boolean optional) + throws InvalidVersionSpecificationException { + VersionRange versionRange = VersionRange.createFromVersionSpec(version); - return artifactFactory.createDependencyArtifact( GROUP_ID, id, versionRange, "jar", null, scope, - inheritedScope, optional ); + return artifactFactory.createDependencyArtifact( + GROUP_ID, id, versionRange, "jar", null, scope, inheritedScope, optional); } - protected ResolutionNode createResolutionNode( Artifact Artifact ) - { - return new ResolutionNode( Artifact, Collections.emptyList() ); - } - protected ResolutionNode createResolutionNode( Artifact Artifact, ResolutionNode parent ) - { - return new ResolutionNode( Artifact, Collections.emptyList(), parent ); + protected ResolutionNode createResolutionNode(Artifact Artifact) { + return new ResolutionNode(Artifact, Collections.emptyList()); } + protected ResolutionNode createResolutionNode(Artifact Artifact, ResolutionNode parent) { + return new ResolutionNode(Artifact, Collections.emptyList(), parent); + } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolverTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolverTest.java index 7b46ee342d..8c18f437f3 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.junit.jupiter.api.Test; @@ -28,14 +27,10 @@ import org.junit.jupiter.api.Test; * @author Mark Hobson * @see FarthestConflictResolver */ -public class FarthestConflictResolverTest - extends AbstractConflictResolverTest -{ +public class FarthestConflictResolverTest extends AbstractConflictResolverTest { // constructors ----------------------------------------------------------- - public FarthestConflictResolverTest() - throws Exception - { + public FarthestConflictResolverTest() throws Exception { super("farthest"); } @@ -49,13 +44,12 @@ public class FarthestConflictResolverTest * */ @Test - public void testDepth() - { - ResolutionNode a1n = createResolutionNode( a1); - ResolutionNode b1n = createResolutionNode( b1); - ResolutionNode a2n = createResolutionNode( a2, b1n ); + public void testDepth() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); - assertResolveConflict( a2n, a1n, a2n ); + assertResolveConflict(a2n, a1n, a2n); } /** @@ -66,13 +60,12 @@ public class FarthestConflictResolverTest * */ @Test - public void testDepthReversed() - { - ResolutionNode b1n = createResolutionNode( b1 ); - ResolutionNode a2n = createResolutionNode( a2, b1n ); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testDepthReversed() { + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a2n, a2n, a1n ); + assertResolveConflict(a2n, a2n, a1n); } /** @@ -83,12 +76,11 @@ public class FarthestConflictResolverTest * */ @Test - public void testEqual() - { - ResolutionNode a1n = createResolutionNode( a1 ); - ResolutionNode a2n = createResolutionNode( a2 ); + public void testEqual() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode a2n = createResolutionNode(a2); - assertResolveConflict( a1n, a1n, a2n ); + assertResolveConflict(a1n, a1n, a2n); } /** @@ -99,11 +91,10 @@ public class FarthestConflictResolverTest * */ @Test - public void testEqualReversed() - { - ResolutionNode a2n = createResolutionNode( a2); - ResolutionNode a1n = createResolutionNode( a1); + public void testEqualReversed() { + ResolutionNode a2n = createResolutionNode(a2); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a2n, a2n, a1n ); + assertResolveConflict(a2n, a2n, a1n); } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolverTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolverTest.java index 34026bc289..7f9d0af8c9 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.junit.jupiter.api.Test; @@ -28,14 +27,10 @@ import org.junit.jupiter.api.Test; * @author Mark Hobson * @see NearestConflictResolver */ -public class NearestConflictResolverTest - extends AbstractConflictResolverTest -{ +public class NearestConflictResolverTest extends AbstractConflictResolverTest { // constructors ----------------------------------------------------------- - public NearestConflictResolverTest() - throws Exception - { + public NearestConflictResolverTest() throws Exception { super("nearest"); } @@ -49,13 +44,12 @@ public class NearestConflictResolverTest * */ @Test - public void testDepth() - { - ResolutionNode a1n = createResolutionNode( a1); - ResolutionNode b1n = createResolutionNode( b1); - ResolutionNode a2n = createResolutionNode( a2, b1n ); + public void testDepth() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); - assertResolveConflict( a1n, a1n, a2n ); + assertResolveConflict(a1n, a1n, a2n); } /** @@ -66,13 +60,12 @@ public class NearestConflictResolverTest * */ @Test - public void testDepthReversed() - { - ResolutionNode b1n = createResolutionNode( b1 ); - ResolutionNode a2n = createResolutionNode( a2, b1n ); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testDepthReversed() { + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a1n, a2n, a1n ); + assertResolveConflict(a1n, a2n, a1n); } /** @@ -83,12 +76,11 @@ public class NearestConflictResolverTest * */ @Test - public void testEqual() - { - ResolutionNode a1n = createResolutionNode( a1 ); - ResolutionNode a2n = createResolutionNode( a2 ); + public void testEqual() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode a2n = createResolutionNode(a2); - assertResolveConflict( a1n, a1n, a2n ); + assertResolveConflict(a1n, a1n, a2n); } /** @@ -99,11 +91,10 @@ public class NearestConflictResolverTest * */ @Test - public void testEqualReversed() - { - ResolutionNode a2n = createResolutionNode( a2); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testEqualReversed() { + ResolutionNode a2n = createResolutionNode(a2); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a2n, a2n, a1n ); + assertResolveConflict(a2n, a2n, a1n); } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolverTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolverTest.java index 874644a9c0..bf1a6646c2 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.junit.jupiter.api.Test; @@ -28,14 +27,10 @@ import org.junit.jupiter.api.Test; * @author Mark Hobson * @see NewestConflictResolver */ -public class NewestConflictResolverTest - extends AbstractConflictResolverTest -{ +public class NewestConflictResolverTest extends AbstractConflictResolverTest { // constructors ----------------------------------------------------------- - public NewestConflictResolverTest() - throws Exception - { + public NewestConflictResolverTest() throws Exception { super("newest"); } @@ -49,13 +44,12 @@ public class NewestConflictResolverTest * */ @Test - public void testDepth() - { - ResolutionNode a1n = createResolutionNode( a1 ); - ResolutionNode b1n = createResolutionNode( b1 ); - ResolutionNode a2n = createResolutionNode( a2, b1n ); + public void testDepth() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); - assertResolveConflict( a2n, a1n, a2n ); + assertResolveConflict(a2n, a1n, a2n); } /** @@ -66,13 +60,12 @@ public class NewestConflictResolverTest * */ @Test - public void testDepthReversed() - { - ResolutionNode b1n = createResolutionNode( b1 ); - ResolutionNode a2n = createResolutionNode( a2, b1n ); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testDepthReversed() { + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a2n, a2n, a1n ); + assertResolveConflict(a2n, a2n, a1n); } /** @@ -83,12 +76,11 @@ public class NewestConflictResolverTest * */ @Test - public void testEqual() - { - ResolutionNode a1n = createResolutionNode( a1 ); - ResolutionNode a2n = createResolutionNode( a2 ); + public void testEqual() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode a2n = createResolutionNode(a2); - assertResolveConflict( a2n, a1n, a2n ); + assertResolveConflict(a2n, a1n, a2n); } /** @@ -99,11 +91,10 @@ public class NewestConflictResolverTest * */ @Test - public void testEqualReversed() - { - ResolutionNode a2n = createResolutionNode( a2 ); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testEqualReversed() { + ResolutionNode a2n = createResolutionNode(a2); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a2n, a2n, a1n ); + assertResolveConflict(a2n, a2n, a1n); } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolverTest.java b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolverTest.java index 76335f26af..77183f104c 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.resolver.conflict; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.resolver.conflict; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.resolver.conflict; import org.apache.maven.artifact.resolver.ResolutionNode; import org.junit.jupiter.api.Test; @@ -28,14 +27,10 @@ import org.junit.jupiter.api.Test; * @author Mark Hobson * @see OldestConflictResolver */ -public class OldestConflictResolverTest - extends AbstractConflictResolverTest -{ +public class OldestConflictResolverTest extends AbstractConflictResolverTest { // constructors ----------------------------------------------------------- - public OldestConflictResolverTest() - throws Exception - { + public OldestConflictResolverTest() throws Exception { super("oldest"); } @@ -49,16 +44,14 @@ public class OldestConflictResolverTest * */ @Test - public void testDepth() - { - ResolutionNode a1n = createResolutionNode( a1 ); - ResolutionNode b1n = createResolutionNode( b1); - ResolutionNode a2n = createResolutionNode( a2, b1n ); + public void testDepth() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); - assertResolveConflict( a1n, a1n, a2n ); + assertResolveConflict(a1n, a1n, a2n); } - /** * Tests that a:1.0 wins in the scenario: *
@@ -67,13 +60,12 @@ public class OldestConflictResolverTest
      * 
*/ @Test - public void testDepthReversed() - { - ResolutionNode b1n = createResolutionNode( b1 ); - ResolutionNode a2n = createResolutionNode( a2, b1n ); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testDepthReversed() { + ResolutionNode b1n = createResolutionNode(b1); + ResolutionNode a2n = createResolutionNode(a2, b1n); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a1n, a2n, a1n ); + assertResolveConflict(a1n, a2n, a1n); } /** @@ -84,12 +76,11 @@ public class OldestConflictResolverTest * */ @Test - public void testEqual() - { - ResolutionNode a1n = createResolutionNode( a1 ); - ResolutionNode a2n = createResolutionNode( a2 ); + public void testEqual() { + ResolutionNode a1n = createResolutionNode(a1); + ResolutionNode a2n = createResolutionNode(a2); - assertResolveConflict( a1n, a1n, a2n ); + assertResolveConflict(a1n, a1n, a2n); } /** @@ -100,11 +91,10 @@ public class OldestConflictResolverTest * */ @Test - public void testEqualReversed() - { - ResolutionNode a2n = createResolutionNode( a2); - ResolutionNode a1n = createResolutionNode( a1 ); + public void testEqualReversed() { + ResolutionNode a2n = createResolutionNode(a2); + ResolutionNode a1n = createResolutionNode(a1); - assertResolveConflict( a1n, a2n, a1n ); + assertResolveConflict(a1n, a2n, a1n); } } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultClasspathTransformationTest.java b/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultClasspathTransformationTest.java index 348dd978fd..f09ae69efc 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultClasspathTransformationTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultClasspathTransformationTest.java @@ -1,38 +1,39 @@ -package org.apache.maven.repository.metadata; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - -import javax.inject.Inject; - -import org.apache.maven.artifact.ArtifactScopeEnum; -import org.codehaus.plexus.testing.PlexusTest; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; +package org.apache.maven.repository.metadata; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import javax.inject.Inject; +import org.apache.maven.artifact.ArtifactScopeEnum; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * * @author Oleg Gusakov * */ @PlexusTest -public class DefaultClasspathTransformationTest -{ +public class DefaultClasspathTransformationTest { @Inject ClasspathTransformation transform; @@ -42,80 +43,73 @@ public class DefaultClasspathTransformationTest MetadataGraphVertex v2; MetadataGraphVertex v3; MetadataGraphVertex v4; - //------------------------------------------------------------------------------------------ - @BeforeEach - public void setUp() throws Exception - { - graph = new MetadataGraph( 4, 3 ); + // ------------------------------------------------------------------------------------------ + @BeforeEach + public void setUp() throws Exception { + graph = new MetadataGraph(4, 3); /* * v2 * v1< * v3-v4 * */ - v1 = graph.addVertex(new ArtifactMetadata("g","a1","1.0")); + v1 = graph.addVertex(new ArtifactMetadata("g", "a1", "1.0")); graph.setEntry(v1); - v2 = graph.addVertex(new ArtifactMetadata("g","a2","1.0")); - v3 = graph.addVertex(new ArtifactMetadata("g","a3","1.0")); - v4 = graph.addVertex(new ArtifactMetadata("g","a4","1.0")); + v2 = graph.addVertex(new ArtifactMetadata("g", "a2", "1.0")); + v3 = graph.addVertex(new ArtifactMetadata("g", "a3", "1.0")); + v4 = graph.addVertex(new ArtifactMetadata("g", "a4", "1.0")); // v1-->v2 - graph.addEdge(v1, v2, new MetadataGraphEdge( "1.1", true, null, null, 2, 1 ) ); - graph.addEdge(v1, v2, new MetadataGraphEdge( "1.2", true, null, null, 2, 2 ) ); + graph.addEdge(v1, v2, new MetadataGraphEdge("1.1", true, null, null, 2, 1)); + graph.addEdge(v1, v2, new MetadataGraphEdge("1.2", true, null, null, 2, 2)); // v1-->v3 - graph.addEdge(v1, v3, new MetadataGraphEdge( "1.1", true, null, null, 2, 1 ) ); - graph.addEdge(v1, v3, new MetadataGraphEdge( "1.2", true, null, null, 4, 2 ) ); + graph.addEdge(v1, v3, new MetadataGraphEdge("1.1", true, null, null, 2, 1)); + graph.addEdge(v1, v3, new MetadataGraphEdge("1.2", true, null, null, 4, 2)); // v3-->v4 - graph.addEdge(v3, v4, new MetadataGraphEdge( "1.1", true, ArtifactScopeEnum.runtime, null, 2, 2 ) ); - graph.addEdge(v3, v4, new MetadataGraphEdge( "1.2", true, ArtifactScopeEnum.test, null, 2, 2 ) ); + graph.addEdge(v3, v4, new MetadataGraphEdge("1.1", true, ArtifactScopeEnum.runtime, null, 2, 2)); + graph.addEdge(v3, v4, new MetadataGraphEdge("1.2", true, ArtifactScopeEnum.test, null, 2, 2)); } - //------------------------------------------------------------------------------------------ - @Test - public void testCompileClasspathTransform() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @Test + public void testCompileClasspathTransform() throws Exception { ClasspathContainer res; - res = transform.transform( graph, ArtifactScopeEnum.compile, false ); + res = transform.transform(graph, ArtifactScopeEnum.compile, false); - assertNotNull( res, "null classpath container after compile transform" ); - assertNotNull( res.getClasspath(), "null classpath after compile transform" ); - assertEquals( 3, res.getClasspath().size(), "compile classpath should have 3 entries" ); + assertNotNull(res, "null classpath container after compile transform"); + assertNotNull(res.getClasspath(), "null classpath after compile transform"); + assertEquals(3, res.getClasspath().size(), "compile classpath should have 3 entries"); } - //------------------------------------------------------------------------------------------ - @Test - public void testRuntimeClasspathTransform() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @Test + public void testRuntimeClasspathTransform() throws Exception { ClasspathContainer res; - res = transform.transform( graph, ArtifactScopeEnum.runtime, false ); + res = transform.transform(graph, ArtifactScopeEnum.runtime, false); - assertNotNull( res, "null classpath container after runtime transform" ); - assertNotNull( res.getClasspath(), "null classpath after runtime transform" ); - assertEquals( 4, res.getClasspath().size(), "runtime classpath should have 4 entries" ); + assertNotNull(res, "null classpath container after runtime transform"); + assertNotNull(res.getClasspath(), "null classpath after runtime transform"); + assertEquals(4, res.getClasspath().size(), "runtime classpath should have 4 entries"); ArtifactMetadata md = res.getClasspath().get(3); - assertEquals("1.1", md.getVersion(), "runtime artifact version should be 1.1" ); + assertEquals("1.1", md.getVersion(), "runtime artifact version should be 1.1"); } - //------------------------------------------------------------------------------------------ - @Test - public void testTestClasspathTransform() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @Test + public void testTestClasspathTransform() throws Exception { ClasspathContainer res; - res = transform.transform( graph, ArtifactScopeEnum.test, false ); + res = transform.transform(graph, ArtifactScopeEnum.test, false); - assertNotNull( res, "null classpath container after test transform" ); - assertNotNull( res.getClasspath(), "null classpath after test transform" ); - assertEquals( 4, res.getClasspath().size(), "test classpath should have 4 entries" ); + assertNotNull(res, "null classpath container after test transform"); + assertNotNull(res.getClasspath(), "null classpath after test transform"); + assertEquals(4, res.getClasspath().size(), "test classpath should have 4 entries"); ArtifactMetadata md = res.getClasspath().get(3); - assertEquals("1.2", md.getVersion(), "test artifact version should be 1.2" ); + assertEquals("1.2", md.getVersion(), "test artifact version should be 1.2"); } - //------------------------------------------------------------------------------------------ - //------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------ } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicyTest.java b/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicyTest.java index ea4352e504..6ab5acf51f 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicyTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicyTest.java @@ -1,59 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.repository.metadata; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * * @author Oleg Gusakov * */ - -public class DefaultGraphConflictResolutionPolicyTest -{ +public class DefaultGraphConflictResolutionPolicyTest { GraphConflictResolutionPolicy policy; MetadataGraphEdge e1; MetadataGraphEdge e2; MetadataGraphEdge e3; - //------------------------------------------------------------------------------------------ - @BeforeEach - public void setUp() throws Exception - { - policy = new DefaultGraphConflictResolutionPolicy(); - e1 = new MetadataGraphEdge( "1.1", true, null, null, 2, 1 ); - e2 = new MetadataGraphEdge( "1.2", true, null, null, 3, 2 ); - e3 = new MetadataGraphEdge( "1.2", true, null, null, 2, 3 ); - } - //------------------------------------------------------------------------------------------ - @Test - public void testDefaultPolicy() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @BeforeEach + public void setUp() throws Exception { + policy = new DefaultGraphConflictResolutionPolicy(); + e1 = new MetadataGraphEdge("1.1", true, null, null, 2, 1); + e2 = new MetadataGraphEdge("1.2", true, null, null, 3, 2); + e3 = new MetadataGraphEdge("1.2", true, null, null, 2, 3); + } + // ------------------------------------------------------------------------------------------ + @Test + public void testDefaultPolicy() throws Exception { MetadataGraphEdge res; - res = policy.apply( e1, e2 ); - assertEquals( "1.1", res.getVersion(), "Wrong depth edge selected" ); + res = policy.apply(e1, e2); + assertEquals("1.1", res.getVersion(), "Wrong depth edge selected"); - res = policy.apply( e1, e3 ); - assertEquals( "1.2", res.getVersion(), "Wrong version edge selected" ); + res = policy.apply(e1, e3); + assertEquals("1.2", res.getVersion(), "Wrong version edge selected"); } - //------------------------------------------------------------------------------------------ - //------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------ } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolverTest.java b/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolverTest.java index 67a003ab17..536b4bb552 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolverTest.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolverTest.java @@ -1,38 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.repository.metadata; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import javax.inject.Inject; - import org.apache.maven.artifact.ArtifactScopeEnum; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * * @author Oleg Gusakov * */ @PlexusTest -public class DefaultGraphConflictResolverTest -{ +public class DefaultGraphConflictResolverTest { @Inject GraphConflictResolver resolver; @@ -42,111 +43,155 @@ public class DefaultGraphConflictResolverTest MetadataGraphVertex v2; MetadataGraphVertex v3; MetadataGraphVertex v4; - //------------------------------------------------------------------------------------------ - @BeforeEach - public void setUp() throws Exception - { + // ------------------------------------------------------------------------------------------ + @BeforeEach + public void setUp() throws Exception { /* * v2 * v1< * v3-v4 * */ - graph = new MetadataGraph( 4, 3 ); - v1 = graph.addVertex(new ArtifactMetadata("g","a1","1.0")); + graph = new MetadataGraph(4, 3); + v1 = graph.addVertex(new ArtifactMetadata("g", "a1", "1.0")); graph.setEntry(v1); - v2 = graph.addVertex(new ArtifactMetadata("g","a2","1.0")); - v3 = graph.addVertex(new ArtifactMetadata("g","a3","1.0")); - v4 = graph.addVertex(new ArtifactMetadata("g","a4","1.0")); + v2 = graph.addVertex(new ArtifactMetadata("g", "a2", "1.0")); + v3 = graph.addVertex(new ArtifactMetadata("g", "a3", "1.0")); + v4 = graph.addVertex(new ArtifactMetadata("g", "a4", "1.0")); // v1-->v2 - graph.addEdge(v1, v2, new MetadataGraphEdge( "1.1", true, null, null, 2, 1 ) ); - graph.addEdge(v1, v2, new MetadataGraphEdge( "1.2", true, null, null, 2, 2 ) ); + graph.addEdge(v1, v2, new MetadataGraphEdge("1.1", true, null, null, 2, 1)); + graph.addEdge(v1, v2, new MetadataGraphEdge("1.2", true, null, null, 2, 2)); // v1-->v3 - graph.addEdge(v1, v3, new MetadataGraphEdge( "1.1", true, null, null, 2, 1 ) ); - graph.addEdge(v1, v3, new MetadataGraphEdge( "1.2", true, null, null, 4, 2 ) ); + graph.addEdge(v1, v3, new MetadataGraphEdge("1.1", true, null, null, 2, 1)); + graph.addEdge(v1, v3, new MetadataGraphEdge("1.2", true, null, null, 4, 2)); // v3-->v4 - graph.addEdge(v3, v4, new MetadataGraphEdge( "1.1", true, ArtifactScopeEnum.runtime, null, 2, 1 ) ); - graph.addEdge(v3, v4, new MetadataGraphEdge( "1.2", true, ArtifactScopeEnum.provided, null, 2, 2 ) ); + graph.addEdge(v3, v4, new MetadataGraphEdge("1.1", true, ArtifactScopeEnum.runtime, null, 2, 1)); + graph.addEdge(v3, v4, new MetadataGraphEdge("1.2", true, ArtifactScopeEnum.provided, null, 2, 2)); } - //------------------------------------------------------------------------------------------ - @Test - public void testCompileResolution() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @Test + public void testCompileResolution() throws Exception { MetadataGraph res; - res = resolver.resolveConflicts( graph, ArtifactScopeEnum.compile ); + res = resolver.resolveConflicts(graph, ArtifactScopeEnum.compile); - assertNotNull( res, "null graph after resolver" ); - assertNotNull( res.getVertices(), "no vertices in the resulting graph after resolver" ); + assertNotNull(res, "null graph after resolver"); + assertNotNull(res.getVertices(), "no vertices in the resulting graph after resolver"); - assertNotNull( res.getExcidentEdges(v1), "no edges in the resulting graph after resolver" ); + assertNotNull(res.getExcidentEdges(v1), "no edges in the resulting graph after resolver"); - assertEquals( 4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver" ); - assertEquals( 2, res.getExcidentEdges(v1).size(), "wrong # of excident edges in the resulting graph entry after resolver" ); + assertEquals(4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver"); + assertEquals( + 2, + res.getExcidentEdges(v1).size(), + "wrong # of excident edges in the resulting graph entry after resolver"); - assertEquals( 1, res.getIncidentEdges(v2).size(), "wrong # of v2 incident edges in the resulting graph after resolver" ); - assertEquals( "1.2", res.getIncidentEdges(v2).get(0).getVersion(), "wrong edge v1-v2 in the resulting graph after resolver" ); + assertEquals( + 1, + res.getIncidentEdges(v2).size(), + "wrong # of v2 incident edges in the resulting graph after resolver"); + assertEquals( + "1.2", + res.getIncidentEdges(v2).get(0).getVersion(), + "wrong edge v1-v2 in the resulting graph after resolver"); - assertEquals( 1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver" ); - assertEquals( "1.1", res.getIncidentEdges(v3).get(0).getVersion(), "wrong edge v1-v3 in the resulting graph after resolver" ); + assertEquals( + 1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver"); + assertEquals( + "1.1", + res.getIncidentEdges(v3).get(0).getVersion(), + "wrong edge v1-v3 in the resulting graph after resolver"); - assertEquals( 1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver" ); - assertEquals( "1.2", res.getIncidentEdges(v4).get(0).getVersion(), "wrong edge v3-v4 in the resulting graph after resolver" ); + assertEquals( + 1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver"); + assertEquals( + "1.2", + res.getIncidentEdges(v4).get(0).getVersion(), + "wrong edge v3-v4 in the resulting graph after resolver"); } - //------------------------------------------------------------------------------------------ - @Test - public void testRuntimeResolution() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @Test + public void testRuntimeResolution() throws Exception { MetadataGraph res; - res = resolver.resolveConflicts( graph, ArtifactScopeEnum.runtime ); + res = resolver.resolveConflicts(graph, ArtifactScopeEnum.runtime); - assertNotNull( res, "null graph after resolver" ); - assertNotNull( res.getVertices(), "no vertices in the resulting graph after resolver" ); - assertNotNull( res.getExcidentEdges(v1), "no edges in the resulting graph after resolver" ); + assertNotNull(res, "null graph after resolver"); + assertNotNull(res.getVertices(), "no vertices in the resulting graph after resolver"); + assertNotNull(res.getExcidentEdges(v1), "no edges in the resulting graph after resolver"); - assertEquals( 4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver" ); - assertEquals( 2, res.getExcidentEdges(v1).size(), "wrong # of excident edges in the resulting graph entry after resolver" ); + assertEquals(4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver"); + assertEquals( + 2, + res.getExcidentEdges(v1).size(), + "wrong # of excident edges in the resulting graph entry after resolver"); - assertEquals( 1, res.getIncidentEdges(v2).size(), "wrong # of v2 incident edges in the resulting graph after resolver" ); - assertEquals( "1.2", res.getIncidentEdges(v2).get(0).getVersion(), "wrong edge v1-v2 in the resulting graph after resolver" ); + assertEquals( + 1, + res.getIncidentEdges(v2).size(), + "wrong # of v2 incident edges in the resulting graph after resolver"); + assertEquals( + "1.2", + res.getIncidentEdges(v2).get(0).getVersion(), + "wrong edge v1-v2 in the resulting graph after resolver"); - assertEquals( 1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver" ); - assertEquals( "1.1", res.getIncidentEdges(v3).get(0).getVersion(), "wrong edge v1-v3 in the resulting graph after resolver" ); + assertEquals( + 1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver"); + assertEquals( + "1.1", + res.getIncidentEdges(v3).get(0).getVersion(), + "wrong edge v1-v3 in the resulting graph after resolver"); - assertEquals( 1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver" ); - assertEquals( "1.1", res.getIncidentEdges(v4).get(0).getVersion(), "wrong edge v3-v4 in the resulting graph after resolver" ); + assertEquals( + 1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver"); + assertEquals( + "1.1", + res.getIncidentEdges(v4).get(0).getVersion(), + "wrong edge v3-v4 in the resulting graph after resolver"); } - //------------------------------------------------------------------------------------------ - @Test - public void testTestResolution() - throws Exception - { + // ------------------------------------------------------------------------------------------ + @Test + public void testTestResolution() throws Exception { MetadataGraph res; - res = resolver.resolveConflicts( graph, ArtifactScopeEnum.test ); + res = resolver.resolveConflicts(graph, ArtifactScopeEnum.test); - assertNotNull( res, "null graph after resolver" ); - assertNotNull( res.getVertices(), "no vertices in the resulting graph after resolver" ); - assertNotNull( res.getExcidentEdges(v1), "no edges in the resulting graph after resolver" ); + assertNotNull(res, "null graph after resolver"); + assertNotNull(res.getVertices(), "no vertices in the resulting graph after resolver"); + assertNotNull(res.getExcidentEdges(v1), "no edges in the resulting graph after resolver"); - assertEquals( 4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver" ); - assertEquals( 2, res.getExcidentEdges(v1).size(), "wrong # of excident edges in the resulting graph entry after resolver" ); + assertEquals(4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver"); + assertEquals( + 2, + res.getExcidentEdges(v1).size(), + "wrong # of excident edges in the resulting graph entry after resolver"); - assertEquals( 1, res.getIncidentEdges(v2).size(), "wrong # of v2 incident edges in the resulting graph after resolver" ); - assertEquals( "1.2", res.getIncidentEdges(v2).get(0).getVersion(), "wrong edge v1-v2 in the resulting graph after resolver" ); + assertEquals( + 1, + res.getIncidentEdges(v2).size(), + "wrong # of v2 incident edges in the resulting graph after resolver"); + assertEquals( + "1.2", + res.getIncidentEdges(v2).get(0).getVersion(), + "wrong edge v1-v2 in the resulting graph after resolver"); - assertEquals( 1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver" ); - assertEquals( "1.1", res.getIncidentEdges(v3).get(0).getVersion(), "wrong edge v1-v3 in the resulting graph after resolver" ); + assertEquals( + 1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver"); + assertEquals( + "1.1", + res.getIncidentEdges(v3).get(0).getVersion(), + "wrong edge v1-v3 in the resulting graph after resolver"); - assertEquals( 1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver" ); - assertEquals( "1.2", res.getIncidentEdges(v4).get(0).getVersion(), "wrong edge v3-v4 in the resulting graph after resolver" ); + assertEquals( + 1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver"); + assertEquals( + "1.2", + res.getIncidentEdges(v4).get(0).getVersion(), + "wrong edge v3-v4 in the resulting graph after resolver"); } - //------------------------------------------------------------------------------------------ - //------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------ } diff --git a/maven-compat/src/test/java/org/apache/maven/repository/metadata/TestMetadataSource.java b/maven-compat/src/test/java/org/apache/maven/repository/metadata/TestMetadataSource.java index efec2e6ea7..d1d37f9bb8 100644 --- a/maven-compat/src/test/java/org/apache/maven/repository/metadata/TestMetadataSource.java +++ b/maven-compat/src/test/java/org/apache/maven/repository/metadata/TestMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,14 @@ package org.apache.maven.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.metadata; import java.util.HashSet; import java.util.List; import java.util.Set; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -32,71 +33,53 @@ import org.apache.maven.repository.legacy.metadata.ArtifactMetadataSource; import org.apache.maven.repository.legacy.metadata.MetadataResolutionRequest; import org.apache.maven.repository.legacy.metadata.ResolutionGroup; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - @Named @Singleton -public class TestMetadataSource - implements ArtifactMetadataSource -{ +public class TestMetadataSource implements ArtifactMetadataSource { @Inject private ArtifactFactory factory; - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { + public ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { Set dependencies = new HashSet<>(); - if ( "g".equals( artifact.getArtifactId() ) ) - { + if ("g".equals(artifact.getArtifactId())) { Artifact a = null; - try - { - a = factory.createBuildArtifact( "org.apache.maven", "h", "1.0", "jar" ); - dependencies.add( a ); - } - catch ( Exception e ) - { - throw new ArtifactMetadataRetrievalException( "Error retrieving metadata", e, a ); + try { + a = factory.createBuildArtifact("org.apache.maven", "h", "1.0", "jar"); + dependencies.add(a); + } catch (Exception e) { + throw new ArtifactMetadataRetrievalException("Error retrieving metadata", e, a); } } - if ( "i".equals( artifact.getArtifactId() ) ) - { + if ("i".equals(artifact.getArtifactId())) { Artifact a = null; - try - { - a = factory.createBuildArtifact( "org.apache.maven", "j", "1.0-SNAPSHOT", "jar" ); - dependencies.add( a ); - } - catch ( Exception e ) - { - throw new ArtifactMetadataRetrievalException( "Error retrieving metadata", e, a ); + try { + a = factory.createBuildArtifact("org.apache.maven", "j", "1.0-SNAPSHOT", "jar"); + dependencies.add(a); + } catch (Exception e) { + throw new ArtifactMetadataRetrievalException("Error retrieving metadata", e, a); } } - - return new ResolutionGroup( artifact, dependencies, remoteRepositories ); + return new ResolutionGroup(artifact, dependencies, remoteRepositories); } - public List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { - throw new UnsupportedOperationException( "Cannot get available versions in this test case" ); + public List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { + throw new UnsupportedOperationException("Cannot get available versions in this test case"); } - public List retrieveAvailableVersionsFromDeploymentRepository( Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws ArtifactMetadataRetrievalException - { - throw new UnsupportedOperationException( "Cannot get available versions in this test case" ); + public List retrieveAvailableVersionsFromDeploymentRepository( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws ArtifactMetadataRetrievalException { + throw new UnsupportedOperationException("Cannot get available versions in this test case"); } - public ResolutionGroup retrieve( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { - return retrieve( request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories() ); + public ResolutionGroup retrieve(MetadataResolutionRequest request) throws ArtifactMetadataRetrievalException { + return retrieve(request.getArtifact(), request.getLocalRepository(), request.getRemoteRepositories()); } - } diff --git a/maven-core/pom.xml b/maven-core/pom.xml index fabf87ee13..7898eba527 100644 --- a/maven-core/pom.xml +++ b/maven-core/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -196,8 +194,8 @@ under the License. - src/main/resources true + src/main/resources @@ -227,16 +225,16 @@ under the License. 1.1.0 - + modello-site-doc - pre-site xdoc + pre-site 1.0.0 diff --git a/maven-core/src/main/java/org/apache/maven/AbstractMavenLifecycleParticipant.java b/maven-core/src/main/java/org/apache/maven/AbstractMavenLifecycleParticipant.java index 09f23d3117..c3384a3b40 100644 --- a/maven-core/src/main/java/org/apache/maven/AbstractMavenLifecycleParticipant.java +++ b/maven-core/src/main/java/org/apache/maven/AbstractMavenLifecycleParticipant.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import org.apache.maven.execution.MavenSession; @@ -31,8 +30,7 @@ import org.apache.maven.execution.MavenSession; * @see MNG-4224 * @since 3.0-alpha-3 */ -public abstract class AbstractMavenLifecycleParticipant -{ +public abstract class AbstractMavenLifecycleParticipant { /** * Invoked after all MavenProject instances have been created. @@ -43,9 +41,7 @@ public abstract class AbstractMavenLifecycleParticipant * @param session the Maven session * @throws MavenExecutionException in case of issue */ - public void afterProjectsRead( MavenSession session ) - throws MavenExecutionException - { + public void afterProjectsRead(MavenSession session) throws MavenExecutionException { // do nothing } @@ -60,9 +56,7 @@ public abstract class AbstractMavenLifecycleParticipant * @throws MavenExecutionException in case of issue */ // TODO This is too early for build extensions, so maybe just remove it? - public void afterSessionStart( MavenSession session ) - throws MavenExecutionException - { + public void afterSessionStart(MavenSession session) throws MavenExecutionException { // do nothing } @@ -78,9 +72,7 @@ public abstract class AbstractMavenLifecycleParticipant * @throws MavenExecutionException in case of issue * @since 3.2.1, MNG-5389 */ - public void afterSessionEnd( MavenSession session ) - throws MavenExecutionException - { + public void afterSessionEnd(MavenSession session) throws MavenExecutionException { // do nothing } } diff --git a/maven-core/src/main/java/org/apache/maven/ArtifactFilterManager.java b/maven-core/src/main/java/org/apache/maven/ArtifactFilterManager.java index 0db1c594f2..8aa777486d 100644 --- a/maven-core/src/main/java/org/apache/maven/ArtifactFilterManager.java +++ b/maven-core/src/main/java/org/apache/maven/ArtifactFilterManager.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.util.Set; - import org.apache.maven.artifact.resolver.filter.ArtifactFilter; /** * ArtifactFilterManager */ -public interface ArtifactFilterManager -{ +public interface ArtifactFilterManager { /** * Returns a filter for core + extension artifacts. * @@ -51,8 +48,7 @@ public interface ArtifactFilterManager * @deprecated use {@code META-INF/maven/extension.xml} to define artifacts exported by Maven core and plugin * extensions. */ - void excludeArtifact( String artifactId ); + void excludeArtifact(String artifactId); Set getCoreArtifactExcludes(); - } diff --git a/maven-core/src/main/java/org/apache/maven/ArtifactFilterManagerDelegate.java b/maven-core/src/main/java/org/apache/maven/ArtifactFilterManagerDelegate.java index 1389325482..7deb000afd 100644 --- a/maven-core/src/main/java/org/apache/maven/ArtifactFilterManagerDelegate.java +++ b/maven-core/src/main/java/org/apache/maven/ArtifactFilterManagerDelegate.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.util.Set; /** * @deprecated use {@code META-INF/maven/extension.xml} to define artifacts exported by Maven core extensions. */ -public interface ArtifactFilterManagerDelegate -{ +public interface ArtifactFilterManagerDelegate { - void addExcludes( Set excludes ); - - void addCoreExcludes( Set excludes ); + void addExcludes(Set excludes); + void addCoreExcludes(Set excludes); } diff --git a/maven-core/src/main/java/org/apache/maven/BuildAbort.java b/maven-core/src/main/java/org/apache/maven/BuildAbort.java index 3255e32b99..6585f9e547 100644 --- a/maven-core/src/main/java/org/apache/maven/BuildAbort.java +++ b/maven-core/src/main/java/org/apache/maven/BuildAbort.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,22 +16,18 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; /** * A special throwable used to signal a graceful abort of the build. */ -public class BuildAbort - extends Error -{ +public class BuildAbort extends Error { - public BuildAbort( String message ) - { - super( message ); + public BuildAbort(String message) { + super(message); } - public BuildAbort( String message, Throwable cause ) - { - super( message, cause ); + public BuildAbort(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-core/src/main/java/org/apache/maven/BuildFailureException.java b/maven-core/src/main/java/org/apache/maven/BuildFailureException.java index d35b0d2afb..f211af2abe 100644 --- a/maven-core/src/main/java/org/apache/maven/BuildFailureException.java +++ b/maven-core/src/main/java/org/apache/maven/BuildFailureException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,22 +16,19 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; /** * One or more builds failed. * * @author Brett Porter */ -public class BuildFailureException - extends Exception -{ - public BuildFailureException( String message ) - { - super( message ); +public class BuildFailureException extends Exception { + public BuildFailureException(String message) { + super(message); } - public BuildFailureException( String message, Throwable cause ) - { - super( message, cause ); + public BuildFailureException(String message, Throwable cause) { + super(message, cause); } } diff --git a/maven-core/src/main/java/org/apache/maven/DefaultArtifactFilterManager.java b/maven-core/src/main/java/org/apache/maven/DefaultArtifactFilterManager.java index 810baaef38..e9b693968c 100644 --- a/maven-core/src/main/java/org/apache/maven/DefaultArtifactFilterManager.java +++ b/maven-core/src/main/java/org/apache/maven/DefaultArtifactFilterManager.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,15 +16,14 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ExclusionSetFilter; import org.apache.maven.extension.internal.CoreExports; @@ -36,10 +33,8 @@ import org.apache.maven.extension.internal.CoreExports; */ @Named @Singleton -@SuppressWarnings( "deprecation" ) -public class DefaultArtifactFilterManager - implements ArtifactFilterManager -{ +@SuppressWarnings("deprecation") +public class DefaultArtifactFilterManager implements ArtifactFilterManager { // this is a live injected collection protected final List delegates; @@ -49,18 +44,14 @@ public class DefaultArtifactFilterManager private final Set coreArtifacts; @Inject - public DefaultArtifactFilterManager( List delegates, - CoreExports coreExports ) - { + public DefaultArtifactFilterManager(List delegates, CoreExports coreExports) { this.delegates = delegates; this.coreArtifacts = coreExports.getExportedArtifacts(); } - private synchronized Set getExcludedArtifacts() - { - if ( excludedArtifacts == null ) - { - excludedArtifacts = new LinkedHashSet<>( coreArtifacts ); + private synchronized Set getExcludedArtifacts() { + if (excludedArtifacts == null) { + excludedArtifacts = new LinkedHashSet<>(coreArtifacts); } return excludedArtifacts; } @@ -70,16 +61,14 @@ public class DefaultArtifactFilterManager * * @see org.apache.maven.ArtifactFilterManager#getArtifactFilter() */ - public ArtifactFilter getArtifactFilter() - { - Set excludes = new LinkedHashSet<>( getExcludedArtifacts() ); + public ArtifactFilter getArtifactFilter() { + Set excludes = new LinkedHashSet<>(getExcludedArtifacts()); - for ( ArtifactFilterManagerDelegate delegate : delegates ) - { - delegate.addExcludes( excludes ); + for (ArtifactFilterManagerDelegate delegate : delegates) { + delegate.addExcludes(excludes); } - return new ExclusionSetFilter( excludes ); + return new ExclusionSetFilter(excludes); } /** @@ -87,26 +76,21 @@ public class DefaultArtifactFilterManager * * @see org.apache.maven.ArtifactFilterManager#getCoreArtifactFilter() */ - public ArtifactFilter getCoreArtifactFilter() - { - return new ExclusionSetFilter( getCoreArtifactExcludes() ); + public ArtifactFilter getCoreArtifactFilter() { + return new ExclusionSetFilter(getCoreArtifactExcludes()); } - public void excludeArtifact( String artifactId ) - { - getExcludedArtifacts().add( artifactId ); + public void excludeArtifact(String artifactId) { + getExcludedArtifacts().add(artifactId); } - public Set getCoreArtifactExcludes() - { - Set excludes = new LinkedHashSet<>( coreArtifacts ); + public Set getCoreArtifactExcludes() { + Set excludes = new LinkedHashSet<>(coreArtifacts); - for ( ArtifactFilterManagerDelegate delegate : delegates ) - { - delegate.addCoreExcludes( excludes ); + for (ArtifactFilterManagerDelegate delegate : delegates) { + delegate.addCoreExcludes(excludes); } return excludes; } - } diff --git a/maven-core/src/main/java/org/apache/maven/DefaultMaven.java b/maven-core/src/main/java/org/apache/maven/DefaultMaven.java index dd47a2d9a7..451f50dc50 100644 --- a/maven-core/src/main/java/org/apache/maven/DefaultMaven.java +++ b/maven-core/src/main/java/org/apache/maven/DefaultMaven.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,8 +16,31 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; +import static java.util.stream.Collectors.toSet; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Stream; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.Session; +import org.apache.maven.api.model.Model; +import org.apache.maven.api.model.Prerequisites; +import org.apache.maven.api.model.Profile; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.execution.BuildResumptionAnalyzer; import org.apache.maven.execution.BuildResumptionDataRepository; @@ -35,15 +56,12 @@ import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.graph.GraphBuilder; import org.apache.maven.graph.ProjectSelector; import org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory; +import org.apache.maven.internal.aether.MavenChainedWorkspaceReader; import org.apache.maven.internal.impl.DefaultSession; import org.apache.maven.internal.impl.DefaultSessionFactory; import org.apache.maven.lifecycle.LifecycleExecutionException; -import org.apache.maven.internal.aether.MavenChainedWorkspaceReader; import org.apache.maven.lifecycle.internal.ExecutionEventCatapult; import org.apache.maven.lifecycle.internal.LifecycleStarter; -import org.apache.maven.api.model.Model; -import org.apache.maven.api.model.Prerequisites; -import org.apache.maven.api.model.Profile; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.model.building.Result; import org.apache.maven.model.superpom.SuperPomProvider; @@ -61,35 +79,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Stream; - -import static java.util.stream.Collectors.toSet; - /** * @author Jason van Zyl */ @Named @Singleton -public class DefaultMaven - implements Maven -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultMaven implements Maven { + private final Logger logger = LoggerFactory.getLogger(getClass()); protected ProjectBuilder projectBuilder; @@ -118,7 +114,7 @@ public class DefaultMaven private final ProjectSelector projectSelector; @Inject - @SuppressWarnings( "checkstyle:ParameterNumber" ) + @SuppressWarnings("checkstyle:ParameterNumber") public DefaultMaven( ProjectBuilder projectBuilder, LifecycleStarter lifecycleStarter, @@ -127,12 +123,11 @@ public class DefaultMaven LegacySupport legacySupport, SessionScope sessionScope, DefaultRepositorySystemSessionFactory repositorySessionFactory, - @Named( GraphBuilder.HINT ) GraphBuilder graphBuilder, + @Named(GraphBuilder.HINT) GraphBuilder graphBuilder, BuildResumptionAnalyzer buildResumptionAnalyzer, BuildResumptionDataRepository buildResumptionDataRepository, SuperPomProvider superPomProvider, - DefaultSessionFactory defaultSessionFactory ) - { + DefaultSessionFactory defaultSessionFactory) { this.projectBuilder = projectBuilder; this.lifecycleStarter = lifecycleStarter; this.container = container; @@ -149,34 +144,23 @@ public class DefaultMaven } @Override - public MavenExecutionResult execute( MavenExecutionRequest request ) - { + public MavenExecutionResult execute(MavenExecutionRequest request) { MavenExecutionResult result; - try - { - result = doExecute( request ); - } - catch ( OutOfMemoryError e ) - { - result = addExceptionToResult( new DefaultMavenExecutionResult(), e ); - } - catch ( RuntimeException e ) - { + try { + result = doExecute(request); + } catch (OutOfMemoryError e) { + result = addExceptionToResult(new DefaultMavenExecutionResult(), e); + } catch (RuntimeException e) { // TODO Hack to make the cycle detection the same for the new graph builder - if ( e.getCause() instanceof ProjectCycleException ) - { - result = addExceptionToResult( new DefaultMavenExecutionResult(), e.getCause() ); + if (e.getCause() instanceof ProjectCycleException) { + result = addExceptionToResult(new DefaultMavenExecutionResult(), e.getCause()); + } else { + result = addExceptionToResult( + new DefaultMavenExecutionResult(), new InternalErrorException("Internal error: " + e, e)); } - else - { - result = addExceptionToResult( new DefaultMavenExecutionResult(), - new InternalErrorException( "Internal error: " + e, e ) ); - } - } - finally - { - legacySupport.setSession( null ); + } finally { + legacySupport.setSession(null); } return result; @@ -210,20 +194,16 @@ public class DefaultMaven // // 11) Execute LifecycleStarter.start() // - @SuppressWarnings( "checkstyle:methodlength" ) - private MavenExecutionResult doExecute( MavenExecutionRequest request ) - { - request.setStartTime( new Date() ); + @SuppressWarnings("checkstyle:methodlength") + private MavenExecutionResult doExecute(MavenExecutionRequest request) { + request.setStartTime(new Date()); MavenExecutionResult result = new DefaultMavenExecutionResult(); - try - { - validateLocalRepository( request ); - } - catch ( LocalRepositoryNotAccessibleException e ) - { - return addExceptionToResult( result, e ); + try { + validateLocalRepository(request); + } catch (LocalRepositoryNotAccessibleException e) { + return addExceptionToResult(result, e); } // @@ -232,73 +212,59 @@ public class DefaultMaven // so that @SessionScoped components can be @Injected into AbstractLifecycleParticipants. // sessionScope.enter(); - try - { - DefaultRepositorySystemSession repoSession = - (DefaultRepositorySystemSession) newRepositorySession( request ); - MavenSession session = new MavenSession( container, repoSession, request, result ); - session.setSession( defaultSessionFactory.getSession( session ) ); + try { + DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) newRepositorySession(request); + MavenSession session = new MavenSession(container, repoSession, request, result); + session.setSession(defaultSessionFactory.getSession(session)); - sessionScope.seed( MavenSession.class, session ); - sessionScope.seed( Session.class, session.getSession() ); - sessionScope.seed( DefaultSession.class, (DefaultSession) session.getSession() ); + sessionScope.seed(MavenSession.class, session); + sessionScope.seed(Session.class, session.getSession()); + sessionScope.seed(DefaultSession.class, (DefaultSession) session.getSession()); - legacySupport.setSession( session ); + legacySupport.setSession(session); - return doExecute( request, session, result, repoSession ); - } - finally - { + return doExecute(request, session, result, repoSession); + } finally { sessionScope.exit(); } } - private MavenExecutionResult doExecute( MavenExecutionRequest request, MavenSession session, - MavenExecutionResult result, DefaultRepositorySystemSession repoSession ) - { - try - { - afterSessionStart( session ); - } - catch ( MavenExecutionException e ) - { - return addExceptionToResult( result, e ); + private MavenExecutionResult doExecute( + MavenExecutionRequest request, + MavenSession session, + MavenExecutionResult result, + DefaultRepositorySystemSession repoSession) { + try { + afterSessionStart(session); + } catch (MavenExecutionException e) { + return addExceptionToResult(result, e); } - eventCatapult.fire( ExecutionEvent.Type.ProjectDiscoveryStarted, session, null ); + eventCatapult.fire(ExecutionEvent.Type.ProjectDiscoveryStarted, session, null); - Result graphResult = buildGraph( session ); + Result graphResult = buildGraph(session); - if ( graphResult.hasErrors() ) - { - return addExceptionToResult( result, graphResult.getProblems().iterator().next().getException() ); + if (graphResult.hasErrors()) { + return addExceptionToResult( + result, graphResult.getProblems().iterator().next().getException()); } - try - { - session.setProjectMap( getProjectMap( session.getProjects() ) ); - } - catch ( DuplicateProjectException e ) - { - return addExceptionToResult( result, e ); + try { + session.setProjectMap(getProjectMap(session.getProjects())); + } catch (DuplicateProjectException e) { + return addExceptionToResult(result, e); } - try - { - setupWorkspaceReader( session, repoSession ); - } - catch ( ComponentLookupException e ) - { - return addExceptionToResult( result, e ); + try { + setupWorkspaceReader(session, repoSession); + } catch (ComponentLookupException e) { + return addExceptionToResult(result, e); } repoSession.setReadOnly(); - try - { - afterProjectsRead( session ); - } - catch ( MavenExecutionException e ) - { - return addExceptionToResult( result, e ); + try { + afterProjectsRead(session); + } catch (MavenExecutionException e) { + return addExceptionToResult(result, e); } // @@ -310,277 +276,223 @@ public class DefaultMaven // not expected that a participant will add or remove projects from the session. // - graphResult = buildGraph( session ); + graphResult = buildGraph(session); - if ( graphResult.hasErrors() ) - { - return addExceptionToResult( result, graphResult.getProblems().iterator().next().getException() ); + if (graphResult.hasErrors()) { + return addExceptionToResult( + result, graphResult.getProblems().iterator().next().getException()); } - try - { - if ( result.hasExceptions() ) - { + try { + if (result.hasExceptions()) { return result; } - result.setTopologicallySortedProjects( session.getProjects() ); + result.setTopologicallySortedProjects(session.getProjects()); - result.setProject( session.getTopLevelProject() ); + result.setProject(session.getTopLevelProject()); - validatePrerequisitesForNonMavenPluginProjects( session.getProjects() ); + validatePrerequisitesForNonMavenPluginProjects(session.getProjects()); - validateRequiredProfiles( session, request.getProfileActivation() ); - if ( session.getResult().hasExceptions() ) - { + validateRequiredProfiles(session, request.getProfileActivation()); + if (session.getResult().hasExceptions()) { return result; } - validateOptionalProfiles( session, request.getProfileActivation() ); + validateOptionalProfiles(session, request.getProfileActivation()); - lifecycleStarter.execute( session ); + lifecycleStarter.execute(session); - validateOptionalProjects( request, session ); - validateOptionalProfiles( session, request.getProfileActivation() ); + validateOptionalProjects(request, session); + validateOptionalProfiles(session, request.getProfileActivation()); - if ( session.getResult().hasExceptions() ) - { - addExceptionToResult( result, session.getResult().getExceptions().get( 0 ) ); - persistResumptionData( result, session ); + if (session.getResult().hasExceptions()) { + addExceptionToResult(result, session.getResult().getExceptions().get(0)); + persistResumptionData(result, session); return result; - } - else - { + } else { session.getAllProjects().stream() - .filter( MavenProject::isExecutionRoot ) + .filter(MavenProject::isExecutionRoot) .findFirst() - .ifPresent( buildResumptionDataRepository::removeResumptionData ); + .ifPresent(buildResumptionDataRepository::removeResumptionData); } - } - finally - { - try - { - afterSessionEnd( session.getProjects(), session ); - } - catch ( MavenExecutionException e ) - { - return addExceptionToResult( result, e ); + } finally { + try { + afterSessionEnd(session.getProjects(), session); + } catch (MavenExecutionException e) { + return addExceptionToResult(result, e); } } return result; } - private void setupWorkspaceReader( MavenSession session, DefaultRepositorySystemSession repoSession ) - throws ComponentLookupException - { + private void setupWorkspaceReader(MavenSession session, DefaultRepositorySystemSession repoSession) + throws ComponentLookupException { // Desired order of precedence for workspace readers before querying the local artifact repositories List workspaceReaders = new ArrayList(); // 1) Reactor workspace reader - workspaceReaders.add( container.lookup( WorkspaceReader.class, ReactorReader.HINT ) ); + workspaceReaders.add(container.lookup(WorkspaceReader.class, ReactorReader.HINT)); // 2) Repository system session-scoped workspace reader WorkspaceReader repoWorkspaceReader = repoSession.getWorkspaceReader(); - if ( repoWorkspaceReader != null ) - { - workspaceReaders.add( repoWorkspaceReader ); + if (repoWorkspaceReader != null) { + workspaceReaders.add(repoWorkspaceReader); } // 3) .. n) Project-scoped workspace readers - for ( WorkspaceReader workspaceReader : getProjectScopedExtensionComponents( session.getProjects(), - WorkspaceReader.class ) ) - { - if ( workspaceReaders.contains( workspaceReader ) ) - { + for (WorkspaceReader workspaceReader : + getProjectScopedExtensionComponents(session.getProjects(), WorkspaceReader.class)) { + if (workspaceReaders.contains(workspaceReader)) { continue; } - workspaceReaders.add( workspaceReader ); + workspaceReaders.add(workspaceReader); } - repoSession.setWorkspaceReader( MavenChainedWorkspaceReader.of( workspaceReaders ) ); + repoSession.setWorkspaceReader(MavenChainedWorkspaceReader.of(workspaceReaders)); } - private void afterSessionStart( MavenSession session ) - throws MavenExecutionException - { + private void afterSessionStart(MavenSession session) throws MavenExecutionException { // CHECKSTYLE_OFF: LineLength - for ( AbstractMavenLifecycleParticipant listener : getExtensionComponents( Collections.emptyList(), - AbstractMavenLifecycleParticipant.class ) ) + for (AbstractMavenLifecycleParticipant listener : + getExtensionComponents(Collections.emptyList(), AbstractMavenLifecycleParticipant.class)) // CHECKSTYLE_ON: LineLength { - listener.afterSessionStart( session ); + listener.afterSessionStart(session); } } - private void afterProjectsRead( MavenSession session ) - throws MavenExecutionException - { + private void afterProjectsRead(MavenSession session) throws MavenExecutionException { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { // CHECKSTYLE_OFF: LineLength - for ( AbstractMavenLifecycleParticipant listener : getExtensionComponents( session.getProjects(), - AbstractMavenLifecycleParticipant.class ) ) + for (AbstractMavenLifecycleParticipant listener : + getExtensionComponents(session.getProjects(), AbstractMavenLifecycleParticipant.class)) // CHECKSTYLE_ON: LineLength { - Thread.currentThread().setContextClassLoader( listener.getClass().getClassLoader() ); + Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader()); - listener.afterProjectsRead( session ); + listener.afterProjectsRead(session); } - } - finally - { - Thread.currentThread().setContextClassLoader( originalClassLoader ); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); } } - private void afterSessionEnd( Collection projects, MavenSession session ) - throws MavenExecutionException - { + private void afterSessionEnd(Collection projects, MavenSession session) + throws MavenExecutionException { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { // CHECKSTYLE_OFF: LineLength - for ( AbstractMavenLifecycleParticipant listener : getExtensionComponents( projects, - AbstractMavenLifecycleParticipant.class ) ) + for (AbstractMavenLifecycleParticipant listener : + getExtensionComponents(projects, AbstractMavenLifecycleParticipant.class)) // CHECKSTYLE_ON: LineLength { - Thread.currentThread().setContextClassLoader( listener.getClass().getClassLoader() ); + Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader()); - listener.afterSessionEnd( session ); + listener.afterSessionEnd(session); } - } - finally - { - Thread.currentThread().setContextClassLoader( originalClassLoader ); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); } } - private void persistResumptionData( MavenExecutionResult result, MavenSession session ) - { - boolean hasLifecycleExecutionExceptions = result.getExceptions().stream() - .anyMatch( LifecycleExecutionException.class::isInstance ); + private void persistResumptionData(MavenExecutionResult result, MavenSession session) { + boolean hasLifecycleExecutionExceptions = + result.getExceptions().stream().anyMatch(LifecycleExecutionException.class::isInstance); - if ( hasLifecycleExecutionExceptions ) - { + if (hasLifecycleExecutionExceptions) { MavenProject rootProject = session.getAllProjects().stream() - .filter( MavenProject::isExecutionRoot ) + .filter(MavenProject::isExecutionRoot) .findFirst() - .orElseThrow( () -> new IllegalStateException( "No project in the session is execution root" ) ); + .orElseThrow(() -> new IllegalStateException("No project in the session is execution root")); - buildResumptionAnalyzer.determineBuildResumptionData( result ).ifPresent( resumption -> - { - try - { - buildResumptionDataRepository.persistResumptionData( rootProject, resumption ); - result.setCanResume( true ); + buildResumptionAnalyzer.determineBuildResumptionData(result).ifPresent(resumption -> { + try { + buildResumptionDataRepository.persistResumptionData(rootProject, resumption); + result.setCanResume(true); + } catch (BuildResumptionPersistenceException e) { + logger.warn("Could not persist build resumption data", e); } - catch ( BuildResumptionPersistenceException e ) - { - logger.warn( "Could not persist build resumption data", e ); - } - } ); + }); } } - public RepositorySystemSession newRepositorySession( MavenExecutionRequest request ) - { - return repositorySessionFactory.newRepositorySession( request ); + public RepositorySystemSession newRepositorySession(MavenExecutionRequest request) { + return repositorySessionFactory.newRepositorySession(request); } - private void validateLocalRepository( MavenExecutionRequest request ) - throws LocalRepositoryNotAccessibleException - { + private void validateLocalRepository(MavenExecutionRequest request) throws LocalRepositoryNotAccessibleException { File localRepoDir = request.getLocalRepositoryPath(); - logger.debug( "Using local repository at " + localRepoDir ); + logger.debug("Using local repository at " + localRepoDir); localRepoDir.mkdirs(); - if ( !localRepoDir.isDirectory() ) - { - throw new LocalRepositoryNotAccessibleException( "Could not create local repository at " + localRepoDir ); + if (!localRepoDir.isDirectory()) { + throw new LocalRepositoryNotAccessibleException("Could not create local repository at " + localRepoDir); } } - private Collection getExtensionComponents( Collection projects, Class role ) - { + private Collection getExtensionComponents(Collection projects, Class role) { Collection foundComponents = new LinkedHashSet<>(); - try - { - foundComponents.addAll( container.lookupList( role ) ); - } - catch ( ComponentLookupException e ) - { + try { + foundComponents.addAll(container.lookupList(role)); + } catch (ComponentLookupException e) { // this is just silly, lookupList should return an empty list! - logger.warn( "Failed to lookup " + role + ": " + e.getMessage() ); + logger.warn("Failed to lookup " + role + ": " + e.getMessage()); } - foundComponents.addAll( getProjectScopedExtensionComponents( projects, role ) ); + foundComponents.addAll(getProjectScopedExtensionComponents(projects, role)); return foundComponents; } - protected Collection getProjectScopedExtensionComponents( Collection projects, Class role ) - { + protected Collection getProjectScopedExtensionComponents(Collection projects, Class role) { Collection foundComponents = new LinkedHashSet<>(); Collection scannedRealms = new HashSet<>(); Thread currentThread = Thread.currentThread(); ClassLoader originalContextClassLoader = currentThread.getContextClassLoader(); - try - { - for ( MavenProject project : projects ) - { + try { + for (MavenProject project : projects) { ClassLoader projectRealm = project.getClassRealm(); - if ( projectRealm != null && scannedRealms.add( projectRealm ) ) - { - currentThread.setContextClassLoader( projectRealm ); + if (projectRealm != null && scannedRealms.add(projectRealm)) { + currentThread.setContextClassLoader(projectRealm); - try - { - foundComponents.addAll( container.lookupList( role ) ); - } - catch ( ComponentLookupException e ) - { + try { + foundComponents.addAll(container.lookupList(role)); + } catch (ComponentLookupException e) { // this is just silly, lookupList should return an empty list! - logger.warn( "Failed to lookup " + role + ": " + e.getMessage() ); + logger.warn("Failed to lookup " + role + ": " + e.getMessage()); } } } return foundComponents; - } - finally - { - currentThread.setContextClassLoader( originalContextClassLoader ); + } finally { + currentThread.setContextClassLoader(originalContextClassLoader); } } - private MavenExecutionResult addExceptionToResult( MavenExecutionResult result, Throwable e ) - { - if ( !result.getExceptions().contains( e ) ) - { - result.addException( e ); + private MavenExecutionResult addExceptionToResult(MavenExecutionResult result, Throwable e) { + if (!result.getExceptions().contains(e)) { + result.addException(e); } return result; } - private void validatePrerequisitesForNonMavenPluginProjects( List projects ) - { - for ( MavenProject mavenProject : projects ) - { - if ( !"maven-plugin".equals( mavenProject.getPackaging() ) ) - { - Prerequisites prerequisites = mavenProject.getModel().getDelegate().getPrerequisites(); - if ( prerequisites != null && prerequisites.getMaven() != null ) - { - logger.warn( "The project " + mavenProject.getId() + " uses prerequisites" - + " which is only intended for maven-plugin projects " - + "but not for non maven-plugin projects. " - + "For such purposes you should use the maven-enforcer-plugin. " - + "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" ); + private void validatePrerequisitesForNonMavenPluginProjects(List projects) { + for (MavenProject mavenProject : projects) { + if (!"maven-plugin".equals(mavenProject.getPackaging())) { + Prerequisites prerequisites = + mavenProject.getModel().getDelegate().getPrerequisites(); + if (prerequisites != null && prerequisites.getMaven() != null) { + logger.warn("The project " + mavenProject.getId() + " uses prerequisites" + + " which is only intended for maven-plugin projects " + + "but not for non maven-plugin projects. " + + "For such purposes you should use the maven-enforcer-plugin. " + + "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html"); } } } @@ -591,32 +503,29 @@ public class DefaultMaven * @param session The Maven session * @return A {@link Set} of profile identifiers, never {@code null}. */ - private Set getAllProfiles( MavenSession session ) - { - final Model superPomModel = superPomProvider.getSuperModel( "4.0.0" ); + private Set getAllProfiles(MavenSession session) { + final Model superPomModel = superPomProvider.getSuperModel("4.0.0"); final Set projectsIncludingParents = new HashSet<>(); - for ( MavenProject project : session.getProjects() ) - { - boolean isAdded = projectsIncludingParents.add( project ); + for (MavenProject project : session.getProjects()) { + boolean isAdded = projectsIncludingParents.add(project); MavenProject parent = project.getParent(); - while ( isAdded && parent != null ) - { - isAdded = projectsIncludingParents.add( parent ); + while (isAdded && parent != null) { + isAdded = projectsIncludingParents.add(parent); parent = parent.getParent(); } } final Stream projectProfiles = projectsIncludingParents.stream() - .flatMap( p -> p.getModel().getDelegate().getProfiles().stream() ) - .map( Profile::getId ); - final Stream settingsProfiles = session.getSettings().getProfiles().stream() - .map( org.apache.maven.settings.Profile::getId ); - final Stream superPomProfiles = superPomModel.getProfiles().stream() - .map( Profile::getId ); + .flatMap(p -> p.getModel().getDelegate().getProfiles().stream()) + .map(Profile::getId); + final Stream settingsProfiles = + session.getSettings().getProfiles().stream().map(org.apache.maven.settings.Profile::getId); + final Stream superPomProfiles = + superPomModel.getProfiles().stream().map(Profile::getId); - return Stream.of( projectProfiles, settingsProfiles, superPomProfiles ) - .flatMap( Function.identity() ) - .collect( toSet() ); + return Stream.of(projectProfiles, settingsProfiles, superPomProfiles) + .flatMap(Function.identity()) + .collect(toSet()); } /** @@ -624,26 +533,26 @@ public class DefaultMaven * @param session the Maven session. * @param profileActivation the requested optional and required profiles. */ - private void validateRequiredProfiles( MavenSession session, ProfileActivation profileActivation ) - { - final Set allAvailableProfiles = getAllProfiles( session ); + private void validateRequiredProfiles(MavenSession session, ProfileActivation profileActivation) { + final Set allAvailableProfiles = getAllProfiles(session); - final Set requiredProfiles = new HashSet<>( ); - requiredProfiles.addAll( profileActivation.getRequiredActiveProfileIds() ); - requiredProfiles.addAll( profileActivation.getRequiredInactiveProfileIds() ); + final Set requiredProfiles = new HashSet<>(); + requiredProfiles.addAll(profileActivation.getRequiredActiveProfileIds()); + requiredProfiles.addAll(profileActivation.getRequiredInactiveProfileIds()); // Check whether the required profiles were found in any of the projects we're building. final Set notFoundRequiredProfiles = requiredProfiles.stream() - .filter( rap -> !allAvailableProfiles.contains( rap ) ) - .collect( toSet() ); + .filter(rap -> !allAvailableProfiles.contains(rap)) + .collect(toSet()); - if ( !notFoundRequiredProfiles.isEmpty() ) - { + if (!notFoundRequiredProfiles.isEmpty()) { // Use SLF4J formatter for consistency with warnings reported by logger final String message = MessageFormatter.format( - "The requested profiles {} could not be activated or deactivated because they do not" - + " exist.", notFoundRequiredProfiles ).getMessage(); - addExceptionToResult( session.getResult(), new MissingProfilesException( message ) ); + "The requested profiles {} could not be activated or deactivated because they do not" + + " exist.", + notFoundRequiredProfiles) + .getMessage(); + addExceptionToResult(session.getResult(), new MissingProfilesException(message)); } } @@ -652,15 +561,14 @@ public class DefaultMaven * @param request the {@link MavenExecutionRequest}. * @param session the {@link MavenSession}. */ - private void validateOptionalProjects( MavenExecutionRequest request, MavenSession session ) - { + private void validateOptionalProjects(MavenExecutionRequest request, MavenSession session) { final ProjectActivation projectActivation = request.getProjectActivation(); final Set allOptionalSelectors = new HashSet<>(); - allOptionalSelectors.addAll( projectActivation.getOptionalActiveProjectSelectors() ); - allOptionalSelectors.addAll( projectActivation.getRequiredActiveProjectSelectors() ); + allOptionalSelectors.addAll(projectActivation.getOptionalActiveProjectSelectors()); + allOptionalSelectors.addAll(projectActivation.getRequiredActiveProjectSelectors()); // We intentionally ignore the results of this method. // As a side effect it will log the optional projects that could not be resolved. - projectSelector.getOptionalProjectsBySelectors( request, session.getAllProjects(), allOptionalSelectors ); + projectSelector.getOptionalProjectsBySelectors(request, session.getAllProjects(), allOptionalSelectors); } /** @@ -668,88 +576,75 @@ public class DefaultMaven * @param session the Maven session. * @param profileActivation the requested optional and required profiles. */ - private void validateOptionalProfiles( MavenSession session, ProfileActivation profileActivation ) - { - final Set allAvailableProfiles = getAllProfiles( session ); + private void validateOptionalProfiles(MavenSession session, ProfileActivation profileActivation) { + final Set allAvailableProfiles = getAllProfiles(session); - final Set optionalProfiles = new HashSet<>( ); - optionalProfiles.addAll( profileActivation.getOptionalActiveProfileIds() ); - optionalProfiles.addAll( profileActivation.getOptionalInactiveProfileIds() ); + final Set optionalProfiles = new HashSet<>(); + optionalProfiles.addAll(profileActivation.getOptionalActiveProfileIds()); + optionalProfiles.addAll(profileActivation.getOptionalInactiveProfileIds()); final Set notFoundOptionalProfiles = optionalProfiles.stream() - .filter( rap -> !allAvailableProfiles.contains( rap ) ) - .collect( toSet() ); + .filter(rap -> !allAvailableProfiles.contains(rap)) + .collect(toSet()); - if ( !notFoundOptionalProfiles.isEmpty() ) - { - logger.info( "The requested optional profiles {} could not be activated or deactivated because they do not" - + " exist.", notFoundOptionalProfiles ); + if (!notFoundOptionalProfiles.isEmpty()) { + logger.info( + "The requested optional profiles {} could not be activated or deactivated because they do not" + + " exist.", + notFoundOptionalProfiles); } } - private Map getProjectMap( Collection projects ) - throws DuplicateProjectException - { + private Map getProjectMap(Collection projects) + throws DuplicateProjectException { Map index = new LinkedHashMap<>(); Map> collisions = new LinkedHashMap<>(); - for ( MavenProject project : projects ) - { - String projectId = ArtifactUtils.key( project.getGroupId(), project.getArtifactId(), project.getVersion() ); + for (MavenProject project : projects) { + String projectId = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion()); - MavenProject collision = index.get( projectId ); + MavenProject collision = index.get(projectId); - if ( collision == null ) - { - index.put( projectId, project ); - } - else - { - List pomFiles = collisions.get( projectId ); + if (collision == null) { + index.put(projectId, project); + } else { + List pomFiles = collisions.get(projectId); - if ( pomFiles == null ) - { - pomFiles = new ArrayList<>( Arrays.asList( collision.getFile(), project.getFile() ) ); - collisions.put( projectId, pomFiles ); - } - else - { - pomFiles.add( project.getFile() ); + if (pomFiles == null) { + pomFiles = new ArrayList<>(Arrays.asList(collision.getFile(), project.getFile())); + collisions.put(projectId, pomFiles); + } else { + pomFiles.add(project.getFile()); } } } - if ( !collisions.isEmpty() ) - { - throw new DuplicateProjectException( "Two or more projects in the reactor" - + " have the same identifier, please make sure that ::" - + " is unique for each project: " + collisions, collisions ); + if (!collisions.isEmpty()) { + throw new DuplicateProjectException( + "Two or more projects in the reactor" + + " have the same identifier, please make sure that ::" + + " is unique for each project: " + collisions, + collisions); } return index; } - private Result buildGraph( MavenSession session ) - { - Result graphResult = graphBuilder.build( session ); - for ( ModelProblem problem : graphResult.getProblems() ) - { - if ( problem.getSeverity() == ModelProblem.Severity.WARNING ) - { - logger.warn( problem.getMessage() ); - } - else - { - logger.error( problem.getMessage() ); + private Result buildGraph(MavenSession session) { + Result graphResult = graphBuilder.build(session); + for (ModelProblem problem : graphResult.getProblems()) { + if (problem.getSeverity() == ModelProblem.Severity.WARNING) { + logger.warn(problem.getMessage()); + } else { + logger.error(problem.getMessage()); } } - if ( !graphResult.hasErrors() ) - { + if (!graphResult.hasErrors()) { ProjectDependencyGraph projectDependencyGraph = graphResult.get(); - session.setProjects( projectDependencyGraph.getSortedProjects() ); - session.setAllProjects( projectDependencyGraph.getAllProjects() ); - session.setProjectDependencyGraph( projectDependencyGraph ); + session.setProjects(projectDependencyGraph.getSortedProjects()); + session.setAllProjects(projectDependencyGraph.getAllProjects()); + session.setProjectDependencyGraph(projectDependencyGraph); } return graphResult; @@ -757,8 +652,7 @@ public class DefaultMaven @Deprecated // 5 January 2014 - protected Logger getLogger() - { + protected Logger getLogger() { return logger; } } diff --git a/maven-core/src/main/java/org/apache/maven/DefaultProjectDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/DefaultProjectDependenciesResolver.java index 41255e78de..3137e1da65 100644 --- a/maven-core/src/main/java/org/apache/maven/DefaultProjectDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/DefaultProjectDependenciesResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.util.Collection; import java.util.Collections; @@ -25,11 +24,9 @@ import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; @@ -52,9 +49,7 @@ import org.apache.maven.repository.RepositorySystem; @Deprecated @Named @Singleton -public class DefaultProjectDependenciesResolver - implements ProjectDependenciesResolver -{ +public class DefaultProjectDependenciesResolver implements ProjectDependenciesResolver { private final RepositorySystem repositorySystem; @@ -62,60 +57,63 @@ public class DefaultProjectDependenciesResolver @Inject public DefaultProjectDependenciesResolver( - RepositorySystem repositorySystem, - ResolutionErrorHandler resolutionErrorHandler ) - { + RepositorySystem repositorySystem, ResolutionErrorHandler resolutionErrorHandler) { this.repositorySystem = repositorySystem; this.resolutionErrorHandler = resolutionErrorHandler; } - public Set resolve( MavenProject project, Collection scopesToResolve, MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - return resolve( Collections.singleton( project ), scopesToResolve, session ); + public Set resolve(MavenProject project, Collection scopesToResolve, MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolve(Collections.singleton(project), scopesToResolve, session); } - public Set resolve( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - Set mavenProjects = Collections.singleton( project ); - return resolveImpl( mavenProjects, scopesToCollect, scopesToResolve, session, - getIgnorableArtifacts( mavenProjects ) ); + public Set resolve( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { + Set mavenProjects = Collections.singleton(project); + return resolveImpl( + mavenProjects, scopesToCollect, scopesToResolve, session, getIgnorableArtifacts(mavenProjects)); } - public Set resolve( Collection projects, Collection scopesToResolve, - MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - return resolveImpl( projects, null, scopesToResolve, session, getIgnorableArtifacts( projects ) ); + public Set resolve( + Collection projects, Collection scopesToResolve, MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolveImpl(projects, null, scopesToResolve, session, getIgnorableArtifacts(projects)); } - public Set resolve( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, - Set ignorableArtifacts ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - return resolveImpl( Collections.singleton( project ), scopesToCollect, scopesToResolve, session, - getIgnorableArtifacts( ignorableArtifacts ) ); + public Set resolve( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + Set ignorableArtifacts) + throws ArtifactResolutionException, ArtifactNotFoundException { + return resolveImpl( + Collections.singleton(project), + scopesToCollect, + scopesToResolve, + session, + getIgnorableArtifacts(ignorableArtifacts)); } - - private Set resolveImpl( Collection projects, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, - Set projectIds ) - throws ArtifactResolutionException, ArtifactNotFoundException - { + private Set resolveImpl( + Collection projects, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + Set projectIds) + throws ArtifactResolutionException, ArtifactNotFoundException { Set resolved = new LinkedHashSet<>(); - if ( projects == null || projects.isEmpty() ) - { + if (projects == null || projects.isEmpty()) { return resolved; } - if ( ( scopesToCollect == null || scopesToCollect.isEmpty() ) - && ( scopesToResolve == null || scopesToResolve.isEmpty() ) ) - { + if ((scopesToCollect == null || scopesToCollect.isEmpty()) + && (scopesToResolve == null || scopesToResolve.isEmpty())) { return resolved; } @@ -151,82 +149,72 @@ public class DefaultProjectDependenciesResolver } */ - CumulativeScopeArtifactFilter resolutionScopeFilter = new CumulativeScopeArtifactFilter( scopesToResolve ); + CumulativeScopeArtifactFilter resolutionScopeFilter = new CumulativeScopeArtifactFilter(scopesToResolve); - CumulativeScopeArtifactFilter collectionScopeFilter = new CumulativeScopeArtifactFilter( scopesToCollect ); - collectionScopeFilter = new CumulativeScopeArtifactFilter( collectionScopeFilter, resolutionScopeFilter ); + CumulativeScopeArtifactFilter collectionScopeFilter = new CumulativeScopeArtifactFilter(scopesToCollect); + collectionScopeFilter = new CumulativeScopeArtifactFilter(collectionScopeFilter, resolutionScopeFilter); - ArtifactResolutionRequest request = - new ArtifactResolutionRequest().setResolveRoot( false ).setResolveTransitively( true ).setCollectionFilter( - collectionScopeFilter ).setResolutionFilter( resolutionScopeFilter ).setLocalRepository( - session.getLocalRepository() ).setOffline( session.isOffline() ).setForceUpdate( - session.getRequest().isUpdateSnapshots() ); - request.setServers( session.getRequest().getServers() ); - request.setMirrors( session.getRequest().getMirrors() ); - request.setProxies( session.getRequest().getProxies() ); + ArtifactResolutionRequest request = new ArtifactResolutionRequest() + .setResolveRoot(false) + .setResolveTransitively(true) + .setCollectionFilter(collectionScopeFilter) + .setResolutionFilter(resolutionScopeFilter) + .setLocalRepository(session.getLocalRepository()) + .setOffline(session.isOffline()) + .setForceUpdate(session.getRequest().isUpdateSnapshots()); + request.setServers(session.getRequest().getServers()); + request.setMirrors(session.getRequest().getMirrors()); + request.setProxies(session.getRequest().getProxies()); - for ( MavenProject project : projects ) - { - request.setArtifact( new ProjectArtifact( project ) ); - request.setArtifactDependencies( project.getDependencyArtifacts() ); - request.setManagedVersionMap( project.getManagedVersionMap() ); - request.setRemoteRepositories( project.getRemoteArtifactRepositories() ); + for (MavenProject project : projects) { + request.setArtifact(new ProjectArtifact(project)); + request.setArtifactDependencies(project.getDependencyArtifacts()); + request.setManagedVersionMap(project.getManagedVersionMap()); + request.setRemoteRepositories(project.getRemoteArtifactRepositories()); - ArtifactResolutionResult result = repositorySystem.resolve( request ); + ArtifactResolutionResult result = repositorySystem.resolve(request); - try - { - resolutionErrorHandler.throwErrors( request, result ); - } - catch ( MultipleArtifactsNotFoundException e ) - { + try { + resolutionErrorHandler.throwErrors(request, result); + } catch (MultipleArtifactsNotFoundException e) { - Collection missing = new HashSet<>( e.getMissingArtifacts() ); + Collection missing = new HashSet<>(e.getMissingArtifacts()); - for ( Iterator it = missing.iterator(); it.hasNext(); ) - { - String key = ArtifactUtils.key( it.next() ); - if ( projectIds.contains( key ) ) - { + for (Iterator it = missing.iterator(); it.hasNext(); ) { + String key = ArtifactUtils.key(it.next()); + if (projectIds.contains(key)) { it.remove(); } } - if ( !missing.isEmpty() ) - { + if (!missing.isEmpty()) { throw e; } } - resolved.addAll( result.getArtifacts() ); + resolved.addAll(result.getArtifacts()); } return resolved; } + private Set getIgnorableArtifacts(Collection projects) { + Set projectIds = new HashSet<>(projects.size() * 2); - private Set getIgnorableArtifacts( Collection projects ) - { - Set projectIds = new HashSet<>( projects.size() * 2 ); - - for ( MavenProject p : projects ) - { - String key = ArtifactUtils.key( p.getGroupId(), p.getArtifactId(), p.getVersion() ); - projectIds.add( key ); + for (MavenProject p : projects) { + String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion()); + projectIds.add(key); } return projectIds; } - private Set getIgnorableArtifacts( Iterable artifactIterable ) - { + private Set getIgnorableArtifacts(Iterable artifactIterable) { Set projectIds = new HashSet<>(); - for ( Artifact artifact : artifactIterable ) - { - String key = ArtifactUtils.key( artifact ); - projectIds.add( key ); + for (Artifact artifact : artifactIterable) { + String key = ArtifactUtils.key(artifact); + projectIds.add(key); } return projectIds; } - } diff --git a/maven-core/src/main/java/org/apache/maven/DuplicateProjectException.java b/maven-core/src/main/java/org/apache/maven/DuplicateProjectException.java index 5d7cec10ea..20c49fa40a 100644 --- a/maven-core/src/main/java/org/apache/maven/DuplicateProjectException.java +++ b/maven-core/src/main/java/org/apache/maven/DuplicateProjectException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.io.File; import java.util.LinkedHashMap; @@ -29,9 +28,7 @@ import java.util.Map; * * @author Benjamin Bentmann */ -public class DuplicateProjectException - extends MavenExecutionException -{ +public class DuplicateProjectException extends MavenExecutionException { private Map> collisions; @@ -41,11 +38,10 @@ public class DuplicateProjectException * @param message The message text, may be {@code null}. * @param collisions The POM files of the projects that collided, indexed by their g:a:v, may be {@code null}. */ - public DuplicateProjectException( String message, Map> collisions ) - { - super( message, (File) null ); + public DuplicateProjectException(String message, Map> collisions) { + super(message, (File) null); - this.collisions = ( collisions != null ) ? collisions : new LinkedHashMap<>(); + this.collisions = (collisions != null) ? collisions : new LinkedHashMap<>(); } /** @@ -53,9 +49,7 @@ public class DuplicateProjectException * * @return The POM files of the projects that collided, indexed by their g:a:v, never {@code null}. */ - public Map> getCollisions() - { + public Map> getCollisions() { return collisions; } - } diff --git a/maven-core/src/main/java/org/apache/maven/InternalErrorException.java b/maven-core/src/main/java/org/apache/maven/InternalErrorException.java index afe92c1b31..470787be51 100644 --- a/maven-core/src/main/java/org/apache/maven/InternalErrorException.java +++ b/maven-core/src/main/java/org/apache/maven/InternalErrorException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,16 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; /** * Signals an internal error in Maven itself, e.g. a programming bug. * * @author Benjamin Bentmann */ -public class InternalErrorException - extends MavenExecutionException -{ +public class InternalErrorException extends MavenExecutionException { - public InternalErrorException( String message, Throwable cause ) - { - super( message, cause ); + public InternalErrorException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-core/src/main/java/org/apache/maven/Maven.java b/maven-core/src/main/java/org/apache/maven/Maven.java index 665da6cbac..28a592d7c1 100644 --- a/maven-core/src/main/java/org/apache/maven/Maven.java +++ b/maven-core/src/main/java/org/apache/maven/Maven.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenExecutionResult; @@ -28,11 +27,10 @@ import org.apache.maven.execution.MavenExecutionResult; * @author Jason van Zyl * @see org.apache.maven.execution.MavenSession */ -public interface Maven -{ +public interface Maven { @Deprecated - @SuppressWarnings( "checkstyle:constantname" ) + @SuppressWarnings("checkstyle:constantname") String POMv4 = "pom.xml"; - MavenExecutionResult execute( MavenExecutionRequest request ); -} \ No newline at end of file + MavenExecutionResult execute(MavenExecutionRequest request); +} diff --git a/maven-core/src/main/java/org/apache/maven/MavenExecutionException.java b/maven-core/src/main/java/org/apache/maven/MavenExecutionException.java index 5708e5252b..1288e4844e 100644 --- a/maven-core/src/main/java/org/apache/maven/MavenExecutionException.java +++ b/maven-core/src/main/java/org/apache/maven/MavenExecutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,38 +16,32 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.io.File; - import org.apache.maven.project.ProjectBuildingException; /** * @author Jason van Zyl */ -public class MavenExecutionException - extends Exception -{ +public class MavenExecutionException extends Exception { private File pomFile; - public MavenExecutionException( String message, File pomFile ) - { - super( message ); + public MavenExecutionException(String message, File pomFile) { + super(message); this.pomFile = pomFile; } - public MavenExecutionException( String message, File pomFile, ProjectBuildingException cause ) - { - super( message, cause ); + public MavenExecutionException(String message, File pomFile, ProjectBuildingException cause) { + super(message, cause); this.pomFile = pomFile; } - public MavenExecutionException( String message, Throwable cause ) - { - super( message, cause ); + public MavenExecutionException(String message, Throwable cause) { + super(message, cause); } - public File getPomFile() - { + public File getPomFile() { return pomFile; } } diff --git a/maven-core/src/main/java/org/apache/maven/MissingModuleException.java b/maven-core/src/main/java/org/apache/maven/MissingModuleException.java index 1bdf87acaa..d16c9d58aa 100644 --- a/maven-core/src/main/java/org/apache/maven/MissingModuleException.java +++ b/maven-core/src/main/java/org/apache/maven/MissingModuleException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,34 +16,29 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.io.File; /** * MissingModuleException */ -public class MissingModuleException - extends MavenExecutionException -{ +public class MissingModuleException extends MavenExecutionException { private File moduleFile; private final String moduleName; - public MissingModuleException( String moduleName, File moduleFile, File pomFile ) - { - super( "The module: " + moduleName + " cannot be found in file: " + moduleFile, pomFile ); + public MissingModuleException(String moduleName, File moduleFile, File pomFile) { + super("The module: " + moduleName + " cannot be found in file: " + moduleFile, pomFile); this.moduleName = moduleName; this.moduleFile = moduleFile; } - public File getModuleFile() - { + public File getModuleFile() { return moduleFile; } - public String getModuleName() - { + public String getModuleName() { return moduleName; } - } diff --git a/maven-core/src/main/java/org/apache/maven/MissingProfilesException.java b/maven-core/src/main/java/org/apache/maven/MissingProfilesException.java index 6e9ee767d5..467dd13cae 100644 --- a/maven-core/src/main/java/org/apache/maven/MissingProfilesException.java +++ b/maven-core/src/main/java/org/apache/maven/MissingProfilesException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,16 +16,14 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; /** * Signals that the user referenced one or more Maven profiles that could not be located in either the project or the * settings. */ -public class MissingProfilesException - extends Exception -{ - public MissingProfilesException( String message ) - { - super( message ); +public class MissingProfilesException extends Exception { + public MissingProfilesException(String message) { + super(message); } } diff --git a/maven-core/src/main/java/org/apache/maven/ProjectBuildFailureException.java b/maven-core/src/main/java/org/apache/maven/ProjectBuildFailureException.java index 66ed3a0842..bdd9b49442 100644 --- a/maven-core/src/main/java/org/apache/maven/ProjectBuildFailureException.java +++ b/maven-core/src/main/java/org/apache/maven/ProjectBuildFailureException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import org.apache.maven.plugin.MojoFailureException; @@ -30,26 +29,21 @@ import org.apache.maven.plugin.MojoFailureException; * @author jdcasey * */ -public class ProjectBuildFailureException - extends BuildFailureException -{ +public class ProjectBuildFailureException extends BuildFailureException { private final String projectId; - public ProjectBuildFailureException( String projectId, MojoFailureException cause ) - { - super( "Build for project: " + projectId + " failed during execution of mojo.", cause ); + public ProjectBuildFailureException(String projectId, MojoFailureException cause) { + super("Build for project: " + projectId + " failed during execution of mojo.", cause); this.projectId = projectId; } - public MojoFailureException getMojoFailureException() - { + public MojoFailureException getMojoFailureException() { return (MojoFailureException) getCause(); } - public String getProjectId() - { + public String getProjectId() { return projectId; } } diff --git a/maven-core/src/main/java/org/apache/maven/ProjectCycleException.java b/maven-core/src/main/java/org/apache/maven/ProjectCycleException.java index b4a6fd0bf3..13fedbafaa 100644 --- a/maven-core/src/main/java/org/apache/maven/ProjectCycleException.java +++ b/maven-core/src/main/java/org/apache/maven/ProjectCycleException.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven; * "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 + * 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 @@ -18,22 +16,19 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import org.codehaus.plexus.util.dag.CycleDetectedException; /** * @author jdcasey */ -public class ProjectCycleException - extends BuildFailureException -{ - public ProjectCycleException( String message ) - { - super( message ); +public class ProjectCycleException extends BuildFailureException { + public ProjectCycleException(String message) { + super(message); } - public ProjectCycleException( String message, CycleDetectedException cause ) - { - super( message, cause ); + public ProjectCycleException(String message, CycleDetectedException cause) { + super(message, cause); } } diff --git a/maven-core/src/main/java/org/apache/maven/ProjectDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/ProjectDependenciesResolver.java index 1537aa731d..b6a077de8c 100644 --- a/maven-core/src/main/java/org/apache/maven/ProjectDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/ProjectDependenciesResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.util.Collection; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; @@ -35,8 +33,7 @@ import org.apache.maven.project.MavenProject; * */ @Deprecated -public interface ProjectDependenciesResolver -{ +public interface ProjectDependenciesResolver { /** * Resolves the transitive dependencies of the specified project. @@ -48,8 +45,8 @@ public interface ProjectDependenciesResolver * @throws ArtifactResolutionException in case of resolution issue * @throws ArtifactNotFoundException if an artifact is not found */ - Set resolve( MavenProject project, Collection scopesToResolve, MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set resolve(MavenProject project, Collection scopesToResolve, MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Resolves the transitive dependencies of the specified project. @@ -62,9 +59,12 @@ public interface ProjectDependenciesResolver * @throws ArtifactResolutionException in case of resolution issue * @throws ArtifactNotFoundException if an artifact is not found */ - Set resolve( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set resolve( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Resolves the transitive dependencies of the specified project. @@ -78,9 +78,13 @@ public interface ProjectDependenciesResolver * @throws ArtifactResolutionException in case of resolution issue * @throws ArtifactNotFoundException if an artifact is not found */ - Set resolve( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, Set ignorableArtifacts ) - throws ArtifactResolutionException, ArtifactNotFoundException; + Set resolve( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + Set ignorableArtifacts) + throws ArtifactResolutionException, ArtifactNotFoundException; /** * Resolves the transitive dependencies of the specified projects. Note that dependencies which can't be resolved @@ -96,8 +100,6 @@ public interface ProjectDependenciesResolver * @throws ArtifactResolutionException in case of resolution issue * @throws ArtifactNotFoundException if an artifact is not found */ - Set resolve( Collection projects, Collection scopes, - MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException; - + Set resolve(Collection projects, Collection scopes, MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException; } diff --git a/maven-core/src/main/java/org/apache/maven/ReactorReader.java b/maven-core/src/main/java/org/apache/maven/ReactorReader.java index e50eabb3cb..ad7dcef4c3 100644 --- a/maven-core/src/main/java/org/apache/maven/ReactorReader.java +++ b/maven-core/src/main/java/org/apache/maven/ReactorReader.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,11 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toMap; import java.io.File; import java.io.IOException; @@ -37,7 +40,8 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; - +import javax.inject.Inject; +import javax.inject.Named; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; @@ -49,30 +53,21 @@ import org.eclipse.aether.util.artifact.ArtifactIdUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Named; - -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.groupingBy; -import static java.util.stream.Collectors.toMap; - /** * An implementation of a workspace reader that knows how to search the Maven reactor for artifacts, either as packaged * jar if it has been built, or only compile output directory if packaging hasn't happened yet. * * @author Jason van Zyl */ -@Named( ReactorReader.HINT ) +@Named(ReactorReader.HINT) @SessionScoped -class ReactorReader - implements MavenWorkspaceReader -{ +class ReactorReader implements MavenWorkspaceReader { public static final String HINT = "reactor"; private static final Collection COMPILE_PHASE_TYPES = - Arrays.asList( "jar", "ejb-client", "war", "rar", "ejb3", "par", "sar", "wsr", "har", "app-client" ); + Arrays.asList("jar", "ejb-client", "war", "rar", "ejb3", "par", "sar", "wsr", "har", "app-client"); - private static final Logger LOGGER = LoggerFactory.getLogger( ReactorReader.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(ReactorReader.class); private final MavenSession session; private final Map projectsByGAV; @@ -80,46 +75,38 @@ class ReactorReader private final WorkspaceRepository repository; private Function projectIntoKey = - s -> ArtifactUtils.key( s.getGroupId(), s.getArtifactId(), s.getVersion() ); + s -> ArtifactUtils.key(s.getGroupId(), s.getArtifactId(), s.getVersion()); private Function projectIntoVersionlessKey = - s -> ArtifactUtils.versionlessKey( s.getGroupId(), s.getArtifactId() ); + s -> ArtifactUtils.versionlessKey(s.getGroupId(), s.getArtifactId()); @Inject - ReactorReader( MavenSession session ) - { + ReactorReader(MavenSession session) { this.session = session; - this.projectsByGAV = - session.getAllProjects().stream() - .collect( toMap( projectIntoKey, identity() ) ); + this.projectsByGAV = session.getAllProjects().stream().collect(toMap(projectIntoKey, identity())); - this.projectsByGA = projectsByGAV.values().stream() - .collect( groupingBy( projectIntoVersionlessKey ) ); + this.projectsByGA = projectsByGAV.values().stream().collect(groupingBy(projectIntoVersionlessKey)); - repository = new WorkspaceRepository( "reactor", new HashSet<>( projectsByGAV.keySet() ) ); + repository = new WorkspaceRepository("reactor", new HashSet<>(projectsByGAV.keySet())); } // // Public API // - public WorkspaceRepository getRepository() - { + public WorkspaceRepository getRepository() { return repository; } - public File findArtifact( Artifact artifact ) - { - String projectKey = ArtifactUtils.key( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() ); + public File findArtifact(Artifact artifact) { + String projectKey = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); - MavenProject project = projectsByGAV.get( projectKey ); + MavenProject project = projectsByGAV.get(projectKey); - if ( project != null ) - { - File file = find( project, artifact ); - if ( file == null && project != project.getExecutionProject() ) - { - file = find( project.getExecutionProject(), artifact ); + if (project != null) { + File file = find(project, artifact); + if (file == null && project != project.getExecutionProject()) { + file = find(project.getExecutionProject(), artifact); } return file; } @@ -127,22 +114,19 @@ class ReactorReader return null; } - public List findVersions( Artifact artifact ) - { - String key = ArtifactUtils.versionlessKey( artifact.getGroupId(), artifact.getArtifactId() ); + public List findVersions(Artifact artifact) { + String key = ArtifactUtils.versionlessKey(artifact.getGroupId(), artifact.getArtifactId()); - return Optional.ofNullable( projectsByGA.get( key ) ) - .orElse( Collections.emptyList() ).stream() - .filter( s -> Objects.nonNull( find( s, artifact ) ) ) - .map( MavenProject::getVersion ) - .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); + return Optional.ofNullable(projectsByGA.get(key)).orElse(Collections.emptyList()).stream() + .filter(s -> Objects.nonNull(find(s, artifact))) + .map(MavenProject::getVersion) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override - public Model findModel( Artifact artifact ) - { - String projectKey = ArtifactUtils.key( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() ); - MavenProject project = projectsByGAV.get( projectKey ); + public Model findModel(Artifact artifact) { + String projectKey = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + MavenProject project = projectsByGAV.get(projectKey); return project == null ? null : project.getModel(); } @@ -150,31 +134,26 @@ class ReactorReader // Implementation // - private File find( MavenProject project, Artifact artifact ) - { - if ( "pom".equals( artifact.getExtension() ) ) - { + private File find(MavenProject project, Artifact artifact) { + if ("pom".equals(artifact.getExtension())) { return project.getFile(); } - Artifact projectArtifact = findMatchingArtifact( project, artifact ); - File packagedArtifactFile = determinePreviouslyPackagedArtifactFile( project, projectArtifact ); + Artifact projectArtifact = findMatchingArtifact(project, artifact); + File packagedArtifactFile = determinePreviouslyPackagedArtifactFile(project, projectArtifact); - if ( hasArtifactFileFromPackagePhase( projectArtifact ) ) - { + if (hasArtifactFileFromPackagePhase(projectArtifact)) { return projectArtifact.getFile(); } // Check whether an earlier Maven run might have produced an artifact that is still on disk. - else if ( packagedArtifactFile != null && packagedArtifactFile.exists() - && isPackagedArtifactUpToDate( project, packagedArtifactFile, artifact ) ) - { + else if (packagedArtifactFile != null + && packagedArtifactFile.exists() + && isPackagedArtifactUpToDate(project, packagedArtifactFile, artifact)) { return packagedArtifactFile; - } - else if ( !hasBeenPackagedDuringThisSession( project ) ) - { + } else if (!hasBeenPackagedDuringThisSession(project)) { // fallback to loose class files only if artifacts haven't been packaged yet // and only for plain old jars. Not war files, not ear files, not anything else. - return determineBuildOutputDirectoryForArtifact( project, artifact ); + return determineBuildOutputDirectoryForArtifact(project, artifact); } // The fall-through indicates that the artifact cannot be found; @@ -182,32 +161,26 @@ class ReactorReader return null; } - private File determineBuildOutputDirectoryForArtifact( final MavenProject project, final Artifact artifact ) - { - if ( isTestArtifact( artifact ) ) - { - if ( project.hasLifecyclePhase( "test-compile" ) ) - { - return new File( project.getBuild().getTestOutputDirectory() ); + private File determineBuildOutputDirectoryForArtifact(final MavenProject project, final Artifact artifact) { + if (isTestArtifact(artifact)) { + if (project.hasLifecyclePhase("test-compile")) { + return new File(project.getBuild().getTestOutputDirectory()); } - } - else - { - String type = artifact.getProperty( "type", "" ); - File outputDirectory = new File( project.getBuild().getOutputDirectory() ); + } else { + String type = artifact.getProperty("type", ""); + File outputDirectory = new File(project.getBuild().getOutputDirectory()); // Check if the project is being built during this session, and if we can expect any output. // There is no need to check if the build has created any outputs, see MNG-2222. - boolean projectCompiledDuringThisSession - = project.hasLifecyclePhase( "compile" ) && COMPILE_PHASE_TYPES.contains( type ); + boolean projectCompiledDuringThisSession = + project.hasLifecyclePhase("compile") && COMPILE_PHASE_TYPES.contains(type); // Check if the project is part of the session (not filtered by -pl, -rf, etc). If so, we check // if a possible earlier Maven invocation produced some output for that project which we can use. - boolean projectHasOutputFromPreviousSession - = !session.getProjects().contains( project ) && outputDirectory.exists(); + boolean projectHasOutputFromPreviousSession = + !session.getProjects().contains(project) && outputDirectory.exists(); - if ( projectHasOutputFromPreviousSession || projectCompiledDuringThisSession ) - { + if (projectHasOutputFromPreviousSession || projectCompiledDuringThisSession) { return outputDirectory; } } @@ -217,95 +190,90 @@ class ReactorReader return null; } - private File determinePreviouslyPackagedArtifactFile( MavenProject project, Artifact artifact ) - { - if ( artifact == null ) - { + private File determinePreviouslyPackagedArtifactFile(MavenProject project, Artifact artifact) { + if (artifact == null) { return null; } - String fileName = String.format( "%s.%s", project.getBuild().getFinalName(), artifact.getExtension() ); - return new File( project.getBuild().getDirectory(), fileName ); + String fileName = String.format("%s.%s", project.getBuild().getFinalName(), artifact.getExtension()); + return new File(project.getBuild().getDirectory(), fileName); } - private boolean hasArtifactFileFromPackagePhase( Artifact projectArtifact ) - { - return projectArtifact != null && projectArtifact.getFile() != null && projectArtifact.getFile().exists(); + private boolean hasArtifactFileFromPackagePhase(Artifact projectArtifact) { + return projectArtifact != null + && projectArtifact.getFile() != null + && projectArtifact.getFile().exists(); } - private boolean isPackagedArtifactUpToDate( MavenProject project, File packagedArtifactFile, Artifact artifact ) - { - Path outputDirectory = Paths.get( project.getBuild().getOutputDirectory() ); - if ( !outputDirectory.toFile().exists() ) - { + private boolean isPackagedArtifactUpToDate(MavenProject project, File packagedArtifactFile, Artifact artifact) { + Path outputDirectory = Paths.get(project.getBuild().getOutputDirectory()); + if (!outputDirectory.toFile().exists()) { return true; } - try ( Stream outputFiles = Files.walk( outputDirectory ) ) - { + try (Stream outputFiles = Files.walk(outputDirectory)) { // Not using File#lastModified() to avoid a Linux JDK8 milliseconds precision bug: JDK-8177809. - long artifactLastModified = Files.getLastModifiedTime( packagedArtifactFile.toPath() ).toMillis(); + long artifactLastModified = + Files.getLastModifiedTime(packagedArtifactFile.toPath()).toMillis(); - if ( session.getProjectBuildingRequest().getBuildStartTime() != null ) - { - long buildStartTime = session.getProjectBuildingRequest().getBuildStartTime().getTime(); - if ( artifactLastModified > buildStartTime ) - { + if (session.getProjectBuildingRequest().getBuildStartTime() != null) { + long buildStartTime = + session.getProjectBuildingRequest().getBuildStartTime().getTime(); + if (artifactLastModified > buildStartTime) { return true; } } Iterator iterator = outputFiles.iterator(); - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { Path outputFile = iterator.next(); - if ( Files.isDirectory( outputFile ) ) - { + if (Files.isDirectory(outputFile)) { continue; } - long outputFileLastModified = Files.getLastModifiedTime( outputFile ).toMillis(); - if ( outputFileLastModified > artifactLastModified ) - { - File alternative = determineBuildOutputDirectoryForArtifact( project, artifact ); - if ( alternative != null ) - { - LOGGER.warn( "File '{}' is more recent than the packaged artifact for '{}'; using '{}' instead", - relativizeOutputFile( outputFile ), project.getArtifactId(), - relativizeOutputFile( alternative.toPath() ) ); - } - else - { - LOGGER.warn( "File '{}' is more recent than the packaged artifact for '{}'; " - + "cannot use the build output directory for this type of artifact", - relativizeOutputFile( outputFile ), project.getArtifactId() ); + long outputFileLastModified = + Files.getLastModifiedTime(outputFile).toMillis(); + if (outputFileLastModified > artifactLastModified) { + File alternative = determineBuildOutputDirectoryForArtifact(project, artifact); + if (alternative != null) { + LOGGER.warn( + "File '{}' is more recent than the packaged artifact for '{}'; using '{}' instead", + relativizeOutputFile(outputFile), + project.getArtifactId(), + relativizeOutputFile(alternative.toPath())); + } else { + LOGGER.warn( + "File '{}' is more recent than the packaged artifact for '{}'; " + + "cannot use the build output directory for this type of artifact", + relativizeOutputFile(outputFile), + project.getArtifactId()); } return false; } } return true; - } - catch ( IOException e ) - { - LOGGER.warn( "An I/O error occurred while checking if the packaged artifact is up-to-date " - + "against the build output directory. " - + "Continuing with the assumption that it is up-to-date.", e ); + } catch (IOException e) { + LOGGER.warn( + "An I/O error occurred while checking if the packaged artifact is up-to-date " + + "against the build output directory. " + + "Continuing with the assumption that it is up-to-date.", + e); return true; } } - private boolean hasBeenPackagedDuringThisSession( MavenProject project ) - { - return project.hasLifecyclePhase( "package" ) || project.hasLifecyclePhase( "install" ) - || project.hasLifecyclePhase( "deploy" ); + private boolean hasBeenPackagedDuringThisSession(MavenProject project) { + return project.hasLifecyclePhase("package") + || project.hasLifecyclePhase("install") + || project.hasLifecyclePhase("deploy"); } - private Path relativizeOutputFile( final Path outputFile ) - { - Path projectBaseDirectory = Paths.get( session.getRequest().getMultiModuleProjectDirectory().toURI() ); - return projectBaseDirectory.relativize( outputFile ); + private Path relativizeOutputFile(final Path outputFile) { + Path projectBaseDirectory = + Paths.get(session.getRequest().getMultiModuleProjectDirectory().toURI()); + return projectBaseDirectory.relativize(outputFile); } /** @@ -315,20 +283,18 @@ class ReactorReader * @param requestedArtifact The artifact to resolve, must not be null. * @return The matching artifact from the project or null if not found. Note that this */ - private Artifact findMatchingArtifact( MavenProject project, Artifact requestedArtifact ) - { - String requestedRepositoryConflictId = ArtifactIdUtils.toVersionlessId( requestedArtifact ); + private Artifact findMatchingArtifact(MavenProject project, Artifact requestedArtifact) { + String requestedRepositoryConflictId = ArtifactIdUtils.toVersionlessId(requestedArtifact); - Artifact mainArtifact = RepositoryUtils.toArtifact( project.getArtifact() ); - if ( requestedRepositoryConflictId.equals( ArtifactIdUtils.toVersionlessId( mainArtifact ) ) ) - { + Artifact mainArtifact = RepositoryUtils.toArtifact(project.getArtifact()); + if (requestedRepositoryConflictId.equals(ArtifactIdUtils.toVersionlessId(mainArtifact))) { return mainArtifact; } - return RepositoryUtils.toArtifacts( project.getAttachedArtifacts() ).stream() - .filter( isRequestedArtifact( requestedArtifact ) ) + return RepositoryUtils.toArtifacts(project.getAttachedArtifacts()).stream() + .filter(isRequestedArtifact(requestedArtifact)) .findFirst() - .orElse( null ); + .orElse(null); } /** @@ -338,14 +304,12 @@ class ReactorReader * @param requestArtifact checked against the given artifact. * @return true if equals, false otherwise. */ - private Predicate isRequestedArtifact( Artifact requestArtifact ) - { - return s -> s.getArtifactId().equals( requestArtifact.getArtifactId() ) - && s.getGroupId().equals( requestArtifact.getGroupId() ) - && s.getVersion().equals( requestArtifact.getVersion() ) - && s.getExtension().equals( requestArtifact.getExtension() ) - && s.getClassifier().equals( requestArtifact.getClassifier() ); - + private Predicate isRequestedArtifact(Artifact requestArtifact) { + return s -> s.getArtifactId().equals(requestArtifact.getArtifactId()) + && s.getGroupId().equals(requestArtifact.getGroupId()) + && s.getVersion().equals(requestArtifact.getVersion()) + && s.getExtension().equals(requestArtifact.getExtension()) + && s.getClassifier().equals(requestArtifact.getClassifier()); } /** @@ -354,9 +318,8 @@ class ReactorReader * @param artifact The artifact to check, must not be {@code null}. * @return {@code true} if the artifact refers to test classes, {@code false} otherwise. */ - private static boolean isTestArtifact( Artifact artifact ) - { - return ( "test-jar".equals( artifact.getProperty( "type", "" ) ) ) - || ( "jar".equals( artifact.getExtension() ) && "tests".equals( artifact.getClassifier() ) ); + private static boolean isTestArtifact(Artifact artifact) { + return ("test-jar".equals(artifact.getProperty("type", ""))) + || ("jar".equals(artifact.getExtension()) && "tests".equals(artifact.getClassifier())); } } diff --git a/maven-core/src/main/java/org/apache/maven/RepositoryUtils.java b/maven-core/src/main/java/org/apache/maven/RepositoryUtils.java index ce840ee2a4..5957f39864 100644 --- a/maven-core/src/main/java/org/apache/maven/RepositoryUtils.java +++ b/maven-core/src/main/java/org/apache/maven/RepositoryUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import java.util.ArrayList; import java.util.Collection; @@ -28,7 +27,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; @@ -59,172 +57,152 @@ import org.eclipse.aether.util.repository.AuthenticationBuilder; * * @author Benjamin Bentmann */ -public class RepositoryUtils -{ +public class RepositoryUtils { - private static String nullify( String string ) - { - return ( string == null || string.length() <= 0 ) ? null : string; + private static String nullify(String string) { + return (string == null || string.length() <= 0) ? null : string; } - private static org.apache.maven.artifact.Artifact toArtifact( Dependency dependency ) - { - if ( dependency == null ) - { + private static org.apache.maven.artifact.Artifact toArtifact(Dependency dependency) { + if (dependency == null) { return null; } - org.apache.maven.artifact.Artifact result = toArtifact( dependency.getArtifact() ); - result.setScope( dependency.getScope() ); - result.setOptional( dependency.isOptional() ); + org.apache.maven.artifact.Artifact result = toArtifact(dependency.getArtifact()); + result.setScope(dependency.getScope()); + result.setOptional(dependency.isOptional()); return result; } - public static org.apache.maven.artifact.Artifact toArtifact( Artifact artifact ) - { - if ( artifact == null ) - { + public static org.apache.maven.artifact.Artifact toArtifact(Artifact artifact) { + if (artifact == null) { return null; } - ArtifactHandler handler = newHandler( artifact ); + ArtifactHandler handler = newHandler(artifact); /* * NOTE: From Artifact.hasClassifier(), an empty string and a null both denote "no classifier". However, some * plugins only check for null, so be sure to nullify an empty classifier. */ - org.apache.maven.artifact.Artifact result = - new org.apache.maven.artifact.DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), - artifact.getVersion(), null, - artifact.getProperty( ArtifactProperties.TYPE, - artifact.getExtension() ), - nullify( artifact.getClassifier() ), handler ); + org.apache.maven.artifact.Artifact result = new org.apache.maven.artifact.DefaultArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion(), + null, + artifact.getProperty(ArtifactProperties.TYPE, artifact.getExtension()), + nullify(artifact.getClassifier()), + handler); - result.setFile( artifact.getFile() ); - result.setResolved( artifact.getFile() != null ); + result.setFile(artifact.getFile()); + result.setResolved(artifact.getFile() != null); - List trail = new ArrayList<>( 1 ); - trail.add( result.getId() ); - result.setDependencyTrail( trail ); + List trail = new ArrayList<>(1); + trail.add(result.getId()); + result.setDependencyTrail(trail); return result; } - public static void toArtifacts( Collection artifacts, - Collection nodes, List trail, - DependencyFilter filter ) - { - for ( DependencyNode node : nodes ) - { - org.apache.maven.artifact.Artifact artifact = toArtifact( node.getDependency() ); + public static void toArtifacts( + Collection artifacts, + Collection nodes, + List trail, + DependencyFilter filter) { + for (DependencyNode node : nodes) { + org.apache.maven.artifact.Artifact artifact = toArtifact(node.getDependency()); - List nodeTrail = new ArrayList<>( trail.size() + 1 ); - nodeTrail.addAll( trail ); - nodeTrail.add( artifact.getId() ); + List nodeTrail = new ArrayList<>(trail.size() + 1); + nodeTrail.addAll(trail); + nodeTrail.add(artifact.getId()); - if ( filter == null || filter.accept( node, Collections.emptyList() ) ) - { - artifact.setDependencyTrail( nodeTrail ); - artifacts.add( artifact ); + if (filter == null || filter.accept(node, Collections.emptyList())) { + artifact.setDependencyTrail(nodeTrail); + artifacts.add(artifact); } - toArtifacts( artifacts, node.getChildren(), nodeTrail, filter ); + toArtifacts(artifacts, node.getChildren(), nodeTrail, filter); } } - public static Artifact toArtifact( org.apache.maven.artifact.Artifact artifact ) - { - if ( artifact == null ) - { + public static Artifact toArtifact(org.apache.maven.artifact.Artifact artifact) { + if (artifact == null) { return null; } String version = artifact.getVersion(); - if ( version == null && artifact.getVersionRange() != null ) - { + if (version == null && artifact.getVersionRange() != null) { version = artifact.getVersionRange().toString(); } Map props = null; - if ( org.apache.maven.artifact.Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) - { - String localPath = ( artifact.getFile() != null ) ? artifact.getFile().getPath() : ""; - props = Collections.singletonMap( ArtifactProperties.LOCAL_PATH, localPath ); + if (org.apache.maven.artifact.Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { + String localPath = (artifact.getFile() != null) ? artifact.getFile().getPath() : ""; + props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, localPath); } - Artifact result = - new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), - artifact.getArtifactHandler().getExtension(), version, props, - newArtifactType( artifact.getType(), artifact.getArtifactHandler() ) ); - result = result.setFile( artifact.getFile() ); + Artifact result = new DefaultArtifact( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getClassifier(), + artifact.getArtifactHandler().getExtension(), + version, + props, + newArtifactType(artifact.getType(), artifact.getArtifactHandler())); + result = result.setFile(artifact.getFile()); return result; } - public static Dependency toDependency( org.apache.maven.artifact.Artifact artifact, - Collection exclusions ) - { - if ( artifact == null ) - { + public static Dependency toDependency( + org.apache.maven.artifact.Artifact artifact, Collection exclusions) { + if (artifact == null) { return null; } - Artifact result = toArtifact( artifact ); + Artifact result = toArtifact(artifact); - List excl = Optional.ofNullable( exclusions ) - .orElse( Collections.emptyList() ) - .stream() - .map( RepositoryUtils::toExclusion ) - .collect( Collectors.toList() ); - return new Dependency( result, artifact.getScope(), artifact.isOptional(), excl ); + List excl = Optional.ofNullable(exclusions).orElse(Collections.emptyList()).stream() + .map(RepositoryUtils::toExclusion) + .collect(Collectors.toList()); + return new Dependency(result, artifact.getScope(), artifact.isOptional(), excl); } - public static List toRepos( List repos ) - { - return Optional.ofNullable( repos ) - .orElse( Collections.emptyList() ) - .stream() - .map( RepositoryUtils::toRepo ) - .collect( Collectors.toList() ); + public static List toRepos(List repos) { + return Optional.ofNullable(repos).orElse(Collections.emptyList()).stream() + .map(RepositoryUtils::toRepo) + .collect(Collectors.toList()); } - public static RemoteRepository toRepo( ArtifactRepository repo ) - { + public static RemoteRepository toRepo(ArtifactRepository repo) { RemoteRepository result = null; - if ( repo != null ) - { + if (repo != null) { RemoteRepository.Builder builder = - new RemoteRepository.Builder( repo.getId(), getLayout( repo ), repo.getUrl() ); - builder.setSnapshotPolicy( toPolicy( repo.getSnapshots() ) ); - builder.setReleasePolicy( toPolicy( repo.getReleases() ) ); - builder.setAuthentication( toAuthentication( repo.getAuthentication() ) ); - builder.setProxy( toProxy( repo.getProxy() ) ); - builder.setMirroredRepositories( toRepos( repo.getMirroredRepositories() ) ); - builder.setBlocked( repo.isBlocked() ); + new RemoteRepository.Builder(repo.getId(), getLayout(repo), repo.getUrl()); + builder.setSnapshotPolicy(toPolicy(repo.getSnapshots())); + builder.setReleasePolicy(toPolicy(repo.getReleases())); + builder.setAuthentication(toAuthentication(repo.getAuthentication())); + builder.setProxy(toProxy(repo.getProxy())); + builder.setMirroredRepositories(toRepos(repo.getMirroredRepositories())); + builder.setBlocked(repo.isBlocked()); result = builder.build(); } return result; } - public static String getLayout( ArtifactRepository repo ) - { - try - { + public static String getLayout(ArtifactRepository repo) { + try { return repo.getLayout().getId(); - } - catch ( LinkageError e ) - { + } catch (LinkageError e) { /* * NOTE: getId() was added in 3.x and is as such not implemented by plugins compiled against 2.x APIs. */ String className = repo.getLayout().getClass().getSimpleName(); - if ( className.endsWith( "RepositoryLayout" ) ) - { - String layout = className.substring( 0, className.length() - "RepositoryLayout".length() ); - if ( layout.length() > 0 ) - { - layout = Character.toLowerCase( layout.charAt( 0 ) ) + layout.substring( 1 ); + if (className.endsWith("RepositoryLayout")) { + String layout = className.substring(0, className.length() - "RepositoryLayout".length()); + if (layout.length() > 0) { + layout = Character.toLowerCase(layout.charAt(0)) + layout.substring(1); return layout; } } @@ -232,145 +210,131 @@ public class RepositoryUtils } } - private static RepositoryPolicy toPolicy( ArtifactRepositoryPolicy policy ) - { + private static RepositoryPolicy toPolicy(ArtifactRepositoryPolicy policy) { RepositoryPolicy result = null; - if ( policy != null ) - { - result = new RepositoryPolicy( policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy() ); + if (policy != null) { + result = new RepositoryPolicy(policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy()); } return result; } - private static Authentication toAuthentication( org.apache.maven.artifact.repository.Authentication auth ) - { + private static Authentication toAuthentication(org.apache.maven.artifact.repository.Authentication auth) { Authentication result = null; - if ( auth != null ) - { + if (auth != null) { AuthenticationBuilder authBuilder = new AuthenticationBuilder(); - authBuilder.addUsername( auth.getUsername() ).addPassword( auth.getPassword() ); - authBuilder.addPrivateKey( auth.getPrivateKey(), auth.getPassphrase() ); + authBuilder.addUsername(auth.getUsername()).addPassword(auth.getPassword()); + authBuilder.addPrivateKey(auth.getPrivateKey(), auth.getPassphrase()); result = authBuilder.build(); } return result; } - private static Proxy toProxy( org.apache.maven.repository.Proxy proxy ) - { + private static Proxy toProxy(org.apache.maven.repository.Proxy proxy) { Proxy result = null; - if ( proxy != null ) - { + if (proxy != null) { AuthenticationBuilder authBuilder = new AuthenticationBuilder(); - authBuilder.addUsername( proxy.getUserName() ).addPassword( proxy.getPassword() ); - result = new Proxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authBuilder.build() ); + authBuilder.addUsername(proxy.getUserName()).addPassword(proxy.getPassword()); + result = new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authBuilder.build()); } return result; } - public static ArtifactHandler newHandler( Artifact artifact ) - { - String type = artifact.getProperty( ArtifactProperties.TYPE, artifact.getExtension() ); + public static ArtifactHandler newHandler(Artifact artifact) { + String type = artifact.getProperty(ArtifactProperties.TYPE, artifact.getExtension()); return new DefaultArtifactHandler( - type, - artifact.getExtension(), - null, - null, - null, - Boolean.parseBoolean( artifact.getProperty( ArtifactProperties.INCLUDES_DEPENDENCIES, "" ) ), - artifact.getProperty( ArtifactProperties.LANGUAGE, null ), - Boolean.parseBoolean( artifact.getProperty( ArtifactProperties.CONSTITUTES_BUILD_PATH, "" ) ) - ); + type, + artifact.getExtension(), + null, + null, + null, + Boolean.parseBoolean(artifact.getProperty(ArtifactProperties.INCLUDES_DEPENDENCIES, "")), + artifact.getProperty(ArtifactProperties.LANGUAGE, null), + Boolean.parseBoolean(artifact.getProperty(ArtifactProperties.CONSTITUTES_BUILD_PATH, ""))); } - public static ArtifactType newArtifactType( String id, ArtifactHandler handler ) - { - return new DefaultArtifactType( id, handler.getExtension(), handler.getClassifier(), handler.getLanguage(), - handler.isAddedToClasspath(), handler.isIncludesDependencies() ); + public static ArtifactType newArtifactType(String id, ArtifactHandler handler) { + return new DefaultArtifactType( + id, + handler.getExtension(), + handler.getClassifier(), + handler.getLanguage(), + handler.isAddedToClasspath(), + handler.isIncludesDependencies()); } - public static Dependency toDependency( org.apache.maven.model.Dependency dependency, - ArtifactTypeRegistry stereotypes ) - { - ArtifactType stereotype = stereotypes.get( dependency.getType() ); - if ( stereotype == null ) - { - stereotype = new DefaultArtifactType( dependency.getType() ); + public static Dependency toDependency( + org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry stereotypes) { + ArtifactType stereotype = stereotypes.get(dependency.getType()); + if (stereotype == null) { + stereotype = new DefaultArtifactType(dependency.getType()); } - boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0; + boolean system = + dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0; Map props = null; - if ( system ) - { - props = Collections.singletonMap( ArtifactProperties.LOCAL_PATH, dependency.getSystemPath() ); + if (system) { + props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, dependency.getSystemPath()); } - Artifact artifact = - new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null, - dependency.getVersion(), props, stereotype ); + Artifact artifact = new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getClassifier(), + null, + dependency.getVersion(), + props, + stereotype); - List exclusions = - dependency.getExclusions().stream().map( RepositoryUtils::toExclusion ).collect( Collectors.toList() ); + List exclusions = dependency.getExclusions().stream() + .map(RepositoryUtils::toExclusion) + .collect(Collectors.toList()); - return new Dependency( artifact, - dependency.getScope(), - dependency.getOptional() != null - ? dependency.isOptional() - : null, - exclusions ); + return new Dependency( + artifact, + dependency.getScope(), + dependency.getOptional() != null ? dependency.isOptional() : null, + exclusions); } - private static Exclusion toExclusion( org.apache.maven.model.Exclusion exclusion ) - { - return new Exclusion( exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*" ); + private static Exclusion toExclusion(org.apache.maven.model.Exclusion exclusion) { + return new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*"); } - public static ArtifactTypeRegistry newArtifactTypeRegistry( ArtifactHandlerManager handlerManager ) - { - return new MavenArtifactTypeRegistry( handlerManager ); + public static ArtifactTypeRegistry newArtifactTypeRegistry(ArtifactHandlerManager handlerManager) { + return new MavenArtifactTypeRegistry(handlerManager); } - static class MavenArtifactTypeRegistry - implements ArtifactTypeRegistry - { + static class MavenArtifactTypeRegistry implements ArtifactTypeRegistry { private final ArtifactHandlerManager handlerManager; - MavenArtifactTypeRegistry( ArtifactHandlerManager handlerManager ) - { + MavenArtifactTypeRegistry(ArtifactHandlerManager handlerManager) { this.handlerManager = handlerManager; } - public ArtifactType get( String stereotypeId ) - { - ArtifactHandler handler = handlerManager.getArtifactHandler( stereotypeId ); - return newArtifactType( stereotypeId, handler ); + public ArtifactType get(String stereotypeId) { + ArtifactHandler handler = handlerManager.getArtifactHandler(stereotypeId); + return newArtifactType(stereotypeId, handler); } - } - public static Collection toArtifacts( Collection artifactsToConvert ) - { - return artifactsToConvert.stream().map( RepositoryUtils::toArtifact ).collect( Collectors.toList() ); + public static Collection toArtifacts(Collection artifactsToConvert) { + return artifactsToConvert.stream().map(RepositoryUtils::toArtifact).collect(Collectors.toList()); } - public static WorkspaceRepository getWorkspace( RepositorySystemSession session ) - { + public static WorkspaceRepository getWorkspace(RepositorySystemSession session) { WorkspaceReader reader = session.getWorkspaceReader(); - return ( reader != null ) ? reader.getRepository() : null; + return (reader != null) ? reader.getRepository() : null; } - public static boolean repositoriesEquals( List r1, List r2 ) - { - if ( r1.size() != r2.size() ) - { + public static boolean repositoriesEquals(List r1, List r2) { + if (r1.size() != r2.size()) { return false; } - for ( Iterator it1 = r1.iterator(), it2 = r2.iterator(); it1.hasNext(); ) - { - if ( !repositoryEquals( it1.next(), it2.next() ) ) - { + for (Iterator it1 = r1.iterator(), it2 = r2.iterator(); it1.hasNext(); ) { + if (!repositoryEquals(it1.next(), it2.next())) { return false; } } @@ -378,43 +342,37 @@ public class RepositoryUtils return true; } - public static int repositoriesHashCode( List repositories ) - { + public static int repositoriesHashCode(List repositories) { int result = 17; - for ( RemoteRepository repository : repositories ) - { - result = 31 * result + repositoryHashCode( repository ); + for (RemoteRepository repository : repositories) { + result = 31 * result + repositoryHashCode(repository); } return result; } - private static int repositoryHashCode( RemoteRepository repository ) - { + private static int repositoryHashCode(RemoteRepository repository) { int result = 17; Object obj = repository.getUrl(); - result = 31 * result + ( obj != null ? obj.hashCode() : 0 ); + result = 31 * result + (obj != null ? obj.hashCode() : 0); return result; } - private static boolean policyEquals( RepositoryPolicy p1, RepositoryPolicy p2 ) - { - if ( p1 == p2 ) - { + private static boolean policyEquals(RepositoryPolicy p1, RepositoryPolicy p2) { + if (p1 == p2) { return true; } // update policy doesn't affect contents - return p1.isEnabled() == p2.isEnabled() && Objects.equals( p1.getChecksumPolicy(), p2.getChecksumPolicy() ); + return p1.isEnabled() == p2.isEnabled() && Objects.equals(p1.getChecksumPolicy(), p2.getChecksumPolicy()); } - private static boolean repositoryEquals( RemoteRepository r1, RemoteRepository r2 ) - { - if ( r1 == r2 ) - { + private static boolean repositoryEquals(RemoteRepository r1, RemoteRepository r2) { + if (r1 == r2) { return true; } - return Objects.equals( r1.getId(), r2.getId() ) && Objects.equals( r1.getUrl(), r2.getUrl() ) - && policyEquals( r1.getPolicy( false ), r2.getPolicy( false ) ) - && policyEquals( r1.getPolicy( true ), r2.getPolicy( true ) ); + return Objects.equals(r1.getId(), r2.getId()) + && Objects.equals(r1.getUrl(), r2.getUrl()) + && policyEquals(r1.getPolicy(false), r2.getPolicy(false)) + && policyEquals(r1.getPolicy(true), r2.getPolicy(true)); } } diff --git a/maven-core/src/main/java/org/apache/maven/SessionScoped.java b/maven-core/src/main/java/org/apache/maven/SessionScoped.java index 7738938c06..e19536bf02 100644 --- a/maven-core/src/main/java/org/apache/maven/SessionScoped.java +++ b/maven-core/src/main/java/org/apache/maven/SessionScoped.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,15 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import com.google.inject.ScopeAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import com.google.inject.ScopeAnnotation; - /** * Indicates that annotated component should be instantiated before session execution starts * and discarded after session execution completes. @@ -34,9 +32,7 @@ import com.google.inject.ScopeAnnotation; * @author Jason van Zyl * @since 3.2.0 */ -@Target( { TYPE } ) -@Retention( RUNTIME ) +@Target({TYPE}) +@Retention(RUNTIME) @ScopeAnnotation -public @interface SessionScoped -{ -} +public @interface SessionScoped {} diff --git a/maven-core/src/main/java/org/apache/maven/artifact/DependencyResolutionRequiredException.java b/maven-core/src/main/java/org/apache/maven/artifact/DependencyResolutionRequiredException.java index 99794231e8..66a1530b44 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/DependencyResolutionRequiredException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/DependencyResolutionRequiredException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; /** * Exception that occurs when an artifact file is used, but has not been resolved. @@ -25,11 +24,8 @@ package org.apache.maven.artifact; * @author Brett Porter * TODO it may be better for artifact.getFile() to throw it - perhaps it is a runtime exception? */ -public class DependencyResolutionRequiredException - extends Exception -{ - public DependencyResolutionRequiredException( Artifact artifact ) - { - super( "Attempted to access the artifact " + artifact + "; which has not yet been resolved" ); +public class DependencyResolutionRequiredException extends Exception { + public DependencyResolutionRequiredException(Artifact artifact) { + super("Attempted to access the artifact " + artifact + "; which has not yet been resolved"); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/InvalidRepositoryException.java b/maven-core/src/main/java/org/apache/maven/artifact/InvalidRepositoryException.java index 62991f11dd..e2ae8e61aa 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/InvalidRepositoryException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/InvalidRepositoryException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact; import java.net.MalformedURLException; - import org.codehaus.plexus.component.repository.exception.ComponentLookupException; /** @@ -28,38 +26,31 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti * * @author Brett Porter */ -public class InvalidRepositoryException - extends Exception -{ +public class InvalidRepositoryException extends Exception { private final String repositoryId; - public InvalidRepositoryException( String message, String repositoryId, MalformedURLException cause ) - { - super( message, cause ); + public InvalidRepositoryException(String message, String repositoryId, MalformedURLException cause) { + super(message, cause); this.repositoryId = repositoryId; } - protected InvalidRepositoryException( String message, String repositoryId, ComponentLookupException cause ) - { - super( message, cause ); + protected InvalidRepositoryException(String message, String repositoryId, ComponentLookupException cause) { + super(message, cause); this.repositoryId = repositoryId; } @Deprecated - public InvalidRepositoryException( String message, Throwable t ) - { - super( message, t ); + public InvalidRepositoryException(String message, Throwable t) { + super(message, t); this.repositoryId = null; } - public InvalidRepositoryException( String message, String repositoryId ) - { - super( message ); + public InvalidRepositoryException(String message, String repositoryId) { + super(message); this.repositoryId = repositoryId; } - public String getRepositoryId() - { + public String getRepositoryId() { return repositoryId; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/factory/ArtifactFactory.java b/maven-core/src/main/java/org/apache/maven/artifact/factory/ArtifactFactory.java index 28f281eb7d..b3b7c36f9c 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/factory/ArtifactFactory.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/factory/ArtifactFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.factory; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.factory; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.factory; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.factory; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; @@ -26,38 +25,56 @@ import org.apache.maven.artifact.versioning.VersionRange; * ArtifactFactory - deprecated */ @Deprecated -@SuppressWarnings( "checkstyle:parameternumber" ) -public interface ArtifactFactory -{ +@SuppressWarnings("checkstyle:parameternumber") +public interface ArtifactFactory { @Deprecated String ROLE = ArtifactFactory.class.getName(); - Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ); + Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type); - Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, - String classifier ); + Artifact createArtifactWithClassifier( + String groupId, String artifactId, String version, String type, String classifier); - Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope ); + Artifact createDependencyArtifact( + String groupId, String artifactId, VersionRange versionRange, String type, String classifier, String scope); - Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, boolean optional ); + Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + boolean optional); - Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, String inheritedScope ); + Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope); - Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, String inheritedScope, boolean optional ); + Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope, + boolean optional); - Artifact createBuildArtifact( String groupId, String artifactId, String version, String packaging ); + Artifact createBuildArtifact(String groupId, String artifactId, String version, String packaging); - Artifact createProjectArtifact( String groupId, String artifactId, String version ); + Artifact createProjectArtifact(String groupId, String artifactId, String version); - Artifact createParentArtifact( String groupId, String artifactId, String version ); + Artifact createParentArtifact(String groupId, String artifactId, String version); - Artifact createPluginArtifact( String groupId, String artifactId, VersionRange versionRange ); + Artifact createPluginArtifact(String groupId, String artifactId, VersionRange versionRange); - Artifact createProjectArtifact( String groupId, String artifactId, String version, String scope ); + Artifact createProjectArtifact(String groupId, String artifactId, String version, String scope); - Artifact createExtensionArtifact( String groupId, String artifactId, VersionRange versionRange ); + Artifact createExtensionArtifact(String groupId, String artifactId, VersionRange versionRange); } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/factory/DefaultArtifactFactory.java b/maven-core/src/main/java/org/apache/maven/artifact/factory/DefaultArtifactFactory.java index 70466a7034..5ee70e9eb5 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/factory/DefaultArtifactFactory.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/factory/DefaultArtifactFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.factory; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.factory; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.artifact.factory; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.factory; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; @@ -35,139 +33,154 @@ import org.apache.maven.artifact.versioning.VersionRange; */ @Named @Singleton -@SuppressWarnings( "checkstyle:parameternumber" ) -public class DefaultArtifactFactory - implements ArtifactFactory -{ +@SuppressWarnings("checkstyle:parameternumber") +public class DefaultArtifactFactory implements ArtifactFactory { private final ArtifactHandlerManager artifactHandlerManager; @Inject - public DefaultArtifactFactory( ArtifactHandlerManager artifactHandlerManager ) - { + public DefaultArtifactFactory(ArtifactHandlerManager artifactHandlerManager) { this.artifactHandlerManager = artifactHandlerManager; } - public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ) - { - return createArtifact( groupId, artifactId, version, scope, type, null, null ); + public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) { + return createArtifact(groupId, artifactId, version, scope, type, null, null); } - public Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, - String classifier ) - { - return createArtifact( groupId, artifactId, version, null, type, classifier, null ); + public Artifact createArtifactWithClassifier( + String groupId, String artifactId, String version, String type, String classifier) { + return createArtifact(groupId, artifactId, version, null, type, classifier, null); } - public Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, - String type, String classifier, String scope ) - { - return createArtifact( groupId, artifactId, versionRange, type, classifier, scope, null ); + public Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope) { + return createArtifact(groupId, artifactId, versionRange, type, classifier, scope, null); } - public Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, - String type, String classifier, String scope, boolean optional ) - { - return createArtifact( groupId, artifactId, versionRange, type, classifier, scope, null, optional ); + public Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + boolean optional) { + return createArtifact(groupId, artifactId, versionRange, type, classifier, scope, null, optional); } - public Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, - String type, String classifier, String scope, String inheritedScope ) - { - return createArtifact( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope ); + public Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope) { + return createArtifact(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope); } - public Artifact createDependencyArtifact( String groupId, String artifactId, VersionRange versionRange, - String type, String classifier, String scope, String inheritedScope, - boolean optional ) - { - return createArtifact( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, optional ); + public Artifact createDependencyArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope, + boolean optional) { + return createArtifact(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, optional); } - public Artifact createBuildArtifact( String groupId, String artifactId, String version, String packaging ) - { - return createArtifact( groupId, artifactId, version, null, packaging, null, null ); + public Artifact createBuildArtifact(String groupId, String artifactId, String version, String packaging) { + return createArtifact(groupId, artifactId, version, null, packaging, null, null); } - public Artifact createProjectArtifact( String groupId, String artifactId, String version ) - { - return createProjectArtifact( groupId, artifactId, version, null ); + public Artifact createProjectArtifact(String groupId, String artifactId, String version) { + return createProjectArtifact(groupId, artifactId, version, null); } - public Artifact createParentArtifact( String groupId, String artifactId, String version ) - { - return createProjectArtifact( groupId, artifactId, version ); + public Artifact createParentArtifact(String groupId, String artifactId, String version) { + return createProjectArtifact(groupId, artifactId, version); } - public Artifact createPluginArtifact( String groupId, String artifactId, VersionRange versionRange ) - { - return createArtifact( groupId, artifactId, versionRange, "maven-plugin", null, Artifact.SCOPE_RUNTIME, null ); + public Artifact createPluginArtifact(String groupId, String artifactId, VersionRange versionRange) { + return createArtifact(groupId, artifactId, versionRange, "maven-plugin", null, Artifact.SCOPE_RUNTIME, null); } - public Artifact createProjectArtifact( String groupId, String artifactId, String version, String scope ) - { - return createArtifact( groupId, artifactId, version, scope, "pom" ); + public Artifact createProjectArtifact(String groupId, String artifactId, String version, String scope) { + return createArtifact(groupId, artifactId, version, scope, "pom"); } - public Artifact createExtensionArtifact( String groupId, String artifactId, VersionRange versionRange ) - { - return createArtifact( groupId, artifactId, versionRange, "jar", null, Artifact.SCOPE_RUNTIME, null ); + public Artifact createExtensionArtifact(String groupId, String artifactId, VersionRange versionRange) { + return createArtifact(groupId, artifactId, versionRange, "jar", null, Artifact.SCOPE_RUNTIME, null); } - private Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type, - String classifier, String inheritedScope ) - { + private Artifact createArtifact( + String groupId, + String artifactId, + String version, + String scope, + String type, + String classifier, + String inheritedScope) { VersionRange versionRange = null; - if ( version != null ) - { - versionRange = VersionRange.createFromVersion( version ); + if (version != null) { + versionRange = VersionRange.createFromVersion(version); } - return createArtifact( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope ); + return createArtifact(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope); } - private Artifact createArtifact( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, String inheritedScope ) - { - return createArtifact( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, false ); + private Artifact createArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope) { + return createArtifact(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, false); } - private Artifact createArtifact( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, String inheritedScope, boolean optional ) - { + private Artifact createArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope, + boolean optional) { String desiredScope = Artifact.SCOPE_RUNTIME; - if ( inheritedScope == null ) - { + if (inheritedScope == null) { desiredScope = scope; - } - else if ( Artifact.SCOPE_TEST.equals( scope ) || Artifact.SCOPE_PROVIDED.equals( scope ) ) - { + } else if (Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_PROVIDED.equals(scope)) { return null; - } - else if ( Artifact.SCOPE_COMPILE.equals( scope ) && Artifact.SCOPE_COMPILE.equals( inheritedScope ) ) - { + } else if (Artifact.SCOPE_COMPILE.equals(scope) && Artifact.SCOPE_COMPILE.equals(inheritedScope)) { // added to retain compile artifactScope. Remove if you want compile inherited as runtime desiredScope = Artifact.SCOPE_COMPILE; } - if ( Artifact.SCOPE_TEST.equals( inheritedScope ) ) - { + if (Artifact.SCOPE_TEST.equals(inheritedScope)) { desiredScope = Artifact.SCOPE_TEST; } - if ( Artifact.SCOPE_PROVIDED.equals( inheritedScope ) ) - { + if (Artifact.SCOPE_PROVIDED.equals(inheritedScope)) { desiredScope = Artifact.SCOPE_PROVIDED; } - if ( Artifact.SCOPE_SYSTEM.equals( scope ) ) - { + if (Artifact.SCOPE_SYSTEM.equals(scope)) { // system scopes come through unchanged... desiredScope = Artifact.SCOPE_SYSTEM; } - ArtifactHandler handler = artifactHandlerManager.getArtifactHandler( type ); + ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type); - return new DefaultArtifact( groupId, artifactId, versionRange, desiredScope, type, classifier, handler, - optional ); + return new DefaultArtifact( + groupId, artifactId, versionRange, desiredScope, type, classifier, handler, optional); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/DefaultArtifactHandler.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/DefaultArtifactHandler.java index d0d2bf4671..b6f10a4878 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/DefaultArtifactHandler.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/DefaultArtifactHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.handler; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler; import static java.util.Objects.requireNonNull; @@ -25,9 +24,7 @@ import static java.util.Objects.requireNonNull; * @author Brett Porter * @author Jason van Zyl */ -public class DefaultArtifactHandler - implements ArtifactHandler -{ +public class DefaultArtifactHandler implements ArtifactHandler { private final String type; private String extension; @@ -51,36 +48,25 @@ public class DefaultArtifactHandler * @deprecated This ctor is present only for Plexus XML defined component compatibility, do not use it. */ @Deprecated - public DefaultArtifactHandler() - { + public DefaultArtifactHandler() { this.type = null; } - public DefaultArtifactHandler( final String type ) - { - this( - type, - null, - null, - null, - null, - false, - null, - false - ); + public DefaultArtifactHandler(final String type) { + this(type, null, null, null, null, false, null, false); } - @SuppressWarnings( "checkstyle:ParameterNumber" ) - public DefaultArtifactHandler( final String type, - final String extension, - final String classifier, - final String directory, - final String packaging, - final boolean includesDependencies, - final String language, - final boolean addedToClasspath ) - { - this.type = requireNonNull( type ); + @SuppressWarnings("checkstyle:ParameterNumber") + public DefaultArtifactHandler( + final String type, + final String extension, + final String classifier, + final String directory, + final String packaging, + final boolean includesDependencies, + final String language, + final boolean addedToClasspath) { + this.type = requireNonNull(type); this.extension = extension; this.classifier = classifier; this.directory = directory; @@ -90,102 +76,83 @@ public class DefaultArtifactHandler this.addedToClasspath = addedToClasspath; } - public String getType() - { + public String getType() { return type; } @Override - public String getExtension() - { - if ( extension == null ) - { + public String getExtension() { + if (extension == null) { return type; } return extension; } - public void setExtension( final String extension ) - { + public void setExtension(final String extension) { this.extension = extension; } @Override - public String getClassifier() - { + public String getClassifier() { return classifier; } - public void setClassifier( final String classifier ) - { + public void setClassifier(final String classifier) { this.classifier = classifier; } @Override - public String getDirectory() - { - if ( directory == null ) - { + public String getDirectory() { + if (directory == null) { return getPackaging() + "s"; } return directory; } - public void setDirectory( final String directory ) - { + public void setDirectory(final String directory) { this.directory = directory; } @Override - public String getPackaging() - { - if ( packaging == null ) - { + public String getPackaging() { + if (packaging == null) { return type; } return packaging; } - public void setPackaging( final String packaging ) - { + public void setPackaging(final String packaging) { this.packaging = packaging; } @Override - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return includesDependencies; } - public void setIncludesDependencies( final boolean includesDependencies ) - { + public void setIncludesDependencies(final boolean includesDependencies) { this.includesDependencies = includesDependencies; } @Override - public String getLanguage() - { - if ( language == null ) - { + public String getLanguage() { + if (language == null) { return "none"; } return language; } - public void setLanguage( final String language ) - { + public void setLanguage(final String language) { this.language = language; } @Override - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return addedToClasspath; } - public void setAddedToClasspath( final boolean addedToClasspath ) - { + public void setAddedToClasspath(final boolean addedToClasspath) { this.addedToClasspath = addedToClasspath; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/ArtifactHandlerManager.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/ArtifactHandlerManager.java index cada9e9352..2004f68a24 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/ArtifactHandlerManager.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/ArtifactHandlerManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.manager; * "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 + * 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 @@ -18,20 +16,19 @@ package org.apache.maven.artifact.handler.manager; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.manager; import java.util.Map; - import org.apache.maven.artifact.handler.ArtifactHandler; /** * @author Jason van Zyl */ -public interface ArtifactHandlerManager -{ +public interface ArtifactHandlerManager { String ROLE = ArtifactHandlerManager.class.getName(); - ArtifactHandler getArtifactHandler( String type ); + ArtifactHandler getArtifactHandler(String type); @Deprecated - void addHandlers( Map handlers ); + void addHandlers(Map handlers); } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/DefaultArtifactHandlerManager.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/DefaultArtifactHandlerManager.java index 3145d5808a..2c7efadc5c 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/DefaultArtifactHandlerManager.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/manager/DefaultArtifactHandlerManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.manager; * "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 + * 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 @@ -18,15 +16,14 @@ package org.apache.maven.artifact.handler.manager; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.manager; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; @@ -35,51 +32,40 @@ import org.apache.maven.artifact.handler.DefaultArtifactHandler; */ @Named @Singleton -public class DefaultArtifactHandlerManager - implements ArtifactHandlerManager -{ +public class DefaultArtifactHandlerManager implements ArtifactHandlerManager { private final Map artifactHandlers; private final Map allHandlers = new ConcurrentHashMap<>(); @Inject - public DefaultArtifactHandlerManager( Map artifactHandlers ) - { + public DefaultArtifactHandlerManager(Map artifactHandlers) { this.artifactHandlers = artifactHandlers; } - public ArtifactHandler getArtifactHandler( String type ) - { - ArtifactHandler handler = allHandlers.get( type ); + public ArtifactHandler getArtifactHandler(String type) { + ArtifactHandler handler = allHandlers.get(type); - if ( handler == null ) - { - handler = artifactHandlers.get( type ); + if (handler == null) { + handler = artifactHandlers.get(type); - if ( handler == null ) - { - handler = new DefaultArtifactHandler( type ); - } - else - { - allHandlers.put( type, handler ); + if (handler == null) { + handler = new DefaultArtifactHandler(type); + } else { + allHandlers.put(type, handler); } } return handler; } - public void addHandlers( Map handlers ) - { + public void addHandlers(Map handlers) { // legacy support for maven-gpg-plugin:1.0 - allHandlers.putAll( handlers ); + allHandlers.putAll(handlers); } @Deprecated - public Set getHandlerTypes() - { + public Set getHandlerTypes() { return artifactHandlers.keySet(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EarArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EarArtifactHandlerProvider.java index fbb5fff5c8..df56cae91c 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EarArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EarArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code ear} artifact handler provider. */ -@Named( "ear" ) +@Named("ear") @Singleton -public class EarArtifactHandlerProvider - implements Provider -{ +public class EarArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public EarArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "ear", - null, - null, - null, - null, - true, - "java", - false - ); + public EarArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("ear", null, null, null, null, true, "java", false); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbArtifactHandlerProvider.java index 5802db61a8..6e558652cc 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code ejb} artifact handler provider. */ -@Named( "ejb" ) +@Named("ejb") @Singleton -public class EjbArtifactHandlerProvider - implements Provider -{ +public class EjbArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public EjbArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "ejb", - "jar", - null, - null, - null, - false, - "java", - true - ); + public EjbArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("ejb", "jar", null, null, null, false, "java", true); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbClientArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbClientArtifactHandlerProvider.java index d225b76045..35702483c6 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbClientArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/EjbClientArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,31 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code ejb-client} artifact handler provider. */ -@Named( "ejb-client" ) +@Named("ejb-client") @Singleton -public class EjbClientArtifactHandlerProvider - implements Provider -{ +public class EjbClientArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public EjbClientArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "ejb-client", - "jar", - "client", - null, - "ejb", - false, - "java", - true - ); + public EjbClientArtifactHandlerProvider() { + this.artifactHandler = + new DefaultArtifactHandler("ejb-client", "jar", "client", null, "ejb", false, "java", true); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JarArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JarArtifactHandlerProvider.java index 0e203ba4c8..f27dfcbca0 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JarArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JarArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code jar} artifact handler provider. */ -@Named( "jar" ) +@Named("jar") @Singleton -public class JarArtifactHandlerProvider - implements Provider -{ +public class JarArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public JarArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "jar", - null, - null, - null, - null, - false, - "java", - true - ); + public JarArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("jar", null, null, null, null, false, "java", true); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavaSourceArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavaSourceArtifactHandlerProvider.java index 37bf394198..2a66975dc6 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavaSourceArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavaSourceArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,31 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code java-source} artifact handler provider. */ -@Named( "java-source" ) +@Named("java-source") @Singleton -public class JavaSourceArtifactHandlerProvider - implements Provider -{ +public class JavaSourceArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public JavaSourceArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "java-source", - "jar", - "sources", - null, - null, - false, - "java", - false - ); + public JavaSourceArtifactHandlerProvider() { + this.artifactHandler = + new DefaultArtifactHandler("java-source", "jar", "sources", null, null, false, "java", false); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavadocArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavadocArtifactHandlerProvider.java index d7d40e36e4..d0dd66e631 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavadocArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/JavadocArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code javadoc} artifact handler provider. */ -@Named( "javadoc" ) +@Named("javadoc") @Singleton -public class JavadocArtifactHandlerProvider - implements Provider -{ +public class JavadocArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public JavadocArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "javadoc", - "jar", - "javadoc", - null, - null, - false, - "java", - true - ); + public JavadocArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("javadoc", "jar", "javadoc", null, null, false, "java", true); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/MavenPluginArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/MavenPluginArtifactHandlerProvider.java index c7122118f6..d8159b36fe 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/MavenPluginArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/MavenPluginArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code maven-plugin} artifact handler provider. */ -@Named( "maven-plugin" ) +@Named("maven-plugin") @Singleton -public class MavenPluginArtifactHandlerProvider - implements Provider -{ +public class MavenPluginArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public MavenPluginArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "maven-plugin", - "jar", - null, - null, - null, - false, - "java", - true - ); + public MavenPluginArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("maven-plugin", "jar", null, null, null, false, "java", true); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/PomArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/PomArtifactHandlerProvider.java index 3696159313..04ecf3fb5b 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/PomArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/PomArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code pom} artifact handler provider. */ -@Named( "pom" ) +@Named("pom") @Singleton -public class PomArtifactHandlerProvider - implements Provider -{ +public class PomArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public PomArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "pom", - null, - null, - null, - null, - false, - "none", - false - ); + public PomArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("pom", null, null, null, null, false, "none", false); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/RarArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/RarArtifactHandlerProvider.java index d2d75b9bb1..d616227e1e 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/RarArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/RarArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code rar} artifact handler provider. */ -@Named( "rar" ) +@Named("rar") @Singleton -public class RarArtifactHandlerProvider - implements Provider -{ +public class RarArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public RarArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "rar", - null, - null, - null, - null, - true, - "java", - false - ); + public RarArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("rar", null, null, null, null, true, "java", false); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/TestJarArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/TestJarArtifactHandlerProvider.java index 57bfe49ddd..f9d2b7f930 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/TestJarArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/TestJarArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code test-jar} artifact handler provider. */ -@Named( "test-jar" ) +@Named("test-jar") @Singleton -public class TestJarArtifactHandlerProvider - implements Provider -{ +public class TestJarArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public TestJarArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "test-jar", - "jar", - "tests", - null, - "jar", - false, - "java", - true - ); + public TestJarArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("test-jar", "jar", "tests", null, "jar", false, "java", true); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/WarArtifactHandlerProvider.java b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/WarArtifactHandlerProvider.java index f2dc46ea29..22e878f4c5 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/WarArtifactHandlerProvider.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/handler/providers/WarArtifactHandlerProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler.providers; * "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 + * 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 @@ -18,43 +16,30 @@ package org.apache.maven.artifact.handler.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.handler.providers; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.DefaultArtifactHandler; /** * {@code war} artifact handler provider. */ -@Named( "war" ) +@Named("war") @Singleton -public class WarArtifactHandlerProvider - implements Provider -{ +public class WarArtifactHandlerProvider implements Provider { private final ArtifactHandler artifactHandler; @Inject - public WarArtifactHandlerProvider() - { - this.artifactHandler = new DefaultArtifactHandler( - "war", - null, - null, - null, - null, - true, - "java", - false - ); + public WarArtifactHandlerProvider() { + this.artifactHandler = new DefaultArtifactHandler("war", null, null, null, null, true, "java", false); } @Override - public ArtifactHandler get() - { + public ArtifactHandler get() { return artifactHandler; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/metadata/AbstractArtifactMetadata.java b/maven-core/src/main/java/org/apache/maven/artifact/metadata/AbstractArtifactMetadata.java index f0de677c6a..1562d19c1b 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/metadata/AbstractArtifactMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/metadata/AbstractArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.metadata; import org.apache.maven.artifact.Artifact; @@ -26,11 +25,9 @@ import org.apache.maven.artifact.Artifact; */ @Deprecated public abstract class AbstractArtifactMetadata - extends org.apache.maven.repository.legacy.metadata.AbstractArtifactMetadata - implements org.apache.maven.artifact.metadata.ArtifactMetadata -{ - protected AbstractArtifactMetadata( Artifact artifact ) - { - super( artifact ); + extends org.apache.maven.repository.legacy.metadata.AbstractArtifactMetadata + implements org.apache.maven.artifact.metadata.ArtifactMetadata { + protected AbstractArtifactMetadata(Artifact artifact) { + super(artifact); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataRetrievalException.java b/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataRetrievalException.java index 342c6fea2d..5330f7e3fc 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataRetrievalException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataRetrievalException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.metadata; import org.apache.maven.artifact.Artifact; @@ -26,17 +25,15 @@ import org.apache.maven.artifact.Artifact; */ @Deprecated public class ArtifactMetadataRetrievalException - extends org.apache.maven.repository.legacy.metadata.ArtifactMetadataRetrievalException -{ + extends org.apache.maven.repository.legacy.metadata.ArtifactMetadataRetrievalException { /** * @param message a message * @deprecated use {@link #ArtifactMetadataRetrievalException(String, Throwable, Artifact)} */ @Deprecated - public ArtifactMetadataRetrievalException( String message ) - { - super( message, null, null ); + public ArtifactMetadataRetrievalException(String message) { + super(message, null, null); } /** @@ -44,9 +41,8 @@ public class ArtifactMetadataRetrievalException * @deprecated use {@link #ArtifactMetadataRetrievalException(String, Throwable, Artifact)} */ @Deprecated - public ArtifactMetadataRetrievalException( Throwable cause ) - { - super( null, cause, null ); + public ArtifactMetadataRetrievalException(Throwable cause) { + super(null, cause, null); } /** @@ -55,14 +51,11 @@ public class ArtifactMetadataRetrievalException * @deprecated use {@link #ArtifactMetadataRetrievalException(String, Throwable, Artifact)} */ @Deprecated - public ArtifactMetadataRetrievalException( String message, - Throwable cause ) - { - super( message, cause, null ); + public ArtifactMetadataRetrievalException(String message, Throwable cause) { + super(message, cause, null); } - public ArtifactMetadataRetrievalException( String message, Throwable cause, Artifact artifact ) - { - super( message, cause, artifact ); + public ArtifactMetadataRetrievalException(String message, Throwable cause, Artifact artifact) { + super(message, cause, artifact); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataSource.java b/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataSource.java index 605230f05d..0bc65986cb 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataSource.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.metadata; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.metadata; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -31,26 +29,22 @@ import org.apache.maven.repository.legacy.metadata.MetadataResolutionRequest; * artifact - deprecated */ @Deprecated -public interface ArtifactMetadataSource - extends org.apache.maven.repository.legacy.metadata.ArtifactMetadataSource -{ +public interface ArtifactMetadataSource extends org.apache.maven.repository.legacy.metadata.ArtifactMetadataSource { - ResolutionGroup retrieve( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException; + ResolutionGroup retrieve(MetadataResolutionRequest request) throws ArtifactMetadataRetrievalException; - ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException; + ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException; - List retrieveAvailableVersions( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException; + List retrieveAvailableVersions(MetadataResolutionRequest request) + throws ArtifactMetadataRetrievalException; - List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException; + List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException; - List retrieveAvailableVersionsFromDeploymentRepository( Artifact artifact, - ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws ArtifactMetadataRetrievalException; -} \ No newline at end of file + List retrieveAvailableVersionsFromDeploymentRepository( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws ArtifactMetadataRetrievalException; +} diff --git a/maven-core/src/main/java/org/apache/maven/artifact/metadata/ResolutionGroup.java b/maven-core/src/main/java/org/apache/maven/artifact/metadata/ResolutionGroup.java index 3503265367..85a6df70be 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/metadata/ResolutionGroup.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/metadata/ResolutionGroup.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.metadata; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.artifact.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.metadata; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -30,20 +28,19 @@ import org.apache.maven.artifact.repository.ArtifactRepository; * ResolutionGroup */ @Deprecated -public class ResolutionGroup - extends org.apache.maven.repository.legacy.metadata.ResolutionGroup -{ +public class ResolutionGroup extends org.apache.maven.repository.legacy.metadata.ResolutionGroup { - public ResolutionGroup( Artifact pomArtifact, Set artifacts, - List resolutionRepositories ) - { - super( pomArtifact, artifacts, resolutionRepositories ); + public ResolutionGroup( + Artifact pomArtifact, Set artifacts, List resolutionRepositories) { + super(pomArtifact, artifacts, resolutionRepositories); } - public ResolutionGroup( Artifact pomArtifact, Artifact relocatedArtifact, Set artifacts, - Map managedVersions, List resolutionRepositories ) - { - super( pomArtifact, relocatedArtifact, artifacts, managedVersions, resolutionRepositories ); + public ResolutionGroup( + Artifact pomArtifact, + Artifact relocatedArtifact, + Set artifacts, + Map managedVersions, + List resolutionRepositories) { + super(pomArtifact, relocatedArtifact, artifacts, managedVersions, resolutionRepositories); } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/DefaultRepositoryRequest.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/DefaultRepositoryRequest.java index 839094f8a5..0956291db2 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/DefaultRepositoryRequest.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/DefaultRepositoryRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.util.ArrayList; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; @@ -30,9 +28,7 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -public class DefaultRepositoryRequest - implements RepositoryRequest -{ +public class DefaultRepositoryRequest implements RepositoryRequest { private boolean offline; @@ -45,8 +41,7 @@ public class DefaultRepositoryRequest /** * Creates an empty repository request. */ - public DefaultRepositoryRequest() - { + public DefaultRepositoryRequest() { // enables no-arg constructor } @@ -55,80 +50,67 @@ public class DefaultRepositoryRequest * * @param repositoryRequest The repository request to copy from, must not be {@code null}. */ - public DefaultRepositoryRequest( RepositoryRequest repositoryRequest ) - { - setLocalRepository( repositoryRequest.getLocalRepository() ); - setRemoteRepositories( repositoryRequest.getRemoteRepositories() ); - setOffline( repositoryRequest.isOffline() ); - setForceUpdate( repositoryRequest.isForceUpdate() ); + public DefaultRepositoryRequest(RepositoryRequest repositoryRequest) { + setLocalRepository(repositoryRequest.getLocalRepository()); + setRemoteRepositories(repositoryRequest.getRemoteRepositories()); + setOffline(repositoryRequest.isOffline()); + setForceUpdate(repositoryRequest.isForceUpdate()); } - public static RepositoryRequest getRepositoryRequest( MavenSession session, MavenProject project ) - { + public static RepositoryRequest getRepositoryRequest(MavenSession session, MavenProject project) { RepositoryRequest request = new DefaultRepositoryRequest(); - request.setLocalRepository( session.getLocalRepository() ); - if ( project != null ) - { - request.setRemoteRepositories( project.getPluginArtifactRepositories() ); + request.setLocalRepository(session.getLocalRepository()); + if (project != null) { + request.setRemoteRepositories(project.getPluginArtifactRepositories()); } - request.setOffline( session.isOffline() ); - request.setForceUpdate( session.getRequest().isUpdateSnapshots() ); + request.setOffline(session.isOffline()); + request.setForceUpdate(session.getRequest().isUpdateSnapshots()); return request; } - public boolean isOffline() - { + public boolean isOffline() { return offline; } - public DefaultRepositoryRequest setOffline( boolean offline ) - { + public DefaultRepositoryRequest setOffline(boolean offline) { this.offline = offline; return this; } - public boolean isForceUpdate() - { + public boolean isForceUpdate() { return forceUpdate; } - public DefaultRepositoryRequest setForceUpdate( boolean forceUpdate ) - { + public DefaultRepositoryRequest setForceUpdate(boolean forceUpdate) { this.forceUpdate = forceUpdate; return this; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } - public DefaultRepositoryRequest setLocalRepository( ArtifactRepository localRepository ) - { + public DefaultRepositoryRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; return this; } - public List getRemoteRepositories() - { - if ( remoteRepositories == null ) - { + public List getRemoteRepositories() { + if (remoteRepositories == null) { remoteRepositories = new ArrayList<>(); } return remoteRepositories; } - public DefaultRepositoryRequest setRemoteRepositories( List remoteRepositories ) - { + public DefaultRepositoryRequest setRemoteRepositories(List remoteRepositories) { this.remoteRepositories = remoteRepositories; return this; } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/LegacyLocalRepositoryManager.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/LegacyLocalRepositoryManager.java index acd7d5f2c4..710984ef39 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/LegacyLocalRepositoryManager.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/LegacyLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,12 +16,12 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Objects; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; @@ -51,9 +49,7 @@ import org.eclipse.aether.repository.RemoteRepository; * * @author Benjamin Bentmann */ -public class LegacyLocalRepositoryManager - implements LocalRepositoryManager -{ +public class LegacyLocalRepositoryManager implements LocalRepositoryManager { private final ArtifactRepository delegate; @@ -61,40 +57,33 @@ public class LegacyLocalRepositoryManager private final boolean realLocalRepo; - public static RepositorySystemSession overlay( ArtifactRepository repository, RepositorySystemSession session, - RepositorySystem system ) - { - if ( repository == null || repository.getBasedir() == null ) - { + public static RepositorySystemSession overlay( + ArtifactRepository repository, RepositorySystemSession session, RepositorySystem system) { + if (repository == null || repository.getBasedir() == null) { return session; } - if ( session != null ) - { + if (session != null) { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); - if ( lrm != null && lrm.getRepository().getBasedir().equals( new File( repository.getBasedir() ) ) ) - { + if (lrm != null && lrm.getRepository().getBasedir().equals(new File(repository.getBasedir()))) { return session; } - } - else - { + } else { session = new DefaultRepositorySystemSession(); } - final LocalRepositoryManager llrm = new LegacyLocalRepositoryManager( repository ); + final LocalRepositoryManager llrm = new LegacyLocalRepositoryManager(repository); - return new DefaultRepositorySystemSession( session ).setLocalRepositoryManager( llrm ); + return new DefaultRepositorySystemSession(session).setLocalRepositoryManager(llrm); } - private LegacyLocalRepositoryManager( ArtifactRepository delegate ) - { - this.delegate = Objects.requireNonNull( delegate, "delegate cannot be null" ); + private LegacyLocalRepositoryManager(ArtifactRepository delegate) { + this.delegate = Objects.requireNonNull(delegate, "delegate cannot be null"); ArtifactRepositoryLayout layout = delegate.getLayout(); - repo = - new LocalRepository( new File( delegate.getBasedir() ), - ( layout != null ) ? layout.getClass().getSimpleName() : "legacy" ); + repo = new LocalRepository( + new File(delegate.getBasedir()), + (layout != null) ? layout.getClass().getSimpleName() : "legacy"); /* * NOTE: "invoker:install" vs "appassembler:assemble": Both mojos use the artifact installer to put an artifact @@ -108,334 +97,253 @@ public class LegacyLocalRepositoryManager * transformation however contradicts the other use case of precisely obeying the repository's layout. The below * flag tries to detect which use case applies to make both plugins happy. */ - realLocalRepo = ( layout instanceof DefaultRepositoryLayout ) && "local".equals( delegate.getId() ); + realLocalRepo = (layout instanceof DefaultRepositoryLayout) && "local".equals(delegate.getId()); } - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return repo; } - public String getPathForLocalArtifact( Artifact artifact ) - { - if ( realLocalRepo ) - { - return delegate.pathOf( RepositoryUtils.toArtifact( artifact.setVersion( artifact.getBaseVersion() ) ) ); + public String getPathForLocalArtifact(Artifact artifact) { + if (realLocalRepo) { + return delegate.pathOf(RepositoryUtils.toArtifact(artifact.setVersion(artifact.getBaseVersion()))); } - return delegate.pathOf( RepositoryUtils.toArtifact( artifact ) ); + return delegate.pathOf(RepositoryUtils.toArtifact(artifact)); } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { - return delegate.pathOf( RepositoryUtils.toArtifact( artifact ) ); + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { + return delegate.pathOf(RepositoryUtils.toArtifact(artifact)); } - public String getPathForLocalMetadata( Metadata metadata ) - { - return delegate.pathOfLocalRepositoryMetadata( new ArtifactMetadataAdapter( metadata ), delegate ); + public String getPathForLocalMetadata(Metadata metadata) { + return delegate.pathOfLocalRepositoryMetadata(new ArtifactMetadataAdapter(metadata), delegate); } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { - return delegate.pathOfLocalRepositoryMetadata( new ArtifactMetadataAdapter( metadata ), - new ArtifactRepositoryAdapter( repository ) ); + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { + return delegate.pathOfLocalRepositoryMetadata( + new ArtifactMetadataAdapter(metadata), new ArtifactRepositoryAdapter(repository)); } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { - String path = getPathForLocalArtifact( request.getArtifact() ); - File file = new File( getRepository().getBasedir(), path ); + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { + String path = getPathForLocalArtifact(request.getArtifact()); + File file = new File(getRepository().getBasedir(), path); - LocalArtifactResult result = new LocalArtifactResult( request ); - if ( file.isFile() ) - { - result.setFile( file ); - result.setAvailable( true ); + LocalArtifactResult result = new LocalArtifactResult(request); + if (file.isFile()) { + result.setFile(file); + result.setAvailable(true); } return result; } - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { Metadata metadata = request.getMetadata(); String path; - if ( request.getRepository() == null ) - { - path = getPathForLocalMetadata( metadata ); - } - else - { - path = getPathForRemoteMetadata( metadata, request.getRepository(), request.getContext() ); + if (request.getRepository() == null) { + path = getPathForLocalMetadata(metadata); + } else { + path = getPathForRemoteMetadata(metadata, request.getRepository(), request.getContext()); } - File file = new File( getRepository().getBasedir(), path ); + File file = new File(getRepository().getBasedir(), path); - LocalMetadataResult result = new LocalMetadataResult( request ); - if ( file.isFile() ) - { - result.setFile( file ); + LocalMetadataResult result = new LocalMetadataResult(request); + if (file.isFile()) { + result.setFile(file); } return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { // noop } - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { + public void add(RepositorySystemSession session, LocalMetadataRegistration request) { // noop } - static class ArtifactMetadataAdapter - implements ArtifactMetadata - { + static class ArtifactMetadataAdapter implements ArtifactMetadata { private final Metadata metadata; - ArtifactMetadataAdapter( Metadata metadata ) - { + ArtifactMetadataAdapter(Metadata metadata) { this.metadata = metadata; } - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return metadata.getVersion().length() > 0; } - public boolean storedInGroupDirectory() - { + public boolean storedInGroupDirectory() { return metadata.getArtifactId().length() <= 0; } - public String getGroupId() - { - return nullify( metadata.getGroupId() ); + public String getGroupId() { + return nullify(metadata.getGroupId()); } - public String getArtifactId() - { - return nullify( metadata.getArtifactId() ); + public String getArtifactId() { + return nullify(metadata.getArtifactId()); } - public String getBaseVersion() - { - return nullify( metadata.getVersion() ); + public String getBaseVersion() { + return nullify(metadata.getVersion()); } - private String nullify( String str ) - { - return ( str == null || str.length() <= 0 ) ? null : str; + private String nullify(String str) { + return (str == null || str.length() <= 0) ? null : str; } - public Object getKey() - { + public Object getKey() { return metadata.toString(); } - public String getRemoteFilename() - { + public String getRemoteFilename() { return metadata.getType(); } - public String getLocalFilename( ArtifactRepository repository ) - { - return insertRepositoryKey( getRemoteFilename(), repository.getKey() ); + public String getLocalFilename(ArtifactRepository repository) { + return insertRepositoryKey(getRemoteFilename(), repository.getKey()); } - private String insertRepositoryKey( String filename, String repositoryKey ) - { + private String insertRepositoryKey(String filename, String repositoryKey) { String result; - int idx = filename.indexOf( '.' ); - if ( idx < 0 ) - { + int idx = filename.indexOf('.'); + if (idx < 0) { result = filename + '-' + repositoryKey; - } - else - { - result = filename.substring( 0, idx ) + '-' + repositoryKey + filename.substring( idx ); + } else { + result = filename.substring(0, idx) + '-' + repositoryKey + filename.substring(idx); } return result; } - public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata ) - { + public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) { // not used } - public void merge( ArtifactMetadata metadata ) - { + public void merge(ArtifactMetadata metadata) { // not used } - public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws RepositoryMetadataStoreException - { + public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataStoreException { // not used } - public String extendedToString() - { + public String extendedToString() { return metadata.toString(); } - } - static class ArtifactRepositoryAdapter - implements ArtifactRepository - { + static class ArtifactRepositoryAdapter implements ArtifactRepository { private final RemoteRepository repository; - ArtifactRepositoryAdapter( RemoteRepository repository ) - { + ArtifactRepositoryAdapter(RemoteRepository repository) { this.repository = repository; } - public String pathOf( org.apache.maven.artifact.Artifact artifact ) - { + public String pathOf(org.apache.maven.artifact.Artifact artifact) { return null; } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata artifactMetadata ) - { + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata) { return null; } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { return null; } - public String getUrl() - { + public String getUrl() { return repository.getUrl(); } - public void setUrl( String url ) - { - } + public void setUrl(String url) {} - public String getBasedir() - { + public String getBasedir() { return null; } - public String getProtocol() - { + public String getProtocol() { return repository.getProtocol(); } - public String getId() - { + public String getId() { return repository.getId(); } - public void setId( String id ) - { - } + public void setId(String id) {} - public ArtifactRepositoryPolicy getSnapshots() - { + public ArtifactRepositoryPolicy getSnapshots() { return null; } - public void setSnapshotUpdatePolicy( ArtifactRepositoryPolicy policy ) - { - } + public void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy policy) {} - public ArtifactRepositoryPolicy getReleases() - { + public ArtifactRepositoryPolicy getReleases() { return null; } - public void setReleaseUpdatePolicy( ArtifactRepositoryPolicy policy ) - { - } + public void setReleaseUpdatePolicy(ArtifactRepositoryPolicy policy) {} - public ArtifactRepositoryLayout getLayout() - { + public ArtifactRepositoryLayout getLayout() { return null; } - public void setLayout( ArtifactRepositoryLayout layout ) - { - } + public void setLayout(ArtifactRepositoryLayout layout) {} - public String getKey() - { + public String getKey() { return getId(); } - public boolean isUniqueVersion() - { + public boolean isUniqueVersion() { return true; } - public boolean isBlacklisted() - { + public boolean isBlacklisted() { return false; } - public void setBlacklisted( boolean blackListed ) - { - } + public void setBlacklisted(boolean blackListed) {} - public org.apache.maven.artifact.Artifact find( org.apache.maven.artifact.Artifact artifact ) - { + public org.apache.maven.artifact.Artifact find(org.apache.maven.artifact.Artifact artifact) { return null; } - public List findVersions( org.apache.maven.artifact.Artifact artifact ) - { + public List findVersions(org.apache.maven.artifact.Artifact artifact) { return Collections.emptyList(); } - public boolean isProjectAware() - { + public boolean isProjectAware() { return false; } - public void setAuthentication( Authentication authentication ) - { - } + public void setAuthentication(Authentication authentication) {} - public Authentication getAuthentication() - { + public Authentication getAuthentication() { return null; } - public void setProxy( Proxy proxy ) - { - } + public void setProxy(Proxy proxy) {} - public Proxy getProxy() - { + public Proxy getProxy() { return null; } - public List getMirroredRepositories() - { + public List getMirroredRepositories() { return Collections.emptyList(); } - public void setMirroredRepositories( List mirroredRepositories ) - { - } + public void setMirroredRepositories(List mirroredRepositories) {} - public boolean isBlocked() - { + public boolean isBlocked() { return false; } - public void setBlocked( boolean blocked ) - { - } - + public void setBlocked(boolean blocked) {} } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/MavenArtifactRepository.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/MavenArtifactRepository.java index ee513e4f73..28701f551f 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/MavenArtifactRepository.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/MavenArtifactRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository; * "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 + * 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 @@ -18,12 +16,12 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Objects; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; @@ -33,10 +31,8 @@ import org.apache.maven.repository.Proxy; * Abstraction of an artifact repository. Artifact repositories can be remote, local, or even build reactor or * IDE workspace. */ -//TODO completely separate local and remote artifact repositories -public class MavenArtifactRepository - implements ArtifactRepository -{ +// TODO completely separate local and remote artifact repositories +public class MavenArtifactRepository implements ArtifactRepository { private static final String LS = System.lineSeparator(); private String id; @@ -61,9 +57,7 @@ public class MavenArtifactRepository private boolean blocked; - public MavenArtifactRepository() - { - } + public MavenArtifactRepository() {} /** * Create a remote download repository. @@ -74,9 +68,12 @@ public class MavenArtifactRepository * @param snapshots the policies to use for snapshots * @param releases the policies to use for releases */ - public MavenArtifactRepository( String id, String url, ArtifactRepositoryLayout layout, - ArtifactRepositoryPolicy snapshots, ArtifactRepositoryPolicy releases ) - { + public MavenArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout layout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { this.id = id; this.url = url; this.layout = layout; @@ -85,137 +82,119 @@ public class MavenArtifactRepository // // Derive these from the URL // - this.protocol = protocol( url ); - this.basedir = basedir( url ); + this.protocol = protocol(url); + this.basedir = basedir(url); } - public String pathOf( Artifact artifact ) - { - return layout.pathOf( artifact ); + public String pathOf(Artifact artifact) { + return layout.pathOf(artifact); } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata artifactMetadata ) - { - return layout.pathOfRemoteRepositoryMetadata( artifactMetadata ); + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata) { + return layout.pathOfRemoteRepositoryMetadata(artifactMetadata); } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return layout.pathOfLocalRepositoryMetadata( metadata, repository ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return layout.pathOfLocalRepositoryMetadata(metadata, repository); } - public void setLayout( ArtifactRepositoryLayout layout ) - { + public void setLayout(ArtifactRepositoryLayout layout) { this.layout = layout; } - public ArtifactRepositoryLayout getLayout() - { + public ArtifactRepositoryLayout getLayout() { return layout; } - public void setSnapshotUpdatePolicy( ArtifactRepositoryPolicy snapshots ) - { + public void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy snapshots) { this.snapshots = snapshots; } - public ArtifactRepositoryPolicy getSnapshots() - { + public ArtifactRepositoryPolicy getSnapshots() { return snapshots; } - public void setReleaseUpdatePolicy( ArtifactRepositoryPolicy releases ) - { + public void setReleaseUpdatePolicy(ArtifactRepositoryPolicy releases) { this.releases = releases; } - public ArtifactRepositoryPolicy getReleases() - { + public ArtifactRepositoryPolicy getReleases() { return releases; } - public String getKey() - { + public String getKey() { return getId(); } - public String toString() - { - StringBuilder sb = new StringBuilder( 256 ); + public String toString() { + StringBuilder sb = new StringBuilder(256); - sb.append( " id: " ).append( getId() ).append( LS ); - sb.append( " url: " ).append( getUrl() ).append( LS ); - sb.append( " layout: " ).append( layout != null ? layout : "none" ); + sb.append(" id: ").append(getId()).append(LS); + sb.append(" url: ").append(getUrl()).append(LS); + sb.append(" layout: ").append(layout != null ? layout : "none"); - if ( proxy != null ) - { - sb.append( LS ).append( " proxy: " ).append( proxy.getHost() ).append( ':' ).append( proxy.getPort() ); + if (proxy != null) { + sb.append(LS) + .append(" proxy: ") + .append(proxy.getHost()) + .append(':') + .append(proxy.getPort()); } - if ( snapshots != null ) - { - sb.append( LS ).append( "snapshots: [enabled => " ).append( snapshots.isEnabled() ); - sb.append( ", update => " ).append( snapshots.getUpdatePolicy() ).append( ']' ); + if (snapshots != null) { + sb.append(LS).append("snapshots: [enabled => ").append(snapshots.isEnabled()); + sb.append(", update => ").append(snapshots.getUpdatePolicy()).append(']'); } - if ( releases != null ) - { - sb.append( LS ).append( "releases: [enabled => " ).append( releases.isEnabled() ); - sb.append( ", update => " ).append( releases.getUpdatePolicy() ).append( ']' ); + if (releases != null) { + sb.append(LS).append("releases: [enabled => ").append(releases.isEnabled()); + sb.append(", update => ").append(releases.getUpdatePolicy()).append(']'); } - sb.append( " blocked: " ).append( isBlocked() ).append( '\n' ); + sb.append(" blocked: ").append(isBlocked()).append('\n'); return sb.toString(); } - public Artifact find( Artifact artifact ) - { - File artifactFile = new File( getBasedir(), pathOf( artifact ) ); + public Artifact find(Artifact artifact) { + File artifactFile = new File(getBasedir(), pathOf(artifact)); // We need to set the file here or the resolver will fail with an NPE, not fully equipped to deal // with multiple local repository implementations yet. - artifact.setFile( artifactFile ); + artifact.setFile(artifactFile); return artifact; } - public List findVersions( Artifact artifact ) - { + public List findVersions(Artifact artifact) { return Collections.emptyList(); } - public String getId() - { + public String getId() { return id; } - public String getUrl() - { + public String getUrl() { return url; } - public String getBasedir() - { + public String getBasedir() { return basedir; } - public String getProtocol() - { + public String getProtocol() { return protocol; } - public void setId( String id ) - { + public void setId(String id) { this.id = id; } - public void setUrl( String url ) - { + public void setUrl(String url) { this.url = url; - this.protocol = protocol( url ); - this.basedir = basedir( url ); + this.protocol = protocol(url); + this.basedir = basedir(url); } // Path Utils @@ -229,15 +208,13 @@ public class MavenArtifactRepository * @param url the url * @return the host name */ - private static String protocol( final String url ) - { - final int pos = url.indexOf( ':' ); + private static String protocol(final String url) { + final int pos = url.indexOf(':'); - if ( pos == -1 ) - { + if (pos == -1) { return ""; } - return url.substring( 0, pos ).trim(); + return url.substring(0, pos).trim(); } /** @@ -247,40 +224,30 @@ public class MavenArtifactRepository * @return the basedir of the repository * TODO need to URL decode for spaces? */ - private String basedir( String url ) - { + private String basedir(String url) { String retValue = null; - if ( protocol.equalsIgnoreCase( "file" ) ) - { - retValue = url.substring( protocol.length() + 1 ); - retValue = decode( retValue ); + if (protocol.equalsIgnoreCase("file")) { + retValue = url.substring(protocol.length() + 1); + retValue = decode(retValue); // special case: if omitted // on protocol, keep path as is - if ( retValue.startsWith( "//" ) ) - { - retValue = retValue.substring( 2 ); + if (retValue.startsWith("//")) { + retValue = retValue.substring(2); - if ( retValue.length() >= 2 && ( retValue.charAt( 1 ) == '|' || retValue.charAt( 1 ) == ':' ) ) - { + if (retValue.length() >= 2 && (retValue.charAt(1) == '|' || retValue.charAt(1) == ':')) { // special case: if there is a windows drive letter, then keep the original return value - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); - } - else - { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); + } else { // Now we expect the host - int index = retValue.indexOf( '/' ); - if ( index >= 0 ) - { - retValue = retValue.substring( index + 1 ); + int index = retValue.indexOf('/'); + if (index >= 0) { + retValue = retValue.substring(index + 1); } // special case: if there is a windows drive letter, then keep the original return value - if ( retValue.length() >= 2 && ( retValue.charAt( 1 ) == '|' || retValue.charAt( 1 ) == ':' ) ) - { - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); - } - else if ( index >= 0 ) - { + if (retValue.length() >= 2 && (retValue.charAt(1) == '|' || retValue.charAt(1) == ':')) { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); + } else if (index >= 0) { // leading / was previously stripped retValue = "/" + retValue; } @@ -288,17 +255,15 @@ public class MavenArtifactRepository } // special case: if there is a windows drive letter using |, switch to : - if ( retValue.length() >= 2 && retValue.charAt( 1 ) == '|' ) - { - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); + if (retValue.length() >= 2 && retValue.charAt(1) == '|') { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); } // normalize separators - retValue = new File( retValue ).getPath(); + retValue = new File(retValue).getPath(); } - if ( retValue == null ) - { + if (retValue == null) { retValue = "/"; } return retValue.trim(); @@ -311,123 +276,97 @@ public class MavenArtifactRepository * @param url The URL to decode, may be null. * @return The decoded URL or null if the input was null. */ - private static String decode( String url ) - { + private static String decode(String url) { String decoded = url; - if ( url != null ) - { + if (url != null) { int pos = -1; - while ( ( pos = decoded.indexOf( '%', pos + 1 ) ) >= 0 ) - { - if ( pos + 2 < decoded.length() ) - { - String hexStr = decoded.substring( pos + 1, pos + 3 ); - char ch = (char) Integer.parseInt( hexStr, 16 ); - decoded = decoded.substring( 0, pos ) + ch + decoded.substring( pos + 3 ); + while ((pos = decoded.indexOf('%', pos + 1)) >= 0) { + if (pos + 2 < decoded.length()) { + String hexStr = decoded.substring(pos + 1, pos + 3); + char ch = (char) Integer.parseInt(hexStr, 16); + decoded = decoded.substring(0, pos) + ch + decoded.substring(pos + 3); } } } return decoded; } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( getId() == null ) ? 0 : getId().hashCode() ); + result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } ArtifactRepository other = (ArtifactRepository) obj; - return eq( getId(), other.getId() ); + return eq(getId(), other.getId()); } - protected static boolean eq( T s1, T s2 ) - { - return Objects.equals( s1, s2 ); + protected static boolean eq(T s1, T s2) { + return Objects.equals(s1, s2); } - public Authentication getAuthentication() - { + public Authentication getAuthentication() { return authentication; } - public void setAuthentication( Authentication authentication ) - { + public void setAuthentication(Authentication authentication) { this.authentication = authentication; } - public Proxy getProxy() - { + public Proxy getProxy() { return proxy; } - public void setProxy( Proxy proxy ) - { + public void setProxy(Proxy proxy) { this.proxy = proxy; } - public boolean isBlacklisted() - { + public boolean isBlacklisted() { return false; } - public void setBlacklisted( boolean blackListed ) - { + public void setBlacklisted(boolean blackListed) { // no op } - public boolean isUniqueVersion() - { + public boolean isUniqueVersion() { return true; } - public boolean isProjectAware() - { + public boolean isProjectAware() { return false; } - public List getMirroredRepositories() - { + public List getMirroredRepositories() { return mirroredRepositories; } - public void setMirroredRepositories( List mirroredRepositories ) - { - if ( mirroredRepositories != null ) - { - this.mirroredRepositories = Collections.unmodifiableList( mirroredRepositories ); - } - else - { + public void setMirroredRepositories(List mirroredRepositories) { + if (mirroredRepositories != null) { + this.mirroredRepositories = Collections.unmodifiableList(mirroredRepositories); + } else { this.mirroredRepositories = Collections.emptyList(); } } - public boolean isBlocked() - { + public boolean isBlocked() { return blocked; } - public void setBlocked( boolean blocked ) - { + public void setBlocked(boolean blocked) { this.blocked = blocked; } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryCache.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryCache.java index bf79d69857..df7c1df102 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryCache.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; /** * Caches auxiliary data used during repository access like already processed metadata. The data in the cache is meant @@ -30,8 +29,7 @@ package org.apache.maven.artifact.repository; // Used by Tycho and will break users and force them to upgrade to Maven 3.1 so we should really leave // this here, possibly indefinitely. // -public interface RepositoryCache -{ +public interface RepositoryCache { /** * Puts the specified data into the cache. Warning: The cache will directly save the provided @@ -42,7 +40,7 @@ public interface RepositoryCache * @param key The key to use associate the data with, must not be {@code null}. * @param data The data to store in the cache, may be {@code null}. */ - void put( RepositoryRequest request, Object key, Object data ); + void put(RepositoryRequest request, Object key, Object data); /** * Gets the specified data from the cache. Warning: The cache will directly return the saved @@ -53,6 +51,5 @@ public interface RepositoryCache * @param key The key to use for lookup of the data, must not be {@code null}. * @return The requested data or {@code null} if none was present in the cache. */ - Object get( RepositoryRequest request, Object key ); - + Object get(RepositoryRequest request, Object key); } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryRequest.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryRequest.java index 55f60686ff..8b476466b2 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryRequest.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/RepositoryRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository; import java.util.List; @@ -26,8 +25,7 @@ import java.util.List; * * @author Benjamin Bentmann */ -public interface RepositoryRequest -{ +public interface RepositoryRequest { /** * Indicates whether network access to remote repositories has been disabled. @@ -42,7 +40,7 @@ public interface RepositoryRequest * @param offline {@code true} to disable remote access, {@code false} to allow network access. * @return This request, never {@code null}. */ - RepositoryRequest setOffline( boolean offline ); + RepositoryRequest setOffline(boolean offline); /** * Indicates whether remote repositories should be re-checked for updated artifacts/metadata regardless of their @@ -60,7 +58,7 @@ public interface RepositoryRequest * false} to use the update policy configured on each repository. * @return This request, never {@code null}. */ - RepositoryRequest setForceUpdate( boolean forceUpdate ); + RepositoryRequest setForceUpdate(boolean forceUpdate); /** * Gets the local repository to use. @@ -75,7 +73,7 @@ public interface RepositoryRequest * @param localRepository The local repository to use. * @return This request, never {@code null}. */ - RepositoryRequest setLocalRepository( ArtifactRepository localRepository ); + RepositoryRequest setLocalRepository(ArtifactRepository localRepository); /** * Gets the remote repositories to use. @@ -90,6 +88,5 @@ public interface RepositoryRequest * @param remoteRepositories The remote repositories to use. * @return This request, never {@code null}. */ - RepositoryRequest setRemoteRepositories( List remoteRepositories ); - + RepositoryRequest setRemoteRepositories(List remoteRepositories); } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/layout/DefaultRepositoryLayout.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/layout/DefaultRepositoryLayout.java index 0590e53a97..8a4f9e29e8 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/layout/DefaultRepositoryLayout.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/layout/DefaultRepositoryLayout.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.layout; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.artifact.repository.layout; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.layout; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -30,86 +28,72 @@ import org.apache.maven.artifact.repository.ArtifactRepository; /** * @author jdcasey */ -@Named( "default" ) +@Named("default") @Singleton -public class DefaultRepositoryLayout - implements ArtifactRepositoryLayout -{ +public class DefaultRepositoryLayout implements ArtifactRepositoryLayout { private static final char PATH_SEPARATOR = '/'; private static final char GROUP_SEPARATOR = '.'; private static final char ARTIFACT_SEPARATOR = '-'; - public String getId() - { + public String getId() { return "default"; } - public String pathOf( Artifact artifact ) - { + public String pathOf(Artifact artifact) { ArtifactHandler artifactHandler = artifact.getArtifactHandler(); - StringBuilder path = new StringBuilder( 128 ); + StringBuilder path = new StringBuilder(128); - path.append( formatAsDirectory( artifact.getGroupId() ) ).append( PATH_SEPARATOR ); - path.append( artifact.getArtifactId() ).append( PATH_SEPARATOR ); - path.append( artifact.getBaseVersion() ).append( PATH_SEPARATOR ); - path.append( artifact.getArtifactId() ).append( ARTIFACT_SEPARATOR ).append( artifact.getVersion() ); + path.append(formatAsDirectory(artifact.getGroupId())).append(PATH_SEPARATOR); + path.append(artifact.getArtifactId()).append(PATH_SEPARATOR); + path.append(artifact.getBaseVersion()).append(PATH_SEPARATOR); + path.append(artifact.getArtifactId()).append(ARTIFACT_SEPARATOR).append(artifact.getVersion()); - if ( artifact.hasClassifier() ) - { - path.append( ARTIFACT_SEPARATOR ).append( artifact.getClassifier() ); + if (artifact.hasClassifier()) { + path.append(ARTIFACT_SEPARATOR).append(artifact.getClassifier()); } - if ( artifactHandler.getExtension() != null && artifactHandler.getExtension().length() > 0 ) - { - path.append( GROUP_SEPARATOR ).append( artifactHandler.getExtension() ); + if (artifactHandler.getExtension() != null + && artifactHandler.getExtension().length() > 0) { + path.append(GROUP_SEPARATOR).append(artifactHandler.getExtension()); } return path.toString(); } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return pathOfRepositoryMetadata( metadata, metadata.getLocalFilename( repository ) ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return pathOfRepositoryMetadata(metadata, metadata.getLocalFilename(repository)); } - private String pathOfRepositoryMetadata( ArtifactMetadata metadata, - String filename ) - { - StringBuilder path = new StringBuilder( 128 ); + private String pathOfRepositoryMetadata(ArtifactMetadata metadata, String filename) { + StringBuilder path = new StringBuilder(128); - path.append( formatAsDirectory( metadata.getGroupId() ) ).append( PATH_SEPARATOR ); - if ( !metadata.storedInGroupDirectory() ) - { - path.append( metadata.getArtifactId() ).append( PATH_SEPARATOR ); + path.append(formatAsDirectory(metadata.getGroupId())).append(PATH_SEPARATOR); + if (!metadata.storedInGroupDirectory()) { + path.append(metadata.getArtifactId()).append(PATH_SEPARATOR); - if ( metadata.storedInArtifactVersionDirectory() ) - { - path.append( metadata.getBaseVersion() ).append( PATH_SEPARATOR ); + if (metadata.storedInArtifactVersionDirectory()) { + path.append(metadata.getBaseVersion()).append(PATH_SEPARATOR); } } - path.append( filename ); + path.append(filename); return path.toString(); } - public String pathOfRemoteRepositoryMetadata( ArtifactMetadata metadata ) - { - return pathOfRepositoryMetadata( metadata, metadata.getRemoteFilename() ); + public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) { + return pathOfRepositoryMetadata(metadata, metadata.getRemoteFilename()); } - private String formatAsDirectory( String directory ) - { - return directory.replace( GROUP_SEPARATOR, PATH_SEPARATOR ); + private String formatAsDirectory(String directory) { + return directory.replace(GROUP_SEPARATOR, PATH_SEPARATOR); } @Override - public String toString() - { + public String toString() { return getId(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java index ed02da8d0b..da14063858 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,7 +16,12 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -29,206 +32,159 @@ import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.WriterFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; - /** * Shared methods of the repository metadata handling. * * @author Brett Porter */ -public abstract class AbstractRepositoryMetadata - implements RepositoryMetadata -{ +public abstract class AbstractRepositoryMetadata implements RepositoryMetadata { private static final String LS = System.lineSeparator(); private Metadata metadata; - protected AbstractRepositoryMetadata( Metadata metadata ) - { + protected AbstractRepositoryMetadata(Metadata metadata) { this.metadata = metadata; } - public String getRemoteFilename() - { + public String getRemoteFilename() { return "maven-metadata.xml"; } - public String getLocalFilename( ArtifactRepository repository ) - { + public String getLocalFilename(ArtifactRepository repository) { return "maven-metadata-" + repository.getKey() + ".xml"; } - public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws RepositoryMetadataStoreException - { - try - { - updateRepositoryMetadata( localRepository, remoteRepository ); - } - catch ( IOException | XmlPullParserException e ) - { - throw new RepositoryMetadataStoreException( "Error updating group repository metadata", e ); + public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataStoreException { + try { + updateRepositoryMetadata(localRepository, remoteRepository); + } catch (IOException | XmlPullParserException e) { + throw new RepositoryMetadataStoreException("Error updating group repository metadata", e); } } - protected void updateRepositoryMetadata( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws IOException, XmlPullParserException - { + protected void updateRepositoryMetadata(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws IOException, XmlPullParserException { MetadataXpp3Reader mappingReader = new MetadataXpp3Reader(); Metadata metadata = null; - File metadataFile = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( this, remoteRepository ) ); + File metadataFile = new File( + localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(this, remoteRepository)); - if ( metadataFile.length() == 0 ) - { - if ( !metadataFile.delete() ) - { + if (metadataFile.length() == 0) { + if (!metadataFile.delete()) { // sleep for 10ms just in case this is windows holding a file lock - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException e ) - { + try { + Thread.sleep(10); + } catch (InterruptedException e) { // ignore } metadataFile.delete(); // if this fails, forget about it, we'll try to overwrite it anyway so no need // to delete on exit } - } - else if ( metadataFile.exists() ) - { - try ( Reader reader = ReaderFactory.newXmlReader( metadataFile ) ) - { - metadata = mappingReader.read( reader, false ); + } else if (metadataFile.exists()) { + try (Reader reader = ReaderFactory.newXmlReader(metadataFile)) { + metadata = mappingReader.read(reader, false); } } boolean changed; // If file could not be found or was not valid, start from scratch - if ( metadata == null ) - { + if (metadata == null) { metadata = this.metadata; changed = true; - } - else - { - changed = metadata.merge( this.metadata ); + } else { + changed = metadata.merge(this.metadata); } // beware meta-versions! String version = metadata.getVersion(); - if ( Artifact.LATEST_VERSION.equals( version ) || Artifact.RELEASE_VERSION.equals( version ) ) - { + if (Artifact.LATEST_VERSION.equals(version) || Artifact.RELEASE_VERSION.equals(version)) { // meta-versions are not valid values...don't write them. - metadata.setVersion( null ); + metadata.setVersion(null); } - if ( changed || !metadataFile.exists() ) - { + if (changed || !metadataFile.exists()) { metadataFile.getParentFile().mkdirs(); - try ( Writer writer = WriterFactory.newXmlWriter( metadataFile ) ) - { + try (Writer writer = WriterFactory.newXmlWriter(metadataFile)) { MetadataXpp3Writer mappingWriter = new MetadataXpp3Writer(); - mappingWriter.write( writer, metadata ); + mappingWriter.write(writer, metadata); } - } - else - { - metadataFile.setLastModified( System.currentTimeMillis() ); + } else { + metadataFile.setLastModified(System.currentTimeMillis()); } } - public String toString() - { + public String toString() { return "repository metadata for: '" + getKey() + "'"; } - protected static Metadata createMetadata( Artifact artifact, Versioning versioning ) - { + protected static Metadata createMetadata(Artifact artifact, Versioning versioning) { Metadata metadata = new Metadata(); - metadata.setGroupId( artifact.getGroupId() ); - metadata.setArtifactId( artifact.getArtifactId() ); - metadata.setVersion( artifact.getVersion() ); - metadata.setVersioning( versioning ); + metadata.setGroupId(artifact.getGroupId()); + metadata.setArtifactId(artifact.getArtifactId()); + metadata.setVersion(artifact.getVersion()); + metadata.setVersioning(versioning); return metadata; } - protected static Versioning createVersioning( Snapshot snapshot ) - { + protected static Versioning createVersioning(Snapshot snapshot) { Versioning versioning = new Versioning(); - versioning.setSnapshot( snapshot ); + versioning.setSnapshot(snapshot); return versioning; } - public void setMetadata( Metadata metadata ) - { + public void setMetadata(Metadata metadata) { this.metadata = metadata; } - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } - public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata ) - { + public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) { // TODO not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact // replaces? AbstractRepositoryMetadata repoMetadata = (AbstractRepositoryMetadata) metadata; - this.metadata.merge( repoMetadata.getMetadata() ); + this.metadata.merge(repoMetadata.getMetadata()); } - public void merge( ArtifactMetadata metadata ) - { + public void merge(ArtifactMetadata metadata) { // TODO not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact // replaces? AbstractRepositoryMetadata repoMetadata = (AbstractRepositoryMetadata) metadata; - this.metadata.merge( repoMetadata.getMetadata() ); + this.metadata.merge(repoMetadata.getMetadata()); } - public String extendedToString() - { - StringBuilder buffer = new StringBuilder( 256 ); + public String extendedToString() { + StringBuilder buffer = new StringBuilder(256); - buffer.append( LS ).append( "Repository Metadata" ).append( LS ).append( "--------------------------" ); - buffer.append( LS ).append( "GroupId: " ).append( getGroupId() ); - buffer.append( LS ).append( "ArtifactId: " ).append( getArtifactId() ); - buffer.append( LS ).append( "Metadata Type: " ).append( getClass().getName() ); + buffer.append(LS).append("Repository Metadata").append(LS).append("--------------------------"); + buffer.append(LS).append("GroupId: ").append(getGroupId()); + buffer.append(LS).append("ArtifactId: ").append(getArtifactId()); + buffer.append(LS).append("Metadata Type: ").append(getClass().getName()); return buffer.toString(); } - public int getNature() - { + public int getNature() { return RELEASE; } - public ArtifactRepositoryPolicy getPolicy( ArtifactRepository repository ) - { + public ArtifactRepositoryPolicy getPolicy(ArtifactRepository repository) { int nature = getNature(); - if ( ( nature & RepositoryMetadata.RELEASE_OR_SNAPSHOT ) == RepositoryMetadata.RELEASE_OR_SNAPSHOT ) - { - ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy( repository.getReleases() ); - policy.merge( repository.getSnapshots() ); + if ((nature & RepositoryMetadata.RELEASE_OR_SNAPSHOT) == RepositoryMetadata.RELEASE_OR_SNAPSHOT) { + ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy(repository.getReleases()); + policy.merge(repository.getSnapshots()); return policy; - } - else if ( ( nature & RepositoryMetadata.SNAPSHOT ) != 0 ) - { + } else if ((nature & RepositoryMetadata.SNAPSHOT) != 0) { return repository.getSnapshots(); - } - else - { + } else { return repository.getReleases(); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/ArtifactRepositoryMetadata.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/ArtifactRepositoryMetadata.java index 85fc60180f..d694499be4 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/ArtifactRepositoryMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/ArtifactRepositoryMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; @@ -31,74 +30,57 @@ import org.apache.maven.artifact.versioning.VersionRange; * * @author Brett Porter */ -public class ArtifactRepositoryMetadata - extends AbstractRepositoryMetadata -{ +public class ArtifactRepositoryMetadata extends AbstractRepositoryMetadata { private Artifact artifact; - public ArtifactRepositoryMetadata( Artifact artifact ) - { - this( artifact, null ); + public ArtifactRepositoryMetadata(Artifact artifact) { + this(artifact, null); } - public ArtifactRepositoryMetadata( Artifact artifact, - Versioning versioning ) - { - super( createMetadata( artifact, versioning ) ); + public ArtifactRepositoryMetadata(Artifact artifact, Versioning versioning) { + super(createMetadata(artifact, versioning)); this.artifact = artifact; } - public boolean storedInGroupDirectory() - { + public boolean storedInGroupDirectory() { return false; } - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return false; } - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } - public String getBaseVersion() - { + public String getBaseVersion() { // Don't want the artifact's version in here, as this is stored in the directory above that return null; } - public Object getKey() - { + public Object getKey() { return "artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId(); } - public boolean isSnapshot() - { + public boolean isSnapshot() { // Don't consider the artifact's version in here, as this is stored in the directory above that return false; } - public int getNature() - { - if ( artifact.getVersion() != null ) - { + public int getNature() { + if (artifact.getVersion() != null) { return artifact.isSnapshot() ? SNAPSHOT : RELEASE; } VersionRange range = artifact.getVersionRange(); - if ( range != null ) - { - for ( Restriction restriction : range.getRestrictions() ) - { - if ( isSnapshot( restriction.getLowerBound() ) || isSnapshot( restriction.getUpperBound() ) ) - { + if (range != null) { + for (Restriction restriction : range.getRestrictions()) { + if (isSnapshot(restriction.getLowerBound()) || isSnapshot(restriction.getUpperBound())) { return RELEASE_OR_SNAPSHOT; } } @@ -107,23 +89,19 @@ public class ArtifactRepositoryMetadata return RELEASE; } - private boolean isSnapshot( ArtifactVersion version ) - { - return version != null && ArtifactUtils.isSnapshot( version.getQualifier() ); + private boolean isSnapshot(ArtifactVersion version) { + return version != null && ArtifactUtils.isSnapshot(version.getQualifier()); } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return null; } - public void setRepository( ArtifactRepository remoteRepository ) - { + public void setRepository(ArtifactRepository remoteRepository) { /* * NOTE: Metadata at the g:a level contains a collection of available versions. After merging, we can't tell * which repository provides which version so the metadata manager must not restrict the artifact resolution to * the repository with the most recent updates. */ } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadata.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadata.java index d7fe50b430..acbfc1045f 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -28,9 +27,7 @@ import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; * @author Brett Porter * TODO not happy about the store method - they use "this" */ -public interface RepositoryMetadata - extends org.apache.maven.artifact.metadata.ArtifactMetadata -{ +public interface RepositoryMetadata extends org.apache.maven.artifact.metadata.ArtifactMetadata { int RELEASE = 1; @@ -50,7 +47,7 @@ public interface RepositoryMetadata * * @param remoteRepository the repository */ - void setRepository( ArtifactRepository remoteRepository ); + void setRepository(ArtifactRepository remoteRepository); /** * Get the repository metadata associated with this marker. @@ -64,7 +61,7 @@ public interface RepositoryMetadata * * @param metadata the metadata */ - void setMetadata( Metadata metadata ); + void setMetadata(Metadata metadata); /** * Whether this represents a snapshot. @@ -87,6 +84,5 @@ public interface RepositoryMetadata * @param repository The repository for which to determine the policy, must not be {@code null}. * @return The policy, never {@code null}. */ - ArtifactRepositoryPolicy getPolicy( ArtifactRepository repository ); - + ArtifactRepositoryPolicy getPolicy(ArtifactRepository repository); } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataDeploymentException.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataDeploymentException.java index 94545650c9..d82c2979cd 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataDeploymentException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataDeploymentException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; /** * Error while deploying repository metadata. * * @author Brett Porter */ -public class RepositoryMetadataDeploymentException - extends Throwable -{ - public RepositoryMetadataDeploymentException( String message ) - { - super( message ); +public class RepositoryMetadataDeploymentException extends Throwable { + public RepositoryMetadataDeploymentException(String message) { + super(message); } - public RepositoryMetadataDeploymentException( String message, - Exception e ) - { - super( message, e ); + public RepositoryMetadataDeploymentException(String message, Exception e) { + super(message, e); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataInstallationException.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataInstallationException.java index 55bb57ed9d..376c9146ed 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataInstallationException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataInstallationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; /** * Error while installing repository metadata. * * @author Brett Porter */ -public class RepositoryMetadataInstallationException - extends Throwable -{ - public RepositoryMetadataInstallationException( String message ) - { - super( message ); +public class RepositoryMetadataInstallationException extends Throwable { + public RepositoryMetadataInstallationException(String message) { + super(message); } - public RepositoryMetadataInstallationException( String message, - Exception e ) - { - super( message, e ); + public RepositoryMetadataInstallationException(String message, Exception e) { + super(message, e); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataManager.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataManager.java index 3eb67f19bb..d5ec0fad12 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataManager.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; import java.util.List; - import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.RepositoryRequest; @@ -28,19 +26,20 @@ import org.apache.maven.artifact.repository.RepositoryRequest; /** * RepositoryMetadataManager */ -public interface RepositoryMetadataManager -{ +public interface RepositoryMetadataManager { - void resolve( RepositoryMetadata repositoryMetadata, RepositoryRequest repositoryRequest ) - throws RepositoryMetadataResolutionException; + void resolve(RepositoryMetadata repositoryMetadata, RepositoryRequest repositoryRequest) + throws RepositoryMetadataResolutionException; - void resolve( RepositoryMetadata repositoryMetadata, List repositories, - ArtifactRepository localRepository ) - throws RepositoryMetadataResolutionException; + void resolve( + RepositoryMetadata repositoryMetadata, + List repositories, + ArtifactRepository localRepository) + throws RepositoryMetadataResolutionException; - void resolveAlways( RepositoryMetadata metadata, ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws RepositoryMetadataResolutionException; + void resolveAlways( + RepositoryMetadata metadata, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataResolutionException; /** * Deploy metadata to the remote repository. @@ -50,9 +49,8 @@ public interface RepositoryMetadataManager * @param deploymentRepository the remote repository to deploy to * @throws RepositoryMetadataDeploymentException in case of metadata deployment issue */ - void deploy( ArtifactMetadata metadata, ArtifactRepository localRepository, - ArtifactRepository deploymentRepository ) - throws RepositoryMetadataDeploymentException; + void deploy(ArtifactMetadata metadata, ArtifactRepository localRepository, ArtifactRepository deploymentRepository) + throws RepositoryMetadataDeploymentException; /** * Install the metadata in the local repository. @@ -61,6 +59,6 @@ public interface RepositoryMetadataManager * @param localRepository the local repository * @throws RepositoryMetadataInstallationException in case of metadata installation issue */ - void install( ArtifactMetadata metadata, ArtifactRepository localRepository ) - throws RepositoryMetadataInstallationException; + void install(ArtifactMetadata metadata, ArtifactRepository localRepository) + throws RepositoryMetadataInstallationException; } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataResolutionException.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataResolutionException.java index 8a6f38d453..f6032aa205 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataResolutionException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/RepositoryMetadataResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.repository.metadata; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.artifact.repository.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata; /** * Error while retrieving repository metadata from the repository. * * @author Brett Porter */ -public class RepositoryMetadataResolutionException - extends Exception -{ - public RepositoryMetadataResolutionException( String message ) - { - super( message ); +public class RepositoryMetadataResolutionException extends Exception { + public RepositoryMetadataResolutionException(String message) { + super(message); } - public RepositoryMetadataResolutionException( String message, - Exception e ) - { - super( message, e ); + public RepositoryMetadataResolutionException(String message, Exception e) { + super(message, e); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/DefaultMetadataReader.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/DefaultMetadataReader.java index e4ca4f93dc..a70ddb716e 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/DefaultMetadataReader.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/DefaultMetadataReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata.io; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.metadata.io; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata.io; import java.io.File; import java.io.IOException; @@ -25,10 +24,8 @@ import java.io.InputStream; import java.io.Reader; import java.util.Map; import java.util.Objects; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader; import org.codehaus.plexus.util.ReaderFactory; @@ -41,52 +38,36 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; */ @Named @Singleton -public class DefaultMetadataReader - implements MetadataReader -{ +public class DefaultMetadataReader implements MetadataReader { - public Metadata read( File input, Map options ) - throws IOException - { - Objects.requireNonNull( input, "input cannot be null" ); + public Metadata read(File input, Map options) throws IOException { + Objects.requireNonNull(input, "input cannot be null"); - return read( ReaderFactory.newXmlReader( input ), options ); + return read(ReaderFactory.newXmlReader(input), options); } - public Metadata read( Reader input, Map options ) - throws IOException - { - Objects.requireNonNull( input, "input cannot be null" ); + public Metadata read(Reader input, Map options) throws IOException { + Objects.requireNonNull(input, "input cannot be null"); - try ( Reader in = input ) - { - return new MetadataXpp3Reader().read( in, isStrict( options ) ); - } - catch ( XmlPullParserException e ) - { - throw new MetadataParseException( e.getMessage(), e.getLineNumber(), e.getColumnNumber(), e ); + try (Reader in = input) { + return new MetadataXpp3Reader().read(in, isStrict(options)); + } catch (XmlPullParserException e) { + throw new MetadataParseException(e.getMessage(), e.getLineNumber(), e.getColumnNumber(), e); } } - public Metadata read( InputStream input, Map options ) - throws IOException - { - Objects.requireNonNull( input, "input cannot be null" ); + public Metadata read(InputStream input, Map options) throws IOException { + Objects.requireNonNull(input, "input cannot be null"); - try ( InputStream in = input ) - { - return new MetadataXpp3Reader().read( in, isStrict( options ) ); - } - catch ( XmlPullParserException e ) - { - throw new MetadataParseException( e.getMessage(), e.getLineNumber(), e.getColumnNumber(), e ); + try (InputStream in = input) { + return new MetadataXpp3Reader().read(in, isStrict(options)); + } catch (XmlPullParserException e) { + throw new MetadataParseException(e.getMessage(), e.getLineNumber(), e.getColumnNumber(), e); } } - private boolean isStrict( Map options ) - { - Object value = ( options != null ) ? options.get( IS_STRICT ) : null; - return value == null || Boolean.parseBoolean( value.toString() ); + private boolean isStrict(Map options) { + Object value = (options != null) ? options.get(IS_STRICT) : null; + return value == null || Boolean.parseBoolean(value.toString()); } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataParseException.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataParseException.java index 427141a39f..de3064b713 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataParseException.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataParseException.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata.io; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.artifact.repository.metadata.io; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata.io; import java.io.IOException; @@ -26,9 +25,7 @@ import java.io.IOException; * * @author Benjamin Bentmann */ -public class MetadataParseException - extends IOException -{ +public class MetadataParseException extends IOException { /** * The one-based index of the line containing the error. @@ -47,9 +44,8 @@ public class MetadataParseException * @param lineNumber The one-based index of the line containing the error or {@code -1} if unknown. * @param columnNumber The one-based index of the column containing the error or {@code -1} if unknown. */ - public MetadataParseException( String message, int lineNumber, int columnNumber ) - { - super( message ); + public MetadataParseException(String message, int lineNumber, int columnNumber) { + super(message); this.lineNumber = lineNumber; this.columnNumber = columnNumber; } @@ -62,10 +58,9 @@ public class MetadataParseException * @param columnNumber The one-based index of the column containing the error or {@code -1} if unknown. * @param cause The nested cause of this error, may be {@code null}. */ - public MetadataParseException( String message, int lineNumber, int columnNumber, Throwable cause ) - { - super( message ); - initCause( cause ); + public MetadataParseException(String message, int lineNumber, int columnNumber, Throwable cause) { + super(message); + initCause(cause); this.lineNumber = lineNumber; this.columnNumber = columnNumber; } @@ -75,8 +70,7 @@ public class MetadataParseException * * @return The one-based index of the line containing the error or a non-positive value if unknown. */ - public int getLineNumber() - { + public int getLineNumber() { return lineNumber; } @@ -85,9 +79,7 @@ public class MetadataParseException * * @return The one-based index of the column containing the error or non-positive value if unknown. */ - public int getColumnNumber() - { + public int getColumnNumber() { return columnNumber; } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataReader.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataReader.java index 232246fd1d..8537a0a1a3 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataReader.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/io/MetadataReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.repository.metadata.io; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ package org.apache.maven.artifact.repository.metadata.io; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.repository.metadata.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Map; - import org.apache.maven.artifact.repository.metadata.Metadata; /** @@ -32,8 +30,7 @@ import org.apache.maven.artifact.repository.metadata.Metadata; * * @author Benjamin Bentmann */ -public interface MetadataReader -{ +public interface MetadataReader { /** * The key for the option to enable strict parsing. This option is of type {@link Boolean} and defaults to {@code @@ -50,8 +47,7 @@ public interface MetadataReader * @throws IOException If the metadata could not be deserialized. * @throws MetadataParseException If the input format could not be parsed. */ - Metadata read( File input, Map options ) - throws IOException, MetadataParseException; + Metadata read(File input, Map options) throws IOException, MetadataParseException; /** * Reads the metadata from the specified character reader. The reader will be automatically closed before the method @@ -63,8 +59,7 @@ public interface MetadataReader * @throws IOException If the metadata could not be deserialized. * @throws MetadataParseException If the input format could not be parsed. */ - Metadata read( Reader input, Map options ) - throws IOException, MetadataParseException; + Metadata read(Reader input, Map options) throws IOException, MetadataParseException; /** * Reads the metadata from the specified byte stream. The stream will be automatically closed before the method @@ -76,7 +71,5 @@ public interface MetadataReader * @throws IOException If the metadata could not be deserialized. * @throws MetadataParseException If the input format could not be parsed. */ - Metadata read( InputStream input, Map options ) - throws IOException, MetadataParseException; - + Metadata read(InputStream input, Map options) throws IOException, MetadataParseException; } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionRequest.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionRequest.java index acf66b1837..27cfba2cf0 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,12 +16,12 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.RepositoryCache; @@ -39,9 +37,7 @@ import org.apache.maven.settings.Server; * * @author Jason van Zyl */ -public class ArtifactResolutionRequest - implements RepositoryRequest -{ +public class ArtifactResolutionRequest implements RepositoryRequest { private static final String LS = System.lineSeparator(); private Artifact artifact; @@ -79,62 +75,52 @@ public class ArtifactResolutionRequest private List proxies; - public ArtifactResolutionRequest() - { + public ArtifactResolutionRequest() { // nothing here } - public ArtifactResolutionRequest( RepositoryRequest request ) - { - setLocalRepository( request.getLocalRepository() ); - setRemoteRepositories( request.getRemoteRepositories() ); - setOffline( request.isOffline() ); - setForceUpdate( request.isForceUpdate() ); + public ArtifactResolutionRequest(RepositoryRequest request) { + setLocalRepository(request.getLocalRepository()); + setRemoteRepositories(request.getRemoteRepositories()); + setOffline(request.isOffline()); + setForceUpdate(request.isForceUpdate()); } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public ArtifactResolutionRequest setArtifact( Artifact artifact ) - { + public ArtifactResolutionRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } - public ArtifactResolutionRequest setArtifactDependencies( Set artifactDependencies ) - { + public ArtifactResolutionRequest setArtifactDependencies(Set artifactDependencies) { this.artifactDependencies = artifactDependencies; return this; } - public Set getArtifactDependencies() - { + public Set getArtifactDependencies() { return artifactDependencies; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } - public ArtifactResolutionRequest setLocalRepository( ArtifactRepository localRepository ) - { + public ArtifactResolutionRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; return this; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - public ArtifactResolutionRequest setRemoteRepositories( List remoteRepositories ) - { + public ArtifactResolutionRequest setRemoteRepositories(List remoteRepositories) { this.remoteRepositories = remoteRepositories; return this; @@ -146,13 +132,11 @@ public class ArtifactResolutionRequest * @return The filter used to determine which of the artifacts in the dependency graph should be traversed or * {@code null} to collect all transitive dependencies. */ - public ArtifactFilter getCollectionFilter() - { + public ArtifactFilter getCollectionFilter() { return collectionFilter; } - public ArtifactResolutionRequest setCollectionFilter( ArtifactFilter filter ) - { + public ArtifactResolutionRequest setCollectionFilter(ArtifactFilter filter) { this.collectionFilter = filter; return this; @@ -165,154 +149,136 @@ public class ArtifactResolutionRequest * @return The filter used to determine which of the artifacts should have their files resolved or {@code null} to * resolve the files for all collected artifacts. */ - public ArtifactFilter getResolutionFilter() - { + public ArtifactFilter getResolutionFilter() { return resolutionFilter; } - public ArtifactResolutionRequest setResolutionFilter( ArtifactFilter filter ) - { + public ArtifactResolutionRequest setResolutionFilter(ArtifactFilter filter) { this.resolutionFilter = filter; return this; } - public List getListeners() - { + public List getListeners() { return listeners; } - public ArtifactResolutionRequest setListeners( List listeners ) - { + public ArtifactResolutionRequest setListeners(List listeners) { this.listeners = listeners; return this; } - public ArtifactResolutionRequest addListener( ResolutionListener listener ) - { - listeners.add( listener ); + public ArtifactResolutionRequest addListener(ResolutionListener listener) { + listeners.add(listener); return this; } - public Map getManagedVersionMap() - { + public Map getManagedVersionMap() { return managedVersionMap; } - public ArtifactResolutionRequest setManagedVersionMap( Map managedVersionMap ) - { + public ArtifactResolutionRequest setManagedVersionMap(Map managedVersionMap) { this.managedVersionMap = managedVersionMap; return this; } - public ArtifactResolutionRequest setResolveRoot( boolean resolveRoot ) - { + public ArtifactResolutionRequest setResolveRoot(boolean resolveRoot) { this.resolveRoot = resolveRoot; return this; } - public boolean isResolveRoot() - { + public boolean isResolveRoot() { return resolveRoot; } - public ArtifactResolutionRequest setResolveTransitively( boolean resolveDependencies ) - { + public ArtifactResolutionRequest setResolveTransitively(boolean resolveDependencies) { this.resolveTransitively = resolveDependencies; return this; } - public boolean isResolveTransitively() - { + public boolean isResolveTransitively() { return resolveTransitively; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder() - .append( "REQUEST: " ).append( LS ) - .append( "artifact: " ).append( artifact ).append( LS ) - .append( artifactDependencies ).append( LS ) - .append( "localRepository: " ).append( localRepository ).append( LS ) - .append( "remoteRepositories: " ).append( remoteRepositories ); + .append("REQUEST: ") + .append(LS) + .append("artifact: ") + .append(artifact) + .append(LS) + .append(artifactDependencies) + .append(LS) + .append("localRepository: ") + .append(localRepository) + .append(LS) + .append("remoteRepositories: ") + .append(remoteRepositories); return sb.toString(); } - public boolean isOffline() - { + public boolean isOffline() { return offline; } - public ArtifactResolutionRequest setOffline( boolean offline ) - { + public ArtifactResolutionRequest setOffline(boolean offline) { this.offline = offline; return this; } - public boolean isForceUpdate() - { + public boolean isForceUpdate() { return forceUpdate; } - public ArtifactResolutionRequest setForceUpdate( boolean forceUpdate ) - { + public ArtifactResolutionRequest setForceUpdate(boolean forceUpdate) { this.forceUpdate = forceUpdate; return this; } - public ArtifactResolutionRequest setServers( List servers ) - { + public ArtifactResolutionRequest setServers(List servers) { this.servers = servers; return this; } - public List getServers() - { - if ( servers == null ) - { + public List getServers() { + if (servers == null) { servers = new ArrayList<>(); } return servers; } - public ArtifactResolutionRequest setMirrors( List mirrors ) - { + public ArtifactResolutionRequest setMirrors(List mirrors) { this.mirrors = mirrors; return this; } - public List getMirrors() - { - if ( mirrors == null ) - { + public List getMirrors() { + if (mirrors == null) { mirrors = new ArrayList<>(); } return mirrors; } - public ArtifactResolutionRequest setProxies( List proxies ) - { + public ArtifactResolutionRequest setProxies(List proxies) { this.proxies = proxies; return this; } - public List getProxies() - { - if ( proxies == null ) - { + public List getProxies() { + if (proxies == null) { proxies = new ArrayList<>(); } @@ -323,8 +289,7 @@ public class ArtifactResolutionRequest // Used by Tycho and will break users and force them to upgrade to Maven 3.1 so we should really leave // this here, possibly indefinitely. // - public ArtifactResolutionRequest setCache( RepositoryCache cache ) - { + public ArtifactResolutionRequest setCache(RepositoryCache cache) { return this; } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionResult.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionResult.java index e5c2a16068..a7ff61e0f8 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionResult.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.versioning.OverConstrainedVersionException; @@ -45,8 +43,7 @@ import org.apache.maven.artifact.versioning.OverConstrainedVersionException; * complex requiring a long list of checks, need to create a parent/interface/encapsulation * for the types of exceptions */ -public class ArtifactResolutionResult -{ +public class ArtifactResolutionResult { private static final String LS = System.lineSeparator(); private Artifact originatingArtifact; @@ -73,115 +70,91 @@ public class ArtifactResolutionResult private Set resolutionNodes; - public Artifact getOriginatingArtifact() - { + public Artifact getOriginatingArtifact() { return originatingArtifact; } - public ArtifactResolutionResult setOriginatingArtifact( final Artifact originatingArtifact ) - { + public ArtifactResolutionResult setOriginatingArtifact(final Artifact originatingArtifact) { this.originatingArtifact = originatingArtifact; return this; } - public void addArtifact( Artifact artifact ) - { - if ( artifacts == null ) - { + public void addArtifact(Artifact artifact) { + if (artifacts == null) { artifacts = new LinkedHashSet<>(); } - artifacts.add( artifact ); + artifacts.add(artifact); } - public Set getArtifacts() - { - if ( artifacts == null ) - { + public Set getArtifacts() { + if (artifacts == null) { artifacts = new LinkedHashSet<>(); } return artifacts; } - public void setArtifacts( Set artifacts ) - { + public void setArtifacts(Set artifacts) { this.artifacts = artifacts; } - public Set getArtifactResolutionNodes() - { - if ( resolutionNodes == null ) - { + public Set getArtifactResolutionNodes() { + if (resolutionNodes == null) { resolutionNodes = new LinkedHashSet<>(); } return resolutionNodes; } - public void setArtifactResolutionNodes( Set resolutionNodes ) - { + public void setArtifactResolutionNodes(Set resolutionNodes) { this.resolutionNodes = resolutionNodes; } - public boolean hasMissingArtifacts() - { + public boolean hasMissingArtifacts() { return missingArtifacts != null && !missingArtifacts.isEmpty(); } - public List getMissingArtifacts() - { - return missingArtifacts == null - ? Collections.emptyList() - : Collections.unmodifiableList( missingArtifacts ); - + public List getMissingArtifacts() { + return missingArtifacts == null ? Collections.emptyList() : Collections.unmodifiableList(missingArtifacts); } - public ArtifactResolutionResult addMissingArtifact( Artifact artifact ) - { - missingArtifacts = initList( missingArtifacts ); + public ArtifactResolutionResult addMissingArtifact(Artifact artifact) { + missingArtifacts = initList(missingArtifacts); - missingArtifacts.add( artifact ); + missingArtifacts.add(artifact); return this; } - public ArtifactResolutionResult setUnresolvedArtifacts( final List unresolvedArtifacts ) - { + public ArtifactResolutionResult setUnresolvedArtifacts(final List unresolvedArtifacts) { this.missingArtifacts = unresolvedArtifacts; return this; } - public boolean isSuccess() - { - return !( hasMissingArtifacts() || hasExceptions() ); + public boolean isSuccess() { + return !(hasMissingArtifacts() || hasExceptions()); } // ------------------------------------------------------------------------ // Exceptions // ------------------------------------------------------------------------ - public boolean hasExceptions() - { + public boolean hasExceptions() { return exceptions != null && !exceptions.isEmpty(); } - public List getExceptions() - { - return exceptions == null - ? Collections.emptyList() - : Collections.unmodifiableList( exceptions ); - + public List getExceptions() { + return exceptions == null ? Collections.emptyList() : Collections.unmodifiableList(exceptions); } // ------------------------------------------------------------------------ // Version Range Violations // ------------------------------------------------------------------------ - public boolean hasVersionRangeViolations() - { + public boolean hasVersionRangeViolations() { return versionRangeViolations != null; } @@ -193,152 +166,131 @@ public class ArtifactResolutionResult * @param e an exception * @return {@code this} */ - public ArtifactResolutionResult addVersionRangeViolation( Exception e ) - { - versionRangeViolations = initList( versionRangeViolations ); + public ArtifactResolutionResult addVersionRangeViolation(Exception e) { + versionRangeViolations = initList(versionRangeViolations); - versionRangeViolations.add( e ); + versionRangeViolations.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public OverConstrainedVersionException getVersionRangeViolation( int i ) - { - return (OverConstrainedVersionException) versionRangeViolations.get( i ); + public OverConstrainedVersionException getVersionRangeViolation(int i) { + return (OverConstrainedVersionException) versionRangeViolations.get(i); } - public List getVersionRangeViolations() - { + public List getVersionRangeViolations() { return versionRangeViolations == null - ? Collections.emptyList() - : Collections.unmodifiableList( versionRangeViolations ); - + ? Collections.emptyList() + : Collections.unmodifiableList(versionRangeViolations); } // ------------------------------------------------------------------------ // Metadata Resolution Exceptions: ArtifactResolutionExceptions // ------------------------------------------------------------------------ - public boolean hasMetadataResolutionExceptions() - { + public boolean hasMetadataResolutionExceptions() { return metadataResolutionExceptions != null; } - public ArtifactResolutionResult addMetadataResolutionException( ArtifactResolutionException e ) - { - metadataResolutionExceptions = initList( metadataResolutionExceptions ); + public ArtifactResolutionResult addMetadataResolutionException(ArtifactResolutionException e) { + metadataResolutionExceptions = initList(metadataResolutionExceptions); - metadataResolutionExceptions.add( e ); + metadataResolutionExceptions.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public ArtifactResolutionException getMetadataResolutionException( int i ) - { - return metadataResolutionExceptions.get( i ); + public ArtifactResolutionException getMetadataResolutionException(int i) { + return metadataResolutionExceptions.get(i); } - public List getMetadataResolutionExceptions() - { + public List getMetadataResolutionExceptions() { return metadataResolutionExceptions == null - ? Collections.emptyList() - : Collections.unmodifiableList( metadataResolutionExceptions ); - + ? Collections.emptyList() + : Collections.unmodifiableList(metadataResolutionExceptions); } // ------------------------------------------------------------------------ // ErrorArtifactExceptions: ArtifactResolutionExceptions // ------------------------------------------------------------------------ - public boolean hasErrorArtifactExceptions() - { + public boolean hasErrorArtifactExceptions() { return errorArtifactExceptions != null; } - public ArtifactResolutionResult addErrorArtifactException( ArtifactResolutionException e ) - { - errorArtifactExceptions = initList( errorArtifactExceptions ); + public ArtifactResolutionResult addErrorArtifactException(ArtifactResolutionException e) { + errorArtifactExceptions = initList(errorArtifactExceptions); - errorArtifactExceptions.add( e ); + errorArtifactExceptions.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public List getErrorArtifactExceptions() - { - if ( errorArtifactExceptions == null ) - { + public List getErrorArtifactExceptions() { + if (errorArtifactExceptions == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( errorArtifactExceptions ); + return Collections.unmodifiableList(errorArtifactExceptions); } // ------------------------------------------------------------------------ // Circular Dependency Exceptions // ------------------------------------------------------------------------ - public boolean hasCircularDependencyExceptions() - { + public boolean hasCircularDependencyExceptions() { return circularDependencyExceptions != null; } - public ArtifactResolutionResult addCircularDependencyException( CyclicDependencyException e ) - { - circularDependencyExceptions = initList( circularDependencyExceptions ); + public ArtifactResolutionResult addCircularDependencyException(CyclicDependencyException e) { + circularDependencyExceptions = initList(circularDependencyExceptions); - circularDependencyExceptions.add( e ); + circularDependencyExceptions.add(e); - exceptions = initList( exceptions ); + exceptions = initList(exceptions); - exceptions.add( e ); + exceptions.add(e); return this; } - public CyclicDependencyException getCircularDependencyException( int i ) - { - return circularDependencyExceptions.get( i ); + public CyclicDependencyException getCircularDependencyException(int i) { + return circularDependencyExceptions.get(i); } - public List getCircularDependencyExceptions() - { - if ( circularDependencyExceptions == null ) - { + public List getCircularDependencyExceptions() { + if (circularDependencyExceptions == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( circularDependencyExceptions ); + return Collections.unmodifiableList(circularDependencyExceptions); } // ------------------------------------------------------------------------ // Repositories // ------------------------------------------------------------------------ - public List getRepositories() - { - if ( repositories == null ) - { + public List getRepositories() { + if (repositories == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( repositories ); + return Collections.unmodifiableList(repositories); } - public ArtifactResolutionResult setRepositories( final List repositories ) - { + public ArtifactResolutionResult setRepositories(final List repositories) { this.repositories = repositories; return this; @@ -348,30 +300,25 @@ public class ArtifactResolutionResult // Internal // - private List initList( final List l ) - { - if ( l == null ) - { + private List initList(final List l) { + if (l == null) { return new ArrayList<>(); } return l; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - if ( artifacts != null ) - { + if (artifacts != null) { int i = 1; - sb.append( "---------" ).append( LS ); - sb.append( artifacts.size() ).append( LS ); - for ( Artifact a : artifacts ) - { - sb.append( i ).append( ' ' ).append( a ).append( LS ); + sb.append("---------").append(LS); + sb.append(artifacts.size()).append(LS); + for (Artifact a : artifacts) { + sb.append(i).append(' ').append(a).append(LS); i++; } - sb.append( "---------" ); + sb.append("---------"); } return sb.toString(); diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler.java index d1603f3a08..d2632e3c39 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.inject.Named; import javax.inject.Singleton; @@ -31,61 +29,54 @@ import javax.inject.Singleton; */ @Named @Singleton -public class DefaultResolutionErrorHandler - implements ResolutionErrorHandler -{ +public class DefaultResolutionErrorHandler implements ResolutionErrorHandler { - public void throwErrors( ArtifactResolutionRequest request, ArtifactResolutionResult result ) - throws ArtifactResolutionException - { + public void throwErrors(ArtifactResolutionRequest request, ArtifactResolutionResult result) + throws ArtifactResolutionException { // Metadata cannot be found - if ( result.hasMetadataResolutionExceptions() ) - { - throw result.getMetadataResolutionException( 0 ); + if (result.hasMetadataResolutionExceptions()) { + throw result.getMetadataResolutionException(0); } // Metadata cannot be retrieved // Cyclic Dependency Error - if ( result.hasCircularDependencyExceptions() ) - { - throw result.getCircularDependencyException( 0 ); + if (result.hasCircularDependencyExceptions()) { + throw result.getCircularDependencyException(0); } // Version Range Violation - if ( result.hasVersionRangeViolations() ) - { - throw result.getVersionRangeViolation( 0 ); + if (result.hasVersionRangeViolations()) { + throw result.getVersionRangeViolation(0); } // Transfer Error - if ( result.hasErrorArtifactExceptions() ) - { - throw result.getErrorArtifactExceptions().get( 0 ); + if (result.hasErrorArtifactExceptions()) { + throw result.getErrorArtifactExceptions().get(0); } - if ( result.hasMissingArtifacts() ) - { - throw new MultipleArtifactsNotFoundException( request.getArtifact(), toList( result.getArtifacts() ), - result.getMissingArtifacts(), - request.getRemoteRepositories() ); + if (result.hasMissingArtifacts()) { + throw new MultipleArtifactsNotFoundException( + request.getArtifact(), + toList(result.getArtifacts()), + result.getMissingArtifacts(), + request.getRemoteRepositories()); } // this should never happen since we checked all possible error sources before but better be sure - if ( result.hasExceptions() ) - { - throw new ArtifactResolutionException( "Unknown error during artifact resolution, " + request + ", " - + result.getExceptions(), request.getArtifact(), request.getRemoteRepositories() ); + if (result.hasExceptions()) { + throw new ArtifactResolutionException( + "Unknown error during artifact resolution, " + request + ", " + result.getExceptions(), + request.getArtifact(), + request.getRemoteRepositories()); } } - private static List toList( Collection items ) - { - return ( items != null ) ? new ArrayList<>( items ) : null; + private static List toList(Collection items) { + return (items != null) ? new ArrayList<>(items) : null; } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionErrorHandler.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionErrorHandler.java index c54e5b6c70..32d5552ff7 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionErrorHandler.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionErrorHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,13 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; /** * @author Benjamin Bentmann */ -public interface ResolutionErrorHandler -{ - - void throwErrors( ArtifactResolutionRequest request, ArtifactResolutionResult result ) - throws ArtifactResolutionException; +public interface ResolutionErrorHandler { + void throwErrors(ArtifactResolutionRequest request, ArtifactResolutionResult result) + throws ArtifactResolutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionListener.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionListener.java index 97687de24c..15371009e1 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; @@ -27,8 +26,7 @@ import org.apache.maven.artifact.versioning.VersionRange; * * @author Brett Porter */ -public interface ResolutionListener -{ +public interface ResolutionListener { String ROLE = ResolutionListener.class.getName(); int TEST_ARTIFACT = 1; @@ -64,32 +62,29 @@ public interface ResolutionListener int MANAGE_ARTIFACT_SYSTEM_PATH = 14; - void testArtifact( Artifact node ); + void testArtifact(Artifact node); - void startProcessChildren( Artifact artifact ); + void startProcessChildren(Artifact artifact); - void endProcessChildren( Artifact artifact ); + void endProcessChildren(Artifact artifact); - void includeArtifact( Artifact artifact ); + void includeArtifact(Artifact artifact); - void omitForNearer( Artifact omitted, - Artifact kept ); + void omitForNearer(Artifact omitted, Artifact kept); - void updateScope( Artifact artifact, - String scope ); + void updateScope(Artifact artifact, String scope); @Deprecated - void manageArtifact( Artifact artifact, - Artifact replacement ); + void manageArtifact(Artifact artifact, Artifact replacement); // TODO Use the following two instead of manageArtifact // TODO Remove ResolutionListenerDM interface - //void manageArtifactVersion( Artifact artifact, Artifact replacement ); + // void manageArtifactVersion( Artifact artifact, Artifact replacement ); - //void manageArtifactScope( Artifact artifact, Artifact replacement ); + // void manageArtifactScope( Artifact artifact, Artifact replacement ); - void omitForCycle( Artifact artifact ); + void omitForCycle(Artifact artifact); /** * This event means that the artifactScope has NOT been updated to a farther node artifactScope because current @@ -98,12 +93,9 @@ public interface ResolutionListener * @param artifact current node artifact, the one in the first level pom * @param ignoredScope artifactScope that was ignored because artifact was in first level pom */ - void updateScopeCurrentPom( Artifact artifact, - String ignoredScope ); + void updateScopeCurrentPom(Artifact artifact, String ignoredScope); - void selectVersionFromRange( Artifact artifact ); + void selectVersionFromRange(Artifact artifact); - void restrictRange( Artifact artifact, - Artifact replacement, - VersionRange newRange ); + void restrictRange(Artifact artifact, Artifact replacement, VersionRange newRange); } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java index b51c49b979..5bb1aa2477 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver; import java.util.ArrayList; import java.util.Collections; @@ -25,7 +24,6 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; @@ -35,8 +33,7 @@ import org.apache.maven.artifact.versioning.OverConstrainedVersionException; /** * ResolutionNode */ -public class ResolutionNode -{ +public class ResolutionNode { private Artifact artifact; private List children; @@ -53,8 +50,7 @@ public class ResolutionNode private List trail; - public ResolutionNode( Artifact artifact, List remoteRepositories ) - { + public ResolutionNode(Artifact artifact, List remoteRepositories) { this.artifact = artifact; this.remoteRepositories = remoteRepositories; depth = 0; @@ -62,50 +58,41 @@ public class ResolutionNode parent = null; } - public ResolutionNode( Artifact artifact, List remoteRepositories, ResolutionNode parent ) - { + public ResolutionNode(Artifact artifact, List remoteRepositories, ResolutionNode parent) { this.artifact = artifact; this.remoteRepositories = remoteRepositories; depth = parent.depth + 1; parents = new ArrayList<>(); - parents.addAll( parent.parents ); - parents.add( parent.getKey() ); + parents.addAll(parent.parents); + parents.add(parent.getKey()); this.parent = parent; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public Object getKey() - { + public Object getKey() { return artifact.getDependencyConflictId(); } - public void addDependencies( Set artifacts, List remoteRepositories, - ArtifactFilter filter ) - throws CyclicDependencyException, OverConstrainedVersionException - { - if ( artifacts != null && !artifacts.isEmpty() ) - { - children = new ArrayList<>( artifacts.size() ); + public void addDependencies( + Set artifacts, List remoteRepositories, ArtifactFilter filter) + throws CyclicDependencyException, OverConstrainedVersionException { + if (artifacts != null && !artifacts.isEmpty()) { + children = new ArrayList<>(artifacts.size()); - for ( Artifact a : artifacts ) - { - if ( parents.contains( a.getDependencyConflictId() ) ) - { - a.setDependencyTrail( getDependencyTrail() ); + for (Artifact a : artifacts) { + if (parents.contains(a.getDependencyConflictId())) { + a.setDependencyTrail(getDependencyTrail()); - throw new CyclicDependencyException( "A dependency has introduced a cycle", a ); + throw new CyclicDependencyException("A dependency has introduced a cycle", a); } - children.add( new ResolutionNode( a, remoteRepositories, this ) ); + children.add(new ResolutionNode(a, remoteRepositories, this)); } - children = Collections.unmodifiableList( children ); - } - else - { + children = Collections.unmodifiableList(children); + } else { children = Collections.emptyList(); } trail = null; @@ -115,49 +102,38 @@ public class ResolutionNode * @return {@link List} < {@link String} > with artifact ids * @throws OverConstrainedVersionException if version specification is over constrained */ - public List getDependencyTrail() - throws OverConstrainedVersionException - { + public List getDependencyTrail() throws OverConstrainedVersionException { List trial = getTrail(); - List ret = new ArrayList<>( trial.size() ); + List ret = new ArrayList<>(trial.size()); - for ( Artifact artifact : trial ) - { - ret.add( artifact.getId() ); + for (Artifact artifact : trial) { + ret.add(artifact.getId()); } return ret; } - private List getTrail() - throws OverConstrainedVersionException - { - if ( trail == null ) - { + private List getTrail() throws OverConstrainedVersionException { + if (trail == null) { List ids = new LinkedList<>(); ResolutionNode node = this; - while ( node != null ) - { + while (node != null) { Artifact artifact = node.getArtifact(); - if ( artifact.getVersion() == null ) - { + if (artifact.getVersion() == null) { // set the recommended version ArtifactVersion selected = artifact.getSelectedVersion(); // MNG-2123: null is a valid response to getSelectedVersion, don't // assume it won't ever be. - if ( selected != null ) - { - artifact.selectVersion( selected.toString() ); - } - else - { - throw new OverConstrainedVersionException( "Unable to get a selected Version for " - + artifact.getArtifactId(), artifact ); + if (selected != null) { + artifact.selectVersion(selected.toString()); + } else { + throw new OverConstrainedVersionException( + "Unable to get a selected Version for " + artifact.getArtifactId(), artifact); } } - ids.add( 0, artifact ); + ids.add(0, artifact); node = node.parent; } trail = ids; @@ -165,8 +141,7 @@ public class ResolutionNode return trail; } - public boolean isResolved() - { + public boolean isResolved() { return children != null; } @@ -175,67 +150,51 @@ public class ResolutionNode * * @return whether the node is direct or transitive dependency */ - public boolean isChildOfRootNode() - { + public boolean isChildOfRootNode() { return parent != null && parent.parent == null; } - public Iterator getChildrenIterator() - { + public Iterator getChildrenIterator() { return children.iterator(); } - public int getDepth() - { + public int getDepth() { return depth; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - public boolean isActive() - { + public boolean isActive() { return active; } - public void enable() - { + public void enable() { active = true; // TODO if it was null, we really need to go find them now... or is this taken care of by the ordering? - if ( children != null ) - { - for ( ResolutionNode node : children ) - { + if (children != null) { + for (ResolutionNode node : children) { node.enable(); } } } - public void disable() - { + public void disable() { active = false; - if ( children != null ) - { - for ( ResolutionNode node : children ) - { + if (children != null) { + for (ResolutionNode node : children) { node.disable(); } } } - public boolean filterTrail( ArtifactFilter filter ) - throws OverConstrainedVersionException - { + public boolean filterTrail(ArtifactFilter filter) throws OverConstrainedVersionException { boolean success = true; - if ( filter != null ) - { - for ( Artifact artifact : getTrail() ) - { - if ( !filter.include( artifact ) ) - { + if (filter != null) { + for (Artifact artifact : getTrail()) { + if (!filter.include(artifact)) { success = false; } } @@ -244,14 +203,11 @@ public class ResolutionNode } @Override - public String toString() - { - return artifact.toString() + " (" + depth + "; " + ( active ? "enabled" : "disabled" ) + ")"; + public String toString() { + return artifact.toString() + " (" + depth + "; " + (active ? "enabled" : "disabled") + ")"; } - public void setArtifact( Artifact artifact ) - { + public void setArtifact(Artifact artifact) { this.artifact = artifact; } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AbstractScopeArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AbstractScopeArtifactFilter.java index 95872dbba0..00407e30df 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AbstractScopeArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AbstractScopeArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import org.apache.maven.artifact.Artifact; @@ -26,9 +25,7 @@ import org.apache.maven.artifact.Artifact; * * @author Brett Porter */ -abstract class AbstractScopeArtifactFilter - implements ArtifactFilter -{ +abstract class AbstractScopeArtifactFilter implements ArtifactFilter { private boolean compileScope; @@ -40,34 +37,24 @@ abstract class AbstractScopeArtifactFilter private boolean systemScope; - void addScopeInternal( String scope ) - { - if ( Artifact.SCOPE_COMPILE.equals( scope ) ) - { + void addScopeInternal(String scope) { + if (Artifact.SCOPE_COMPILE.equals(scope)) { systemScope = true; providedScope = true; compileScope = true; - } - else if ( Artifact.SCOPE_RUNTIME.equals( scope ) ) - { + } else if (Artifact.SCOPE_RUNTIME.equals(scope)) { compileScope = true; runtimeScope = true; - } - else if ( Artifact.SCOPE_COMPILE_PLUS_RUNTIME.equals( scope ) ) - { + } else if (Artifact.SCOPE_COMPILE_PLUS_RUNTIME.equals(scope)) { systemScope = true; providedScope = true; compileScope = true; runtimeScope = true; - } - else if ( Artifact.SCOPE_RUNTIME_PLUS_SYSTEM.equals( scope ) ) - { + } else if (Artifact.SCOPE_RUNTIME_PLUS_SYSTEM.equals(scope)) { systemScope = true; compileScope = true; runtimeScope = true; - } - else if ( Artifact.SCOPE_TEST.equals( scope ) ) - { + } else if (Artifact.SCOPE_TEST.equals(scope)) { systemScope = true; providedScope = true; compileScope = true; @@ -76,32 +63,19 @@ abstract class AbstractScopeArtifactFilter } } - public boolean include( Artifact artifact ) - { - if ( Artifact.SCOPE_COMPILE.equals( artifact.getScope() ) ) - { + public boolean include(Artifact artifact) { + if (Artifact.SCOPE_COMPILE.equals(artifact.getScope())) { return compileScope; - } - else if ( Artifact.SCOPE_RUNTIME.equals( artifact.getScope() ) ) - { + } else if (Artifact.SCOPE_RUNTIME.equals(artifact.getScope())) { return runtimeScope; - } - else if ( Artifact.SCOPE_TEST.equals( artifact.getScope() ) ) - { + } else if (Artifact.SCOPE_TEST.equals(artifact.getScope())) { return testScope; - } - else if ( Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ) ) - { + } else if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) { return providedScope; - } - else if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) - { + } else if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { return systemScope; - } - else - { + } else { return true; } } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilter.java index 669773dd99..c100358dbd 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; /** @@ -32,68 +30,55 @@ import org.apache.maven.artifact.Artifact; * * @author Brett Porter */ -public class AndArtifactFilter - implements ArtifactFilter -{ +public class AndArtifactFilter implements ArtifactFilter { private Set filters; - public AndArtifactFilter() - { + public AndArtifactFilter() { this.filters = new LinkedHashSet<>(); } - public AndArtifactFilter( List filters ) - { - this.filters = new LinkedHashSet<>( filters ); + public AndArtifactFilter(List filters) { + this.filters = new LinkedHashSet<>(filters); } - public boolean include( Artifact artifact ) - { + public boolean include(Artifact artifact) { boolean include = true; - for ( Iterator i = filters.iterator(); i.hasNext() && include; ) - { + for (Iterator i = filters.iterator(); i.hasNext() && include; ) { ArtifactFilter filter = i.next(); - if ( !filter.include( artifact ) ) - { + if (!filter.include(artifact)) { include = false; } } return include; } - public void add( ArtifactFilter artifactFilter ) - { - filters.add( artifactFilter ); + public void add(ArtifactFilter artifactFilter) { + filters.add(artifactFilter); } - public List getFilters() - { - return new ArrayList<>( filters ); + public List getFilters() { + return new ArrayList<>(filters); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + filters.hashCode(); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof AndArtifactFilter ) ) - { + if (!(obj instanceof AndArtifactFilter)) { return false; } AndArtifactFilter other = (AndArtifactFilter) obj; - return filters.equals( other.filters ); + return filters.equals(other.filters); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/CumulativeScopeArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/CumulativeScopeArtifactFilter.java index e92ece2fef..fcb7fc0d5d 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/CumulativeScopeArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/CumulativeScopeArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.Collection; import java.util.HashSet; @@ -32,9 +31,7 @@ import java.util.Set; * @author Brett Porter * @author jdcasey */ -public class CumulativeScopeArtifactFilter - extends AbstractScopeArtifactFilter -{ +public class CumulativeScopeArtifactFilter extends AbstractScopeArtifactFilter { private Set scopes; @@ -43,11 +40,10 @@ public class CumulativeScopeArtifactFilter * * @param scopes The scopes to enable, along with all implied scopes, may be {@code null}. */ - public CumulativeScopeArtifactFilter( Collection scopes ) - { + public CumulativeScopeArtifactFilter(Collection scopes) { this.scopes = new HashSet<>(); - addScopes( scopes ); + addScopes(scopes); } /** @@ -55,45 +51,36 @@ public class CumulativeScopeArtifactFilter * * @param filters The filters to combine, may be {@code null}. */ - public CumulativeScopeArtifactFilter( CumulativeScopeArtifactFilter... filters ) - { + public CumulativeScopeArtifactFilter(CumulativeScopeArtifactFilter... filters) { this.scopes = new HashSet<>(); - if ( filters != null ) - { - for ( CumulativeScopeArtifactFilter filter : filters ) - { - addScopes( filter.getScopes() ); + if (filters != null) { + for (CumulativeScopeArtifactFilter filter : filters) { + addScopes(filter.getScopes()); } } } - private void addScopes( Collection scopes ) - { - if ( scopes != null ) - { - for ( String scope : scopes ) - { - addScope( scope ); + private void addScopes(Collection scopes) { + if (scopes != null) { + for (String scope : scopes) { + addScope(scope); } } } - private void addScope( String scope ) - { - this.scopes.add( scope ); + private void addScope(String scope) { + this.scopes.add(scope); - addScopeInternal( scope ); + addScopeInternal(scope); } - public Set getScopes() - { + public Set getScopes() { return scopes; } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + scopes.hashCode(); @@ -102,21 +89,17 @@ public class CumulativeScopeArtifactFilter } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof CumulativeScopeArtifactFilter ) ) - { + if (!(obj instanceof CumulativeScopeArtifactFilter)) { return false; } CumulativeScopeArtifactFilter that = (CumulativeScopeArtifactFilter) obj; - return scopes.equals( that.scopes ); + return scopes.equals(that.scopes); } - } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExcludesArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExcludesArtifactFilter.java index e448af4dde..a26e837594 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExcludesArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExcludesArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.List; - import org.apache.maven.artifact.Artifact; /** @@ -29,16 +27,12 @@ import org.apache.maven.artifact.Artifact; * @author Brett Porter * TODO I think this is equiv. to exclusion set filter in maven-core */ -public class ExcludesArtifactFilter - extends IncludesArtifactFilter -{ - public ExcludesArtifactFilter( List patterns ) - { - super( patterns ); +public class ExcludesArtifactFilter extends IncludesArtifactFilter { + public ExcludesArtifactFilter(List patterns) { + super(patterns); } - public boolean include( Artifact artifact ) - { - return !super.include( artifact ); + public boolean include(Artifact artifact) { + return !super.include(artifact); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilter.java index 18d4e833a0..6f981ccf4e 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,54 +16,48 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.List; import java.util.function.Predicate; - import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Exclusion; /** * Filter to exclude from a list of artifact patterns. */ -public class ExclusionArtifactFilter implements ArtifactFilter -{ +public class ExclusionArtifactFilter implements ArtifactFilter { private static final String WILDCARD = "*"; private final List exclusions; - public ExclusionArtifactFilter( List exclusions ) - { + public ExclusionArtifactFilter(List exclusions) { this.exclusions = exclusions; } - private Predicate sameArtifactId( Artifact artifact ) - { - return exclusion -> exclusion.getArtifactId().equals( artifact.getArtifactId() ); + private Predicate sameArtifactId(Artifact artifact) { + return exclusion -> exclusion.getArtifactId().equals(artifact.getArtifactId()); } - private Predicate sameGroupId( Artifact artifact ) - { - return exclusion -> exclusion.getGroupId().equals( artifact.getGroupId() ); + private Predicate sameGroupId(Artifact artifact) { + return exclusion -> exclusion.getGroupId().equals(artifact.getGroupId()); } - private Predicate groupIdIsWildcard = exclusion -> WILDCARD.equals( exclusion.getGroupId() ); + private Predicate groupIdIsWildcard = exclusion -> WILDCARD.equals(exclusion.getGroupId()); - private Predicate artifactIdIsWildcard = exclusion -> WILDCARD.equals( exclusion.getArtifactId() ); + private Predicate artifactIdIsWildcard = exclusion -> WILDCARD.equals(exclusion.getArtifactId()); - private Predicate groupIdAndArtifactIdIsWildcard = groupIdIsWildcard.and( artifactIdIsWildcard ); + private Predicate groupIdAndArtifactIdIsWildcard = groupIdIsWildcard.and(artifactIdIsWildcard); - private Predicate exclude( Artifact artifact ) - { + private Predicate exclude(Artifact artifact) { return groupIdAndArtifactIdIsWildcard - .or( groupIdIsWildcard.and( sameArtifactId( artifact ) ) ) - .or( artifactIdIsWildcard.and( sameGroupId( artifact ) ) ) - .or( sameGroupId( artifact ).and( sameArtifactId( artifact ) ) ); + .or(groupIdIsWildcard.and(sameArtifactId(artifact))) + .or(artifactIdIsWildcard.and(sameGroupId(artifact))) + .or(sameGroupId(artifact).and(sameArtifactId(artifact))); } @Override - public boolean include( Artifact artifact ) - { - return !exclusions.stream().anyMatch( exclude( artifact ) ); + public boolean include(Artifact artifact) { + return !exclusions.stream().anyMatch(exclude(artifact)); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionSetFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionSetFilter.java index 57c6177a30..409d1aa3c9 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionSetFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExclusionSetFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,69 +16,58 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; /** * @author Jason van Zyl */ -public class ExclusionSetFilter - implements ArtifactFilter -{ +public class ExclusionSetFilter implements ArtifactFilter { private Set excludes; - public ExclusionSetFilter( String[] excludes ) - { - this.excludes = new LinkedHashSet<>( Arrays.asList( excludes ) ); + public ExclusionSetFilter(String[] excludes) { + this.excludes = new LinkedHashSet<>(Arrays.asList(excludes)); } - public ExclusionSetFilter( Set excludes ) - { + public ExclusionSetFilter(Set excludes) { this.excludes = excludes; } - public boolean include( Artifact artifact ) - { + public boolean include(Artifact artifact) { String id = artifact.getArtifactId(); - if ( excludes.contains( id ) ) - { + if (excludes.contains(id)) { return false; } id = artifact.getGroupId() + ':' + id; - return !excludes.contains( id ); - + return !excludes.contains(id); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + excludes.hashCode(); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof ExclusionSetFilter ) ) - { + if (!(obj instanceof ExclusionSetFilter)) { return false; } ExclusionSetFilter other = (ExclusionSetFilter) obj; - return excludes.equals( other.excludes ); + return excludes.equals(other.excludes); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/IncludesArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/IncludesArtifactFilter.java index 7a3b6c7cbe..978d2113c2 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/IncludesArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/IncludesArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.artifact.Artifact; /** @@ -32,40 +30,32 @@ import org.apache.maven.artifact.Artifact; * * @author Brett Porter */ -public class IncludesArtifactFilter - implements ArtifactFilter -{ +public class IncludesArtifactFilter implements ArtifactFilter { private final Set patterns; - public IncludesArtifactFilter( List patterns ) - { - this.patterns = new LinkedHashSet<>( patterns ); + public IncludesArtifactFilter(List patterns) { + this.patterns = new LinkedHashSet<>(patterns); } - public boolean include( Artifact artifact ) - { + public boolean include(Artifact artifact) { String id = artifact.getGroupId() + ":" + artifact.getArtifactId(); boolean matched = false; - for ( Iterator i = patterns.iterator(); i.hasNext() & !matched; ) - { + for (Iterator i = patterns.iterator(); i.hasNext() & !matched; ) { // TODO what about wildcards? Just specifying groups? versions? - if ( id.equals( i.next() ) ) - { + if (id.equals(i.next())) { matched = true; } } return matched; } - public List getPatterns() - { - return new ArrayList<>( patterns ); + public List getPatterns() { + return new ArrayList<>(patterns); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + patterns.hashCode(); @@ -73,21 +63,18 @@ public class IncludesArtifactFilter } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } // make sure IncludesArtifactFilter is not equal ExcludesArtifactFilter! - if ( obj == null || getClass() != obj.getClass() ) - { + if (obj == null || getClass() != obj.getClass()) { return false; } IncludesArtifactFilter other = (IncludesArtifactFilter) obj; - return patterns.equals( other.patterns ); + return patterns.equals(other.patterns); } } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java index d87ee85e71..090b14b649 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.artifact.resolver.filter; import java.util.Objects; @@ -26,50 +25,41 @@ import java.util.Objects; * * @author Brett Porter */ -public class ScopeArtifactFilter - extends AbstractScopeArtifactFilter -{ +public class ScopeArtifactFilter extends AbstractScopeArtifactFilter { private final String scope; - public ScopeArtifactFilter( String scope ) - { + public ScopeArtifactFilter(String scope) { this.scope = scope; - addScopeInternal( scope ); + addScopeInternal(scope); } - public String getScope() - { + public String getScope() { return scope; } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + ( scope != null ? scope.hashCode() : 0 ); + hash = hash * 31 + (scope != null ? scope.hashCode() : 0); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof ScopeArtifactFilter ) ) - { + if (!(obj instanceof ScopeArtifactFilter)) { return false; } ScopeArtifactFilter other = (ScopeArtifactFilter) obj; - return Objects.equals( scope, other.scope ); + return Objects.equals(scope, other.scope); } - } diff --git a/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java b/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java index 79563822d0..1e326752f8 100644 --- a/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java +++ b/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java @@ -1,5 +1,3 @@ -package org.apache.maven.bridge; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.bridge; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.bridge; import java.io.File; import java.net.MalformedURLException; @@ -30,11 +29,9 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -67,139 +64,116 @@ import org.eclipse.aether.repository.RemoteRepository; /** * @author Jason van Zyl */ -@Named( "default" ) +@Named("default") @Singleton -public class MavenRepositorySystem -{ +public class MavenRepositorySystem { private final ArtifactHandlerManager artifactHandlerManager; private final Map layouts; @Inject - public MavenRepositorySystem( ArtifactHandlerManager artifactHandlerManager, - Map layouts ) - { + public MavenRepositorySystem( + ArtifactHandlerManager artifactHandlerManager, Map layouts) { this.artifactHandlerManager = artifactHandlerManager; this.layouts = layouts; } // DefaultProjectBuilder - public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ) - { - return createArtifactX( groupId, artifactId, version, scope, type ); + public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) { + return createArtifactX(groupId, artifactId, version, scope, type); } // DefaultProjectBuilder - public Artifact createProjectArtifact( String groupId, String artifactId, String metaVersionId ) - { - return createProjectArtifactX( groupId, artifactId, metaVersionId ); + public Artifact createProjectArtifact(String groupId, String artifactId, String metaVersionId) { + return createProjectArtifactX(groupId, artifactId, metaVersionId); } // DefaultProjectBuilder - public Artifact createDependencyArtifact( Dependency d ) - { - if ( d.getVersion() == null ) - { + public Artifact createDependencyArtifact(Dependency d) { + if (d.getVersion() == null) { return null; } VersionRange versionRange; - try - { - versionRange = VersionRange.createFromVersionSpec( d.getVersion() ); - } - catch ( InvalidVersionSpecificationException e ) - { + try { + versionRange = VersionRange.createFromVersionSpec(d.getVersion()); + } catch (InvalidVersionSpecificationException e) { return null; } - Artifact artifact = - createDependencyArtifactX( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), - d.getClassifier(), d.getScope(), d.isOptional() ); + Artifact artifact = createDependencyArtifactX( + d.getGroupId(), + d.getArtifactId(), + versionRange, + d.getType(), + d.getClassifier(), + d.getScope(), + d.isOptional()); - if ( Artifact.SCOPE_SYSTEM.equals( d.getScope() ) && d.getSystemPath() != null ) - { - artifact.setFile( new File( d.getSystemPath() ) ); + if (Artifact.SCOPE_SYSTEM.equals(d.getScope()) && d.getSystemPath() != null) { + artifact.setFile(new File(d.getSystemPath())); } - if ( !d.getExclusions().isEmpty() ) - { - artifact.setDependencyFilter( new ExclusionArtifactFilter( d.getExclusions() ) ); + if (!d.getExclusions().isEmpty()) { + artifact.setDependencyFilter(new ExclusionArtifactFilter(d.getExclusions())); } return artifact; } // DefaultProjectBuilder - public Artifact createExtensionArtifact( String groupId, String artifactId, String version ) - { + public Artifact createExtensionArtifact(String groupId, String artifactId, String version) { VersionRange versionRange; - try - { - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { + try { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { return null; } - return createExtensionArtifactX( groupId, artifactId, versionRange ); + return createExtensionArtifactX(groupId, artifactId, versionRange); } // DefaultProjectBuilder - public Artifact createParentArtifact( String groupId, String artifactId, String version ) - { - return createParentArtifactX( groupId, artifactId, version ); + public Artifact createParentArtifact(String groupId, String artifactId, String version) { + return createParentArtifactX(groupId, artifactId, version); } // DefaultProjectBuilder - public Artifact createPluginArtifact( Plugin plugin ) - { + public Artifact createPluginArtifact(Plugin plugin) { VersionRange versionRange; - try - { + try { String version = plugin.getVersion(); - if ( StringUtils.isEmpty( version ) ) - { + if (StringUtils.isEmpty(version)) { version = "RELEASE"; } - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { return null; } - return createPluginArtifactX( plugin.getGroupId(), plugin.getArtifactId(), versionRange ); + return createPluginArtifactX(plugin.getGroupId(), plugin.getArtifactId(), versionRange); } - public void injectMirror( List repositories, List mirrors ) - { - if ( repositories != null && mirrors != null ) - { - for ( ArtifactRepository repository : repositories ) - { - Mirror mirror = getMirror( repository, mirrors ); - injectMirror( repository, mirror ); + public void injectMirror(List repositories, List mirrors) { + if (repositories != null && mirrors != null) { + for (ArtifactRepository repository : repositories) { + Mirror mirror = getMirror(repository, mirrors); + injectMirror(repository, mirror); } } } - private Mirror getMirror( RepositorySystemSession session, ArtifactRepository repository ) - { - if ( session != null ) - { + private Mirror getMirror(RepositorySystemSession session, ArtifactRepository repository) { + if (session != null) { org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector(); - if ( selector != null ) - { - RemoteRepository repo = selector.getMirror( RepositoryUtils.toRepo( repository ) ); - if ( repo != null ) - { + if (selector != null) { + RemoteRepository repo = selector.getMirror(RepositoryUtils.toRepo(repository)); + if (repo != null) { Mirror mirror = new Mirror(); - mirror.setId( repo.getId() ); - mirror.setUrl( repo.getUrl() ); - mirror.setLayout( repo.getContentType() ); - mirror.setBlocked( repo.isBlocked() ); + mirror.setId(repo.getId()); + mirror.setUrl(repo.getUrl()); + mirror.setLayout(repo.getContentType()); + mirror.setBlocked(repo.isBlocked()); return mirror; } } @@ -207,58 +181,52 @@ public class MavenRepositorySystem return null; } - public void injectMirror( RepositorySystemSession session, List repositories ) - { - if ( repositories != null && session != null ) - { - for ( ArtifactRepository repository : repositories ) - { - Mirror mirror = getMirror( session, repository ); - injectMirror( repository, mirror ); + public void injectMirror(RepositorySystemSession session, List repositories) { + if (repositories != null && session != null) { + for (ArtifactRepository repository : repositories) { + Mirror mirror = getMirror(session, repository); + injectMirror(repository, mirror); } } } - private void injectMirror( ArtifactRepository repository, Mirror mirror ) - { - if ( mirror != null ) - { - ArtifactRepository original = - createArtifactRepository( repository.getId(), repository.getUrl(), repository.getLayout(), - repository.getSnapshots(), repository.getReleases() ); + private void injectMirror(ArtifactRepository repository, Mirror mirror) { + if (mirror != null) { + ArtifactRepository original = createArtifactRepository( + repository.getId(), + repository.getUrl(), + repository.getLayout(), + repository.getSnapshots(), + repository.getReleases()); - repository.setMirroredRepositories( Collections.singletonList( original ) ); + repository.setMirroredRepositories(Collections.singletonList(original)); - repository.setId( mirror.getId() ); - repository.setUrl( mirror.getUrl() ); + repository.setId(mirror.getId()); + repository.setUrl(mirror.getUrl()); - if ( StringUtils.isNotEmpty( mirror.getLayout() ) ) - { - repository.setLayout( getLayout( mirror.getLayout() ) ); + if (StringUtils.isNotEmpty(mirror.getLayout())) { + repository.setLayout(getLayout(mirror.getLayout())); } - repository.setBlocked( mirror.isBlocked() ); + repository.setBlocked(mirror.isBlocked()); } } - private Authentication getAuthentication( RepositorySystemSession session, ArtifactRepository repository ) - { - if ( session != null ) - { + private Authentication getAuthentication(RepositorySystemSession session, ArtifactRepository repository) { + if (session != null) { AuthenticationSelector selector = session.getAuthenticationSelector(); - if ( selector != null ) - { - RemoteRepository repo = RepositoryUtils.toRepo( repository ); - org.eclipse.aether.repository.Authentication auth = selector.getAuthentication( repo ); - if ( auth != null ) - { - repo = new RemoteRepository.Builder( repo ).setAuthentication( auth ).build(); - AuthenticationContext authCtx = AuthenticationContext.forRepository( session, repo ); - Authentication result = - new Authentication( authCtx.get( AuthenticationContext.USERNAME ), - authCtx.get( AuthenticationContext.PASSWORD ) ); - result.setPrivateKey( authCtx.get( AuthenticationContext.PRIVATE_KEY_PATH ) ); - result.setPassphrase( authCtx.get( AuthenticationContext.PRIVATE_KEY_PASSPHRASE ) ); + if (selector != null) { + RemoteRepository repo = RepositoryUtils.toRepo(repository); + org.eclipse.aether.repository.Authentication auth = selector.getAuthentication(repo); + if (auth != null) { + repo = new RemoteRepository.Builder(repo) + .setAuthentication(auth) + .build(); + AuthenticationContext authCtx = AuthenticationContext.forRepository(session, repo); + Authentication result = new Authentication( + authCtx.get(AuthenticationContext.USERNAME), authCtx.get(AuthenticationContext.PASSWORD)); + result.setPrivateKey(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH)); + result.setPassphrase(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE)); authCtx.close(); return result; } @@ -267,40 +235,34 @@ public class MavenRepositorySystem return null; } - public void injectAuthentication( RepositorySystemSession session, List repositories ) - { - if ( repositories != null && session != null ) - { - for ( ArtifactRepository repository : repositories ) - { - repository.setAuthentication( getAuthentication( session, repository ) ); + public void injectAuthentication(RepositorySystemSession session, List repositories) { + if (repositories != null && session != null) { + for (ArtifactRepository repository : repositories) { + repository.setAuthentication(getAuthentication(session, repository)); } } } - private Proxy getProxy( RepositorySystemSession session, ArtifactRepository repository ) - { - if ( session != null ) - { + private Proxy getProxy(RepositorySystemSession session, ArtifactRepository repository) { + if (session != null) { ProxySelector selector = session.getProxySelector(); - if ( selector != null ) - { - RemoteRepository repo = RepositoryUtils.toRepo( repository ); - org.eclipse.aether.repository.Proxy proxy = selector.getProxy( repo ); - if ( proxy != null ) - { + if (selector != null) { + RemoteRepository repo = RepositoryUtils.toRepo(repository); + org.eclipse.aether.repository.Proxy proxy = selector.getProxy(repo); + if (proxy != null) { Proxy p = new Proxy(); - p.setHost( proxy.getHost() ); - p.setProtocol( proxy.getType() ); - p.setPort( proxy.getPort() ); - if ( proxy.getAuthentication() != null ) - { - repo = new RemoteRepository.Builder( repo ).setProxy( proxy ).build(); - AuthenticationContext authCtx = AuthenticationContext.forProxy( session, repo ); - p.setUserName( authCtx.get( AuthenticationContext.USERNAME ) ); - p.setPassword( authCtx.get( AuthenticationContext.PASSWORD ) ); - p.setNtlmDomain( authCtx.get( AuthenticationContext.NTLM_DOMAIN ) ); - p.setNtlmHost( authCtx.get( AuthenticationContext.NTLM_WORKSTATION ) ); + p.setHost(proxy.getHost()); + p.setProtocol(proxy.getType()); + p.setPort(proxy.getPort()); + if (proxy.getAuthentication() != null) { + repo = new RemoteRepository.Builder(repo) + .setProxy(proxy) + .build(); + AuthenticationContext authCtx = AuthenticationContext.forProxy(session, repo); + p.setUserName(authCtx.get(AuthenticationContext.USERNAME)); + p.setPassword(authCtx.get(AuthenticationContext.PASSWORD)); + p.setNtlmDomain(authCtx.get(AuthenticationContext.NTLM_DOMAIN)); + p.setNtlmHost(authCtx.get(AuthenticationContext.NTLM_WORKSTATION)); authCtx.close(); } return p; @@ -310,301 +272,286 @@ public class MavenRepositorySystem return null; } - public void injectProxy( RepositorySystemSession session, List repositories ) - { - if ( repositories != null && session != null ) - { - for ( ArtifactRepository repository : repositories ) - { - repository.setProxy( getProxy( session, repository ) ); + public void injectProxy(RepositorySystemSession session, List repositories) { + if (repositories != null && session != null) { + for (ArtifactRepository repository : repositories) { + repository.setProxy(getProxy(session, repository)); } } } - private ArtifactRepositoryLayout getLayout( String id ) - { - return layouts.get( id ); + private ArtifactRepositoryLayout getLayout(String id) { + return layouts.get(id); } - // // Taken from LegacyRepositorySystem // - public static org.apache.maven.model.Repository fromSettingsRepository( org.apache.maven.settings.Repository - settingsRepository ) - { + public static org.apache.maven.model.Repository fromSettingsRepository( + org.apache.maven.settings.Repository settingsRepository) { org.apache.maven.model.Repository modelRepository = new org.apache.maven.model.Repository(); - modelRepository.setId( settingsRepository.getId() ); - modelRepository.setLayout( settingsRepository.getLayout() ); - modelRepository.setName( settingsRepository.getName() ); - modelRepository.setUrl( settingsRepository.getUrl() ); - modelRepository.setReleases( fromSettingsRepositoryPolicy( settingsRepository.getReleases() ) ); - modelRepository.setSnapshots( fromSettingsRepositoryPolicy( settingsRepository.getSnapshots() ) ); + modelRepository.setId(settingsRepository.getId()); + modelRepository.setLayout(settingsRepository.getLayout()); + modelRepository.setName(settingsRepository.getName()); + modelRepository.setUrl(settingsRepository.getUrl()); + modelRepository.setReleases(fromSettingsRepositoryPolicy(settingsRepository.getReleases())); + modelRepository.setSnapshots(fromSettingsRepositoryPolicy(settingsRepository.getSnapshots())); return modelRepository; } public static org.apache.maven.model.RepositoryPolicy fromSettingsRepositoryPolicy( - org.apache.maven.settings.RepositoryPolicy settingsRepositoryPolicy ) - { + org.apache.maven.settings.RepositoryPolicy settingsRepositoryPolicy) { org.apache.maven.model.RepositoryPolicy modelRepositoryPolicy = new org.apache.maven.model.RepositoryPolicy(); - if ( settingsRepositoryPolicy != null ) - { - modelRepositoryPolicy.setEnabled( settingsRepositoryPolicy.isEnabled() ); - modelRepositoryPolicy.setUpdatePolicy( settingsRepositoryPolicy.getUpdatePolicy() ); - modelRepositoryPolicy.setChecksumPolicy( settingsRepositoryPolicy.getChecksumPolicy() ); + if (settingsRepositoryPolicy != null) { + modelRepositoryPolicy.setEnabled(settingsRepositoryPolicy.isEnabled()); + modelRepositoryPolicy.setUpdatePolicy(settingsRepositoryPolicy.getUpdatePolicy()); + modelRepositoryPolicy.setChecksumPolicy(settingsRepositoryPolicy.getChecksumPolicy()); } return modelRepositoryPolicy; } - public static ArtifactRepository buildArtifactRepository( org.apache.maven.settings.Repository repo ) - throws InvalidRepositoryException - { - return buildArtifactRepository( fromSettingsRepository( repo ) ); + public static ArtifactRepository buildArtifactRepository(org.apache.maven.settings.Repository repo) + throws InvalidRepositoryException { + return buildArtifactRepository(fromSettingsRepository(repo)); } - public static ArtifactRepository buildArtifactRepository( org.apache.maven.model.Repository repo ) - throws InvalidRepositoryException - { - if ( repo != null ) - { + public static ArtifactRepository buildArtifactRepository(org.apache.maven.model.Repository repo) + throws InvalidRepositoryException { + if (repo != null) { String id = repo.getId(); - if ( StringUtils.isEmpty( id ) ) - { - throw new InvalidRepositoryException( "Repository identifier missing", "" ); + if (StringUtils.isEmpty(id)) { + throw new InvalidRepositoryException("Repository identifier missing", ""); } String url = repo.getUrl(); - if ( StringUtils.isEmpty( url ) ) - { - throw new InvalidRepositoryException( "URL missing for repository " + id, id ); + if (StringUtils.isEmpty(url)) { + throw new InvalidRepositoryException("URL missing for repository " + id, id); } - ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy( repo.getSnapshots() ); + ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy(repo.getSnapshots()); - ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy( repo.getReleases() ); + ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy(repo.getReleases()); ArtifactRepositoryLayout layout = new DefaultRepositoryLayout(); - return createArtifactRepository( id, url, layout, snapshots, releases ); - } - else - { + return createArtifactRepository(id, url, layout, snapshots, releases); + } else { return null; } } - public static ArtifactRepositoryPolicy buildArtifactRepositoryPolicy( org.apache.maven.model.RepositoryPolicy - policy ) - { + public static ArtifactRepositoryPolicy buildArtifactRepositoryPolicy( + org.apache.maven.model.RepositoryPolicy policy) { boolean enabled = true; String updatePolicy = null; String checksumPolicy = null; - if ( policy != null ) - { + if (policy != null) { enabled = policy.isEnabled(); - if ( policy.getUpdatePolicy() != null ) - { + if (policy.getUpdatePolicy() != null) { updatePolicy = policy.getUpdatePolicy(); } - if ( policy.getChecksumPolicy() != null ) - { + if (policy.getChecksumPolicy() != null) { checksumPolicy = policy.getChecksumPolicy(); } } - return new ArtifactRepositoryPolicy( enabled, updatePolicy, checksumPolicy ); + return new ArtifactRepositoryPolicy(enabled, updatePolicy, checksumPolicy); } - public ArtifactRepository createArtifactRepository( String id, String url, String layoutId, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - throws Exception - { - ArtifactRepositoryLayout layout = layouts.get( layoutId ); + public ArtifactRepository createArtifactRepository( + String id, + String url, + String layoutId, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) + throws Exception { + ArtifactRepositoryLayout layout = layouts.get(layoutId); - checkLayout( id, layoutId, layout ); + checkLayout(id, layoutId, layout); - return createArtifactRepository( id, url, layout, snapshots, releases ); + return createArtifactRepository(id, url, layout, snapshots, releases); } - private void checkLayout( String repositoryId, String layoutId, ArtifactRepositoryLayout layout ) - throws Exception - { - if ( layout == null ) - { - throw new Exception( String.format( "Cannot find ArtifactRepositoryLayout instance for: %s %s", layoutId, - repositoryId ) ); + private void checkLayout(String repositoryId, String layoutId, ArtifactRepositoryLayout layout) throws Exception { + if (layout == null) { + throw new Exception( + String.format("Cannot find ArtifactRepositoryLayout instance for: %s %s", layoutId, repositoryId)); } } - public static ArtifactRepository createArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - { - if ( snapshots == null ) - { + public static ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + if (snapshots == null) { snapshots = new ArtifactRepositoryPolicy(); } - if ( releases == null ) - { + if (releases == null) { releases = new ArtifactRepositoryPolicy(); } ArtifactRepository repository; - if ( repositoryLayout instanceof ArtifactRepositoryLayout2 ) - { - repository = - ( (ArtifactRepositoryLayout2) repositoryLayout ).newMavenArtifactRepository( id, url, snapshots, - releases ); - } - else - { - repository = new MavenArtifactRepository( id, url, repositoryLayout, snapshots, releases ); + if (repositoryLayout instanceof ArtifactRepositoryLayout2) { + repository = ((ArtifactRepositoryLayout2) repositoryLayout) + .newMavenArtifactRepository(id, url, snapshots, releases); + } else { + repository = new MavenArtifactRepository(id, url, repositoryLayout, snapshots, releases); } return repository; } // ArtifactFactory - private Artifact createArtifactX( String groupId, String artifactId, String version, String scope, String type ) - { - return createArtifactX( groupId, artifactId, version, scope, type, null, null ); + private Artifact createArtifactX(String groupId, String artifactId, String version, String scope, String type) { + return createArtifactX(groupId, artifactId, version, scope, type, null, null); } - private Artifact createDependencyArtifactX( String groupId, String artifactId, VersionRange versionRange, - String type, String classifier, String scope, boolean optional ) - { - return createArtifactX( groupId, artifactId, versionRange, type, classifier, scope, null, optional ); + private Artifact createDependencyArtifactX( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + boolean optional) { + return createArtifactX(groupId, artifactId, versionRange, type, classifier, scope, null, optional); } - private Artifact createProjectArtifactX( String groupId, String artifactId, String version ) - { - return createProjectArtifactX( groupId, artifactId, version, null ); + private Artifact createProjectArtifactX(String groupId, String artifactId, String version) { + return createProjectArtifactX(groupId, artifactId, version, null); } - private Artifact createParentArtifactX( String groupId, String artifactId, String version ) - { - return createProjectArtifactX( groupId, artifactId, version ); + private Artifact createParentArtifactX(String groupId, String artifactId, String version) { + return createProjectArtifactX(groupId, artifactId, version); } - private Artifact createPluginArtifactX( String groupId, String artifactId, VersionRange versionRange ) - { - return createArtifactX( groupId, artifactId, versionRange, "maven-plugin", null, Artifact.SCOPE_RUNTIME, null ); + private Artifact createPluginArtifactX(String groupId, String artifactId, VersionRange versionRange) { + return createArtifactX(groupId, artifactId, versionRange, "maven-plugin", null, Artifact.SCOPE_RUNTIME, null); } - private Artifact createProjectArtifactX( String groupId, String artifactId, String version, String scope ) - { - return createArtifactX( groupId, artifactId, version, scope, "pom" ); + private Artifact createProjectArtifactX(String groupId, String artifactId, String version, String scope) { + return createArtifactX(groupId, artifactId, version, scope, "pom"); } - private Artifact createExtensionArtifactX( String groupId, String artifactId, VersionRange versionRange ) - { - return createArtifactX( groupId, artifactId, versionRange, "jar", null, Artifact.SCOPE_RUNTIME, null ); + private Artifact createExtensionArtifactX(String groupId, String artifactId, VersionRange versionRange) { + return createArtifactX(groupId, artifactId, versionRange, "jar", null, Artifact.SCOPE_RUNTIME, null); } - private Artifact createArtifactX( String groupId, String artifactId, String version, String scope, String type, - String classifier, String inheritedScope ) - { + private Artifact createArtifactX( + String groupId, + String artifactId, + String version, + String scope, + String type, + String classifier, + String inheritedScope) { VersionRange versionRange = null; - if ( version != null ) - { - versionRange = VersionRange.createFromVersion( version ); + if (version != null) { + versionRange = VersionRange.createFromVersion(version); } - return createArtifactX( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope ); + return createArtifactX(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope); } - private Artifact createArtifactX( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, String inheritedScope ) - { - return createArtifactX( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, false ); + private Artifact createArtifactX( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope) { + return createArtifactX(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, false); } - @SuppressWarnings( "checkstyle:parameternumber" ) - private Artifact createArtifactX( String groupId, String artifactId, VersionRange versionRange, String type, - String classifier, String scope, String inheritedScope, boolean optional ) - { + @SuppressWarnings("checkstyle:parameternumber") + private Artifact createArtifactX( + String groupId, + String artifactId, + VersionRange versionRange, + String type, + String classifier, + String scope, + String inheritedScope, + boolean optional) { String desiredScope = Artifact.SCOPE_RUNTIME; - if ( inheritedScope == null ) - { + if (inheritedScope == null) { desiredScope = scope; - } - else if ( Artifact.SCOPE_TEST.equals( scope ) || Artifact.SCOPE_PROVIDED.equals( scope ) ) - { + } else if (Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_PROVIDED.equals(scope)) { return null; - } - else if ( Artifact.SCOPE_COMPILE.equals( scope ) && Artifact.SCOPE_COMPILE.equals( inheritedScope ) ) - { + } else if (Artifact.SCOPE_COMPILE.equals(scope) && Artifact.SCOPE_COMPILE.equals(inheritedScope)) { // added to retain compile artifactScope. Remove if you want compile inherited as runtime desiredScope = Artifact.SCOPE_COMPILE; } - if ( Artifact.SCOPE_TEST.equals( inheritedScope ) ) - { + if (Artifact.SCOPE_TEST.equals(inheritedScope)) { desiredScope = Artifact.SCOPE_TEST; } - if ( Artifact.SCOPE_PROVIDED.equals( inheritedScope ) ) - { + if (Artifact.SCOPE_PROVIDED.equals(inheritedScope)) { desiredScope = Artifact.SCOPE_PROVIDED; } - if ( Artifact.SCOPE_SYSTEM.equals( scope ) ) - { + if (Artifact.SCOPE_SYSTEM.equals(scope)) { // system scopes come through unchanged... desiredScope = Artifact.SCOPE_SYSTEM; } - ArtifactHandler handler = artifactHandlerManager.getArtifactHandler( type ); + ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type); - return new DefaultArtifact( groupId, artifactId, versionRange, desiredScope, type, classifier, handler, - optional ); + return new DefaultArtifact( + groupId, artifactId, versionRange, desiredScope, type, classifier, handler, optional); } // // Code taken from LegacyRepositorySystem // - public ArtifactRepository createDefaultRemoteRepository( MavenExecutionRequest request ) - throws Exception - { - return createRepository( RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID, - true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, false, - ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, - ArtifactRepositoryPolicy.DEFAULT_CHECKSUM_POLICY ); + public ArtifactRepository createDefaultRemoteRepository(MavenExecutionRequest request) throws Exception { + return createRepository( + RepositorySystem.DEFAULT_REMOTE_REPO_URL, + RepositorySystem.DEFAULT_REMOTE_REPO_ID, + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, + false, + ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, + ArtifactRepositoryPolicy.DEFAULT_CHECKSUM_POLICY); } - public ArtifactRepository createRepository( String url, String repositoryId, boolean releases, - String releaseUpdates, boolean snapshots, String snapshotUpdates, - String checksumPolicy ) throws Exception - { + public ArtifactRepository createRepository( + String url, + String repositoryId, + boolean releases, + String releaseUpdates, + boolean snapshots, + String snapshotUpdates, + String checksumPolicy) + throws Exception { ArtifactRepositoryPolicy snapshotsPolicy = - new ArtifactRepositoryPolicy( snapshots, snapshotUpdates, checksumPolicy ); + new ArtifactRepositoryPolicy(snapshots, snapshotUpdates, checksumPolicy); ArtifactRepositoryPolicy releasesPolicy = - new ArtifactRepositoryPolicy( releases, releaseUpdates, checksumPolicy ); + new ArtifactRepositoryPolicy(releases, releaseUpdates, checksumPolicy); - return createArtifactRepository( repositoryId, url, "default", snapshotsPolicy, releasesPolicy ); + return createArtifactRepository(repositoryId, url, "default", snapshotsPolicy, releasesPolicy); } - public Set getRepoIds( List repositories ) - { + public Set getRepoIds(List repositories) { Set repoIds = new HashSet<>(); - if ( repositories != null ) - { - for ( ArtifactRepository repository : repositories ) - { - repoIds.add( repository.getId() ); + if (repositories != null) { + for (ArtifactRepository repository : repositories) { + repoIds.add(repository.getId()); } } @@ -618,98 +565,86 @@ public class MavenRepositorySystem * @return corresponding effective repositories * @since 3.6.1 */ - public List getEffectiveRepositories( List repositories ) - { - if ( repositories == null ) - { + public List getEffectiveRepositories(List repositories) { + if (repositories == null) { return null; } Map> reposByKey = new LinkedHashMap<>(); - for ( ArtifactRepository repository : repositories ) - { + for (ArtifactRepository repository : repositories) { String key = repository.getId(); - List aliasedRepos = reposByKey.computeIfAbsent( key, k -> new ArrayList<>() ); + List aliasedRepos = reposByKey.computeIfAbsent(key, k -> new ArrayList<>()); - aliasedRepos.add( repository ); + aliasedRepos.add(repository); } List effectiveRepositories = new ArrayList<>(); - for ( List aliasedRepos : reposByKey.values() ) - { + for (List aliasedRepos : reposByKey.values()) { List mirroredRepos = new ArrayList<>(); - List releasePolicies = - new ArrayList<>( aliasedRepos.size() ); + List releasePolicies = new ArrayList<>(aliasedRepos.size()); - for ( ArtifactRepository aliasedRepo : aliasedRepos ) - { - releasePolicies.add( aliasedRepo.getReleases() ); - mirroredRepos.addAll( aliasedRepo.getMirroredRepositories() ); + for (ArtifactRepository aliasedRepo : aliasedRepos) { + releasePolicies.add(aliasedRepo.getReleases()); + mirroredRepos.addAll(aliasedRepo.getMirroredRepositories()); } - ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy( releasePolicies ); + ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy(releasePolicies); - List snapshotPolicies = - new ArrayList<>( aliasedRepos.size() ); + List snapshotPolicies = new ArrayList<>(aliasedRepos.size()); - for ( ArtifactRepository aliasedRepo : aliasedRepos ) - { - snapshotPolicies.add( aliasedRepo.getSnapshots() ); + for (ArtifactRepository aliasedRepo : aliasedRepos) { + snapshotPolicies.add(aliasedRepo.getSnapshots()); } - ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy( snapshotPolicies ); + ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy(snapshotPolicies); - ArtifactRepository aliasedRepo = aliasedRepos.get( 0 ); + ArtifactRepository aliasedRepo = aliasedRepos.get(0); - ArtifactRepository effectiveRepository = - createArtifactRepository( aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), - snapshotPolicy, releasePolicy ); + ArtifactRepository effectiveRepository = createArtifactRepository( + aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), snapshotPolicy, releasePolicy); - effectiveRepository.setAuthentication( aliasedRepo.getAuthentication() ); + effectiveRepository.setAuthentication(aliasedRepo.getAuthentication()); - effectiveRepository.setProxy( aliasedRepo.getProxy() ); + effectiveRepository.setProxy(aliasedRepo.getProxy()); - effectiveRepository.setMirroredRepositories( mirroredRepos ); + effectiveRepository.setMirroredRepositories(mirroredRepos); - effectiveRepository.setBlocked( aliasedRepo.isBlocked() ); + effectiveRepository.setBlocked(aliasedRepo.isBlocked()); - effectiveRepositories.add( effectiveRepository ); + effectiveRepositories.add(effectiveRepository); } return effectiveRepositories; } - private ArtifactRepositoryPolicy getEffectivePolicy( Collection policies ) - { + private ArtifactRepositoryPolicy getEffectivePolicy(Collection policies) { ArtifactRepositoryPolicy effectivePolicy = null; - for ( ArtifactRepositoryPolicy policy : policies ) - { - if ( effectivePolicy == null ) - { - effectivePolicy = new ArtifactRepositoryPolicy( policy ); - } - else - { - effectivePolicy.merge( policy ); + for (ArtifactRepositoryPolicy policy : policies) { + if (effectivePolicy == null) { + effectivePolicy = new ArtifactRepositoryPolicy(policy); + } else { + effectivePolicy.merge(policy); } } return effectivePolicy; } - public ArtifactRepository createLocalRepository( MavenExecutionRequest request, File localRepository ) - throws Exception - { - return createRepository( "file://" + localRepository.toURI().getRawPath(), - RepositorySystem.DEFAULT_LOCAL_REPO_ID, true, - ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, true, - ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, - ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE ); + public ArtifactRepository createLocalRepository(MavenExecutionRequest request, File localRepository) + throws Exception { + return createRepository( + "file://" + localRepository.toURI().getRawPath(), + RepositorySystem.DEFAULT_LOCAL_REPO_ID, + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, + true, + ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, + ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE); } private static final String WILDCARD = "*"; @@ -718,24 +653,18 @@ public class MavenRepositorySystem private static final String EXTERNAL_HTTP_WILDCARD = "external:http:*"; - public static Mirror getMirror( ArtifactRepository repository, List mirrors ) - { + public static Mirror getMirror(ArtifactRepository repository, List mirrors) { String repoId = repository.getId(); - if ( repoId != null && mirrors != null ) - { - for ( Mirror mirror : mirrors ) - { - if ( repoId.equals( mirror.getMirrorOf() ) && matchesLayout( repository, mirror ) ) - { + if (repoId != null && mirrors != null) { + for (Mirror mirror : mirrors) { + if (repoId.equals(mirror.getMirrorOf()) && matchesLayout(repository, mirror)) { return mirror; } } - for ( Mirror mirror : mirrors ) - { - if ( matchPattern( repository, mirror.getMirrorOf() ) && matchesLayout( repository, mirror ) ) - { + for (Mirror mirror : mirrors) { + if (matchPattern(repository, mirror.getMirrorOf()) && matchesLayout(repository, mirror)) { return mirror; } } @@ -758,52 +687,40 @@ public class MavenRepositorySystem * @param pattern used for match. * @return true if the repository is a match to this pattern. */ - static boolean matchPattern( ArtifactRepository originalRepository, String pattern ) - { + static boolean matchPattern(ArtifactRepository originalRepository, String pattern) { boolean result = false; String originalId = originalRepository.getId(); // simple checks first to short circuit processing below. - if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) ) - { + if (WILDCARD.equals(pattern) || pattern.equals(originalId)) { result = true; - } - else - { + } else { // process the list - String[] repos = pattern.split( "," ); - for ( String repo : repos ) - { + String[] repos = pattern.split(","); + for (String repo : repos) { // see if this is a negative match - if ( repo.length() > 1 && repo.startsWith( "!" ) ) - { - if ( repo.substring( 1 ).equals( originalId ) ) - { + if (repo.length() > 1 && repo.startsWith("!")) { + if (repo.substring(1).equals(originalId)) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match - else if ( repo.equals( originalId ) ) - { + else if (repo.equals(originalId)) { result = true; break; } // check for external:* - else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( originalRepository ) ) - { + else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } // check for external:http:* - else if ( EXTERNAL_HTTP_WILDCARD.equals( repo ) && isExternalHttpRepo( originalRepository ) ) - { + else if (EXTERNAL_HTTP_WILDCARD.equals(repo) && isExternalHttpRepo(originalRepository)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo - } - else if ( WILDCARD.equals( repo ) ) - { + } else if (WILDCARD.equals(repo)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } @@ -818,23 +735,18 @@ public class MavenRepositorySystem * @param originalRepository * @return true if external. */ - static boolean isExternalRepo( ArtifactRepository originalRepository ) - { - try - { - URL url = new URL( originalRepository.getUrl() ); - return !( isLocal( url.getHost() ) || url.getProtocol().equals( "file" ) ); - } - catch ( MalformedURLException e ) - { + static boolean isExternalRepo(ArtifactRepository originalRepository) { + try { + URL url = new URL(originalRepository.getUrl()); + return !(isLocal(url.getHost()) || url.getProtocol().equals("file")); + } catch (MalformedURLException e) { // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it return false; } } - private static boolean isLocal( String host ) - { - return "localhost".equals( host ) || "127.0.0.1".equals( host ); + private static boolean isLocal(String host) { + return "localhost".equals(host) || "127.0.0.1".equals(host); } /** @@ -843,25 +755,22 @@ public class MavenRepositorySystem * @param originalRepository * @return true if external. */ - static boolean isExternalHttpRepo( ArtifactRepository originalRepository ) - { - try - { - URL url = new URL( originalRepository.getUrl() ); - return ( "http".equalsIgnoreCase( url.getProtocol() ) || "dav".equalsIgnoreCase( url.getProtocol() ) - || "dav:http".equalsIgnoreCase( url.getProtocol() ) - || "dav+http".equalsIgnoreCase( url.getProtocol() ) ) && !isLocal( url.getHost() ); - } - catch ( MalformedURLException e ) - { + static boolean isExternalHttpRepo(ArtifactRepository originalRepository) { + try { + URL url = new URL(originalRepository.getUrl()); + return ("http".equalsIgnoreCase(url.getProtocol()) + || "dav".equalsIgnoreCase(url.getProtocol()) + || "dav:http".equalsIgnoreCase(url.getProtocol()) + || "dav+http".equalsIgnoreCase(url.getProtocol())) + && !isLocal(url.getHost()); + } catch (MalformedURLException e) { // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it return false; } } - static boolean matchesLayout( ArtifactRepository repository, Mirror mirror ) - { - return matchesLayout( RepositoryUtils.getLayout( repository ), mirror.getMirrorOfLayouts() ); + static boolean matchesLayout(ArtifactRepository repository, Mirror mirror) { + return matchesLayout(RepositoryUtils.getLayout(repository), mirror.getMirrorOfLayouts()); } /** @@ -872,43 +781,31 @@ public class MavenRepositorySystem * @return {@code true} if the layouts associated with the mirror match the layout of the original repository, * {@code false} otherwise. */ - static boolean matchesLayout( String repoLayout, String mirrorLayout ) - { + static boolean matchesLayout(String repoLayout, String mirrorLayout) { boolean result = false; // simple checks first to short circuit processing below. - if ( StringUtils.isEmpty( mirrorLayout ) || WILDCARD.equals( mirrorLayout ) ) - { + if (StringUtils.isEmpty(mirrorLayout) || WILDCARD.equals(mirrorLayout)) { result = true; - } - else if ( mirrorLayout.equals( repoLayout ) ) - { + } else if (mirrorLayout.equals(repoLayout)) { result = true; - } - else - { + } else { // process the list - String[] layouts = mirrorLayout.split( "," ); - for ( String layout : layouts ) - { + String[] layouts = mirrorLayout.split(","); + for (String layout : layouts) { // see if this is a negative match - if ( layout.length() > 1 && layout.startsWith( "!" ) ) - { - if ( layout.substring( 1 ).equals( repoLayout ) ) - { + if (layout.length() > 1 && layout.startsWith("!")) { + if (layout.substring(1).equals(repoLayout)) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match - else if ( layout.equals( repoLayout ) ) - { + else if (layout.equals(repoLayout)) { result = true; break; - } - else if ( WILDCARD.equals( layout ) ) - { + } else if (WILDCARD.equals(layout)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/ArtifactClassRealmConstituent.java b/maven-core/src/main/java/org/apache/maven/classrealm/ArtifactClassRealmConstituent.java index 16d3e7b432..e4340f5684 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/ArtifactClassRealmConstituent.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/ArtifactClassRealmConstituent.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,59 +16,48 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.classrealm; import java.io.File; - import org.eclipse.aether.artifact.Artifact; /** * @author Benjamin Bentmann */ -class ArtifactClassRealmConstituent - implements ClassRealmConstituent -{ +class ArtifactClassRealmConstituent implements ClassRealmConstituent { private final Artifact artifact; - ArtifactClassRealmConstituent( Artifact artifact ) - { + ArtifactClassRealmConstituent(Artifact artifact) { this.artifact = artifact; } - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } - public String getType() - { + public String getType() { return artifact.getExtension(); } - public String getClassifier() - { + public String getClassifier() { return artifact.getClassifier(); } - public String getVersion() - { + public String getVersion() { return artifact.getBaseVersion(); } - public File getFile() - { + public File getFile() { return artifact.getFile(); } @Override - public String toString() - { + public String toString() { return artifact.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmConstituent.java b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmConstituent.java index f658eb4359..401b9cdc81 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmConstituent.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmConstituent.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.classrealm; import java.io.File; @@ -26,8 +25,7 @@ import java.io.File; * * @author Benjamin Bentmann */ -public interface ClassRealmConstituent -{ +public interface ClassRealmConstituent { /** * Gets the group id of the constituent's artifact. @@ -70,5 +68,4 @@ public interface ClassRealmConstituent * @return The file, never {@code null}. */ File getFile(); - } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManager.java b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManager.java index e5d15143ed..627ed8a060 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManager.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.classrealm; import java.util.List; import java.util.Map; - import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.codehaus.plexus.classworlds.realm.ClassRealm; @@ -34,8 +32,7 @@ import org.eclipse.aether.artifact.Artifact; * * @author Benjamin Bentmann */ -public interface ClassRealmManager -{ +public interface ClassRealmManager { /** * Gets the class realm hosting the Maven core. @@ -59,7 +56,7 @@ public interface ClassRealmManager * missing file) will automatically be excluded from the realm. * @return The new project realm, never {@code null}. */ - ClassRealm createProjectRealm( Model model, List artifacts ); + ClassRealm createProjectRealm(Model model, List artifacts); /** * Creates a new class realm for the specified build extension. @@ -69,7 +66,7 @@ public interface ClassRealmManager * missing file) will automatically be excluded from the realm. * @return The new extension realm, never {@code null}. */ - ClassRealm createExtensionRealm( Plugin extension, List artifacts ); + ClassRealm createExtensionRealm(Plugin extension, List artifacts); /** * Creates a new class realm for the specified plugin. @@ -82,7 +79,10 @@ public interface ClassRealmManager * missing file) will automatically be excluded from the realm. * @return The new plugin realm, never {@code null}. */ - ClassRealm createPluginRealm( Plugin plugin, ClassLoader parent, List parentImports, - Map foreignImports, List artifacts ); - + ClassRealm createPluginRealm( + Plugin plugin, + ClassLoader parent, + List parentImports, + Map foreignImports, + List artifacts); } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManagerDelegate.java b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManagerDelegate.java index b0229b9793..fcfb9ab61e 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManagerDelegate.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManagerDelegate.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,7 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.classrealm; import org.codehaus.plexus.classworlds.realm.ClassRealm; @@ -28,9 +26,7 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; * * @author igor */ -public interface ClassRealmManagerDelegate -{ - - void setupRealm( ClassRealm classRealm, ClassRealmRequest request ); +public interface ClassRealmManagerDelegate { + void setupRealm(ClassRealm classRealm, ClassRealmRequest request); } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmRequest.java b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmRequest.java index f1dc42754e..c5838fa3af 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmRequest.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.classrealm; import java.util.List; import java.util.Map; @@ -27,14 +26,12 @@ import java.util.Map; * * @author Benjamin Bentmann */ -public interface ClassRealmRequest -{ +public interface ClassRealmRequest { /** * The type of a class realm. */ - enum RealmType - { + enum RealmType { /** * The class realm for the public API of the Maven core. */ @@ -97,5 +94,4 @@ public interface ClassRealmRequest * @return The modifiable list of constituents for the class realm, never {@code null}. */ List getConstituents(); - } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmManager.java b/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmManager.java index 50e0e3c6f1..6eb24613ff 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmManager.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.classrealm; import java.io.File; import java.net.MalformedURLException; @@ -30,11 +29,9 @@ import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.TreeMap; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.classrealm.ClassRealmRequest.RealmType; import org.apache.maven.extension.internal.CoreExports; @@ -59,9 +56,7 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultClassRealmManager - implements ClassRealmManager -{ +public class DefaultClassRealmManager implements ClassRealmManager { public static final String API_REALMID = "maven.api"; /** @@ -74,7 +69,7 @@ public class DefaultClassRealmManager */ private static final ClassLoader PARENT_CLASSLOADER = ClassWorld.class.getClassLoader(); - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final ClassWorld world; @@ -92,54 +87,48 @@ public class DefaultClassRealmManager private final Set providedArtifacts; @Inject - public DefaultClassRealmManager( PlexusContainer container, - List delegates, - CoreExports exports ) - { - this.world = ( (MutablePlexusContainer) container ).getClassWorld(); + public DefaultClassRealmManager( + PlexusContainer container, List delegates, CoreExports exports) { + this.world = ((MutablePlexusContainer) container).getClassWorld(); this.containerRealm = container.getContainerRealm(); this.delegates = delegates; Map foreignImports = exports.getExportedPackages(); - this.mavenApiRealm = - createRealm( API_REALMID, RealmType.Core, null /* parent */, null /* parentImports */, - foreignImports, null /* artifacts */ ); + this.mavenApiRealm = createRealm( + API_REALMID, + RealmType.Core, + null /* parent */, + null /* parentImports */, + foreignImports, + null /* artifacts */); this.providedArtifacts = exports.getExportedArtifacts(); } - private ClassRealm newRealm( String id ) - { - synchronized ( world ) - { + private ClassRealm newRealm(String id) { + synchronized (world) { String realmId = id; Random random = new Random(); - while ( true ) - { - try - { - ClassRealm classRealm = world.newRealm( realmId, null ); + while (true) { + try { + ClassRealm classRealm = world.newRealm(realmId, null); - if ( logger.isDebugEnabled() ) - { - logger.debug( "Created new class realm " + realmId ); + if (logger.isDebugEnabled()) { + logger.debug("Created new class realm " + realmId); } return classRealm; - } - catch ( DuplicateRealmException e ) - { + } catch (DuplicateRealmException e) { realmId = id + '-' + random.nextInt(); } } } } - public ClassRealm getMavenApiRealm() - { + public ClassRealm getMavenApiRealm() { return mavenApiRealm; } @@ -155,254 +144,226 @@ public class DefaultClassRealmManager * missing file) will automatically be excluded from the realm. * @return The created class realm, never {@code null}. */ - private ClassRealm createRealm( String baseRealmId, RealmType type, ClassLoader parent, List parentImports, - Map foreignImports, List artifacts ) - { + private ClassRealm createRealm( + String baseRealmId, + RealmType type, + ClassLoader parent, + List parentImports, + Map foreignImports, + List artifacts) { Set artifactIds = new LinkedHashSet<>(); List constituents = new ArrayList<>(); - if ( artifacts != null ) - { - for ( Artifact artifact : artifacts ) - { - if ( !isProvidedArtifact( artifact ) ) - { - artifactIds.add( getId( artifact ) ); - if ( artifact.getFile() != null ) - { - constituents.add( new ArtifactClassRealmConstituent( artifact ) ); + if (artifacts != null) { + for (Artifact artifact : artifacts) { + if (!isProvidedArtifact(artifact)) { + artifactIds.add(getId(artifact)); + if (artifact.getFile() != null) { + constituents.add(new ArtifactClassRealmConstituent(artifact)); } } } } - if ( parentImports != null ) - { - parentImports = new ArrayList<>( parentImports ); - } - else - { + if (parentImports != null) { + parentImports = new ArrayList<>(parentImports); + } else { parentImports = new ArrayList<>(); } - if ( foreignImports != null ) - { - foreignImports = new TreeMap<>( foreignImports ); - } - else - { + if (foreignImports != null) { + foreignImports = new TreeMap<>(foreignImports); + } else { foreignImports = new TreeMap<>(); } - ClassRealm classRealm = newRealm( baseRealmId ); + ClassRealm classRealm = newRealm(baseRealmId); - if ( parent != null ) - { - classRealm.setParentClassLoader( parent ); + if (parent != null) { + classRealm.setParentClassLoader(parent); } - callDelegates( classRealm, type, parent, parentImports, foreignImports, constituents ); + callDelegates(classRealm, type, parent, parentImports, foreignImports, constituents); - wireRealm( classRealm, parentImports, foreignImports ); + wireRealm(classRealm, parentImports, foreignImports); - Set includedIds = populateRealm( classRealm, constituents ); + Set includedIds = populateRealm(classRealm, constituents); - if ( logger.isDebugEnabled() ) - { - artifactIds.removeAll( includedIds ); + if (logger.isDebugEnabled()) { + artifactIds.removeAll(includedIds); - for ( String id : artifactIds ) - { - logger.debug( " Excluded: " + id ); + for (String id : artifactIds) { + logger.debug(" Excluded: " + id); } } return classRealm; } - public ClassRealm getCoreRealm() - { + public ClassRealm getCoreRealm() { return containerRealm; } - public ClassRealm createProjectRealm( Model model, List artifacts ) - { - Objects.requireNonNull( model, "model cannot be null" ); + public ClassRealm createProjectRealm(Model model, List artifacts) { + Objects.requireNonNull(model, "model cannot be null"); ClassLoader parent = getMavenApiRealm(); - return createRealm( getKey( model ), RealmType.Project, parent, null, null, artifacts ); + return createRealm(getKey(model), RealmType.Project, parent, null, null, artifacts); } - private static String getKey( Model model ) - { + private static String getKey(Model model) { return "project>" + model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion(); } - public ClassRealm createExtensionRealm( Plugin plugin, List artifacts ) - { - Objects.requireNonNull( plugin, "plugin cannot be null" ); + public ClassRealm createExtensionRealm(Plugin plugin, List artifacts) { + Objects.requireNonNull(plugin, "plugin cannot be null"); - Map foreignImports = - Collections.singletonMap( "", getMavenApiRealm() ); + Map foreignImports = Collections.singletonMap("", getMavenApiRealm()); - return createRealm( getKey( plugin, true ), RealmType.Extension, PARENT_CLASSLOADER, null, - foreignImports, artifacts ); + return createRealm( + getKey(plugin, true), RealmType.Extension, PARENT_CLASSLOADER, null, foreignImports, artifacts); } - private boolean isProvidedArtifact( Artifact artifact ) - { - return providedArtifacts.contains( artifact.getGroupId() + ":" + artifact.getArtifactId() ); + private boolean isProvidedArtifact(Artifact artifact) { + return providedArtifacts.contains(artifact.getGroupId() + ":" + artifact.getArtifactId()); } - public ClassRealm createPluginRealm( Plugin plugin, ClassLoader parent, List parentImports, - Map foreignImports, List artifacts ) - { - Objects.requireNonNull( plugin, "plugin cannot be null" ); + public ClassRealm createPluginRealm( + Plugin plugin, + ClassLoader parent, + List parentImports, + Map foreignImports, + List artifacts) { + Objects.requireNonNull(plugin, "plugin cannot be null"); - if ( parent == null ) - { + if (parent == null) { parent = PARENT_CLASSLOADER; } - return createRealm( getKey( plugin, false ), RealmType.Plugin, parent, parentImports, foreignImports, - artifacts ); + return createRealm(getKey(plugin, false), RealmType.Plugin, parent, parentImports, foreignImports, artifacts); } - private static String getKey( Plugin plugin, boolean extension ) - { - String version = ArtifactUtils.toSnapshotVersion( plugin.getVersion() ); - return ( extension ? "extension>" : "plugin>" ) + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" - + version; + private static String getKey(Plugin plugin, boolean extension) { + String version = ArtifactUtils.toSnapshotVersion(plugin.getVersion()); + return (extension ? "extension>" : "plugin>") + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + + version; } - private static String getId( Artifact artifact ) - { - return getId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), - artifact.getClassifier(), artifact.getBaseVersion() ); + private static String getId(Artifact artifact) { + return getId( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getExtension(), + artifact.getClassifier(), + artifact.getBaseVersion()); } - private static String getId( ClassRealmConstituent constituent ) - { - return getId( constituent.getGroupId(), constituent.getArtifactId(), constituent.getType(), - constituent.getClassifier(), constituent.getVersion() ); + private static String getId(ClassRealmConstituent constituent) { + return getId( + constituent.getGroupId(), + constituent.getArtifactId(), + constituent.getType(), + constituent.getClassifier(), + constituent.getVersion()); } - private static String getId( String gid, String aid, String type, String cls, String ver ) - { - return gid + ':' + aid + ':' + type + ( StringUtils.isNotEmpty( cls ) ? ':' + cls : "" ) + ':' + ver; + private static String getId(String gid, String aid, String type, String cls, String ver) { + return gid + ':' + aid + ':' + type + (StringUtils.isNotEmpty(cls) ? ':' + cls : "") + ':' + ver; } - private void callDelegates( ClassRealm classRealm, RealmType type, ClassLoader parent, List parentImports, - Map foreignImports, List constituents ) - { - List delegates = new ArrayList<>( this.delegates ); + private void callDelegates( + ClassRealm classRealm, + RealmType type, + ClassLoader parent, + List parentImports, + Map foreignImports, + List constituents) { + List delegates = new ArrayList<>(this.delegates); - if ( !delegates.isEmpty() ) - { + if (!delegates.isEmpty()) { ClassRealmRequest request = - new DefaultClassRealmRequest( type, parent, parentImports, foreignImports, constituents ); + new DefaultClassRealmRequest(type, parent, parentImports, foreignImports, constituents); - for ( ClassRealmManagerDelegate delegate : delegates ) - { - try - { - delegate.setupRealm( classRealm, request ); - } - catch ( Exception e ) - { - logger.error( delegate.getClass().getName() + " failed to setup class realm " + classRealm + ": " - + e.getMessage(), e ); + for (ClassRealmManagerDelegate delegate : delegates) { + try { + delegate.setupRealm(classRealm, request); + } catch (Exception e) { + logger.error( + delegate.getClass().getName() + " failed to setup class realm " + classRealm + ": " + + e.getMessage(), + e); } } } } - private Set populateRealm( ClassRealm classRealm, List constituents ) - { + private Set populateRealm(ClassRealm classRealm, List constituents) { Set includedIds = new LinkedHashSet<>(); - if ( logger.isDebugEnabled() ) - { - logger.debug( "Populating class realm " + classRealm.getId() ); + if (logger.isDebugEnabled()) { + logger.debug("Populating class realm " + classRealm.getId()); } - for ( ClassRealmConstituent constituent : constituents ) - { + for (ClassRealmConstituent constituent : constituents) { File file = constituent.getFile(); - String id = getId( constituent ); - includedIds.add( id ); + String id = getId(constituent); + includedIds.add(id); - if ( logger.isDebugEnabled() ) - { - logger.debug( " Included: " + id ); + if (logger.isDebugEnabled()) { + logger.debug(" Included: " + id); } - try - { - classRealm.addURL( file.toURI().toURL() ); - } - catch ( MalformedURLException e ) - { + try { + classRealm.addURL(file.toURI().toURL()); + } catch (MalformedURLException e) { // Not going to happen - logger.error( e.getMessage(), e ); + logger.error(e.getMessage(), e); } } return includedIds; } - private void wireRealm( ClassRealm classRealm, List parentImports, Map foreignImports ) - { - if ( foreignImports != null && !foreignImports.isEmpty() ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Importing foreign packages into class realm " + classRealm.getId() ); + private void wireRealm(ClassRealm classRealm, List parentImports, Map foreignImports) { + if (foreignImports != null && !foreignImports.isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug("Importing foreign packages into class realm " + classRealm.getId()); } - for ( Map.Entry entry : foreignImports.entrySet() ) - { + for (Map.Entry entry : foreignImports.entrySet()) { ClassLoader importedRealm = entry.getValue(); String imp = entry.getKey(); - if ( logger.isDebugEnabled() ) - { - logger.debug( " Imported: " + imp + " < " + getId( importedRealm ) ); + if (logger.isDebugEnabled()) { + logger.debug(" Imported: " + imp + " < " + getId(importedRealm)); } - classRealm.importFrom( importedRealm, imp ); + classRealm.importFrom(importedRealm, imp); } } - if ( parentImports != null && !parentImports.isEmpty() ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Importing parent packages into class realm " + classRealm.getId() ); + if (parentImports != null && !parentImports.isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug("Importing parent packages into class realm " + classRealm.getId()); } - for ( String imp : parentImports ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( " Imported: " + imp + " < " + getId( classRealm.getParentClassLoader() ) ); + for (String imp : parentImports) { + if (logger.isDebugEnabled()) { + logger.debug(" Imported: " + imp + " < " + getId(classRealm.getParentClassLoader())); } - classRealm.importFromParent( imp ); + classRealm.importFromParent(imp); } } } - private String getId( ClassLoader classLoader ) - { - if ( classLoader instanceof ClassRealm ) - { - return ( (ClassRealm) classLoader ).getId(); + private String getId(ClassLoader classLoader) { + if (classLoader instanceof ClassRealm) { + return ((ClassRealm) classLoader).getId(); } - return String.valueOf( classLoader ); + return String.valueOf(classLoader); } - } diff --git a/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmRequest.java b/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmRequest.java index 8694b0142f..4a6344dbbd 100644 --- a/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmRequest.java +++ b/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.classrealm; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.classrealm; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.classrealm; import java.util.List; import java.util.Map; @@ -25,9 +24,7 @@ import java.util.Map; /** * @author Benjamin Bentmann */ -class DefaultClassRealmRequest - implements ClassRealmRequest -{ +class DefaultClassRealmRequest implements ClassRealmRequest { private final RealmType type; @@ -39,9 +36,12 @@ class DefaultClassRealmRequest private final List constituents; - DefaultClassRealmRequest( RealmType type, ClassLoader parent, List parentImports, - Map foreignImports, List constituents ) - { + DefaultClassRealmRequest( + RealmType type, + ClassLoader parent, + List parentImports, + Map foreignImports, + List constituents) { this.type = type; this.parent = parent; this.parentImports = parentImports; @@ -49,34 +49,27 @@ class DefaultClassRealmRequest this.constituents = constituents; } - public RealmType getType() - { + public RealmType getType() { return type; } - public ClassLoader getParent() - { + public ClassLoader getParent() { return parent; } - public List getImports() - { + public List getImports() { return getParentImports(); } - public List getParentImports() - { + public List getParentImports() { return parentImports; } - public Map getForeignImports() - { + public Map getForeignImports() { return foreignImports; } - public List getConstituents() - { + public List getConstituents() { return constituents; } - } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/BasedirBeanConfigurationPathTranslator.java b/maven-core/src/main/java/org/apache/maven/configuration/BasedirBeanConfigurationPathTranslator.java index 9859f586ad..28c75229da 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/BasedirBeanConfigurationPathTranslator.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/BasedirBeanConfigurationPathTranslator.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; import java.io.File; @@ -26,9 +25,7 @@ import java.io.File; * * @author Benjamin Bentmann */ -public class BasedirBeanConfigurationPathTranslator - implements BeanConfigurationPathTranslator -{ +public class BasedirBeanConfigurationPathTranslator implements BeanConfigurationPathTranslator { private final File basedir; @@ -38,34 +35,25 @@ public class BasedirBeanConfigurationPathTranslator * @param basedir The base directory to resolve relative paths against, may be {@code null} to disable path * translation. */ - public BasedirBeanConfigurationPathTranslator( File basedir ) - { + public BasedirBeanConfigurationPathTranslator(File basedir) { this.basedir = basedir; } - public File translatePath( File path ) - { + public File translatePath(File path) { File result = path; - if ( path != null && basedir != null ) - { - if ( path.isAbsolute() ) - { + if (path != null && basedir != null) { + if (path.isAbsolute()) { // path is already absolute, we're done - } - else if ( path.getPath().startsWith( File.separator ) ) - { + } else if (path.getPath().startsWith(File.separator)) { // drive-relative Windows path, don't align with base dir but with drive root result = path.getAbsoluteFile(); - } - else - { + } else { // an ordinary relative path, align with base dir - result = new File( new File( basedir, path.getPath() ).toURI().normalize() ).getAbsoluteFile(); + result = new File(new File(basedir, path.getPath()).toURI().normalize()).getAbsoluteFile(); } } return result; } - } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationException.java b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationException.java index 3d10ed4a52..684101662c 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationException.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,20 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; /** * Thrown when a bean couldn't be configured. * * @author Benjamin Bentmann */ -public class BeanConfigurationException - extends Exception -{ +public class BeanConfigurationException extends Exception { - public BeanConfigurationException( String message ) - { - super( message ); + public BeanConfigurationException(String message) { + super(message); } - public BeanConfigurationException( String message, Throwable cause ) - { - super( message, cause ); + public BeanConfigurationException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationPathTranslator.java b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationPathTranslator.java index 396633916e..2aac417c75 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationPathTranslator.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationPathTranslator.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; import java.io.File; @@ -27,8 +26,7 @@ import java.io.File; * * @author Benjamin Bentmann */ -public interface BeanConfigurationPathTranslator -{ +public interface BeanConfigurationPathTranslator { /** * Translates the specified path. @@ -36,6 +34,5 @@ public interface BeanConfigurationPathTranslator * @param path The path to translate, may be {@code null}. * @return The translated path or {@code null} if none. */ - File translatePath( File path ); - + File translatePath(File path); } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationRequest.java b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationRequest.java index 91d687f6de..bf9501da54 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationRequest.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,14 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; /** * A request to configure a bean from some configuration in the POM or similar. * * @author Benjamin Bentmann */ -public interface BeanConfigurationRequest -{ +public interface BeanConfigurationRequest { /** * Gets the bean to configure. Eventually, a valid request must have a bean set. @@ -40,7 +38,7 @@ public interface BeanConfigurationRequest * @param bean The bean to configure, may be {@code null}. * @return This request for chaining, never {@code null}. */ - BeanConfigurationRequest setBean( Object bean ); + BeanConfigurationRequest setBean(Object bean); /** * Gets the configuration to unmarshal into the bean. @@ -57,7 +55,7 @@ public interface BeanConfigurationRequest * @param configuration The configuration to unmarshal, may be {@code null}. * @return This request for chaining, never {@code null}. */ - BeanConfigurationRequest setConfiguration( Object configuration ); + BeanConfigurationRequest setConfiguration(Object configuration); /** * Sets the configuration to unmarshal into the bean. The configuration should be taken from @@ -69,7 +67,7 @@ public interface BeanConfigurationRequest * @param element Configuration element name to unmarshal or {@code null} to unmarshal entire configuration. * @return This request for chaining, never {@code null}. */ - BeanConfigurationRequest setConfiguration( Object configuration, String element ); + BeanConfigurationRequest setConfiguration(Object configuration, String element); /** * Returns configuration element name or {@code null}. @@ -95,7 +93,7 @@ public interface BeanConfigurationRequest * @param classLoader The class loader to load referenced types from, may be {@code null}. * @return This request for chaining, never {@code null}. */ - BeanConfigurationRequest setClassLoader( ClassLoader classLoader ); + BeanConfigurationRequest setClassLoader(ClassLoader classLoader); /** * Gets the optional preprocessor for configuration values. @@ -110,7 +108,7 @@ public interface BeanConfigurationRequest * @param valuePreprocessor The preprocessor for configuration values, may be {@code null} if unneeded. * @return This request for chaining, never {@code null}. */ - BeanConfigurationRequest setValuePreprocessor( BeanConfigurationValuePreprocessor valuePreprocessor ); + BeanConfigurationRequest setValuePreprocessor(BeanConfigurationValuePreprocessor valuePreprocessor); /** * Gets the optional path translator for configuration values unmarshalled to files. @@ -125,6 +123,5 @@ public interface BeanConfigurationRequest * @param pathTranslator The path translator for files, may be {@code null} if unneeded. * @return This request for chaining, never {@code null}. */ - BeanConfigurationRequest setPathTranslator( BeanConfigurationPathTranslator pathTranslator ); - + BeanConfigurationRequest setPathTranslator(BeanConfigurationPathTranslator pathTranslator); } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationValuePreprocessor.java b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationValuePreprocessor.java index 63f8517399..4e1a166a89 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationValuePreprocessor.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationValuePreprocessor.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; /** * Preprocesses a value from a bean configuration before the bean configurator unmarshals it into a bean property. A @@ -25,8 +24,7 @@ package org.apache.maven.configuration; * * @author Benjamin Bentmann */ -public interface BeanConfigurationValuePreprocessor -{ +public interface BeanConfigurationValuePreprocessor { /** * Preprocesses the specified bean configuration value. The optional type provided to this method is a hint (not a @@ -39,7 +37,5 @@ public interface BeanConfigurationValuePreprocessor * @return The processed configuration value or {@code null} if none. * @throws BeanConfigurationException If an error occurred while preprocessing the value. */ - Object preprocessValue( String value, Class type ) - throws BeanConfigurationException; - + Object preprocessValue(String value, Class type) throws BeanConfigurationException; } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurator.java b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurator.java index 36d23ecac9..9365ba6fa7 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurator.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; /** * Unmarshals some textual configuration from the POM or similar into the properties of a bean. This component works @@ -28,8 +27,7 @@ package org.apache.maven.configuration; * @since 3.0 * @author Benjamin Bentmann */ -public interface BeanConfigurator -{ +public interface BeanConfigurator { /** * Performs the specified bean configuration. @@ -38,7 +36,5 @@ public interface BeanConfigurator * {@code null}. * @throws BeanConfigurationException If the bean configuration could not be successfully processed. */ - void configureBean( BeanConfigurationRequest request ) - throws BeanConfigurationException; - + void configureBean(BeanConfigurationRequest request) throws BeanConfigurationException; } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/DefaultBeanConfigurationRequest.java b/maven-core/src/main/java/org/apache/maven/configuration/DefaultBeanConfigurationRequest.java index 5ec69f5976..5e5291c1ff 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/DefaultBeanConfigurationRequest.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/DefaultBeanConfigurationRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; import org.apache.commons.lang3.Validate; import org.apache.maven.model.Build; @@ -32,9 +31,7 @@ import org.codehaus.plexus.util.StringUtils; * * @author Benjamin Bentmann */ -public class DefaultBeanConfigurationRequest - implements BeanConfigurationRequest -{ +public class DefaultBeanConfigurationRequest implements BeanConfigurationRequest { private Object bean; @@ -48,34 +45,28 @@ public class DefaultBeanConfigurationRequest private BeanConfigurationPathTranslator pathTranslator; - public Object getBean() - { + public Object getBean() { return bean; } - public DefaultBeanConfigurationRequest setBean( Object bean ) - { + public DefaultBeanConfigurationRequest setBean(Object bean) { this.bean = bean; return this; } - public Object getConfiguration() - { + public Object getConfiguration() { return configuration; } - public String getConfigurationElement() - { + public String getConfigurationElement() { return configurationElement; } - public DefaultBeanConfigurationRequest setConfiguration( Object configuration ) - { - return setConfiguration( configuration, null ); + public DefaultBeanConfigurationRequest setConfiguration(Object configuration) { + return setConfiguration(configuration, null); } - public DefaultBeanConfigurationRequest setConfiguration( Object configuration, String element ) - { + public DefaultBeanConfigurationRequest setConfiguration(Object configuration, String element) { this.configuration = configuration; this.configurationElement = element; return this; @@ -94,56 +85,41 @@ public class DefaultBeanConfigurationRequest * empty to use the general plugin configuration. * @return This request for chaining, never {@code null}. */ - public DefaultBeanConfigurationRequest setConfiguration( Model model, String pluginGroupId, - String pluginArtifactId, String pluginExecutionId ) - { - Plugin plugin = findPlugin( model, pluginGroupId, pluginArtifactId ); - if ( plugin != null ) - { - if ( StringUtils.isNotEmpty( pluginExecutionId ) ) - { - for ( PluginExecution execution : plugin.getExecutions() ) - { - if ( pluginExecutionId.equals( execution.getId() ) ) - { - setConfiguration( execution.getConfiguration() ); + public DefaultBeanConfigurationRequest setConfiguration( + Model model, String pluginGroupId, String pluginArtifactId, String pluginExecutionId) { + Plugin plugin = findPlugin(model, pluginGroupId, pluginArtifactId); + if (plugin != null) { + if (StringUtils.isNotEmpty(pluginExecutionId)) { + for (PluginExecution execution : plugin.getExecutions()) { + if (pluginExecutionId.equals(execution.getId())) { + setConfiguration(execution.getConfiguration()); break; } } - } - else - { - setConfiguration( plugin.getConfiguration() ); + } else { + setConfiguration(plugin.getConfiguration()); } } return this; } - private Plugin findPlugin( Model model, String groupId, String artifactId ) - { - Validate.notBlank( groupId, "groupId can neither be null, empty nor blank" ); - Validate.notBlank( artifactId, "artifactId can neither be null, empty nor blank" ); + private Plugin findPlugin(Model model, String groupId, String artifactId) { + Validate.notBlank(groupId, "groupId can neither be null, empty nor blank"); + Validate.notBlank(artifactId, "artifactId can neither be null, empty nor blank"); - if ( model != null ) - { + if (model != null) { Build build = model.getBuild(); - if ( build != null ) - { - for ( Plugin plugin : build.getPlugins() ) - { - if ( groupId.equals( plugin.getGroupId() ) && artifactId.equals( plugin.getArtifactId() ) ) - { + if (build != null) { + for (Plugin plugin : build.getPlugins()) { + if (groupId.equals(plugin.getGroupId()) && artifactId.equals(plugin.getArtifactId())) { return plugin; } } PluginManagement mgmt = build.getPluginManagement(); - if ( mgmt != null ) - { - for ( Plugin plugin : mgmt.getPlugins() ) - { - if ( groupId.equals( plugin.getGroupId() ) && artifactId.equals( plugin.getArtifactId() ) ) - { + if (mgmt != null) { + for (Plugin plugin : mgmt.getPlugins()) { + if (groupId.equals(plugin.getGroupId()) && artifactId.equals(plugin.getArtifactId())) { return plugin; } } @@ -154,37 +130,30 @@ public class DefaultBeanConfigurationRequest return null; } - public ClassLoader getClassLoader() - { + public ClassLoader getClassLoader() { return classLoader; } - public DefaultBeanConfigurationRequest setClassLoader( ClassLoader classLoader ) - { + public DefaultBeanConfigurationRequest setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } - public BeanConfigurationValuePreprocessor getValuePreprocessor() - { + public BeanConfigurationValuePreprocessor getValuePreprocessor() { return valuePreprocessor; } - public DefaultBeanConfigurationRequest setValuePreprocessor( BeanConfigurationValuePreprocessor valuePreprocessor ) - { + public DefaultBeanConfigurationRequest setValuePreprocessor(BeanConfigurationValuePreprocessor valuePreprocessor) { this.valuePreprocessor = valuePreprocessor; return this; } - public BeanConfigurationPathTranslator getPathTranslator() - { + public BeanConfigurationPathTranslator getPathTranslator() { return pathTranslator; } - public DefaultBeanConfigurationRequest setPathTranslator( BeanConfigurationPathTranslator pathTranslator ) - { + public DefaultBeanConfigurationRequest setPathTranslator(BeanConfigurationPathTranslator pathTranslator) { this.pathTranslator = pathTranslator; return this; } - } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultBeanConfigurator.java b/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultBeanConfigurator.java index 6d170896b8..14c08a2bd8 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultBeanConfigurator.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultBeanConfigurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,14 @@ package org.apache.maven.configuration.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration.internal; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.configuration.BeanConfigurationException; import org.apache.maven.configuration.BeanConfigurationPathTranslator; import org.apache.maven.configuration.BeanConfigurationRequest; @@ -52,145 +49,115 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; */ @Named @Singleton -public class DefaultBeanConfigurator - implements BeanConfigurator -{ +public class DefaultBeanConfigurator implements BeanConfigurator { private final ConverterLookup converterLookup; - public DefaultBeanConfigurator() - { + public DefaultBeanConfigurator() { converterLookup = new EnhancedConverterLookup(); } - public void configureBean( BeanConfigurationRequest request ) - throws BeanConfigurationException - { - Objects.requireNonNull( request, "request cannot be null" ); - Objects.requireNonNull( request.getBean(), "request.bean cannot be null" ); + public void configureBean(BeanConfigurationRequest request) throws BeanConfigurationException { + Objects.requireNonNull(request, "request cannot be null"); + Objects.requireNonNull(request.getBean(), "request.bean cannot be null"); Object configuration = request.getConfiguration(); - if ( configuration == null ) - { + if (configuration == null) { return; } PlexusConfiguration plexusConfig; - if ( configuration instanceof PlexusConfiguration ) - { + if (configuration instanceof PlexusConfiguration) { plexusConfig = (PlexusConfiguration) configuration; - } - else if ( configuration instanceof Xpp3Dom ) - { - plexusConfig = new XmlPlexusConfiguration( (Xpp3Dom) configuration ); - } - else - { - throw new BeanConfigurationException( "unsupported bean configuration source (" - + configuration.getClass().getName() + ")" ); + } else if (configuration instanceof Xpp3Dom) { + plexusConfig = new XmlPlexusConfiguration((Xpp3Dom) configuration); + } else { + throw new BeanConfigurationException("unsupported bean configuration source (" + + configuration.getClass().getName() + ")"); } - if ( request.getConfigurationElement() != null ) - { - plexusConfig = plexusConfig.getChild( request.getConfigurationElement() ); + if (request.getConfigurationElement() != null) { + plexusConfig = plexusConfig.getChild(request.getConfigurationElement()); } ClassLoader classLoader = request.getClassLoader(); - if ( classLoader == null ) - { + if (classLoader == null) { classLoader = request.getBean().getClass().getClassLoader(); } - BeanExpressionEvaluator evaluator = new BeanExpressionEvaluator( request ); + BeanExpressionEvaluator evaluator = new BeanExpressionEvaluator(request); ObjectWithFieldsConverter converter = new EnhancedConfigurationConverter(); - try - { - converter.processConfiguration( converterLookup, request.getBean(), classLoader, - plexusConfig, evaluator, null ); - } - catch ( ComponentConfigurationException e ) - { - throw new BeanConfigurationException( e.getMessage(), e ); + try { + converter.processConfiguration( + converterLookup, request.getBean(), classLoader, plexusConfig, evaluator, null); + } catch (ComponentConfigurationException e) { + throw new BeanConfigurationException(e.getMessage(), e); } } - static class BeanExpressionEvaluator - implements TypeAwareExpressionEvaluator - { + static class BeanExpressionEvaluator implements TypeAwareExpressionEvaluator { private final BeanConfigurationValuePreprocessor preprocessor; private final BeanConfigurationPathTranslator translator; - BeanExpressionEvaluator( BeanConfigurationRequest request ) - { + BeanExpressionEvaluator(BeanConfigurationRequest request) { preprocessor = request.getValuePreprocessor(); translator = request.getPathTranslator(); } - public Object evaluate( String expression, Class type ) - throws ExpressionEvaluationException - { - if ( preprocessor != null ) - { - try - { - return preprocessor.preprocessValue( expression, type ); - } - catch ( BeanConfigurationException e ) - { - throw new ExpressionEvaluationException( e.getMessage(), e ); + public Object evaluate(String expression, Class type) throws ExpressionEvaluationException { + if (preprocessor != null) { + try { + return preprocessor.preprocessValue(expression, type); + } catch (BeanConfigurationException e) { + throw new ExpressionEvaluationException(e.getMessage(), e); } } return expression; } - public Object evaluate( String expression ) - throws ExpressionEvaluationException - { - return evaluate( expression, null ); + public Object evaluate(String expression) throws ExpressionEvaluationException { + return evaluate(expression, null); } - public File alignToBaseDirectory( File file ) - { - if ( translator != null ) - { - return translator.translatePath( file ); + public File alignToBaseDirectory(File file) { + if (translator != null) { + return translator.translatePath(file); } return file; } - } - static class PathConverter extends AbstractBasicConverter - { + static class PathConverter extends AbstractBasicConverter { @Override - public boolean canConvert( Class type ) - { - return Path.class.equals( type ); + public boolean canConvert(Class type) { + return Path.class.equals(type); } @Override - protected Object fromString( String value ) throws ComponentConfigurationException - { - return Paths.get( value.replace( '/' == File.separatorChar ? '\\' : '/', File.separatorChar ) ); + protected Object fromString(String value) throws ComponentConfigurationException { + return Paths.get(value.replace('/' == File.separatorChar ? '\\' : '/', File.separatorChar)); } @Override - public Object fromConfiguration( final ConverterLookup lookup, final PlexusConfiguration configuration, - final Class type, final Class enclosingType, final ClassLoader loader, - final ExpressionEvaluator evaluator, final ConfigurationListener listener ) - throws ComponentConfigurationException - { + public Object fromConfiguration( + final ConverterLookup lookup, + final PlexusConfiguration configuration, + final Class type, + final Class enclosingType, + final ClassLoader loader, + final ExpressionEvaluator evaluator, + final ConfigurationListener listener) + throws ComponentConfigurationException { final Object result = - super.fromConfiguration( lookup, configuration, type, enclosingType, loader, evaluator, listener ); + super.fromConfiguration(lookup, configuration, type, enclosingType, loader, evaluator, listener); return result instanceof Path - ? evaluator.alignToBaseDirectory( ( (Path) result ).toFile() ).toPath() : result; + ? evaluator.alignToBaseDirectory(((Path) result).toFile()).toPath() + : result; } - } - } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedComponentConfigurator.java b/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedComponentConfigurator.java index defe38bcef..ba30ded3df 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedComponentConfigurator.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedComponentConfigurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.configuration.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration.internal; import javax.inject.Named; import javax.inject.Singleton; - import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.BasicComponentConfigurator; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; @@ -35,33 +33,34 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; * and {@link EnhancedConverterLookup}. */ @Singleton -@Named( "enhanced" ) -public class EnhancedComponentConfigurator - extends BasicComponentConfigurator -{ +@Named("enhanced") +public class EnhancedComponentConfigurator extends BasicComponentConfigurator { - public EnhancedComponentConfigurator() - { + public EnhancedComponentConfigurator() { converterLookup = new EnhancedConverterLookup(); } @Override - public void configureComponent( final Object component, final PlexusConfiguration configuration, - final ExpressionEvaluator evaluator, final ClassRealm realm, - final ConfigurationListener listener ) - throws ComponentConfigurationException - { - try - { - ClassRealmConverter.pushContextRealm( realm ); + public void configureComponent( + final Object component, + final PlexusConfiguration configuration, + final ExpressionEvaluator evaluator, + final ClassRealm realm, + final ConfigurationListener listener) + throws ComponentConfigurationException { + try { + ClassRealmConverter.pushContextRealm(realm); - new EnhancedConfigurationConverter().processConfiguration( converterLookup, component, realm, // - configuration, evaluator, listener ); - } - finally - { + new EnhancedConfigurationConverter() + .processConfiguration( + converterLookup, + component, + realm, // + configuration, + evaluator, + listener); + } finally { ClassRealmConverter.popContextRealm(); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConfigurationConverter.java b/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConfigurationConverter.java index 8bab9a9c12..f782763d70 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConfigurationConverter.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConfigurationConverter.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration.internal; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; @@ -33,91 +32,68 @@ import org.eclipse.sisu.plexus.CompositeBeanHelper; * An enhanced {@link ObjectWithFieldsConverter} leveraging the {@link TypeAwareExpressionEvaluator} * interface. */ -class EnhancedConfigurationConverter - extends ObjectWithFieldsConverter -{ - protected Object fromExpression( final PlexusConfiguration configuration, final ExpressionEvaluator evaluator, - final Class type ) - throws ComponentConfigurationException - { +class EnhancedConfigurationConverter extends ObjectWithFieldsConverter { + protected Object fromExpression( + final PlexusConfiguration configuration, final ExpressionEvaluator evaluator, final Class type) + throws ComponentConfigurationException { String value = configuration.getValue(); - try - { + try { Object result = null; - if ( null != value && value.length() > 0 ) - { - if ( evaluator instanceof TypeAwareExpressionEvaluator ) - { - result = ( (TypeAwareExpressionEvaluator) evaluator ).evaluate( value, type ); - } - else - { - result = evaluator.evaluate( value ); + if (null != value && value.length() > 0) { + if (evaluator instanceof TypeAwareExpressionEvaluator) { + result = ((TypeAwareExpressionEvaluator) evaluator).evaluate(value, type); + } else { + result = evaluator.evaluate(value); } } - if ( null == result && configuration.getChildCount() == 0 ) - { - value = configuration.getAttribute( "default-value" ); - if ( null != value && value.length() > 0 ) - { - if ( evaluator instanceof TypeAwareExpressionEvaluator ) - { - result = ( (TypeAwareExpressionEvaluator) evaluator ).evaluate( value, type ); - } - else - { - result = evaluator.evaluate( value ); + if (null == result && configuration.getChildCount() == 0) { + value = configuration.getAttribute("default-value"); + if (null != value && value.length() > 0) { + if (evaluator instanceof TypeAwareExpressionEvaluator) { + result = ((TypeAwareExpressionEvaluator) evaluator).evaluate(value, type); + } else { + result = evaluator.evaluate(value); } } } - failIfNotTypeCompatible( result, type, configuration ); + failIfNotTypeCompatible(result, type, configuration); return result; - } - catch ( final ExpressionEvaluationException e ) - { - final String reason = - String.format( "Cannot evaluate expression '%s' for configuration entry '%s'", value, - configuration.getName() ); + } catch (final ExpressionEvaluationException e) { + final String reason = String.format( + "Cannot evaluate expression '%s' for configuration entry '%s'", value, configuration.getName()); - throw new ComponentConfigurationException( configuration, reason, e ); + throw new ComponentConfigurationException(configuration, reason, e); } } - - public Object fromConfiguration( final ConverterLookup lookup, final PlexusConfiguration configuration, - final Class type, final Class enclosingType, final ClassLoader loader, - final ExpressionEvaluator evaluator, final ConfigurationListener listener ) - throws ComponentConfigurationException - { - final Object value = fromExpression( configuration, evaluator, type ); - if ( type.isInstance( value ) ) - { + public Object fromConfiguration( + final ConverterLookup lookup, + final PlexusConfiguration configuration, + final Class type, + final Class enclosingType, + final ClassLoader loader, + final ExpressionEvaluator evaluator, + final ConfigurationListener listener) + throws ComponentConfigurationException { + final Object value = fromExpression(configuration, evaluator, type); + if (type.isInstance(value)) { return value; } - try - { - final Class implType = getClassForImplementationHint( type, configuration, loader ); - if ( null == value && implType.isInterface() && configuration.getChildCount() == 0 ) - { + try { + final Class implType = getClassForImplementationHint(type, configuration, loader); + if (null == value && implType.isInterface() && configuration.getChildCount() == 0) { return null; // nothing to process } - final Object bean = instantiateObject( implType ); - if ( null == value ) - { - processConfiguration( lookup, bean, loader, configuration, evaluator, listener ); - } - else - { - new CompositeBeanHelper( lookup, loader, evaluator, listener ) - .setDefault( bean, value, configuration ); + final Object bean = instantiateObject(implType); + if (null == value) { + processConfiguration(lookup, bean, loader, configuration, evaluator, listener); + } else { + new CompositeBeanHelper(lookup, loader, evaluator, listener).setDefault(bean, value, configuration); } return bean; - } - catch ( final ComponentConfigurationException e ) - { - if ( null == e.getFailedConfiguration() ) - { - e.setFailedConfiguration( configuration ); + } catch (final ComponentConfigurationException e) { + if (null == e.getFailedConfiguration()) { + e.setFailedConfiguration(configuration); } throw e; } diff --git a/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConverterLookup.java b/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConverterLookup.java index 9399cec117..e8c2ed1a19 100644 --- a/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConverterLookup.java +++ b/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedConverterLookup.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.configuration.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration.internal; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; @@ -25,26 +24,23 @@ import org.codehaus.plexus.component.configurator.converters.composite.ObjectWit import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.converters.lookup.DefaultConverterLookup; -class EnhancedConverterLookup implements ConverterLookup -{ +class EnhancedConverterLookup implements ConverterLookup { private final ConverterLookup delegate = new DefaultConverterLookup(); - EnhancedConverterLookup() - { - registerConverter( new DefaultBeanConfigurator.PathConverter() ); + EnhancedConverterLookup() { + registerConverter(new DefaultBeanConfigurator.PathConverter()); } @Override - public void registerConverter( ConfigurationConverter converter ) - { - delegate.registerConverter( converter ); + public void registerConverter(ConfigurationConverter converter) { + delegate.registerConverter(converter); } @Override - public ConfigurationConverter lookupConverterForType( Class type ) throws ComponentConfigurationException - { - ConfigurationConverter converter = delegate.lookupConverterForType( type ); - return converter.getClass().equals( ObjectWithFieldsConverter.class ) - ? new EnhancedConfigurationConverter() : converter; + public ConfigurationConverter lookupConverterForType(Class type) throws ComponentConfigurationException { + ConfigurationConverter converter = delegate.lookupConverterForType(type); + return converter.getClass().equals(ObjectWithFieldsConverter.class) + ? new EnhancedConfigurationConverter() + : converter; } } diff --git a/maven-core/src/main/java/org/apache/maven/eventspy/AbstractEventSpy.java b/maven-core/src/main/java/org/apache/maven/eventspy/AbstractEventSpy.java index 091322751d..13efb349a1 100644 --- a/maven-core/src/main/java/org/apache/maven/eventspy/AbstractEventSpy.java +++ b/maven-core/src/main/java/org/apache/maven/eventspy/AbstractEventSpy.java @@ -1,5 +1,3 @@ -package org.apache.maven.eventspy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,28 +16,17 @@ package org.apache.maven.eventspy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.eventspy; /** * A skeleton eventspy that does nothing other than helping implementors. * @since 3.0.2 */ -public abstract class AbstractEventSpy - implements EventSpy -{ +public abstract class AbstractEventSpy implements EventSpy { - public void init( Context context ) - throws Exception - { - } + public void init(Context context) throws Exception {} - public void onEvent( Object event ) - throws Exception - { - } - - public void close() - throws Exception - { - } + public void onEvent(Object event) throws Exception {} + public void close() throws Exception {} } diff --git a/maven-core/src/main/java/org/apache/maven/eventspy/EventSpy.java b/maven-core/src/main/java/org/apache/maven/eventspy/EventSpy.java index bdc2dac219..14f6d577df 100644 --- a/maven-core/src/main/java/org/apache/maven/eventspy/EventSpy.java +++ b/maven-core/src/main/java/org/apache/maven/eventspy/EventSpy.java @@ -1,5 +1,3 @@ -package org.apache.maven.eventspy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.eventspy; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.eventspy; import java.util.Map; @@ -29,13 +28,11 @@ import java.util.Map; * interface. * @since 3.0.2 */ -public interface EventSpy -{ +public interface EventSpy { /** * Context */ - interface Context - { + interface Context { /** * Gets key-value pairs providing information about the Maven runtime. @@ -43,7 +40,6 @@ public interface EventSpy * @return The key-value pairs, never {@code null}. */ Map getData(); - } /** @@ -51,8 +47,7 @@ public interface EventSpy * * @param context The event spy context, never {@code null}. */ - void init( Context context ) - throws Exception; + void init(Context context) throws Exception; /** * Notifies the spy of some build event/operation. @@ -67,13 +62,10 @@ public interface EventSpy * @see org.apache.maven.execution.ExecutionEvent * @see org.eclipse.aether.RepositoryEvent */ - void onEvent( Object event ) - throws Exception; + void onEvent(Object event) throws Exception; /** * Notifies the spy of Maven's termination, allowing it to free any resources allocated by it. */ - void close() - throws Exception; - + void close() throws Exception; } diff --git a/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyDispatcher.java b/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyDispatcher.java index 4b04a18308..65b1ca8c7e 100644 --- a/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyDispatcher.java +++ b/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyDispatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.eventspy.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,13 @@ package org.apache.maven.eventspy.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.eventspy.internal; import java.util.ArrayList; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.eventspy.EventSpy; import org.apache.maven.execution.ExecutionListener; import org.eclipse.aether.RepositoryListener; @@ -38,106 +35,77 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class EventSpyDispatcher -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class EventSpyDispatcher { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final List eventSpies; @Inject - public EventSpyDispatcher( List eventSpies ) - { + public EventSpyDispatcher(List eventSpies) { // make copy to get rid of needless overhead for dynamic lookups - this.eventSpies = new ArrayList<>( eventSpies ); + this.eventSpies = new ArrayList<>(eventSpies); } - public ExecutionListener chainListener( ExecutionListener listener ) - { - if ( eventSpies.isEmpty() ) - { + public ExecutionListener chainListener(ExecutionListener listener) { + if (eventSpies.isEmpty()) { return listener; } - return new EventSpyExecutionListener( this, listener ); + return new EventSpyExecutionListener(this, listener); } - public RepositoryListener chainListener( RepositoryListener listener ) - { - if ( eventSpies.isEmpty() ) - { + public RepositoryListener chainListener(RepositoryListener listener) { + if (eventSpies.isEmpty()) { return listener; } - return new EventSpyRepositoryListener( this, listener ); + return new EventSpyRepositoryListener(this, listener); } - public void init( EventSpy.Context context ) - { - if ( eventSpies.isEmpty() ) - { + public void init(EventSpy.Context context) { + if (eventSpies.isEmpty()) { return; } - for ( EventSpy eventSpy : eventSpies ) - { - try - { - eventSpy.init( context ); - } - catch ( Exception | LinkageError e ) - { - logError( "initialize", e, eventSpy ); + for (EventSpy eventSpy : eventSpies) { + try { + eventSpy.init(context); + } catch (Exception | LinkageError e) { + logError("initialize", e, eventSpy); } } } - public void onEvent( Object event ) - { - if ( eventSpies.isEmpty() ) - { + public void onEvent(Object event) { + if (eventSpies.isEmpty()) { return; } - for ( EventSpy eventSpy : eventSpies ) - { - try - { - eventSpy.onEvent( event ); - } - catch ( Exception | LinkageError e ) - { - logError( "notify", e, eventSpy ); + for (EventSpy eventSpy : eventSpies) { + try { + eventSpy.onEvent(event); + } catch (Exception | LinkageError e) { + logError("notify", e, eventSpy); } } } - public void close() - { - if ( eventSpies.isEmpty() ) - { + public void close() { + if (eventSpies.isEmpty()) { return; } - for ( EventSpy eventSpy : eventSpies ) - { - try - { + for (EventSpy eventSpy : eventSpies) { + try { eventSpy.close(); - } - catch ( Exception | LinkageError e ) - { - logError( "close", e, eventSpy ); + } catch (Exception | LinkageError e) { + logError("close", e, eventSpy); } } } - private void logError( String action, Throwable e, EventSpy spy ) - { + private void logError(String action, Throwable e, EventSpy spy) { String msg = "Failed to " + action + " spy " + spy.getClass().getName() + ": " + e.getMessage(); - if ( logger.isDebugEnabled() ) - { - logger.warn( msg, e ); - } - else - { - logger.warn( msg ); + if (logger.isDebugEnabled()) { + logger.warn(msg, e); + } else { + logger.warn(msg); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyExecutionListener.java b/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyExecutionListener.java index b79b7208a1..e240d54b2d 100644 --- a/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.eventspy.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.eventspy.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.eventspy.internal; import org.apache.maven.execution.AbstractExecutionListener; import org.apache.maven.execution.ExecutionEvent; @@ -27,137 +26,116 @@ import org.apache.maven.execution.ExecutionListener; * Forwards execution events to EventSpies. * @since 3.0.2 */ -class EventSpyExecutionListener - extends AbstractExecutionListener -{ +class EventSpyExecutionListener extends AbstractExecutionListener { private final EventSpyDispatcher dispatcher; private final ExecutionListener delegate; - EventSpyExecutionListener( EventSpyDispatcher dispatcher, ExecutionListener delegate ) - { + EventSpyExecutionListener(EventSpyDispatcher dispatcher, ExecutionListener delegate) { this.dispatcher = dispatcher; this.delegate = delegate; } @Override - public void projectDiscoveryStarted( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.projectDiscoveryStarted( event ); + public void projectDiscoveryStarted(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.projectDiscoveryStarted(event); } @Override - public void sessionStarted( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.sessionStarted( event ); + public void sessionStarted(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.sessionStarted(event); } @Override - public void sessionEnded( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.sessionEnded( event ); + public void sessionEnded(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.sessionEnded(event); } @Override - public void projectSkipped( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.projectSkipped( event ); + public void projectSkipped(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.projectSkipped(event); } @Override - public void projectStarted( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.projectStarted( event ); + public void projectStarted(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.projectStarted(event); } @Override - public void projectSucceeded( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.projectSucceeded( event ); + public void projectSucceeded(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.projectSucceeded(event); } @Override - public void projectFailed( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.projectFailed( event ); + public void projectFailed(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.projectFailed(event); } @Override - public void forkStarted( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.forkStarted( event ); + public void forkStarted(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.forkStarted(event); } @Override - public void forkSucceeded( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.forkSucceeded( event ); + public void forkSucceeded(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.forkSucceeded(event); } @Override - public void forkFailed( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.forkFailed( event ); + public void forkFailed(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.forkFailed(event); } @Override - public void mojoSkipped( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.mojoSkipped( event ); + public void mojoSkipped(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.mojoSkipped(event); } @Override - public void mojoStarted( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.mojoStarted( event ); + public void mojoStarted(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.mojoStarted(event); } @Override - public void mojoSucceeded( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.mojoSucceeded( event ); + public void mojoSucceeded(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.mojoSucceeded(event); } @Override - public void mojoFailed( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.mojoFailed( event ); + public void mojoFailed(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.mojoFailed(event); } @Override - public void forkedProjectStarted( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.forkedProjectStarted( event ); + public void forkedProjectStarted(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.forkedProjectStarted(event); } @Override - public void forkedProjectSucceeded( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.forkedProjectSucceeded( event ); + public void forkedProjectSucceeded(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.forkedProjectSucceeded(event); } @Override - public void forkedProjectFailed( ExecutionEvent event ) - { - dispatcher.onEvent( event ); - delegate.forkedProjectFailed( event ); + public void forkedProjectFailed(ExecutionEvent event) { + dispatcher.onEvent(event); + delegate.forkedProjectFailed(event); } - } diff --git a/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyRepositoryListener.java b/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyRepositoryListener.java index aef3226ca1..fe2724c117 100644 --- a/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyRepositoryListener.java +++ b/maven-core/src/main/java/org/apache/maven/eventspy/internal/EventSpyRepositoryListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.eventspy.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.eventspy.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.eventspy.internal; import org.eclipse.aether.AbstractRepositoryListener; import org.eclipse.aether.RepositoryEvent; @@ -27,150 +26,127 @@ import org.eclipse.aether.RepositoryListener; * Forwards repository events to EventSpies. * @since 3.0.2 */ -class EventSpyRepositoryListener - extends AbstractRepositoryListener -{ +class EventSpyRepositoryListener extends AbstractRepositoryListener { private final EventSpyDispatcher dispatcher; private final RepositoryListener delegate; - EventSpyRepositoryListener( EventSpyDispatcher dispatcher, RepositoryListener delegate ) - { + EventSpyRepositoryListener(EventSpyDispatcher dispatcher, RepositoryListener delegate) { this.dispatcher = dispatcher; this.delegate = delegate; } @Override - public void artifactDeployed( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactDeployed( event ); + public void artifactDeployed(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactDeployed(event); } @Override - public void artifactDeploying( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactDeploying( event ); + public void artifactDeploying(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactDeploying(event); } @Override - public void artifactDescriptorInvalid( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactDescriptorInvalid( event ); + public void artifactDescriptorInvalid(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactDescriptorInvalid(event); } @Override - public void artifactDescriptorMissing( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactDescriptorMissing( event ); + public void artifactDescriptorMissing(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactDescriptorMissing(event); } @Override - public void artifactInstalled( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactInstalled( event ); + public void artifactInstalled(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactInstalled(event); } @Override - public void artifactInstalling( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactInstalling( event ); + public void artifactInstalling(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactInstalling(event); } @Override - public void artifactResolved( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactResolved( event ); + public void artifactResolved(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactResolved(event); } @Override - public void artifactResolving( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactResolving( event ); + public void artifactResolving(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactResolving(event); } @Override - public void metadataDeployed( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataDeployed( event ); + public void metadataDeployed(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataDeployed(event); } @Override - public void metadataDeploying( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataDeploying( event ); + public void metadataDeploying(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataDeploying(event); } @Override - public void metadataInstalled( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataInstalled( event ); + public void metadataInstalled(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataInstalled(event); } @Override - public void metadataInstalling( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataInstalling( event ); + public void metadataInstalling(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataInstalling(event); } @Override - public void metadataInvalid( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataInvalid( event ); + public void metadataInvalid(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataInvalid(event); } @Override - public void metadataResolved( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataResolved( event ); + public void metadataResolved(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataResolved(event); } @Override - public void metadataResolving( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataResolving( event ); + public void metadataResolving(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataResolving(event); } @Override - public void artifactDownloaded( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactDownloaded( event ); + public void artifactDownloaded(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactDownloaded(event); } @Override - public void artifactDownloading( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.artifactDownloading( event ); + public void artifactDownloading(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.artifactDownloading(event); } @Override - public void metadataDownloaded( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataDownloaded( event ); + public void metadataDownloaded(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataDownloaded(event); } @Override - public void metadataDownloading( RepositoryEvent event ) - { - dispatcher.onEvent( event ); - delegate.metadataDownloading( event ); + public void metadataDownloading(RepositoryEvent event) { + dispatcher.onEvent(event); + delegate.metadataDownloading(event); } - } diff --git a/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java b/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java index 3e21587965..4b52cb7327 100644 --- a/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java +++ b/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.exception; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.exception; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven.exception; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.exception; import java.io.IOException; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.model.building.ModelProblemUtils; @@ -90,248 +87,183 @@ Plugins: */ @Named @Singleton -public class DefaultExceptionHandler - implements ExceptionHandler -{ +public class DefaultExceptionHandler implements ExceptionHandler { - public ExceptionSummary handleException( Throwable exception ) - { - return handle( "", exception ); + public ExceptionSummary handleException(Throwable exception) { + return handle("", exception); } - private ExceptionSummary handle( String message, Throwable exception ) - { - String reference = getReference( exception ); + private ExceptionSummary handle(String message, Throwable exception) { + String reference = getReference(exception); List children = null; - if ( exception instanceof ProjectBuildingException ) - { - List results = ( (ProjectBuildingException) exception ).getResults(); + if (exception instanceof ProjectBuildingException) { + List results = ((ProjectBuildingException) exception).getResults(); children = new ArrayList<>(); - for ( ProjectBuildingResult result : results ) - { - ExceptionSummary child = handle( result ); - if ( child != null ) - { - children.add( child ); + for (ProjectBuildingResult result : results) { + ExceptionSummary child = handle(result); + if (child != null) { + children.add(child); } } - message = "The build could not read " + children.size() + " project" + ( children.size() == 1 ? "" : "s" ); - } - else - { - message = getMessage( message, exception ); + message = "The build could not read " + children.size() + " project" + (children.size() == 1 ? "" : "s"); + } else { + message = getMessage(message, exception); } - return new ExceptionSummary( exception, message, reference, children ); + return new ExceptionSummary(exception, message, reference, children); } - private ExceptionSummary handle( ProjectBuildingResult result ) - { + private ExceptionSummary handle(ProjectBuildingResult result) { List children = new ArrayList<>(); - for ( ModelProblem problem : result.getProblems() ) - { - ExceptionSummary child = handle( problem, result.getProjectId() ); - if ( child != null ) - { - children.add( child ); + for (ModelProblem problem : result.getProblems()) { + ExceptionSummary child = handle(problem, result.getProjectId()); + if (child != null) { + children.add(child); } } - if ( children.isEmpty() ) - { + if (children.isEmpty()) { return null; } String message = System.lineSeparator() - + "The project " + ( result.getProjectId().isEmpty() ? "" : result.getProjectId() + " " ) - + "(" + result.getPomFile() + ") has " - + children.size() + " error" + ( children.size() == 1 ? "" : "s" ); + + "The project " + (result.getProjectId().isEmpty() ? "" : result.getProjectId() + " ") + + "(" + result.getPomFile() + ") has " + + children.size() + " error" + (children.size() == 1 ? "" : "s"); - return new ExceptionSummary( null, message, null, children ); + return new ExceptionSummary(null, message, null, children); } - private ExceptionSummary handle( ModelProblem problem, String projectId ) - { - if ( ModelProblem.Severity.ERROR.compareTo( problem.getSeverity() ) >= 0 ) - { + private ExceptionSummary handle(ModelProblem problem, String projectId) { + if (ModelProblem.Severity.ERROR.compareTo(problem.getSeverity()) >= 0) { String message = problem.getMessage(); - String location = ModelProblemUtils.formatLocation( problem, projectId ); + String location = ModelProblemUtils.formatLocation(problem, projectId); - if ( !location.isEmpty() ) - { + if (!location.isEmpty()) { message += " @ " + location; } - return handle( message, problem.getException() ); - } - else - { + return handle(message, problem.getException()); + } else { return null; } } - private String getReference( Throwable exception ) - { + private String getReference(Throwable exception) { String reference = ""; - if ( exception != null ) - { - if ( exception instanceof MojoExecutionException ) - { + if (exception != null) { + if (exception instanceof MojoExecutionException) { reference = MojoExecutionException.class.getSimpleName(); Throwable cause = exception.getCause(); - if ( cause instanceof IOException ) - { + if (cause instanceof IOException) { cause = cause.getCause(); - if ( cause instanceof ConnectException ) - { + if (cause instanceof ConnectException) { reference = ConnectException.class.getSimpleName(); } } - } - else if ( exception instanceof MojoFailureException ) - { + } else if (exception instanceof MojoFailureException) { reference = MojoFailureException.class.getSimpleName(); - } - else if ( exception instanceof LinkageError ) - { + } else if (exception instanceof LinkageError) { reference = LinkageError.class.getSimpleName(); - } - else if ( exception instanceof PluginExecutionException ) - { + } else if (exception instanceof PluginExecutionException) { Throwable cause = exception.getCause(); - if ( cause instanceof PluginContainerException ) - { + if (cause instanceof PluginContainerException) { Throwable cause2 = cause.getCause(); - if ( cause2 instanceof NoClassDefFoundError ) - { + if (cause2 instanceof NoClassDefFoundError) { String message = cause2.getMessage(); - if ( message != null && message.contains( "org/sonatype/aether/" ) ) - { + if (message != null && message.contains("org/sonatype/aether/")) { reference = "AetherClassNotFound"; } } } - if ( StringUtils.isEmpty( reference ) ) - { - reference = getReference( cause ); + if (StringUtils.isEmpty(reference)) { + reference = getReference(cause); } - if ( StringUtils.isEmpty( reference ) ) - { + if (StringUtils.isEmpty(reference)) { reference = exception.getClass().getSimpleName(); } - } - else if ( exception instanceof LifecycleExecutionException ) - { - reference = getReference( exception.getCause() ); - } - else if ( isNoteworthyException( exception ) ) - { + } else if (exception instanceof LifecycleExecutionException) { + reference = getReference(exception.getCause()); + } else if (isNoteworthyException(exception)) { reference = exception.getClass().getSimpleName(); } } - if ( StringUtils.isNotEmpty( reference ) && !reference.startsWith( "http:" ) ) - { + if (StringUtils.isNotEmpty(reference) && !reference.startsWith("http:")) { reference = "http://cwiki.apache.org/confluence/display/MAVEN/" + reference; } return reference; } - private boolean isNoteworthyException( Throwable exception ) - { - if ( exception == null ) - { + private boolean isNoteworthyException(Throwable exception) { + if (exception == null) { return false; - } - else if ( exception instanceof Error ) - { + } else if (exception instanceof Error) { return true; - } - else if ( exception instanceof RuntimeException ) - { + } else if (exception instanceof RuntimeException) { return false; - } - else - { - return !exception.getClass().getName().startsWith( "java" ); + } else { + return !exception.getClass().getName().startsWith("java"); } } - private String getMessage( String message, Throwable exception ) - { - String fullMessage = ( message != null ) ? message : ""; + private String getMessage(String message, Throwable exception) { + String fullMessage = (message != null) ? message : ""; - for ( Throwable t = exception; t != null; t = t.getCause() ) - { + for (Throwable t = exception; t != null; t = t.getCause()) { String exceptionMessage = t.getMessage(); - if ( t instanceof AbstractMojoExecutionException ) - { - String longMessage = ( (AbstractMojoExecutionException) t ).getLongMessage(); - if ( StringUtils.isNotEmpty( longMessage ) ) - { - if ( StringUtils.isEmpty( exceptionMessage ) || longMessage.contains( exceptionMessage ) ) - { + if (t instanceof AbstractMojoExecutionException) { + String longMessage = ((AbstractMojoExecutionException) t).getLongMessage(); + if (StringUtils.isNotEmpty(longMessage)) { + if (StringUtils.isEmpty(exceptionMessage) || longMessage.contains(exceptionMessage)) { exceptionMessage = longMessage; - } - else if ( !exceptionMessage.contains( longMessage ) ) - { - exceptionMessage = join( exceptionMessage, System.lineSeparator() + longMessage ); + } else if (!exceptionMessage.contains(longMessage)) { + exceptionMessage = join(exceptionMessage, System.lineSeparator() + longMessage); } } } - if ( StringUtils.isEmpty( exceptionMessage ) ) - { + if (StringUtils.isEmpty(exceptionMessage)) { exceptionMessage = t.getClass().getSimpleName(); } - if ( t instanceof UnknownHostException && !fullMessage.contains( "host" ) ) - { - fullMessage = join( fullMessage, "Unknown host " + exceptionMessage ); - } - else if ( !fullMessage.contains( exceptionMessage ) ) - { - fullMessage = join( fullMessage, exceptionMessage ); + if (t instanceof UnknownHostException && !fullMessage.contains("host")) { + fullMessage = join(fullMessage, "Unknown host " + exceptionMessage); + } else if (!fullMessage.contains(exceptionMessage)) { + fullMessage = join(fullMessage, exceptionMessage); } } return fullMessage.trim(); } - private String join( String message1, String message2 ) - { + private String join(String message1, String message2) { String message = ""; - if ( StringUtils.isNotEmpty( message1 ) ) - { + if (StringUtils.isNotEmpty(message1)) { message = message1.trim(); } - if ( StringUtils.isNotEmpty( message2 ) ) - { - if ( StringUtils.isNotEmpty( message ) ) - { - if ( message.endsWith( "." ) || message.endsWith( "!" ) || message.endsWith( ":" ) ) - { + if (StringUtils.isNotEmpty(message2)) { + if (StringUtils.isNotEmpty(message)) { + if (message.endsWith(".") || message.endsWith("!") || message.endsWith(":")) { message += " "; - } - else - { + } else { message += ": "; } } @@ -341,5 +273,4 @@ public class DefaultExceptionHandler return message; } - } diff --git a/maven-core/src/main/java/org/apache/maven/exception/ExceptionHandler.java b/maven-core/src/main/java/org/apache/maven/exception/ExceptionHandler.java index 47865f679b..b68f378553 100644 --- a/maven-core/src/main/java/org/apache/maven/exception/ExceptionHandler.java +++ b/maven-core/src/main/java/org/apache/maven/exception/ExceptionHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.exception; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.exception; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.exception; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.exception; /** * Transform an exception into useful end-user message. * * @since 3.0-alpha-3 */ -public interface ExceptionHandler -{ - ExceptionSummary handleException( Throwable e ); +public interface ExceptionHandler { + ExceptionSummary handleException(Throwable e); } diff --git a/maven-core/src/main/java/org/apache/maven/exception/ExceptionSummary.java b/maven-core/src/main/java/org/apache/maven/exception/ExceptionSummary.java index b72bab601e..7473e380a2 100644 --- a/maven-core/src/main/java/org/apache/maven/exception/ExceptionSummary.java +++ b/maven-core/src/main/java/org/apache/maven/exception/ExceptionSummary.java @@ -1,5 +1,3 @@ -package org.apache.maven.exception; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.exception; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.exception; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.exception; import java.util.Collections; import java.util.List; @@ -32,8 +31,7 @@ import java.util.List; *
  • child exception summaries.
  • * */ -public class ExceptionSummary -{ +public class ExceptionSummary { private Throwable exception; @@ -43,40 +41,30 @@ public class ExceptionSummary private List children; - public ExceptionSummary( Throwable exception, String message, String reference ) - { - this( exception, message, reference, null ); + public ExceptionSummary(Throwable exception, String message, String reference) { + this(exception, message, reference, null); } - public ExceptionSummary( Throwable exception, String message, String reference, List children ) - { + public ExceptionSummary(Throwable exception, String message, String reference, List children) { this.exception = exception; - this.message = ( message != null ) ? message : ""; - this.reference = ( reference != null ) ? reference : ""; - this.children = ( children != null ) - ? Collections.unmodifiableList( children ) - : Collections.emptyList(); - + this.message = (message != null) ? message : ""; + this.reference = (reference != null) ? reference : ""; + this.children = (children != null) ? Collections.unmodifiableList(children) : Collections.emptyList(); } - public Throwable getException() - { + public Throwable getException() { return exception; } - public String getMessage() - { + public String getMessage() { return message; } - public String getReference() - { + public String getReference() { return reference; } - public List getChildren() - { + public List getChildren() { return children; } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/AbstractExecutionListener.java b/maven-core/src/main/java/org/apache/maven/execution/AbstractExecutionListener.java index 89665007ff..986c08e344 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/AbstractExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/execution/AbstractExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,99 +16,80 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; /** * Provides a skeleton implementation for execution listeners. The methods of this class are empty. * * @author Benjamin Bentmann */ -public class AbstractExecutionListener - implements ExecutionListener -{ +public class AbstractExecutionListener implements ExecutionListener { - public void projectDiscoveryStarted( ExecutionEvent event ) - { + public void projectDiscoveryStarted(ExecutionEvent event) { // default does nothing } - public void sessionStarted( ExecutionEvent event ) - { + public void sessionStarted(ExecutionEvent event) { // default does nothing } - public void sessionEnded( ExecutionEvent event ) - { + public void sessionEnded(ExecutionEvent event) { // default does nothing } - public void projectSkipped( ExecutionEvent event ) - { + public void projectSkipped(ExecutionEvent event) { // default does nothing } - public void projectStarted( ExecutionEvent event ) - { + public void projectStarted(ExecutionEvent event) { // default does nothing } - public void projectSucceeded( ExecutionEvent event ) - { + public void projectSucceeded(ExecutionEvent event) { // default does nothing } - public void projectFailed( ExecutionEvent event ) - { + public void projectFailed(ExecutionEvent event) { // default does nothing } - public void forkStarted( ExecutionEvent event ) - { + public void forkStarted(ExecutionEvent event) { // default does nothing } - public void forkSucceeded( ExecutionEvent event ) - { + public void forkSucceeded(ExecutionEvent event) { // default does nothing } - public void forkFailed( ExecutionEvent event ) - { + public void forkFailed(ExecutionEvent event) { // default does nothing } - public void mojoSkipped( ExecutionEvent event ) - { + public void mojoSkipped(ExecutionEvent event) { // default does nothing } - public void mojoStarted( ExecutionEvent event ) - { + public void mojoStarted(ExecutionEvent event) { // default does nothing } - public void mojoSucceeded( ExecutionEvent event ) - { + public void mojoSucceeded(ExecutionEvent event) { // default does nothing } - public void mojoFailed( ExecutionEvent event ) - { + public void mojoFailed(ExecutionEvent event) { // default does nothing } - public void forkedProjectStarted( ExecutionEvent event ) - { + public void forkedProjectStarted(ExecutionEvent event) { // default does nothing } - public void forkedProjectSucceeded( ExecutionEvent event ) - { + public void forkedProjectSucceeded(ExecutionEvent event) { // default does nothing } - public void forkedProjectFailed( ExecutionEvent event ) - { + public void forkedProjectFailed(ExecutionEvent event) { // default does nothing } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ActivationSettings.java b/maven-core/src/main/java/org/apache/maven/execution/ActivationSettings.java index 4e8f8a2d1e..a56b1f72f3 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ActivationSettings.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ActivationSettings.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,16 +16,16 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; /** * Describes whether a target should be activated or not, and if that is required or optional. */ -enum ActivationSettings -{ - ACTIVATION_OPTIONAL( true, true ), - ACTIVATION_REQUIRED( true, false ), - DEACTIVATION_OPTIONAL( false, true ), - DEACTIVATION_REQUIRED( false, false ); +enum ActivationSettings { + ACTIVATION_OPTIONAL(true, true), + ACTIVATION_REQUIRED(true, false), + DEACTIVATION_OPTIONAL(false, true), + DEACTIVATION_REQUIRED(false, false); /** * Should the target be active? @@ -38,20 +36,15 @@ enum ActivationSettings */ final boolean optional; - ActivationSettings( final boolean active, final boolean optional ) - { + ActivationSettings(final boolean active, final boolean optional) { this.active = active; this.optional = optional; } - static ActivationSettings of( final boolean active, final boolean optional ) - { - if ( optional ) - { + static ActivationSettings of(final boolean active, final boolean optional) { + if (optional) { return active ? ACTIVATION_OPTIONAL : DEACTIVATION_OPTIONAL; - } - else - { + } else { return active ? ACTIVATION_REQUIRED : DEACTIVATION_REQUIRED; } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildFailure.java b/maven-core/src/main/java/org/apache/maven/execution/BuildFailure.java index bf8f62baff..f8a4bf56cc 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildFailure.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildFailure.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.project.MavenProject; @@ -26,9 +25,7 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -public class BuildFailure - extends BuildSummary -{ +public class BuildFailure extends BuildSummary { /** * The cause of the build failure. @@ -42,9 +39,8 @@ public class BuildFailure * @param time The build time of the project in milliseconds. * @param cause The cause of the build failure, may be {@code null}. */ - public BuildFailure( MavenProject project, long time, Throwable cause ) - { - super( project, time ); + public BuildFailure(MavenProject project, long time, Throwable cause) { + super(project, time); this.cause = cause; } @@ -53,9 +49,7 @@ public class BuildFailure * * @return The cause of the build failure or {@code null} if unknown. */ - public Throwable getCause() - { + public Throwable getCause() { return cause; } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionAnalyzer.java b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionAnalyzer.java index fa3db8a343..0ce454a276 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionAnalyzer.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionAnalyzer.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.Optional; @@ -25,12 +24,11 @@ import java.util.Optional; * Instances of this class are responsible for determining whether it makes sense to "resume" a build (i.e., using * the {@code --resume} flag. */ -public interface BuildResumptionAnalyzer -{ +public interface BuildResumptionAnalyzer { /** * Construct an instance of {@link BuildResumptionData} based on the outcome of the current Maven build. * @param result Outcome of the current Maven build. * @return A {@link BuildResumptionData} instance or {@link Optional#empty()} if resuming the build is not possible. */ - Optional determineBuildResumptionData( MavenExecutionResult result ); + Optional determineBuildResumptionData(MavenExecutionResult result); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionData.java b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionData.java index 4aa5e25695..d46adf2a7d 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionData.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionData.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,21 +16,20 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.List; /** * This class holds the information required to enable resuming a Maven build with {@code --resume}. */ -public class BuildResumptionData -{ +public class BuildResumptionData { /** * The list of projects that remain to be built. */ private final List remainingProjects; - public BuildResumptionData ( final List remainingProjects ) - { + public BuildResumptionData(final List remainingProjects) { this.remainingProjects = remainingProjects; } @@ -40,9 +37,7 @@ public class BuildResumptionData * Returns the projects that still need to be built when resuming. * @return A list containing the group and artifact id of the projects. */ - public List getRemainingProjects() - { + public List getRemainingProjects() { return this.remainingProjects; } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionDataRepository.java b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionDataRepository.java index 36453f662a..fa09f1f553 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionDataRepository.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionDataRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.project.MavenProject; @@ -26,8 +25,7 @@ import org.apache.maven.project.MavenProject; * builds of the same project, that have the -r command-line flag, skip successfully built projects during earlier * invocations of Maven. */ -public interface BuildResumptionDataRepository -{ +public interface BuildResumptionDataRepository { /** * Persists any data needed to resume the build at a later point in time, using a new Maven invocation. This method * may also decide it is not needed or meaningful to persist such data, and return false to indicate @@ -37,7 +35,7 @@ public interface BuildResumptionDataRepository * @param buildResumptionData Information needed to resume the build. * @throws BuildResumptionPersistenceException When an error occurs while persisting data. */ - void persistResumptionData( MavenProject rootProject, BuildResumptionData buildResumptionData ) + void persistResumptionData(MavenProject rootProject, BuildResumptionData buildResumptionData) throws BuildResumptionPersistenceException; /** @@ -45,12 +43,11 @@ public interface BuildResumptionDataRepository * @param request The execution request that will be enriched. * @param rootProject The root project that is being built. */ - void applyResumptionData( MavenExecutionRequest request, MavenProject rootProject ); + void applyResumptionData(MavenExecutionRequest request, MavenProject rootProject); /** * Removes previously stored resumption data. * @param rootProject The root project that is being built. */ - void removeResumptionData( MavenProject rootProject ); - + void removeResumptionData(MavenProject rootProject); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionPersistenceException.java b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionPersistenceException.java index 1f9e8026a8..2b5566ea4f 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionPersistenceException.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildResumptionPersistenceException.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,14 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; /** * This exception will be thrown when something fails while persisting build resumption data. * @see BuildResumptionDataRepository#persistResumptionData */ -public class BuildResumptionPersistenceException extends Exception -{ - public BuildResumptionPersistenceException( String message, Throwable cause ) - { - super( message, cause ); +public class BuildResumptionPersistenceException extends Exception { + public BuildResumptionPersistenceException(String message, Throwable cause) { + super(message, cause); } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildSuccess.java b/maven-core/src/main/java/org/apache/maven/execution/BuildSuccess.java index 3d0e8bd7b2..536d8fabed 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildSuccess.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildSuccess.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.project.MavenProject; @@ -26,9 +25,7 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -public class BuildSuccess - extends BuildSummary -{ +public class BuildSuccess extends BuildSummary { /** * Creates a new build summary for the specified project. @@ -36,9 +33,7 @@ public class BuildSuccess * @param project The project being summarized, must not be {@code null}. * @param time The build time of the project in milliseconds. */ - public BuildSuccess( MavenProject project, long time ) - { - super( project, time ); + public BuildSuccess(MavenProject project, long time) { + super(project, time); } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/BuildSummary.java b/maven-core/src/main/java/org/apache/maven/execution/BuildSummary.java index 79599b5db8..26cb661be7 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/BuildSummary.java +++ b/maven-core/src/main/java/org/apache/maven/execution/BuildSummary.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.Objects; - import org.apache.maven.project.MavenProject; /** @@ -28,8 +26,7 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -public abstract class BuildSummary -{ +public abstract class BuildSummary { /** * The project being summarized. @@ -47,9 +44,8 @@ public abstract class BuildSummary * @param project The project being summarized, must not be {@code null}. * @param time The build time of the project in milliseconds. */ - protected BuildSummary( MavenProject project, long time ) - { - this.project = Objects.requireNonNull( project, "project cannot be null" ); + protected BuildSummary(MavenProject project, long time) { + this.project = Objects.requireNonNull(project, "project cannot be null"); // TODO Validate for < 0? this.time = time; } @@ -59,8 +55,7 @@ public abstract class BuildSummary * * @return The project being summarized, never {@code null}. */ - public MavenProject getProject() - { + public MavenProject getProject() { return project; } @@ -69,9 +64,7 @@ public abstract class BuildSummary * * @return The build time of the project in milliseconds. */ - public long getTime() - { + public long getTime() { return time; } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzer.java b/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzer.java index d8d1183457..44e27abb54 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzer.java +++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzer.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,57 +16,51 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; -import org.apache.maven.project.MavenProject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Named; -import javax.inject.Singleton; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.project.MavenProject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Default implementation of {@link BuildResumptionAnalyzer}. */ @Named @Singleton -public class DefaultBuildResumptionAnalyzer implements BuildResumptionAnalyzer -{ - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultBuildResumptionAnalyzer.class ); +public class DefaultBuildResumptionAnalyzer implements BuildResumptionAnalyzer { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultBuildResumptionAnalyzer.class); @Override - public Optional determineBuildResumptionData( final MavenExecutionResult result ) - { - if ( !result.hasExceptions() ) - { + public Optional determineBuildResumptionData(final MavenExecutionResult result) { + if (!result.hasExceptions()) { return Optional.empty(); } List sortedProjects = result.getTopologicallySortedProjects(); - boolean hasNoSuccess = sortedProjects.stream() - .noneMatch( project -> result.getBuildSummary( project ) instanceof BuildSuccess ); + boolean hasNoSuccess = + sortedProjects.stream().noneMatch(project -> result.getBuildSummary(project) instanceof BuildSuccess); - if ( hasNoSuccess ) - { + if (hasNoSuccess) { return Optional.empty(); } List remainingProjects = sortedProjects.stream() - .filter( project -> result.getBuildSummary( project ) == null - || result.getBuildSummary( project ) instanceof BuildFailure ) - .map( project -> project.getGroupId() + ":" + project.getArtifactId() ) - .collect( Collectors.toList() ); + .filter(project -> result.getBuildSummary(project) == null + || result.getBuildSummary(project) instanceof BuildFailure) + .map(project -> project.getGroupId() + ":" + project.getArtifactId()) + .collect(Collectors.toList()); - if ( remainingProjects.isEmpty() ) - { - LOGGER.info( "No remaining projects found, resuming the build would not make sense." ); + if (remainingProjects.isEmpty()) { + LOGGER.info("No remaining projects found, resuming the build would not make sense."); return Optional.empty(); } - return Optional.of( new BuildResumptionData( remainingProjects ) ); + return Optional.of(new BuildResumptionData(remainingProjects)); } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionDataRepository.java b/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionDataRepository.java index 73a0c1aeb0..ea3fa84e25 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionDataRepository.java +++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionDataRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,8 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.project.MavenProject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Named; -import javax.inject.Singleton; import java.io.IOException; import java.io.Reader; import java.io.Writer; @@ -34,6 +26,12 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import java.util.stream.Stream; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.commons.lang3.StringUtils; +import org.apache.maven.project.MavenProject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This implementation of {@link BuildResumptionDataRepository} persists information in a properties file. The file is @@ -41,99 +39,80 @@ import java.util.stream.Stream; */ @Named @Singleton -public class DefaultBuildResumptionDataRepository implements BuildResumptionDataRepository -{ +public class DefaultBuildResumptionDataRepository implements BuildResumptionDataRepository { private static final String RESUME_PROPERTIES_FILENAME = "resume.properties"; private static final String REMAINING_PROJECTS = "remainingProjects"; private static final String PROPERTY_DELIMITER = ", "; - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultBuildResumptionDataRepository.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultBuildResumptionDataRepository.class); @Override - public void persistResumptionData( MavenProject rootProject, BuildResumptionData buildResumptionData ) - throws BuildResumptionPersistenceException - { - Properties properties = convertToProperties( buildResumptionData ); + public void persistResumptionData(MavenProject rootProject, BuildResumptionData buildResumptionData) + throws BuildResumptionPersistenceException { + Properties properties = convertToProperties(buildResumptionData); - Path resumeProperties = Paths.get( rootProject.getBuild().getDirectory(), RESUME_PROPERTIES_FILENAME ); - try - { - Files.createDirectories( resumeProperties.getParent() ); - try ( Writer writer = Files.newBufferedWriter( resumeProperties ) ) - { - properties.store( writer, null ); + Path resumeProperties = Paths.get(rootProject.getBuild().getDirectory(), RESUME_PROPERTIES_FILENAME); + try { + Files.createDirectories(resumeProperties.getParent()); + try (Writer writer = Files.newBufferedWriter(resumeProperties)) { + properties.store(writer, null); } - } - catch ( IOException e ) - { + } catch (IOException e) { String message = "Could not create " + RESUME_PROPERTIES_FILENAME + " file."; - throw new BuildResumptionPersistenceException( message, e ); + throw new BuildResumptionPersistenceException(message, e); } } - private Properties convertToProperties( final BuildResumptionData buildResumptionData ) - { + private Properties convertToProperties(final BuildResumptionData buildResumptionData) { Properties properties = new Properties(); - String value = String.join( PROPERTY_DELIMITER, buildResumptionData.getRemainingProjects() ); - properties.setProperty( REMAINING_PROJECTS, value ); + String value = String.join(PROPERTY_DELIMITER, buildResumptionData.getRemainingProjects()); + properties.setProperty(REMAINING_PROJECTS, value); return properties; } @Override - public void applyResumptionData( MavenExecutionRequest request, MavenProject rootProject ) - { - Properties properties = loadResumptionFile( Paths.get( rootProject.getBuild().getDirectory() ) ); - applyResumptionProperties( request, properties ); + public void applyResumptionData(MavenExecutionRequest request, MavenProject rootProject) { + Properties properties = + loadResumptionFile(Paths.get(rootProject.getBuild().getDirectory())); + applyResumptionProperties(request, properties); } @Override - public void removeResumptionData( MavenProject rootProject ) - { - Path resumeProperties = Paths.get( rootProject.getBuild().getDirectory(), RESUME_PROPERTIES_FILENAME ); - try - { - Files.deleteIfExists( resumeProperties ); - } - catch ( IOException e ) - { - LOGGER.warn( "Could not delete {} file. ", RESUME_PROPERTIES_FILENAME, e ); + public void removeResumptionData(MavenProject rootProject) { + Path resumeProperties = Paths.get(rootProject.getBuild().getDirectory(), RESUME_PROPERTIES_FILENAME); + try { + Files.deleteIfExists(resumeProperties); + } catch (IOException e) { + LOGGER.warn("Could not delete {} file. ", RESUME_PROPERTIES_FILENAME, e); } } - private Properties loadResumptionFile( Path rootBuildDirectory ) - { + private Properties loadResumptionFile(Path rootBuildDirectory) { Properties properties = new Properties(); - Path path = rootBuildDirectory.resolve( RESUME_PROPERTIES_FILENAME ); - if ( !Files.exists( path ) ) - { - LOGGER.warn( "The {} file does not exist. The --resume / -r feature will not work.", path ); + Path path = rootBuildDirectory.resolve(RESUME_PROPERTIES_FILENAME); + if (!Files.exists(path)) { + LOGGER.warn("The {} file does not exist. The --resume / -r feature will not work.", path); return properties; } - try ( Reader reader = Files.newBufferedReader( path ) ) - { - properties.load( reader ); - } - catch ( IOException e ) - { - LOGGER.warn( "Unable to read {}. The --resume / -r feature will not work.", path ); + try (Reader reader = Files.newBufferedReader(path)) { + properties.load(reader); + } catch (IOException e) { + LOGGER.warn("Unable to read {}. The --resume / -r feature will not work.", path); } return properties; } // This method is made package-private for testing purposes - void applyResumptionProperties( MavenExecutionRequest request, Properties properties ) - { - if ( properties.containsKey( REMAINING_PROJECTS ) - && StringUtils.isEmpty( request.getResumeFrom() ) ) - { - String propertyValue = properties.getProperty( REMAINING_PROJECTS ); - Stream.of( propertyValue.split( PROPERTY_DELIMITER ) ) - .filter( StringUtils::isNotEmpty ) - .forEach( request.getProjectActivation()::activateOptionalProject ); - LOGGER.info( "Resuming from {} due to the --resume / -r feature.", propertyValue ); + void applyResumptionProperties(MavenExecutionRequest request, Properties properties) { + if (properties.containsKey(REMAINING_PROJECTS) && StringUtils.isEmpty(request.getResumeFrom())) { + String propertyValue = properties.getProperty(REMAINING_PROJECTS); + Stream.of(propertyValue.split(PROPERTY_DELIMITER)) + .filter(StringUtils::isNotEmpty) + .forEach(request.getProjectActivation()::activateOptionalProject); + LOGGER.info("Resuming from {} due to the --resume / -r feature.", propertyValue); } } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java index b559fb9904..2f4735990f 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.io.File; import java.util.ArrayList; @@ -27,7 +26,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.eventspy.internal.EventSpyDispatcher; import org.apache.maven.model.Profile; @@ -46,9 +44,7 @@ import org.eclipse.aether.transfer.TransferListener; /** * @author Jason van Zyl */ -public class DefaultMavenExecutionRequest - implements MavenExecutionRequest -{ +public class DefaultMavenExecutionRequest implements MavenExecutionRequest { private RepositoryCache repositoryCache = new DefaultRepositoryCache(); @@ -160,59 +156,53 @@ public class DefaultMavenExecutionRequest private Map data; - public DefaultMavenExecutionRequest() - { - } + public DefaultMavenExecutionRequest() {} - public static MavenExecutionRequest copy( MavenExecutionRequest original ) - { + public static MavenExecutionRequest copy(MavenExecutionRequest original) { DefaultMavenExecutionRequest copy = new DefaultMavenExecutionRequest(); - copy.setLocalRepository( original.getLocalRepository() ); - copy.setLocalRepositoryPath( original.getLocalRepositoryPath() ); - copy.setOffline( original.isOffline() ); - copy.setInteractiveMode( original.isInteractiveMode() ); - copy.setCacheNotFound( original.isCacheNotFound() ); - copy.setCacheTransferError( original.isCacheTransferError() ); - copy.setProxies( original.getProxies() ); - copy.setServers( original.getServers() ); - copy.setMirrors( original.getMirrors() ); - copy.setProfiles( original.getProfiles() ); - copy.setPluginGroups( original.getPluginGroups() ); - copy.setProjectPresent( original.isProjectPresent() ); - copy.setUserSettingsFile( original.getUserSettingsFile() ); - copy.setGlobalSettingsFile( original.getGlobalSettingsFile() ); - copy.setUserToolchainsFile( original.getUserToolchainsFile() ); - copy.setGlobalToolchainsFile( original.getGlobalToolchainsFile() ); - copy.setBaseDirectory( ( original.getBaseDirectory() != null ) ? new File( original.getBaseDirectory() ) - : null ); - copy.setGoals( original.getGoals() ); - copy.setRecursive( original.isRecursive() ); - copy.setPom( original.getPom() ); - copy.setSystemProperties( original.getSystemProperties() ); - copy.setUserProperties( original.getUserProperties() ); - copy.setShowErrors( original.isShowErrors() ); - copy.setActiveProfiles( original.getActiveProfiles() ); - copy.setInactiveProfiles( original.getInactiveProfiles() ); - copy.setTransferListener( original.getTransferListener() ); - copy.setLoggingLevel( original.getLoggingLevel() ); - copy.setGlobalChecksumPolicy( original.getGlobalChecksumPolicy() ); - copy.setUpdateSnapshots( original.isUpdateSnapshots() ); - copy.setRemoteRepositories( original.getRemoteRepositories() ); - copy.setPluginArtifactRepositories( original.getPluginArtifactRepositories() ); - copy.setRepositoryCache( original.getRepositoryCache() ); - copy.setWorkspaceReader( original.getWorkspaceReader() ); - copy.setNoSnapshotUpdates( original.isNoSnapshotUpdates() ); - copy.setExecutionListener( original.getExecutionListener() ); - copy.setUseLegacyLocalRepository( original.isUseLegacyLocalRepository() ); - copy.setBuilderId( original.getBuilderId() ); + copy.setLocalRepository(original.getLocalRepository()); + copy.setLocalRepositoryPath(original.getLocalRepositoryPath()); + copy.setOffline(original.isOffline()); + copy.setInteractiveMode(original.isInteractiveMode()); + copy.setCacheNotFound(original.isCacheNotFound()); + copy.setCacheTransferError(original.isCacheTransferError()); + copy.setProxies(original.getProxies()); + copy.setServers(original.getServers()); + copy.setMirrors(original.getMirrors()); + copy.setProfiles(original.getProfiles()); + copy.setPluginGroups(original.getPluginGroups()); + copy.setProjectPresent(original.isProjectPresent()); + copy.setUserSettingsFile(original.getUserSettingsFile()); + copy.setGlobalSettingsFile(original.getGlobalSettingsFile()); + copy.setUserToolchainsFile(original.getUserToolchainsFile()); + copy.setGlobalToolchainsFile(original.getGlobalToolchainsFile()); + copy.setBaseDirectory((original.getBaseDirectory() != null) ? new File(original.getBaseDirectory()) : null); + copy.setGoals(original.getGoals()); + copy.setRecursive(original.isRecursive()); + copy.setPom(original.getPom()); + copy.setSystemProperties(original.getSystemProperties()); + copy.setUserProperties(original.getUserProperties()); + copy.setShowErrors(original.isShowErrors()); + copy.setActiveProfiles(original.getActiveProfiles()); + copy.setInactiveProfiles(original.getInactiveProfiles()); + copy.setTransferListener(original.getTransferListener()); + copy.setLoggingLevel(original.getLoggingLevel()); + copy.setGlobalChecksumPolicy(original.getGlobalChecksumPolicy()); + copy.setUpdateSnapshots(original.isUpdateSnapshots()); + copy.setRemoteRepositories(original.getRemoteRepositories()); + copy.setPluginArtifactRepositories(original.getPluginArtifactRepositories()); + copy.setRepositoryCache(original.getRepositoryCache()); + copy.setWorkspaceReader(original.getWorkspaceReader()); + copy.setNoSnapshotUpdates(original.isNoSnapshotUpdates()); + copy.setExecutionListener(original.getExecutionListener()); + copy.setUseLegacyLocalRepository(original.isUseLegacyLocalRepository()); + copy.setBuilderId(original.getBuilderId()); return copy; } @Override - public String getBaseDirectory() - { - if ( basedir == null ) - { + public String getBaseDirectory() { + if (basedir == null) { return null; } @@ -220,32 +210,26 @@ public class DefaultMavenExecutionRequest } @Override - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } @Override - public File getLocalRepositoryPath() - { + public File getLocalRepositoryPath() { return localRepositoryPath; } @Override - public List getGoals() - { - if ( goals == null ) - { + public List getGoals() { + if (goals == null) { goals = new ArrayList<>(); } return goals; } @Override - public Properties getSystemProperties() - { - if ( systemProperties == null ) - { + public Properties getSystemProperties() { + if (systemProperties == null) { systemProperties = new Properties(); } @@ -253,10 +237,8 @@ public class DefaultMavenExecutionRequest } @Override - public Properties getUserProperties() - { - if ( userProperties == null ) - { + public Properties getUserProperties() { + if (userProperties == null) { userProperties = new Properties(); } @@ -264,108 +246,88 @@ public class DefaultMavenExecutionRequest } @Override - public File getPom() - { + public File getPom() { return pom; } @Override - public String getReactorFailureBehavior() - { + public String getReactorFailureBehavior() { return reactorFailureBehavior; } @Override - public List getSelectedProjects() - { + public List getSelectedProjects() { return this.projectActivation.getSelectedProjects(); } @Override - public List getExcludedProjects() - { + public List getExcludedProjects() { return this.projectActivation.getExcludedProjects(); } @Override - public boolean isResume() - { + public boolean isResume() { return resume; } @Override - public String getResumeFrom() - { + public String getResumeFrom() { return resumeFrom; } @Override - public String getMakeBehavior() - { + public String getMakeBehavior() { return makeBehavior; } @Override - public Date getStartTime() - { + public Date getStartTime() { return startTime; } @Override - public boolean isShowErrors() - { + public boolean isShowErrors() { return showErrors; } @Override - public boolean isInteractiveMode() - { + public boolean isInteractiveMode() { return interactiveMode; } @Override - public MavenExecutionRequest setActiveProfiles( List activeProfiles ) - { - if ( activeProfiles != null ) - { - this.profileActivation.overwriteActiveProfiles( activeProfiles ); + public MavenExecutionRequest setActiveProfiles(List activeProfiles) { + if (activeProfiles != null) { + this.profileActivation.overwriteActiveProfiles(activeProfiles); } return this; } @Override - public MavenExecutionRequest setInactiveProfiles( List inactiveProfiles ) - { - if ( inactiveProfiles != null ) - { - this.profileActivation.overwriteInactiveProfiles( inactiveProfiles ); + public MavenExecutionRequest setInactiveProfiles(List inactiveProfiles) { + if (inactiveProfiles != null) { + this.profileActivation.overwriteInactiveProfiles(inactiveProfiles); } return this; } @Override - public ProjectActivation getProjectActivation() - { + public ProjectActivation getProjectActivation() { return this.projectActivation; } @Override - public ProfileActivation getProfileActivation() - { + public ProfileActivation getProfileActivation() { return this.profileActivation; } @Override - public MavenExecutionRequest setRemoteRepositories( List remoteRepositories ) - { - if ( remoteRepositories != null ) - { - this.remoteRepositories = new ArrayList<>( remoteRepositories ); - } - else - { + public MavenExecutionRequest setRemoteRepositories(List remoteRepositories) { + if (remoteRepositories != null) { + this.remoteRepositories = new ArrayList<>(remoteRepositories); + } else { this.remoteRepositories = null; } @@ -373,76 +335,62 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest setPluginArtifactRepositories( List pluginArtifactRepositories ) - { - if ( pluginArtifactRepositories != null ) - { - this.pluginArtifactRepositories = new ArrayList<>( pluginArtifactRepositories ); - } - else - { + public MavenExecutionRequest setPluginArtifactRepositories(List pluginArtifactRepositories) { + if (pluginArtifactRepositories != null) { + this.pluginArtifactRepositories = new ArrayList<>(pluginArtifactRepositories); + } else { this.pluginArtifactRepositories = null; } return this; } - public void setProjectBuildingConfiguration( ProjectBuildingRequest projectBuildingConfiguration ) - { + public void setProjectBuildingConfiguration(ProjectBuildingRequest projectBuildingConfiguration) { this.projectBuildingRequest = projectBuildingConfiguration; } @Override - public List getActiveProfiles() - { + public List getActiveProfiles() { return this.profileActivation.getActiveProfiles(); } @Override - public List getInactiveProfiles() - { + public List getInactiveProfiles() { return this.profileActivation.getInactiveProfiles(); } @Override - public TransferListener getTransferListener() - { + public TransferListener getTransferListener() { return transferListener; } @Override - public int getLoggingLevel() - { + public int getLoggingLevel() { return loggingLevel; } @Override - public boolean isOffline() - { + public boolean isOffline() { return offline; } @Override - public boolean isUpdateSnapshots() - { + public boolean isUpdateSnapshots() { return updateSnapshots; } @Override - public boolean isNoSnapshotUpdates() - { + public boolean isNoSnapshotUpdates() { return noSnapshotUpdates; } @Override - public String getGlobalChecksumPolicy() - { + public String getGlobalChecksumPolicy() { return globalChecksumPolicy; } @Override - public boolean isRecursive() - { + public boolean isRecursive() { return recursive; } @@ -451,38 +399,31 @@ public class DefaultMavenExecutionRequest // ---------------------------------------------------------------------- @Override - public MavenExecutionRequest setBaseDirectory( File basedir ) - { + public MavenExecutionRequest setBaseDirectory(File basedir) { this.basedir = basedir; return this; } @Override - public MavenExecutionRequest setStartTime( Date startTime ) - { + public MavenExecutionRequest setStartTime(Date startTime) { this.startTime = startTime; return this; } @Override - public MavenExecutionRequest setShowErrors( boolean showErrors ) - { + public MavenExecutionRequest setShowErrors(boolean showErrors) { this.showErrors = showErrors; return this; } @Override - public MavenExecutionRequest setGoals( List goals ) - { - if ( goals != null ) - { - this.goals = new ArrayList<>( goals ); - } - else - { + public MavenExecutionRequest setGoals(List goals) { + if (goals != null) { + this.goals = new ArrayList<>(goals); + } else { this.goals = null; } @@ -490,43 +431,35 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest setLocalRepository( ArtifactRepository localRepository ) - { + public MavenExecutionRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; - if ( localRepository != null ) - { - setLocalRepositoryPath( new File( localRepository.getBasedir() ).getAbsoluteFile() ); + if (localRepository != null) { + setLocalRepositoryPath(new File(localRepository.getBasedir()).getAbsoluteFile()); } return this; } @Override - public MavenExecutionRequest setLocalRepositoryPath( File localRepository ) - { + public MavenExecutionRequest setLocalRepositoryPath(File localRepository) { localRepositoryPath = localRepository; return this; } @Override - public MavenExecutionRequest setLocalRepositoryPath( String localRepository ) - { - localRepositoryPath = ( localRepository != null ) ? new File( localRepository ) : null; + public MavenExecutionRequest setLocalRepositoryPath(String localRepository) { + localRepositoryPath = (localRepository != null) ? new File(localRepository) : null; return this; } @Override - public MavenExecutionRequest setSystemProperties( Properties properties ) - { - if ( properties != null ) - { - this.systemProperties = SystemProperties.copyProperties( properties ); - } - else - { + public MavenExecutionRequest setSystemProperties(Properties properties) { + if (properties != null) { + this.systemProperties = SystemProperties.copyProperties(properties); + } else { this.systemProperties = null; } @@ -534,15 +467,11 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest setUserProperties( Properties userProperties ) - { - if ( userProperties != null ) - { + public MavenExecutionRequest setUserProperties(Properties userProperties) { + if (userProperties != null) { this.userProperties = new Properties(); - this.userProperties.putAll( userProperties ); - } - else - { + this.userProperties.putAll(userProperties); + } else { this.userProperties = null; } @@ -550,186 +479,158 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest setReactorFailureBehavior( String failureBehavior ) - { + public MavenExecutionRequest setReactorFailureBehavior(String failureBehavior) { reactorFailureBehavior = failureBehavior; return this; } @Override - public MavenExecutionRequest setSelectedProjects( List selectedProjects ) - { - if ( selectedProjects != null ) - { - this.projectActivation.overwriteActiveProjects( selectedProjects ); + public MavenExecutionRequest setSelectedProjects(List selectedProjects) { + if (selectedProjects != null) { + this.projectActivation.overwriteActiveProjects(selectedProjects); } return this; } @Override - public MavenExecutionRequest setExcludedProjects( List excludedProjects ) - { - if ( excludedProjects != null ) - { - this.projectActivation.overwriteInactiveProjects( excludedProjects ); + public MavenExecutionRequest setExcludedProjects(List excludedProjects) { + if (excludedProjects != null) { + this.projectActivation.overwriteInactiveProjects(excludedProjects); } return this; } @Override - public MavenExecutionRequest setResume( boolean resume ) - { + public MavenExecutionRequest setResume(boolean resume) { this.resume = resume; return this; } @Override - public MavenExecutionRequest setResumeFrom( String project ) - { + public MavenExecutionRequest setResumeFrom(String project) { this.resumeFrom = project; return this; } @Override - public MavenExecutionRequest setMakeBehavior( String makeBehavior ) - { + public MavenExecutionRequest setMakeBehavior(String makeBehavior) { this.makeBehavior = makeBehavior; return this; } @Override - public MavenExecutionRequest addActiveProfile( String profile ) - { - if ( !getActiveProfiles().contains( profile ) ) - { - getActiveProfiles().add( profile ); + public MavenExecutionRequest addActiveProfile(String profile) { + if (!getActiveProfiles().contains(profile)) { + getActiveProfiles().add(profile); } return this; } @Override - public MavenExecutionRequest addInactiveProfile( String profile ) - { - if ( !getInactiveProfiles().contains( profile ) ) - { - getInactiveProfiles().add( profile ); + public MavenExecutionRequest addInactiveProfile(String profile) { + if (!getInactiveProfiles().contains(profile)) { + getInactiveProfiles().add(profile); } return this; } @Override - public MavenExecutionRequest addActiveProfiles( List profiles ) - { - for ( String profile : profiles ) - { - addActiveProfile( profile ); + public MavenExecutionRequest addActiveProfiles(List profiles) { + for (String profile : profiles) { + addActiveProfile(profile); } return this; } @Override - public MavenExecutionRequest addInactiveProfiles( List profiles ) - { - for ( String profile : profiles ) - { - addInactiveProfile( profile ); + public MavenExecutionRequest addInactiveProfiles(List profiles) { + for (String profile : profiles) { + addInactiveProfile(profile); } return this; } - public MavenExecutionRequest setUseReactor( boolean reactorActive ) - { + public MavenExecutionRequest setUseReactor(boolean reactorActive) { useReactor = reactorActive; return this; } - public boolean useReactor() - { + public boolean useReactor() { return useReactor; } /** @deprecated use {@link #setPom(File)} */ @Deprecated - public MavenExecutionRequest setPomFile( String pomFilename ) - { - if ( pomFilename != null ) - { - pom = new File( pomFilename ); + public MavenExecutionRequest setPomFile(String pomFilename) { + if (pomFilename != null) { + pom = new File(pomFilename); } return this; } @Override - public MavenExecutionRequest setPom( File pom ) - { + public MavenExecutionRequest setPom(File pom) { this.pom = pom; return this; } @Override - public MavenExecutionRequest setInteractiveMode( boolean interactive ) - { + public MavenExecutionRequest setInteractiveMode(boolean interactive) { interactiveMode = interactive; return this; } @Override - public MavenExecutionRequest setTransferListener( TransferListener transferListener ) - { + public MavenExecutionRequest setTransferListener(TransferListener transferListener) { this.transferListener = transferListener; return this; } @Override - public MavenExecutionRequest setLoggingLevel( int loggingLevel ) - { + public MavenExecutionRequest setLoggingLevel(int loggingLevel) { this.loggingLevel = loggingLevel; return this; } @Override - public MavenExecutionRequest setOffline( boolean offline ) - { + public MavenExecutionRequest setOffline(boolean offline) { this.offline = offline; return this; } @Override - public MavenExecutionRequest setUpdateSnapshots( boolean updateSnapshots ) - { + public MavenExecutionRequest setUpdateSnapshots(boolean updateSnapshots) { this.updateSnapshots = updateSnapshots; return this; } @Override - public MavenExecutionRequest setNoSnapshotUpdates( boolean noSnapshotUpdates ) - { + public MavenExecutionRequest setNoSnapshotUpdates(boolean noSnapshotUpdates) { this.noSnapshotUpdates = noSnapshotUpdates; return this; } @Override - public MavenExecutionRequest setGlobalChecksumPolicy( String globalChecksumPolicy ) - { + public MavenExecutionRequest setGlobalChecksumPolicy(String globalChecksumPolicy) { this.globalChecksumPolicy = globalChecksumPolicy; return this; @@ -740,24 +641,18 @@ public class DefaultMavenExecutionRequest // ---------------------------------------------------------------------------- @Override - public List getProxies() - { - if ( proxies == null ) - { + public List getProxies() { + if (proxies == null) { proxies = new ArrayList<>(); } return proxies; } @Override - public MavenExecutionRequest setProxies( List proxies ) - { - if ( proxies != null ) - { - this.proxies = new ArrayList<>( proxies ); - } - else - { + public MavenExecutionRequest setProxies(List proxies) { + if (proxies != null) { + this.proxies = new ArrayList<>(proxies); + } else { this.proxies = null; } @@ -765,42 +660,33 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest addProxy( Proxy proxy ) - { - Objects.requireNonNull( proxy, "proxy cannot be null" ); + public MavenExecutionRequest addProxy(Proxy proxy) { + Objects.requireNonNull(proxy, "proxy cannot be null"); - for ( Proxy p : getProxies() ) - { - if ( p.getId() != null && p.getId().equals( proxy.getId() ) ) - { + for (Proxy p : getProxies()) { + if (p.getId() != null && p.getId().equals(proxy.getId())) { return this; } } - getProxies().add( proxy ); + getProxies().add(proxy); return this; } @Override - public List getServers() - { - if ( servers == null ) - { + public List getServers() { + if (servers == null) { servers = new ArrayList<>(); } return servers; } @Override - public MavenExecutionRequest setServers( List servers ) - { - if ( servers != null ) - { - this.servers = new ArrayList<>( servers ); - } - else - { + public MavenExecutionRequest setServers(List servers) { + if (servers != null) { + this.servers = new ArrayList<>(servers); + } else { this.servers = null; } @@ -808,42 +694,33 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest addServer( Server server ) - { - Objects.requireNonNull( server, "server cannot be null" ); + public MavenExecutionRequest addServer(Server server) { + Objects.requireNonNull(server, "server cannot be null"); - for ( Server p : getServers() ) - { - if ( p.getId() != null && p.getId().equals( server.getId() ) ) - { + for (Server p : getServers()) { + if (p.getId() != null && p.getId().equals(server.getId())) { return this; } } - getServers().add( server ); + getServers().add(server); return this; } @Override - public List getMirrors() - { - if ( mirrors == null ) - { + public List getMirrors() { + if (mirrors == null) { mirrors = new ArrayList<>(); } return mirrors; } @Override - public MavenExecutionRequest setMirrors( List mirrors ) - { - if ( mirrors != null ) - { - this.mirrors = new ArrayList<>( mirrors ); - } - else - { + public MavenExecutionRequest setMirrors(List mirrors) { + if (mirrors != null) { + this.mirrors = new ArrayList<>(mirrors); + } else { this.mirrors = null; } @@ -851,42 +728,33 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest addMirror( Mirror mirror ) - { - Objects.requireNonNull( mirror, "mirror cannot be null" ); + public MavenExecutionRequest addMirror(Mirror mirror) { + Objects.requireNonNull(mirror, "mirror cannot be null"); - for ( Mirror p : getMirrors() ) - { - if ( p.getId() != null && p.getId().equals( mirror.getId() ) ) - { + for (Mirror p : getMirrors()) { + if (p.getId() != null && p.getId().equals(mirror.getId())) { return this; } } - getMirrors().add( mirror ); + getMirrors().add(mirror); return this; } @Override - public List getProfiles() - { - if ( profiles == null ) - { + public List getProfiles() { + if (profiles == null) { profiles = new ArrayList<>(); } return profiles; } @Override - public MavenExecutionRequest setProfiles( List profiles ) - { - if ( profiles != null ) - { - this.profiles = new ArrayList<>( profiles ); - } - else - { + public MavenExecutionRequest setProfiles(List profiles) { + if (profiles != null) { + this.profiles = new ArrayList<>(profiles); + } else { this.profiles = null; } @@ -894,10 +762,8 @@ public class DefaultMavenExecutionRequest } @Override - public List getPluginGroups() - { - if ( pluginGroups == null ) - { + public List getPluginGroups() { + if (pluginGroups == null) { pluginGroups = new ArrayList<>(); } @@ -905,14 +771,10 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest setPluginGroups( List pluginGroups ) - { - if ( pluginGroups != null ) - { - this.pluginGroups = new ArrayList<>( pluginGroups ); - } - else - { + public MavenExecutionRequest setPluginGroups(List pluginGroups) { + if (pluginGroups != null) { + this.pluginGroups = new ArrayList<>(pluginGroups); + } else { this.pluginGroups = null; } @@ -920,30 +782,25 @@ public class DefaultMavenExecutionRequest } @Override - public MavenExecutionRequest addPluginGroup( String pluginGroup ) - { - if ( !getPluginGroups().contains( pluginGroup ) ) - { - getPluginGroups().add( pluginGroup ); + public MavenExecutionRequest addPluginGroup(String pluginGroup) { + if (!getPluginGroups().contains(pluginGroup)) { + getPluginGroups().add(pluginGroup); } return this; } @Override - public MavenExecutionRequest addPluginGroups( List pluginGroups ) - { - for ( String pluginGroup : pluginGroups ) - { - addPluginGroup( pluginGroup ); + public MavenExecutionRequest addPluginGroups(List pluginGroups) { + for (String pluginGroup : pluginGroups) { + addPluginGroup(pluginGroup); } return this; } @Override - public MavenExecutionRequest setRecursive( boolean recursive ) - { + public MavenExecutionRequest setRecursive(boolean recursive) { this.recursive = recursive; return this; @@ -953,14 +810,12 @@ public class DefaultMavenExecutionRequest private ProjectBuildingRequest projectBuildingRequest; @Override - public boolean isProjectPresent() - { + public boolean isProjectPresent() { return isProjectPresent; } @Override - public MavenExecutionRequest setProjectPresent( boolean projectPresent ) - { + public MavenExecutionRequest setProjectPresent(boolean projectPresent) { isProjectPresent = projectPresent; return this; @@ -969,107 +824,89 @@ public class DefaultMavenExecutionRequest // Settings files @Override - public File getUserSettingsFile() - { + public File getUserSettingsFile() { return userSettingsFile; } @Override - public MavenExecutionRequest setUserSettingsFile( File userSettingsFile ) - { + public MavenExecutionRequest setUserSettingsFile(File userSettingsFile) { this.userSettingsFile = userSettingsFile; return this; } @Override - public File getGlobalSettingsFile() - { + public File getGlobalSettingsFile() { return globalSettingsFile; } @Override - public MavenExecutionRequest setGlobalSettingsFile( File globalSettingsFile ) - { + public MavenExecutionRequest setGlobalSettingsFile(File globalSettingsFile) { this.globalSettingsFile = globalSettingsFile; return this; } @Override - public File getUserToolchainsFile() - { + public File getUserToolchainsFile() { return userToolchainsFile; } @Override - public MavenExecutionRequest setUserToolchainsFile( File userToolchainsFile ) - { + public MavenExecutionRequest setUserToolchainsFile(File userToolchainsFile) { this.userToolchainsFile = userToolchainsFile; return this; } @Override - public File getGlobalToolchainsFile() - { + public File getGlobalToolchainsFile() { return globalToolchainsFile; } @Override - public MavenExecutionRequest setGlobalToolchainsFile( File globalToolchainsFile ) - { + public MavenExecutionRequest setGlobalToolchainsFile(File globalToolchainsFile) { this.globalToolchainsFile = globalToolchainsFile; return this; } @Override - public MavenExecutionRequest addRemoteRepository( ArtifactRepository repository ) - { - for ( ArtifactRepository repo : getRemoteRepositories() ) - { - if ( repo.getId() != null && repo.getId().equals( repository.getId() ) ) - { + public MavenExecutionRequest addRemoteRepository(ArtifactRepository repository) { + for (ArtifactRepository repo : getRemoteRepositories()) { + if (repo.getId() != null && repo.getId().equals(repository.getId())) { return this; } } - getRemoteRepositories().add( repository ); + getRemoteRepositories().add(repository); return this; } @Override - public List getRemoteRepositories() - { - if ( remoteRepositories == null ) - { + public List getRemoteRepositories() { + if (remoteRepositories == null) { remoteRepositories = new ArrayList<>(); } return remoteRepositories; } @Override - public MavenExecutionRequest addPluginArtifactRepository( ArtifactRepository repository ) - { - for ( ArtifactRepository repo : getPluginArtifactRepositories() ) - { - if ( repo.getId() != null && repo.getId().equals( repository.getId() ) ) - { + public MavenExecutionRequest addPluginArtifactRepository(ArtifactRepository repository) { + for (ArtifactRepository repo : getPluginArtifactRepositories()) { + if (repo.getId() != null && repo.getId().equals(repository.getId())) { return this; } } - getPluginArtifactRepositories().add( repository ); + getPluginArtifactRepositories().add(repository); return this; } @Override - public List getPluginArtifactRepositories() - { - if ( pluginArtifactRepositories == null ) - { + public List getPluginArtifactRepositories() { + if (pluginArtifactRepositories == null) { pluginArtifactRepositories = new ArrayList<>(); } return pluginArtifactRepositories; @@ -1077,196 +914,166 @@ public class DefaultMavenExecutionRequest // TODO this does not belong here. @Override - public ProjectBuildingRequest getProjectBuildingRequest() - { - if ( projectBuildingRequest == null ) - { + public ProjectBuildingRequest getProjectBuildingRequest() { + if (projectBuildingRequest == null) { projectBuildingRequest = new DefaultProjectBuildingRequest(); - projectBuildingRequest.setLocalRepository( getLocalRepository() ); - projectBuildingRequest.setSystemProperties( getSystemProperties() ); - projectBuildingRequest.setUserProperties( getUserProperties() ); - projectBuildingRequest.setRemoteRepositories( getRemoteRepositories() ); - projectBuildingRequest.setPluginArtifactRepositories( getPluginArtifactRepositories() ); - projectBuildingRequest.setActiveProfileIds( getActiveProfiles() ); - projectBuildingRequest.setInactiveProfileIds( getInactiveProfiles() ); - projectBuildingRequest.setProfiles( getProfiles() ); - projectBuildingRequest.setProcessPlugins( true ); - projectBuildingRequest.setBuildStartTime( getStartTime() ); + projectBuildingRequest.setLocalRepository(getLocalRepository()); + projectBuildingRequest.setSystemProperties(getSystemProperties()); + projectBuildingRequest.setUserProperties(getUserProperties()); + projectBuildingRequest.setRemoteRepositories(getRemoteRepositories()); + projectBuildingRequest.setPluginArtifactRepositories(getPluginArtifactRepositories()); + projectBuildingRequest.setActiveProfileIds(getActiveProfiles()); + projectBuildingRequest.setInactiveProfileIds(getInactiveProfiles()); + projectBuildingRequest.setProfiles(getProfiles()); + projectBuildingRequest.setProcessPlugins(true); + projectBuildingRequest.setBuildStartTime(getStartTime()); } return projectBuildingRequest; } @Override - public MavenExecutionRequest addProfile( Profile profile ) - { - Objects.requireNonNull( profile, "profile cannot be null" ); + public MavenExecutionRequest addProfile(Profile profile) { + Objects.requireNonNull(profile, "profile cannot be null"); - for ( Profile p : getProfiles() ) - { - if ( p.getId() != null && p.getId().equals( profile.getId() ) ) - { + for (Profile p : getProfiles()) { + if (p.getId() != null && p.getId().equals(profile.getId())) { return this; } } - getProfiles().add( profile ); + getProfiles().add(profile); return this; } @Override - public RepositoryCache getRepositoryCache() - { + public RepositoryCache getRepositoryCache() { return repositoryCache; } @Override - public MavenExecutionRequest setRepositoryCache( RepositoryCache repositoryCache ) - { + public MavenExecutionRequest setRepositoryCache(RepositoryCache repositoryCache) { this.repositoryCache = repositoryCache; return this; } @Override - public ExecutionListener getExecutionListener() - { + public ExecutionListener getExecutionListener() { return executionListener; } @Override - public MavenExecutionRequest setExecutionListener( ExecutionListener executionListener ) - { + public MavenExecutionRequest setExecutionListener(ExecutionListener executionListener) { this.executionListener = executionListener; return this; } @Override - public void setDegreeOfConcurrency( final int degreeOfConcurrency ) - { + public void setDegreeOfConcurrency(final int degreeOfConcurrency) { this.degreeOfConcurrency = degreeOfConcurrency; } @Override - public int getDegreeOfConcurrency() - { + public int getDegreeOfConcurrency() { return degreeOfConcurrency; } @Override - public WorkspaceReader getWorkspaceReader() - { + public WorkspaceReader getWorkspaceReader() { return workspaceReader; } @Override - public MavenExecutionRequest setWorkspaceReader( WorkspaceReader workspaceReader ) - { + public MavenExecutionRequest setWorkspaceReader(WorkspaceReader workspaceReader) { this.workspaceReader = workspaceReader; return this; } @Override - public boolean isCacheTransferError() - { + public boolean isCacheTransferError() { return cacheTransferError; } @Override - public MavenExecutionRequest setCacheTransferError( boolean cacheTransferError ) - { + public MavenExecutionRequest setCacheTransferError(boolean cacheTransferError) { this.cacheTransferError = cacheTransferError; return this; } @Override - public boolean isCacheNotFound() - { + public boolean isCacheNotFound() { return cacheNotFound; } @Override - public MavenExecutionRequest setCacheNotFound( boolean cacheNotFound ) - { + public MavenExecutionRequest setCacheNotFound(boolean cacheNotFound) { this.cacheNotFound = cacheNotFound; return this; } @Override - public boolean isUseLegacyLocalRepository() - { + public boolean isUseLegacyLocalRepository() { return this.useLegacyLocalRepositoryManager; } @Override - public MavenExecutionRequest setUseLegacyLocalRepository( boolean useLegacyLocalRepositoryManager ) - { + public MavenExecutionRequest setUseLegacyLocalRepository(boolean useLegacyLocalRepositoryManager) { this.useLegacyLocalRepositoryManager = useLegacyLocalRepositoryManager; return this; } @Override - public MavenExecutionRequest setBuilderId( String builderId ) - { + public MavenExecutionRequest setBuilderId(String builderId) { this.builderId = builderId; return this; } @Override - public String getBuilderId() - { + public String getBuilderId() { return builderId; } @Override - public Map> getToolchains() - { - if ( toolchains == null ) - { + public Map> getToolchains() { + if (toolchains == null) { toolchains = new HashMap<>(); } return toolchains; } @Override - public MavenExecutionRequest setToolchains( Map> toolchains ) - { + public MavenExecutionRequest setToolchains(Map> toolchains) { this.toolchains = toolchains; return this; } @Override - public void setMultiModuleProjectDirectory( File directory ) - { + public void setMultiModuleProjectDirectory(File directory) { this.multiModuleProjectDirectory = directory; } @Override - public File getMultiModuleProjectDirectory() - { + public File getMultiModuleProjectDirectory() { return multiModuleProjectDirectory; } @Override - public MavenExecutionRequest setEventSpyDispatcher( EventSpyDispatcher eventSpyDispatcher ) - { + public MavenExecutionRequest setEventSpyDispatcher(EventSpyDispatcher eventSpyDispatcher) { this.eventSpyDispatcher = eventSpyDispatcher; return this; } @Override - public EventSpyDispatcher getEventSpyDispatcher() - { + public EventSpyDispatcher getEventSpyDispatcher() { return eventSpyDispatcher; } @Override - public Map getData() - { - if ( data == null ) - { + public Map getData() { + if (data == null) { data = new HashMap<>(); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulator.java b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulator.java index 6737c81aa3..370ad944d0 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulator.java +++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulator.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.io.File; import java.util.ArrayList; @@ -25,27 +24,19 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.bridge.MavenRepositorySystem; import org.apache.maven.repository.RepositorySystem; -// -// All of this needs to go away and be couched in terms of the execution request -// import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Repository; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.SettingsUtils; -// -// Settings in core -// import org.apache.maven.toolchain.model.PersistedToolchains; import org.apache.maven.toolchain.model.ToolchainModel; import org.codehaus.plexus.util.StringUtils; @@ -55,55 +46,46 @@ import org.codehaus.plexus.util.StringUtils; */ @Named @Singleton -public class DefaultMavenExecutionRequestPopulator - implements MavenExecutionRequestPopulator -{ +public class DefaultMavenExecutionRequestPopulator implements MavenExecutionRequestPopulator { private final MavenRepositorySystem repositorySystem; @Inject - public DefaultMavenExecutionRequestPopulator( MavenRepositorySystem repositorySystem ) - { + public DefaultMavenExecutionRequestPopulator(MavenRepositorySystem repositorySystem) { this.repositorySystem = repositorySystem; } - @Override - public MavenExecutionRequest populateFromToolchains( MavenExecutionRequest request, PersistedToolchains toolchains ) - throws MavenExecutionRequestPopulationException - { - if ( toolchains != null ) - { - Map> groupedToolchains = new HashMap<>( 2 ); + public MavenExecutionRequest populateFromToolchains(MavenExecutionRequest request, PersistedToolchains toolchains) + throws MavenExecutionRequestPopulationException { + if (toolchains != null) { + Map> groupedToolchains = new HashMap<>(2); - for ( ToolchainModel model : toolchains.getToolchains() ) - { - if ( !groupedToolchains.containsKey( model.getType() ) ) - { - groupedToolchains.put( model.getType(), new ArrayList<>() ); + for (ToolchainModel model : toolchains.getToolchains()) { + if (!groupedToolchains.containsKey(model.getType())) { + groupedToolchains.put(model.getType(), new ArrayList<>()); } - groupedToolchains.get( model.getType() ).add( model ); + groupedToolchains.get(model.getType()).add(model); } - request.setToolchains( groupedToolchains ); + request.setToolchains(groupedToolchains); } return request; } @Override - public MavenExecutionRequest populateDefaults( MavenExecutionRequest request ) - throws MavenExecutionRequestPopulationException - { - baseDirectory( request ); + public MavenExecutionRequest populateDefaults(MavenExecutionRequest request) + throws MavenExecutionRequestPopulationException { + baseDirectory(request); - localRepository( request ); + localRepository(request); - populateDefaultPluginGroups( request ); + populateDefaultPluginGroups(request); - injectDefaultRepositories( request ); + injectDefaultRepositories(request); - injectDefaultPluginRepositories( request ); + injectDefaultPluginRepositories(request); return request; } @@ -112,51 +94,38 @@ public class DefaultMavenExecutionRequestPopulator // // - private void populateDefaultPluginGroups( MavenExecutionRequest request ) - { - request.addPluginGroup( "org.apache.maven.plugins" ); - request.addPluginGroup( "org.codehaus.mojo" ); + private void populateDefaultPluginGroups(MavenExecutionRequest request) { + request.addPluginGroup("org.apache.maven.plugins"); + request.addPluginGroup("org.codehaus.mojo"); } - private void injectDefaultRepositories( MavenExecutionRequest request ) - throws MavenExecutionRequestPopulationException - { - Set definedRepositories = repositorySystem.getRepoIds( request.getRemoteRepositories() ); + private void injectDefaultRepositories(MavenExecutionRequest request) + throws MavenExecutionRequestPopulationException { + Set definedRepositories = repositorySystem.getRepoIds(request.getRemoteRepositories()); - if ( !definedRepositories.contains( RepositorySystem.DEFAULT_REMOTE_REPO_ID ) ) - { - try - { - request.addRemoteRepository( repositorySystem.createDefaultRemoteRepository( request ) ); - } - catch ( Exception e ) - { - throw new MavenExecutionRequestPopulationException( "Cannot create default remote repository.", e ); + if (!definedRepositories.contains(RepositorySystem.DEFAULT_REMOTE_REPO_ID)) { + try { + request.addRemoteRepository(repositorySystem.createDefaultRemoteRepository(request)); + } catch (Exception e) { + throw new MavenExecutionRequestPopulationException("Cannot create default remote repository.", e); } } } - private void injectDefaultPluginRepositories( MavenExecutionRequest request ) - throws MavenExecutionRequestPopulationException - { - Set definedRepositories = repositorySystem.getRepoIds( request.getPluginArtifactRepositories() ); + private void injectDefaultPluginRepositories(MavenExecutionRequest request) + throws MavenExecutionRequestPopulationException { + Set definedRepositories = repositorySystem.getRepoIds(request.getPluginArtifactRepositories()); - if ( !definedRepositories.contains( RepositorySystem.DEFAULT_REMOTE_REPO_ID ) ) - { - try - { - request.addPluginArtifactRepository( repositorySystem.createDefaultRemoteRepository( request ) ); - } - catch ( Exception e ) - { - throw new MavenExecutionRequestPopulationException( "Cannot create default remote repository.", e ); + if (!definedRepositories.contains(RepositorySystem.DEFAULT_REMOTE_REPO_ID)) { + try { + request.addPluginArtifactRepository(repositorySystem.createDefaultRemoteRepository(request)); + } catch (Exception e) { + throw new MavenExecutionRequestPopulationException("Cannot create default remote repository.", e); } } } - private void localRepository( MavenExecutionRequest request ) - throws MavenExecutionRequestPopulationException - { + private void localRepository(MavenExecutionRequest request) throws MavenExecutionRequestPopulationException { // ------------------------------------------------------------------------ // Local Repository // @@ -165,14 +134,12 @@ public class DefaultMavenExecutionRequestPopulator // 3. Use default value // ------------------------------------------------------------------------ - if ( request.getLocalRepository() == null ) - { - request.setLocalRepository( createLocalRepository( request ) ); + if (request.getLocalRepository() == null) { + request.setLocalRepository(createLocalRepository(request)); } - if ( request.getLocalRepositoryPath() == null ) - { - request.setLocalRepositoryPath( new File( request.getLocalRepository().getBasedir() ).getAbsoluteFile() ); + if (request.getLocalRepositoryPath() == null) { + request.setLocalRepositoryPath(new File(request.getLocalRepository().getBasedir()).getAbsoluteFile()); } } @@ -180,36 +147,28 @@ public class DefaultMavenExecutionRequestPopulator // Artifact Transfer Mechanism // ------------------------------------------------------------------------ - private ArtifactRepository createLocalRepository( MavenExecutionRequest request ) - throws MavenExecutionRequestPopulationException - { + private ArtifactRepository createLocalRepository(MavenExecutionRequest request) + throws MavenExecutionRequestPopulationException { String localRepositoryPath = null; - if ( request.getLocalRepositoryPath() != null ) - { + if (request.getLocalRepositoryPath() != null) { localRepositoryPath = request.getLocalRepositoryPath().getAbsolutePath(); } - if ( StringUtils.isEmpty( localRepositoryPath ) ) - { + if (StringUtils.isEmpty(localRepositoryPath)) { localRepositoryPath = RepositorySystem.defaultUserLocalRepository.getAbsolutePath(); } - try - { - return repositorySystem.createLocalRepository( request, new File( localRepositoryPath ) ); - } - catch ( Exception e ) - { - throw new MavenExecutionRequestPopulationException( "Cannot create local repository.", e ); + try { + return repositorySystem.createLocalRepository(request, new File(localRepositoryPath)); + } catch (Exception e) { + throw new MavenExecutionRequestPopulationException("Cannot create local repository.", e); } } - private void baseDirectory( MavenExecutionRequest request ) - { - if ( request.getBaseDirectory() == null && request.getPom() != null ) - { - request.setBaseDirectory( request.getPom().getAbsoluteFile().getParentFile() ); + private void baseDirectory(MavenExecutionRequest request) { + if (request.getBaseDirectory() == null && request.getPom() != null) { + request.setBaseDirectory(request.getPom().getAbsoluteFile().getParentFile()); } } @@ -217,27 +176,24 @@ public class DefaultMavenExecutionRequestPopulator @Override @Deprecated - public MavenExecutionRequest populateFromSettings( MavenExecutionRequest request, Settings settings ) - throws MavenExecutionRequestPopulationException - { - if ( settings == null ) - { + public MavenExecutionRequest populateFromSettings(MavenExecutionRequest request, Settings settings) + throws MavenExecutionRequestPopulationException { + if (settings == null) { return request; } - request.setOffline( settings.isOffline() ); + request.setOffline(settings.isOffline()); - request.setInteractiveMode( settings.isInteractiveMode() ); + request.setInteractiveMode(settings.isInteractiveMode()); - request.setPluginGroups( settings.getPluginGroups() ); + request.setPluginGroups(settings.getPluginGroups()); - request.setLocalRepositoryPath( settings.getLocalRepository() ); + request.setLocalRepositoryPath(settings.getLocalRepository()); - for ( Server server : settings.getServers() ) - { + for (Server server : settings.getServers()) { server = server.clone(); - request.addServer( server ); + request.addServer(server); } // @@ -252,16 +208,14 @@ public class DefaultMavenExecutionRequestPopulator // // - for ( Proxy proxy : settings.getProxies() ) - { - if ( !proxy.isActive() ) - { + for (Proxy proxy : settings.getProxies()) { + if (!proxy.isActive()) { continue; } proxy = proxy.clone(); - request.addProxy( proxy ); + request.addProxy(proxy); } // @@ -272,45 +226,32 @@ public class DefaultMavenExecutionRequestPopulator //
    // - for ( Mirror mirror : settings.getMirrors() ) - { + for (Mirror mirror : settings.getMirrors()) { mirror = mirror.clone(); - request.addMirror( mirror ); + request.addMirror(mirror); } - request.setActiveProfiles( settings.getActiveProfiles() ); + request.setActiveProfiles(settings.getActiveProfiles()); - for ( org.apache.maven.settings.Profile rawProfile : settings.getProfiles() ) - { - request.addProfile( SettingsUtils.convertFromSettingsProfile( rawProfile.getDelegate() ) ); + for (org.apache.maven.settings.Profile rawProfile : settings.getProfiles()) { + request.addProfile(SettingsUtils.convertFromSettingsProfile(rawProfile.getDelegate())); - if ( settings.getActiveProfiles().contains( rawProfile.getId() ) ) - { + if (settings.getActiveProfiles().contains(rawProfile.getId())) { List remoteRepositories = rawProfile.getRepositories(); - for ( Repository remoteRepository : remoteRepositories ) - { - try - { - request.addRemoteRepository( - MavenRepositorySystem.buildArtifactRepository( remoteRepository ) ); - } - catch ( InvalidRepositoryException e ) - { + for (Repository remoteRepository : remoteRepositories) { + try { + request.addRemoteRepository(MavenRepositorySystem.buildArtifactRepository(remoteRepository)); + } catch (InvalidRepositoryException e) { // do nothing for now } } List pluginRepositories = rawProfile.getPluginRepositories(); - for ( Repository pluginRepo : pluginRepositories ) - { - try - { - request.addPluginArtifactRepository( - MavenRepositorySystem.buildArtifactRepository( pluginRepo ) ); - } - catch ( InvalidRepositoryException e ) - { + for (Repository pluginRepo : pluginRepositories) { + try { + request.addPluginArtifactRepository(MavenRepositorySystem.buildArtifactRepository(pluginRepo)); + } catch (InvalidRepositoryException e) { // do nothing for now } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java index ecddd6608e..10481c797d 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java +++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,20 +16,18 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; - import org.apache.maven.project.DependencyResolutionResult; import org.apache.maven.project.MavenProject; /** @author Jason van Zyl */ -public class DefaultMavenExecutionResult - implements MavenExecutionResult -{ +public class DefaultMavenExecutionResult implements MavenExecutionResult { private MavenProject project; private List topologicallySortedProjects = Collections.emptyList(); @@ -40,86 +36,71 @@ public class DefaultMavenExecutionResult private final List exceptions = new CopyOnWriteArrayList<>(); - private final Map buildSummaries = - Collections.synchronizedMap( new IdentityHashMap<>() ); + private final Map buildSummaries = Collections.synchronizedMap(new IdentityHashMap<>()); private boolean canResume = false; - public MavenExecutionResult setProject( MavenProject project ) - { + public MavenExecutionResult setProject(MavenProject project) { this.project = project; return this; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public MavenExecutionResult setTopologicallySortedProjects( List topologicallySortedProjects ) - { + public MavenExecutionResult setTopologicallySortedProjects(List topologicallySortedProjects) { this.topologicallySortedProjects = topologicallySortedProjects; return this; } - public List getTopologicallySortedProjects() - { + public List getTopologicallySortedProjects() { return null == topologicallySortedProjects - ? Collections.emptyList() - : Collections.unmodifiableList( topologicallySortedProjects ); - + ? Collections.emptyList() + : Collections.unmodifiableList(topologicallySortedProjects); } - public DependencyResolutionResult getDependencyResolutionResult() - { + public DependencyResolutionResult getDependencyResolutionResult() { return dependencyResolutionResult; } - public MavenExecutionResult setDependencyResolutionResult( DependencyResolutionResult dependencyResolutionResult ) - { + public MavenExecutionResult setDependencyResolutionResult(DependencyResolutionResult dependencyResolutionResult) { this.dependencyResolutionResult = dependencyResolutionResult; return this; } - public List getExceptions() - { + public List getExceptions() { return exceptions; } - public MavenExecutionResult addException( Throwable t ) - { - exceptions.add( t ); + public MavenExecutionResult addException(Throwable t) { + exceptions.add(t); return this; } - public boolean hasExceptions() - { + public boolean hasExceptions() { return !getExceptions().isEmpty(); } - public BuildSummary getBuildSummary( MavenProject project ) - { - return buildSummaries.get( project ); + public BuildSummary getBuildSummary(MavenProject project) { + return buildSummaries.get(project); } - public void addBuildSummary( BuildSummary summary ) - { - buildSummaries.put( summary.getProject(), summary ); + public void addBuildSummary(BuildSummary summary) { + buildSummaries.put(summary.getProject(), summary); } @Override - public boolean canResume() - { + public boolean canResume() { return canResume; } @Override - public void setCanResume( boolean canResume ) - { + public void setCanResume(boolean canResume) { this.canResume = canResume; } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ExecutionEvent.java b/maven-core/src/main/java/org/apache/maven/execution/ExecutionEvent.java index 0ee7f57ad7..1655dfbe3a 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ExecutionEvent.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ExecutionEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; @@ -27,14 +26,12 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -public interface ExecutionEvent -{ +public interface ExecutionEvent { /** * The possible types of execution events. */ - enum Type - { + enum Type { ProjectDiscoveryStarted, SessionStarted, SessionEnded, @@ -88,5 +85,4 @@ public interface ExecutionEvent * @return The exception or {@code null} if none. */ Exception getException(); - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ExecutionListener.java b/maven-core/src/main/java/org/apache/maven/execution/ExecutionListener.java index ad3f345a27..406540efa1 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; /** * Defines events that Maven fires during a build. Warning: This interface might be extended in future @@ -26,41 +25,39 @@ package org.apache.maven.execution; * * @author Benjamin Bentmann */ -public interface ExecutionListener -{ +public interface ExecutionListener { - void projectDiscoveryStarted( ExecutionEvent event ); + void projectDiscoveryStarted(ExecutionEvent event); - void sessionStarted( ExecutionEvent event ); + void sessionStarted(ExecutionEvent event); - void sessionEnded( ExecutionEvent event ); + void sessionEnded(ExecutionEvent event); - void projectSkipped( ExecutionEvent event ); + void projectSkipped(ExecutionEvent event); - void projectStarted( ExecutionEvent event ); + void projectStarted(ExecutionEvent event); - void projectSucceeded( ExecutionEvent event ); + void projectSucceeded(ExecutionEvent event); - void projectFailed( ExecutionEvent event ); + void projectFailed(ExecutionEvent event); - void mojoSkipped( ExecutionEvent event ); + void mojoSkipped(ExecutionEvent event); - void mojoStarted( ExecutionEvent event ); + void mojoStarted(ExecutionEvent event); - void mojoSucceeded( ExecutionEvent event ); + void mojoSucceeded(ExecutionEvent event); - void mojoFailed( ExecutionEvent event ); + void mojoFailed(ExecutionEvent event); - void forkStarted( ExecutionEvent event ); + void forkStarted(ExecutionEvent event); - void forkSucceeded( ExecutionEvent event ); + void forkSucceeded(ExecutionEvent event); - void forkFailed( ExecutionEvent event ); + void forkFailed(ExecutionEvent event); - void forkedProjectStarted( ExecutionEvent event ); + void forkedProjectStarted(ExecutionEvent event); - void forkedProjectSucceeded( ExecutionEvent event ); - - void forkedProjectFailed( ExecutionEvent event ); + void forkedProjectSucceeded(ExecutionEvent event); + void forkedProjectFailed(ExecutionEvent event); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequest.java b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequest.java index 3989c5fa92..66dd799613 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,25 +16,21 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.io.File; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.eventspy.internal.EventSpyDispatcher; import org.apache.maven.model.Profile; import org.apache.maven.project.ProjectBuildingRequest; -// -// These settings values need to be removed and pushed down into a provider of configuration information -// import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Server; -// import org.apache.maven.toolchain.model.ToolchainModel; import org.codehaus.plexus.logging.Logger; import org.eclipse.aether.RepositoryCache; @@ -46,8 +40,7 @@ import org.eclipse.aether.transfer.TransferListener; /** * @author Jason van Zyl */ -public interface MavenExecutionRequest -{ +public interface MavenExecutionRequest { // ---------------------------------------------------------------------- // Logging // ---------------------------------------------------------------------- @@ -97,17 +90,17 @@ public interface MavenExecutionRequest // ---------------------------------------------------------------------- // Base directory - MavenExecutionRequest setBaseDirectory( File basedir ); + MavenExecutionRequest setBaseDirectory(File basedir); String getBaseDirectory(); // Timing (remove this) - MavenExecutionRequest setStartTime( Date start ); + MavenExecutionRequest setStartTime(Date start); Date getStartTime(); // Goals - MavenExecutionRequest setGoals( List goals ); + MavenExecutionRequest setGoals(List goals); List getGoals(); @@ -120,7 +113,7 @@ public interface MavenExecutionRequest * @param systemProperties The system properties, may be {@code null}. * @return This request, never {@code null}. */ - MavenExecutionRequest setSystemProperties( Properties systemProperties ); + MavenExecutionRequest setSystemProperties(Properties systemProperties); /** * Gets the system properties to use for interpolation and profile activation. The system properties are collected @@ -138,7 +131,7 @@ public interface MavenExecutionRequest * @param userProperties The user properties, may be {@code null}. * @return This request, never {@code null}. */ - MavenExecutionRequest setUserProperties( Properties userProperties ); + MavenExecutionRequest setUserProperties(Properties userProperties); /** * Gets the user properties to use for interpolation and profile activation. The user properties have been @@ -150,7 +143,7 @@ public interface MavenExecutionRequest Properties getUserProperties(); // Reactor - MavenExecutionRequest setReactorFailureBehavior( String failureBehavior ); + MavenExecutionRequest setReactorFailureBehavior(String failureBehavior); String getReactorFailureBehavior(); @@ -158,7 +151,7 @@ public interface MavenExecutionRequest * @deprecated Since Maven 4: use {@link #getProjectActivation()}. */ @Deprecated - MavenExecutionRequest setSelectedProjects( List projects ); + MavenExecutionRequest setSelectedProjects(List projects); /** * @deprecated Since Maven 4: use {@link #getProjectActivation()}. @@ -173,7 +166,7 @@ public interface MavenExecutionRequest * @deprecated Since Maven 4: use {@link #getProjectActivation()}. */ @Deprecated - MavenExecutionRequest setExcludedProjects( List projects ); + MavenExecutionRequest setExcludedProjects(List projects); /** * @return the excluded projects, never {@code null} @@ -188,18 +181,18 @@ public interface MavenExecutionRequest * @param resume Whether or not to resume a previous build. * @return This request, never {@code null}. */ - MavenExecutionRequest setResume( boolean resume ); + MavenExecutionRequest setResume(boolean resume); /** * @return Whether the build should be resumed from the data in the resume.properties file. */ boolean isResume(); - MavenExecutionRequest setResumeFrom( String project ); + MavenExecutionRequest setResumeFrom(String project); String getResumeFrom(); - MavenExecutionRequest setMakeBehavior( String makeBehavior ); + MavenExecutionRequest setMakeBehavior(String makeBehavior); String getMakeBehavior(); @@ -208,7 +201,7 @@ public interface MavenExecutionRequest * * @param degreeOfConcurrency */ - void setDegreeOfConcurrency( int degreeOfConcurrency ); + void setDegreeOfConcurrency(int degreeOfConcurrency); /** * @return the degree of concurrency for the build. @@ -216,96 +209,96 @@ public interface MavenExecutionRequest int getDegreeOfConcurrency(); // Recursive (really to just process the top-level POM) - MavenExecutionRequest setRecursive( boolean recursive ); + MavenExecutionRequest setRecursive(boolean recursive); boolean isRecursive(); - MavenExecutionRequest setPom( File pom ); + MavenExecutionRequest setPom(File pom); File getPom(); // Errors - MavenExecutionRequest setShowErrors( boolean showErrors ); + MavenExecutionRequest setShowErrors(boolean showErrors); boolean isShowErrors(); // Transfer listeners - MavenExecutionRequest setTransferListener( TransferListener transferListener ); + MavenExecutionRequest setTransferListener(TransferListener transferListener); TransferListener getTransferListener(); // Logging - MavenExecutionRequest setLoggingLevel( int loggingLevel ); + MavenExecutionRequest setLoggingLevel(int loggingLevel); int getLoggingLevel(); // Update snapshots - MavenExecutionRequest setUpdateSnapshots( boolean updateSnapshots ); + MavenExecutionRequest setUpdateSnapshots(boolean updateSnapshots); boolean isUpdateSnapshots(); - MavenExecutionRequest setNoSnapshotUpdates( boolean noSnapshotUpdates ); + MavenExecutionRequest setNoSnapshotUpdates(boolean noSnapshotUpdates); boolean isNoSnapshotUpdates(); // Checksum policy - MavenExecutionRequest setGlobalChecksumPolicy( String globalChecksumPolicy ); + MavenExecutionRequest setGlobalChecksumPolicy(String globalChecksumPolicy); String getGlobalChecksumPolicy(); // Local repository - MavenExecutionRequest setLocalRepositoryPath( String localRepository ); + MavenExecutionRequest setLocalRepositoryPath(String localRepository); - MavenExecutionRequest setLocalRepositoryPath( File localRepository ); + MavenExecutionRequest setLocalRepositoryPath(File localRepository); File getLocalRepositoryPath(); - MavenExecutionRequest setLocalRepository( ArtifactRepository repository ); + MavenExecutionRequest setLocalRepository(ArtifactRepository repository); ArtifactRepository getLocalRepository(); // Interactive - MavenExecutionRequest setInteractiveMode( boolean interactive ); + MavenExecutionRequest setInteractiveMode(boolean interactive); boolean isInteractiveMode(); // Offline - MavenExecutionRequest setOffline( boolean offline ); + MavenExecutionRequest setOffline(boolean offline); boolean isOffline(); boolean isCacheTransferError(); - MavenExecutionRequest setCacheTransferError( boolean cacheTransferError ); + MavenExecutionRequest setCacheTransferError(boolean cacheTransferError); boolean isCacheNotFound(); - MavenExecutionRequest setCacheNotFound( boolean cacheNotFound ); + MavenExecutionRequest setCacheNotFound(boolean cacheNotFound); // Profiles List getProfiles(); - MavenExecutionRequest addProfile( Profile profile ); + MavenExecutionRequest addProfile(Profile profile); - MavenExecutionRequest setProfiles( List profiles ); + MavenExecutionRequest setProfiles(List profiles); /** * @deprecated Since Maven 4: use {@link #getProfileActivation()}. */ @Deprecated - MavenExecutionRequest addActiveProfile( String profile ); + MavenExecutionRequest addActiveProfile(String profile); /** * @deprecated Since Maven 4: use {@link #getProfileActivation()}. */ @Deprecated - MavenExecutionRequest addActiveProfiles( List profiles ); + MavenExecutionRequest addActiveProfiles(List profiles); /** * @deprecated Since Maven 4: use {@link #getProfileActivation()}. */ @Deprecated - MavenExecutionRequest setActiveProfiles( List profiles ); + MavenExecutionRequest setActiveProfiles(List profiles); /** * @return The list of profiles that the user wants to activate. @@ -318,19 +311,19 @@ public interface MavenExecutionRequest * @deprecated Since Maven 4: use {@link #getProfileActivation()}. */ @Deprecated - MavenExecutionRequest addInactiveProfile( String profile ); + MavenExecutionRequest addInactiveProfile(String profile); /** * @deprecated Since Maven 4: use {@link #getProfileActivation()}. */ @Deprecated - MavenExecutionRequest addInactiveProfiles( List profiles ); + MavenExecutionRequest addInactiveProfiles(List profiles); /** * @deprecated Since Maven 4: use {@link #getProfileActivation()}. */ @Deprecated - MavenExecutionRequest setInactiveProfiles( List profiles ); + MavenExecutionRequest setInactiveProfiles(List profiles); /** * @return The list of profiles that the user wants to de-activate. @@ -354,48 +347,48 @@ public interface MavenExecutionRequest // Proxies List getProxies(); - MavenExecutionRequest setProxies( List proxies ); + MavenExecutionRequest setProxies(List proxies); - MavenExecutionRequest addProxy( Proxy proxy ); + MavenExecutionRequest addProxy(Proxy proxy); // Servers List getServers(); - MavenExecutionRequest setServers( List servers ); + MavenExecutionRequest setServers(List servers); - MavenExecutionRequest addServer( Server server ); + MavenExecutionRequest addServer(Server server); // Mirrors List getMirrors(); - MavenExecutionRequest setMirrors( List mirrors ); + MavenExecutionRequest setMirrors(List mirrors); - MavenExecutionRequest addMirror( Mirror mirror ); + MavenExecutionRequest addMirror(Mirror mirror); // Plugin groups List getPluginGroups(); - MavenExecutionRequest setPluginGroups( List pluginGroups ); + MavenExecutionRequest setPluginGroups(List pluginGroups); - MavenExecutionRequest addPluginGroup( String pluginGroup ); + MavenExecutionRequest addPluginGroup(String pluginGroup); - MavenExecutionRequest addPluginGroups( List pluginGroups ); + MavenExecutionRequest addPluginGroups(List pluginGroups); boolean isProjectPresent(); - MavenExecutionRequest setProjectPresent( boolean isProjectPresent ); + MavenExecutionRequest setProjectPresent(boolean isProjectPresent); File getUserSettingsFile(); - MavenExecutionRequest setUserSettingsFile( File userSettingsFile ); + MavenExecutionRequest setUserSettingsFile(File userSettingsFile); File getGlobalSettingsFile(); - MavenExecutionRequest setGlobalSettingsFile( File globalSettingsFile ); + MavenExecutionRequest setGlobalSettingsFile(File globalSettingsFile); - MavenExecutionRequest addRemoteRepository( ArtifactRepository repository ); + MavenExecutionRequest addRemoteRepository(ArtifactRepository repository); - MavenExecutionRequest addPluginArtifactRepository( ArtifactRepository repository ); + MavenExecutionRequest addPluginArtifactRepository(ArtifactRepository repository); /** * Set a new list of remote repositories to use the execution request. This is necessary if you perform @@ -405,25 +398,25 @@ public interface MavenExecutionRequest * @param repositories * @return This request, never {@code null}. */ - MavenExecutionRequest setRemoteRepositories( List repositories ); + MavenExecutionRequest setRemoteRepositories(List repositories); List getRemoteRepositories(); - MavenExecutionRequest setPluginArtifactRepositories( List repositories ); + MavenExecutionRequest setPluginArtifactRepositories(List repositories); List getPluginArtifactRepositories(); - MavenExecutionRequest setRepositoryCache( RepositoryCache repositoryCache ); + MavenExecutionRequest setRepositoryCache(RepositoryCache repositoryCache); RepositoryCache getRepositoryCache(); WorkspaceReader getWorkspaceReader(); - MavenExecutionRequest setWorkspaceReader( WorkspaceReader workspaceReader ); + MavenExecutionRequest setWorkspaceReader(WorkspaceReader workspaceReader); File getUserToolchainsFile(); - MavenExecutionRequest setUserToolchainsFile( File userToolchainsFile ); + MavenExecutionRequest setUserToolchainsFile(File userToolchainsFile); /** * @@ -439,11 +432,11 @@ public interface MavenExecutionRequest * @return this request * @since 3.3.0 */ - MavenExecutionRequest setGlobalToolchainsFile( File globalToolchainsFile ); + MavenExecutionRequest setGlobalToolchainsFile(File globalToolchainsFile); ExecutionListener getExecutionListener(); - MavenExecutionRequest setExecutionListener( ExecutionListener executionListener ); + MavenExecutionRequest setExecutionListener(ExecutionListener executionListener); ProjectBuildingRequest getProjectBuildingRequest(); @@ -455,7 +448,7 @@ public interface MavenExecutionRequest /** * @since 3.1 */ - MavenExecutionRequest setUseLegacyLocalRepository( boolean useLegacyLocalRepository ); + MavenExecutionRequest setUseLegacyLocalRepository(boolean useLegacyLocalRepository); /** * Controls the {@link org.apache.maven.lifecycle.internal.builder.Builder} used by Maven by specification @@ -463,7 +456,7 @@ public interface MavenExecutionRequest * * @since 3.2.0 */ - MavenExecutionRequest setBuilderId( String builderId ); + MavenExecutionRequest setBuilderId(String builderId); /** * Controls the {@link org.apache.maven.lifecycle.internal.builder.Builder} used by Maven by specification @@ -479,7 +472,7 @@ public interface MavenExecutionRequest * @return this request * @since 3.3.0 */ - MavenExecutionRequest setToolchains( Map> toolchains ); + MavenExecutionRequest setToolchains(Map> toolchains); /** * @@ -491,7 +484,7 @@ public interface MavenExecutionRequest /** * @since 3.3.0 */ - void setMultiModuleProjectDirectory( File file ); + void setMultiModuleProjectDirectory(File file); /** * @since 3.3.0 @@ -501,7 +494,7 @@ public interface MavenExecutionRequest /** * @since 3.3.0 */ - MavenExecutionRequest setEventSpyDispatcher( EventSpyDispatcher eventSpyDispatcher ); + MavenExecutionRequest setEventSpyDispatcher(EventSpyDispatcher eventSpyDispatcher); /** * @since 3.3.0 diff --git a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulationException.java b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulationException.java index ddd6ad2266..29c5bcd872 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulationException.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,26 +16,21 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; /** * @author Jason van Zyl */ -public class MavenExecutionRequestPopulationException - extends Exception -{ - public MavenExecutionRequestPopulationException( String message ) - { - super( message ); +public class MavenExecutionRequestPopulationException extends Exception { + public MavenExecutionRequestPopulationException(String message) { + super(message); } - public MavenExecutionRequestPopulationException( Throwable cause ) - { - super( cause ); + public MavenExecutionRequestPopulationException(Throwable cause) { + super(cause); } - public MavenExecutionRequestPopulationException( String message, - Throwable cause ) - { - super( message, cause ); + public MavenExecutionRequestPopulationException(String message, Throwable cause) { + super(message, cause); } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulator.java b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulator.java index c2d4c845fd..1a5dbf8929 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulator.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionRequestPopulator.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.settings.Settings; import org.apache.maven.toolchain.model.PersistedToolchains; @@ -27,8 +26,7 @@ import org.apache.maven.toolchain.model.PersistedToolchains; * * @author Benjamin Bentmann */ -public interface MavenExecutionRequestPopulator -{ +public interface MavenExecutionRequestPopulator { /** * Copies the values from the given toolchains into the specified execution request. This method will replace any * existing values in the execution request that are controlled by the toolchains. Hence, it is expected that this @@ -40,8 +38,8 @@ public interface MavenExecutionRequestPopulator * @throws MavenExecutionRequestPopulationException If the execution request could not be populated. * @since 3.3.0 */ - MavenExecutionRequest populateFromToolchains( MavenExecutionRequest request, PersistedToolchains toolchains ) - throws MavenExecutionRequestPopulationException; + MavenExecutionRequest populateFromToolchains(MavenExecutionRequest request, PersistedToolchains toolchains) + throws MavenExecutionRequestPopulationException; /** * Injects default values like plugin groups or repositories into the specified execution request. @@ -50,8 +48,8 @@ public interface MavenExecutionRequestPopulator * @return The populated execution request, never {@code null}. * @throws MavenExecutionRequestPopulationException If the execution request could not be populated. */ - MavenExecutionRequest populateDefaults( MavenExecutionRequest request ) - throws MavenExecutionRequestPopulationException; + MavenExecutionRequest populateDefaults(MavenExecutionRequest request) + throws MavenExecutionRequestPopulationException; /*if_not[MAVEN4]*/ @@ -66,8 +64,8 @@ public interface MavenExecutionRequestPopulator * @throws MavenExecutionRequestPopulationException If the execution request could not be populated. */ @Deprecated - MavenExecutionRequest populateFromSettings( MavenExecutionRequest request, Settings settings ) - throws MavenExecutionRequestPopulationException; + MavenExecutionRequest populateFromSettings(MavenExecutionRequest request, Settings settings) + throws MavenExecutionRequestPopulationException; /*end[MAVEN4]*/ diff --git a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionResult.java b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionResult.java index 8a099bb8b0..f04a4b3190 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionResult.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MavenExecutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,28 +16,29 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.List; - import org.apache.maven.project.DependencyResolutionResult; import org.apache.maven.project.MavenProject; /** * @author Jason van Zyl */ -public interface MavenExecutionResult -{ - MavenExecutionResult setProject( MavenProject project ); +public interface MavenExecutionResult { + MavenExecutionResult setProject(MavenProject project); + MavenProject getProject(); - MavenExecutionResult setTopologicallySortedProjects( List projects ); + MavenExecutionResult setTopologicallySortedProjects(List projects); /** * @return the sorted list, or an empty list if there are no projects. */ List getTopologicallySortedProjects(); - MavenExecutionResult setDependencyResolutionResult( DependencyResolutionResult result ); + MavenExecutionResult setDependencyResolutionResult(DependencyResolutionResult result); + DependencyResolutionResult getDependencyResolutionResult(); // for each exception @@ -49,7 +48,7 @@ public interface MavenExecutionResult // - xmlpull parser exception List getExceptions(); - MavenExecutionResult addException( Throwable e ); + MavenExecutionResult addException(Throwable e); boolean hasExceptions(); @@ -59,14 +58,14 @@ public interface MavenExecutionResult * @param project The project to get the build summary for, must not be {@code null}. * @return The build summary for the project or {@code null} if the project has not been built (yet). */ - BuildSummary getBuildSummary( MavenProject project ); + BuildSummary getBuildSummary(MavenProject project); /** * Add the specified build summary. * * @param summary The build summary to add, must not be {@code null}. */ - void addBuildSummary( BuildSummary summary ); + void addBuildSummary(BuildSummary summary); /** * Indicates whether or not the build could be resumed by a second invocation of Maven. @@ -81,5 +80,5 @@ public interface MavenExecutionResult * @see BuildResumptionDataRepository * @see #canResume() */ - void setCanResume( boolean canResume ); + void setCanResume(boolean canResume); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java b/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java index 3617438e81..1b6af0075a 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.io.File; import java.util.Arrays; @@ -28,7 +27,6 @@ import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; - import org.apache.maven.api.Session; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.RepositoryCache; @@ -50,9 +48,7 @@ import org.eclipse.aether.RepositorySystemSession; * * @author Jason van Zyl */ -public class MavenSession - implements Cloneable -{ +public class MavenSession implements Cloneable { private MavenExecutionRequest request; private MavenExecutionResult result; @@ -87,36 +83,30 @@ public class MavenSession * ({@link PluginDescriptor#getPluginLookupKey()}). Plugin contexts itself are mappings of {@link String} keys to * {@link Object} values. */ - @SuppressWarnings( "checkstyle:linelength" ) - private final ConcurrentMap>> pluginContextsByProjectAndPluginKey = - new ConcurrentHashMap<>(); + @SuppressWarnings("checkstyle:linelength") + private final ConcurrentMap>> + pluginContextsByProjectAndPluginKey = new ConcurrentHashMap<>(); - - public void setProjects( List projects ) - { - if ( !projects.isEmpty() ) - { - MavenProject first = projects.get( 0 ); - this.currentProject = ThreadLocal.withInitial( () -> first ); - this.topLevelProject = - projects.stream().filter( project -> project.isExecutionRoot() ).findFirst() - .orElse( first ); - } - else - { + public void setProjects(List projects) { + if (!projects.isEmpty()) { + MavenProject first = projects.get(0); + this.currentProject = ThreadLocal.withInitial(() -> first); + this.topLevelProject = projects.stream() + .filter(project -> project.isExecutionRoot()) + .findFirst() + .orElse(first); + } else { this.currentProject = new ThreadLocal<>(); this.topLevelProject = null; } this.projects = projects; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return request.getLocalRepository(); } - public List getGoals() - { + public List getGoals() { return request.getGoals(); } @@ -127,8 +117,7 @@ public class MavenSession * * @return The user properties, never {@code null}. */ - public Properties getUserProperties() - { + public Properties getUserProperties() { return request.getUserProperties(); } @@ -138,69 +127,56 @@ public class MavenSession * * @return The system properties, never {@code null}. */ - public Properties getSystemProperties() - { + public Properties getSystemProperties() { return request.getSystemProperties(); } - public Settings getSettings() - { + public Settings getSettings() { return settings; } - public List getProjects() - { + public List getProjects() { return projects; } - public String getExecutionRootDirectory() - { + public String getExecutionRootDirectory() { return request.getBaseDirectory(); } - public MavenExecutionRequest getRequest() - { + public MavenExecutionRequest getRequest() { return request; } - public void setCurrentProject( MavenProject currentProject ) - { - this.currentProject.set( currentProject ); + public void setCurrentProject(MavenProject currentProject) { + this.currentProject.set(currentProject); } - public MavenProject getCurrentProject() - { + public MavenProject getCurrentProject() { return currentProject.get(); } - public ProjectBuildingRequest getProjectBuildingRequest() - { - return request.getProjectBuildingRequest().setRepositorySession( getRepositorySession() ); + public ProjectBuildingRequest getProjectBuildingRequest() { + return request.getProjectBuildingRequest().setRepositorySession(getRepositorySession()); } - public List getPluginGroups() - { + public List getPluginGroups() { return request.getPluginGroups(); } - public boolean isOffline() - { + public boolean isOffline() { return request.isOffline(); } - public MavenProject getTopLevelProject() - { + public MavenProject getTopLevelProject() { return topLevelProject; } - public MavenExecutionResult getResult() - { + public MavenExecutionResult getResult() { return result; } // Backward compat - /** * Returns the plugin context for given key ({@link PluginDescriptor#getPluginLookupKey()} and * {@link MavenProject}, never returns {@code null} as if context not present, creates it. @@ -209,87 +185,72 @@ public class MavenSession * implements {@link ConcurrentMap} as well. * */ - public Map getPluginContext( PluginDescriptor plugin, MavenProject project ) - { + public Map getPluginContext(PluginDescriptor plugin, MavenProject project) { String projectKey = project.getId(); - ConcurrentMap> pluginContextsByKey = pluginContextsByProjectAndPluginKey - .computeIfAbsent( projectKey, k -> new ConcurrentHashMap<>() ); + ConcurrentMap> pluginContextsByKey = + pluginContextsByProjectAndPluginKey.computeIfAbsent(projectKey, k -> new ConcurrentHashMap<>()); String pluginKey = plugin.getPluginLookupKey(); - return pluginContextsByKey.computeIfAbsent( pluginKey, k -> new ConcurrentHashMap<>() ); + return pluginContextsByKey.computeIfAbsent(pluginKey, k -> new ConcurrentHashMap<>()); } - public ProjectDependencyGraph getProjectDependencyGraph() - { + public ProjectDependencyGraph getProjectDependencyGraph() { return projectDependencyGraph; } - public void setProjectDependencyGraph( ProjectDependencyGraph projectDependencyGraph ) - { + public void setProjectDependencyGraph(ProjectDependencyGraph projectDependencyGraph) { this.projectDependencyGraph = projectDependencyGraph; } - public String getReactorFailureBehavior() - { + public String getReactorFailureBehavior() { return request.getReactorFailureBehavior(); } @Override - public MavenSession clone() - { - try - { + public MavenSession clone() { + try { MavenSession clone = (MavenSession) super.clone(); // the default must become the current project of the thread that clones this MavenProject current = getCurrentProject(); // we replace the thread local of the clone to prevent write through and enforce the new default value - clone.currentProject = ThreadLocal.withInitial( () -> current ); + clone.currentProject = ThreadLocal.withInitial(() -> current); return clone; - } - catch ( CloneNotSupportedException e ) - { - throw new RuntimeException( "Bug", e ); + } catch (CloneNotSupportedException e) { + throw new RuntimeException("Bug", e); } } - public Date getStartTime() - { + public Date getStartTime() { return request.getStartTime(); } - public boolean isParallel() - { + public boolean isParallel() { return parallel; } - public void setParallel( boolean parallel ) - { + public void setParallel(boolean parallel) { this.parallel = parallel; } - public RepositorySystemSession getRepositorySession() - { + public RepositorySystemSession getRepositorySession() { return repositorySession; } private Map projectMap; - public void setProjectMap( Map projectMap ) - { + public void setProjectMap(Map projectMap) { this.projectMap = projectMap; } /** This is a provisional method and may be removed */ - public List getAllProjects() - { + public List getAllProjects() { return allProjects; } /** This is a provisional method and may be removed */ - public void setAllProjects( List allProjects ) - { + public void setAllProjects(List allProjects) { this.allProjects = allProjects; } @@ -307,66 +268,92 @@ public class MavenSession @Deprecated /** @deprecated This appears not to be used anywhere within Maven itself. */ - public Map getProjectMap() - { + public Map getProjectMap() { return projectMap; } @Deprecated - public MavenSession( PlexusContainer container, RepositorySystemSession repositorySession, - MavenExecutionRequest request, MavenExecutionResult result ) - { + public MavenSession( + PlexusContainer container, + RepositorySystemSession repositorySession, + MavenExecutionRequest request, + MavenExecutionResult result) { this.container = container; this.request = request; this.result = result; - this.settings = adaptSettings( request ); + this.settings = adaptSettings(request); this.repositorySession = repositorySession; } @Deprecated - public MavenSession( PlexusContainer container, MavenExecutionRequest request, MavenExecutionResult result, - MavenProject project ) - { - this( container, request, result, Arrays.asList( new MavenProject[]{project} ) ); + public MavenSession( + PlexusContainer container, + MavenExecutionRequest request, + MavenExecutionResult result, + MavenProject project) { + this(container, request, result, Arrays.asList(new MavenProject[] {project})); } @Deprecated - @SuppressWarnings( "checkstyle:parameternumber" ) - public MavenSession( PlexusContainer container, Settings settings, ArtifactRepository localRepository, - EventDispatcher eventDispatcher, ReactorManager unused, List goals, - String executionRootDir, Properties executionProperties, Date startTime ) - { - this( container, settings, localRepository, eventDispatcher, unused, goals, executionRootDir, - executionProperties, null, startTime ); + @SuppressWarnings("checkstyle:parameternumber") + public MavenSession( + PlexusContainer container, + Settings settings, + ArtifactRepository localRepository, + EventDispatcher eventDispatcher, + ReactorManager unused, + List goals, + String executionRootDir, + Properties executionProperties, + Date startTime) { + this( + container, + settings, + localRepository, + eventDispatcher, + unused, + goals, + executionRootDir, + executionProperties, + null, + startTime); } @Deprecated - @SuppressWarnings( "checkstyle:parameternumber" ) - public MavenSession( PlexusContainer container, Settings settings, ArtifactRepository localRepository, - EventDispatcher eventDispatcher, ReactorManager unused, List goals, - String executionRootDir, Properties executionProperties, Properties userProperties, - Date startTime ) - { + @SuppressWarnings("checkstyle:parameternumber") + public MavenSession( + PlexusContainer container, + Settings settings, + ArtifactRepository localRepository, + EventDispatcher eventDispatcher, + ReactorManager unused, + List goals, + String executionRootDir, + Properties executionProperties, + Properties userProperties, + Date startTime) { this.container = container; this.settings = settings; this.executionProperties = executionProperties; this.request = new DefaultMavenExecutionRequest(); - this.request.setUserProperties( userProperties ); - this.request.setLocalRepository( localRepository ); - this.request.setGoals( goals ); - this.request.setBaseDirectory( ( executionRootDir != null ) ? new File( executionRootDir ) : null ); - this.request.setStartTime( startTime ); + this.request.setUserProperties(userProperties); + this.request.setLocalRepository(localRepository); + this.request.setGoals(goals); + this.request.setBaseDirectory((executionRootDir != null) ? new File(executionRootDir) : null); + this.request.setStartTime(startTime); } @Deprecated - public MavenSession( PlexusContainer container, MavenExecutionRequest request, MavenExecutionResult result, - List projects ) - { + public MavenSession( + PlexusContainer container, + MavenExecutionRequest request, + MavenExecutionResult result, + List projects) { this.container = container; this.request = request; this.result = result; - this.settings = adaptSettings( request ); - setProjects( projects ); + this.settings = adaptSettings(request); + setProjects(projects); } /** @@ -375,26 +362,25 @@ public class MavenSession * The CLI feeds into an execution request so if a particular value is present in the execution request * then we will take that over the value coming from the user settings. */ - private static Settings adaptSettings( MavenExecutionRequest request ) - { + private static Settings adaptSettings(MavenExecutionRequest request) { File localRepo = request.getLocalRepositoryPath(); - return new Settings( org.apache.maven.api.settings.Settings.newBuilder() - .localRepository( localRepo != null ? localRepo.getAbsolutePath() : null ) - .interactiveMode( request.isInteractiveMode() ) - .offline( request.isOffline() ) - .proxies( request.getProxies().stream().map( Proxy::getDelegate ).collect( Collectors.toList() ) ) - .servers( request.getServers().stream().map( Server::getDelegate ).collect( Collectors.toList() ) ) - .mirrors( request.getMirrors().stream().map( Mirror::getDelegate ).collect( Collectors.toList() ) ) - .profiles( request.getProfiles().stream() - .map( SettingsUtils::convertToSettingsProfile ).collect( Collectors.toList() ) ) - .activeProfiles( request.getActiveProfiles() ) - .pluginGroups( request.getPluginGroups() ) - .build() ); + return new Settings(org.apache.maven.api.settings.Settings.newBuilder() + .localRepository(localRepo != null ? localRepo.getAbsolutePath() : null) + .interactiveMode(request.isInteractiveMode()) + .offline(request.isOffline()) + .proxies(request.getProxies().stream().map(Proxy::getDelegate).collect(Collectors.toList())) + .servers(request.getServers().stream().map(Server::getDelegate).collect(Collectors.toList())) + .mirrors(request.getMirrors().stream().map(Mirror::getDelegate).collect(Collectors.toList())) + .profiles(request.getProfiles().stream() + .map(SettingsUtils::convertToSettingsProfile) + .collect(Collectors.toList())) + .activeProfiles(request.getActiveProfiles()) + .pluginGroups(request.getPluginGroups()) + .build()); } @Deprecated - public List getSortedProjects() - { + public List getSortedProjects() { return getProjects(); } @@ -403,20 +389,17 @@ public class MavenSession // Used by Tycho and will break users and force them to upgrade to Maven 3.1 so we should really leave // this here, possibly indefinitely. // - public RepositoryCache getRepositoryCache() - { + public RepositoryCache getRepositoryCache() { return null; } @Deprecated - public EventDispatcher getEventDispatcher() - { + public EventDispatcher getEventDispatcher() { return null; } @Deprecated - public boolean isUsingPOMsFromFilesystem() - { + public boolean isUsingPOMsFromFilesystem() { return request.isProjectPresent(); } @@ -424,59 +407,46 @@ public class MavenSession * @deprecated Use either {@link #getUserProperties()} or {@link #getSystemProperties()}. */ @Deprecated - public Properties getExecutionProperties() - { - if ( executionProperties == null ) - { + public Properties getExecutionProperties() { + if (executionProperties == null) { executionProperties = new Properties(); - executionProperties.putAll( request.getSystemProperties() ); - executionProperties.putAll( request.getUserProperties() ); + executionProperties.putAll(request.getSystemProperties()); + executionProperties.putAll(request.getUserProperties()); } return executionProperties; } @Deprecated - public PlexusContainer getContainer() - { + public PlexusContainer getContainer() { return container; } @Deprecated - public Object lookup( String role ) - throws ComponentLookupException - { - return container.lookup( role ); + public Object lookup(String role) throws ComponentLookupException { + return container.lookup(role); } @Deprecated - public Object lookup( String role, String roleHint ) - throws ComponentLookupException - { - return container.lookup( role, roleHint ); + public Object lookup(String role, String roleHint) throws ComponentLookupException { + return container.lookup(role, roleHint); } @Deprecated - public List lookupList( String role ) - throws ComponentLookupException - { - return container.lookupList( role ); + public List lookupList(String role) throws ComponentLookupException { + return container.lookupList(role); } @Deprecated - public Map lookupMap( String role ) - throws ComponentLookupException - { - return container.lookupMap( role ); + public Map lookupMap(String role) throws ComponentLookupException { + return container.lookupMap(role); } - public Session getSession() - { + public Session getSession() { return session; } - public void setSession( Session session ) - { + public void setSession(Session session) { this.session = session; } /*end[MAVEN4]*/ diff --git a/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionEvent.java b/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionEvent.java index 85a58cb481..5022f0fda8 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionEvent.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.MojoExecution; @@ -34,8 +33,7 @@ import org.apache.maven.project.MavenProject; * @see org.apache.maven.execution.scope.WeakMojoExecutionListener * @since 3.1.2 */ -public class MojoExecutionEvent -{ +public class MojoExecutionEvent { private final MavenSession session; private final MavenProject project; @@ -46,14 +44,12 @@ public class MojoExecutionEvent private final Throwable cause; - public MojoExecutionEvent( MavenSession session, MavenProject project, MojoExecution mojoExecution, Mojo mojo ) - { - this( session, project, mojoExecution, mojo, null ); + public MojoExecutionEvent(MavenSession session, MavenProject project, MojoExecution mojoExecution, Mojo mojo) { + this(session, project, mojoExecution, mojo, null); } - public MojoExecutionEvent( MavenSession session, MavenProject project, MojoExecution mojoExecution, Mojo mojo, - Throwable cause ) - { + public MojoExecutionEvent( + MavenSession session, MavenProject project, MojoExecution mojoExecution, Mojo mojo, Throwable cause) { this.session = session; this.project = project; this.mojoExecution = mojoExecution; @@ -61,28 +57,23 @@ public class MojoExecutionEvent this.cause = cause; } - public MavenSession getSession() - { + public MavenSession getSession() { return session; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public MojoExecution getExecution() - { + public MojoExecution getExecution() { return mojoExecution; } - public Mojo getMojo() - { + public Mojo getMojo() { return mojo; } - public Throwable getCause() - { + public Throwable getCause() { return cause; } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionListener.java b/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionListener.java index 97d6b03987..b935fb804c 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/execution/MojoExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.plugin.MojoExecutionException; @@ -30,13 +29,10 @@ import org.apache.maven.plugin.MojoExecutionException; * @see org.apache.maven.execution.scope.WeakMojoExecutionListener * @since 3.1.2 */ -public interface MojoExecutionListener -{ - void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException; +public interface MojoExecutionListener { + void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException; - void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException; + void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException; - void afterExecutionFailure( MojoExecutionEvent event ); + void afterExecutionFailure(MojoExecutionEvent event); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ProfileActivation.java b/maven-core/src/main/java/org/apache/maven/execution/ProfileActivation.java index ad00a74054..1672c8c17c 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ProfileActivation.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ProfileActivation.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,9 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; + +import static java.util.stream.Collectors.toSet; import java.util.ArrayList; import java.util.Collections; @@ -27,14 +28,11 @@ import java.util.Map; import java.util.Set; import java.util.function.Predicate; -import static java.util.stream.Collectors.toSet; - /** * Container for storing the request from the user to activate or de-activate certain profiles and optionally fail the * build if those profiles do not exist. */ -public class ProfileActivation -{ +public class ProfileActivation { private final Map activations = new HashMap<>(); /** @@ -42,9 +40,8 @@ public class ProfileActivation * @deprecated Use {@link #getRequiredActiveProfileIds()} and {@link #getOptionalActiveProfileIds()} instead. */ @Deprecated - public List getActiveProfiles() - { - return Collections.unmodifiableList( new ArrayList<>( getProfileIds( pa -> pa.active ) ) ); + public List getActiveProfiles() { + return Collections.unmodifiableList(new ArrayList<>(getProfileIds(pa -> pa.active))); } /** @@ -52,9 +49,8 @@ public class ProfileActivation * @deprecated Use {@link #getRequiredInactiveProfileIds()} and {@link #getOptionalInactiveProfileIds()} instead. */ @Deprecated - public List getInactiveProfiles() - { - return Collections.unmodifiableList( new ArrayList<>( getProfileIds( pa -> !pa.active ) ) ); + public List getInactiveProfiles() { + return Collections.unmodifiableList(new ArrayList<>(getProfileIds(pa -> !pa.active))); } /** @@ -63,10 +59,9 @@ public class ProfileActivation * @deprecated Use {@link #activateOptionalProfile(String)} or {@link #activateRequiredProfile(String)} instead. */ @Deprecated - public void overwriteActiveProfiles( List activeProfileIds ) - { - getActiveProfiles().forEach( this.activations::remove ); - activeProfileIds.forEach( this::activateOptionalProfile ); + public void overwriteActiveProfiles(List activeProfileIds) { + getActiveProfiles().forEach(this.activations::remove); + activeProfileIds.forEach(this::activateOptionalProfile); } /** @@ -75,46 +70,41 @@ public class ProfileActivation * @deprecated Use {@link #deactivateOptionalProfile(String)} or {@link #deactivateRequiredProfile(String)} instead. */ @Deprecated - public void overwriteInactiveProfiles( List inactiveProfileIds ) - { - getInactiveProfiles().forEach( this.activations::remove ); - inactiveProfileIds.forEach( this::deactivateOptionalProfile ); + public void overwriteInactiveProfiles(List inactiveProfileIds) { + getInactiveProfiles().forEach(this.activations::remove); + inactiveProfileIds.forEach(this::deactivateOptionalProfile); } /** * Mark a profile as required and activated. * @param id The identifier of the profile. */ - public void activateRequiredProfile( String id ) - { - this.activations.put( id, ActivationSettings.ACTIVATION_REQUIRED ); + public void activateRequiredProfile(String id) { + this.activations.put(id, ActivationSettings.ACTIVATION_REQUIRED); } /** * Mark a profile as optional and activated. * @param id The identifier of the profile. */ - public void activateOptionalProfile( String id ) - { - this.activations.put( id, ActivationSettings.ACTIVATION_OPTIONAL ); + public void activateOptionalProfile(String id) { + this.activations.put(id, ActivationSettings.ACTIVATION_OPTIONAL); } /** * Mark a profile as required and deactivated. * @param id The identifier of the profile. */ - public void deactivateRequiredProfile( String id ) - { - this.activations.put( id, ActivationSettings.DEACTIVATION_REQUIRED ); + public void deactivateRequiredProfile(String id) { + this.activations.put(id, ActivationSettings.DEACTIVATION_REQUIRED); } /** * Mark a profile as optional and deactivated. * @param id The identifier of the profile. */ - public void deactivateOptionalProfile( String id ) - { - this.activations.put( id, ActivationSettings.DEACTIVATION_OPTIONAL ); + public void deactivateOptionalProfile(String id) { + this.activations.put(id, ActivationSettings.DEACTIVATION_OPTIONAL); } /** @@ -123,49 +113,43 @@ public class ProfileActivation * @param active Should the profile be activated? * @param optional Can the build continue if the profile does not exist? */ - public void addProfileActivation( String id, boolean active, boolean optional ) - { - final ActivationSettings settings = ActivationSettings.of( active, optional ); - this.activations.put( id, settings ); + public void addProfileActivation(String id, boolean active, boolean optional) { + final ActivationSettings settings = ActivationSettings.of(active, optional); + this.activations.put(id, settings); } - private Set getProfileIds( final Predicate predicate ) - { + private Set getProfileIds(final Predicate predicate) { return this.activations.entrySet().stream() - .filter( e -> predicate.test( e.getValue() ) ) - .map( Map.Entry::getKey ) - .collect( toSet() ); + .filter(e -> predicate.test(e.getValue())) + .map(Map.Entry::getKey) + .collect(toSet()); } /** * @return Required active profile identifiers, never {@code null}. */ - public Set getRequiredActiveProfileIds() - { - return getProfileIds( pa -> !pa.optional && pa.active ); + public Set getRequiredActiveProfileIds() { + return getProfileIds(pa -> !pa.optional && pa.active); } /** * @return Optional active profile identifiers, never {@code null}. */ - public Set getOptionalActiveProfileIds() - { - return getProfileIds( pa -> pa.optional && pa.active ); + public Set getOptionalActiveProfileIds() { + return getProfileIds(pa -> pa.optional && pa.active); } /** * @return Required inactive profile identifiers, never {@code null}. */ - public Set getRequiredInactiveProfileIds() - { - return getProfileIds( pa -> !pa.optional && !pa.active ); + public Set getRequiredInactiveProfileIds() { + return getProfileIds(pa -> !pa.optional && !pa.active); } /** * @return Optional inactive profile identifiers, never {@code null}. */ - public Set getOptionalInactiveProfileIds() - { - return getProfileIds( pa -> pa.optional && !pa.active ); + public Set getOptionalInactiveProfileIds() { + return getProfileIds(pa -> pa.optional && !pa.active); } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ProjectActivation.java b/maven-core/src/main/java/org/apache/maven/execution/ProjectActivation.java index a1d366cb28..8a197dc035 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ProjectActivation.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ProjectActivation.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,6 +16,9 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; + +import static java.util.stream.Collectors.toSet; import java.util.ArrayList; import java.util.Collections; @@ -27,16 +28,12 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; -import static java.util.stream.Collectors.toSet; - /** * Container for storing the request from the user to activate or deactivate certain projects and optionally fail the * build if those projects do not exist. */ -public class ProjectActivation -{ - private static class ProjectActivationSettings - { +public class ProjectActivation { + private static class ProjectActivationSettings { /** * The selector of a project. This can be the project directory, [groupId]:[artifactId] or :[artifactId]. */ @@ -47,8 +44,7 @@ public class ProjectActivation */ final ActivationSettings activationSettings; - ProjectActivationSettings( String selector, ActivationSettings activationSettings ) - { + ProjectActivationSettings(String selector, ActivationSettings activationSettings) { this.selector = selector; this.activationSettings = activationSettings; } @@ -65,55 +61,45 @@ public class ProjectActivation * @param active Should the project be activated? * @param optional Can the build continue if the project does not exist? */ - public void addProjectActivation( String selector, boolean active, boolean optional ) - { - final ActivationSettings settings = ActivationSettings.of( active, optional ); - this.activations.add( new ProjectActivationSettings( selector, settings ) ); + public void addProjectActivation(String selector, boolean active, boolean optional) { + final ActivationSettings settings = ActivationSettings.of(active, optional); + this.activations.add(new ProjectActivationSettings(selector, settings)); } - private Stream getProjects( final Predicate predicate ) - { - return this.activations.stream() - .filter( activation -> predicate.test( activation.activationSettings ) ); + private Stream getProjects(final Predicate predicate) { + return this.activations.stream().filter(activation -> predicate.test(activation.activationSettings)); } - private Set getProjectSelectors( final Predicate predicate ) - { - return getProjects( predicate ) - .map( activation -> activation.selector ) - .collect( toSet() ); + private Set getProjectSelectors(final Predicate predicate) { + return getProjects(predicate).map(activation -> activation.selector).collect(toSet()); } /** * @return Required active project selectors, never {@code null}. */ - public Set getRequiredActiveProjectSelectors() - { - return getProjectSelectors( pa -> !pa.optional && pa.active ); + public Set getRequiredActiveProjectSelectors() { + return getProjectSelectors(pa -> !pa.optional && pa.active); } /** * @return Optional active project selectors, never {@code null}. */ - public Set getOptionalActiveProjectSelectors() - { - return getProjectSelectors( pa -> pa.optional && pa.active ); + public Set getOptionalActiveProjectSelectors() { + return getProjectSelectors(pa -> pa.optional && pa.active); } /** * @return Required inactive project selectors, never {@code null}. */ - public Set getRequiredInactiveProjectSelectors() - { - return getProjectSelectors( pa -> !pa.optional && !pa.active ); + public Set getRequiredInactiveProjectSelectors() { + return getProjectSelectors(pa -> !pa.optional && !pa.active); } /** * @return Optional inactive project selectors, never {@code null}. */ - public Set getOptionalInactiveProjectSelectors() - { - return getProjectSelectors( pa -> pa.optional && !pa.active ); + public Set getOptionalInactiveProjectSelectors() { + return getProjectSelectors(pa -> pa.optional && !pa.active); } /** @@ -122,9 +108,8 @@ public class ProjectActivation * instead. */ @Deprecated - public List getSelectedProjects() - { - return Collections.unmodifiableList( new ArrayList<>( getProjectSelectors( pa -> pa.active ) ) ); + public List getSelectedProjects() { + return Collections.unmodifiableList(new ArrayList<>(getProjectSelectors(pa -> pa.active))); } /** @@ -133,9 +118,8 @@ public class ProjectActivation * instead. */ @Deprecated - public List getExcludedProjects() - { - return Collections.unmodifiableList( new ArrayList<>( getProjectSelectors( pa -> !pa.active ) ) ); + public List getExcludedProjects() { + return Collections.unmodifiableList(new ArrayList<>(getProjectSelectors(pa -> !pa.active))); } /** @@ -144,11 +128,10 @@ public class ProjectActivation * @deprecated Use {@link #activateOptionalProject(String)} or {@link #activateRequiredProject(String)} instead. */ @Deprecated - public void overwriteActiveProjects( List activeProjectSelectors ) - { - List projects = getProjects( pa -> pa.active ).collect( Collectors.toList() ); - this.activations.removeAll( projects ); - activeProjectSelectors.forEach( this::activateOptionalProject ); + public void overwriteActiveProjects(List activeProjectSelectors) { + List projects = getProjects(pa -> pa.active).collect(Collectors.toList()); + this.activations.removeAll(projects); + activeProjectSelectors.forEach(this::activateOptionalProject); } /** @@ -157,51 +140,45 @@ public class ProjectActivation * @deprecated Use {@link #deactivateOptionalProject(String)} or {@link #deactivateRequiredProject(String)} instead. */ @Deprecated - public void overwriteInactiveProjects( List inactiveProjectSelectors ) - { - List projects = getProjects( pa -> !pa.active ).collect( Collectors.toList() ); - this.activations.removeAll( projects ); - inactiveProjectSelectors.forEach( this::deactivateOptionalProject ); + public void overwriteInactiveProjects(List inactiveProjectSelectors) { + List projects = getProjects(pa -> !pa.active).collect(Collectors.toList()); + this.activations.removeAll(projects); + inactiveProjectSelectors.forEach(this::deactivateOptionalProject); } /** * Mark a project as required and activated. * @param selector The selector of the project. */ - public void activateRequiredProject( String selector ) - { - this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.ACTIVATION_REQUIRED ) ); + public void activateRequiredProject(String selector) { + this.activations.add(new ProjectActivationSettings(selector, ActivationSettings.ACTIVATION_REQUIRED)); } /** * Mark a project as optional and activated. * @param selector The selector of the project. */ - public void activateOptionalProject( String selector ) - { - this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.ACTIVATION_OPTIONAL ) ); + public void activateOptionalProject(String selector) { + this.activations.add(new ProjectActivationSettings(selector, ActivationSettings.ACTIVATION_OPTIONAL)); } /** * Mark a project as required and deactivated. * @param selector The selector of the project. */ - public void deactivateRequiredProject( String selector ) - { - this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.DEACTIVATION_REQUIRED ) ); + public void deactivateRequiredProject(String selector) { + this.activations.add(new ProjectActivationSettings(selector, ActivationSettings.DEACTIVATION_REQUIRED)); } /** * Mark a project as optional and deactivated. * @param selector The selector of the project. */ - public void deactivateOptionalProject( String selector ) - { - this.activations.add( new ProjectActivationSettings( selector, ActivationSettings.DEACTIVATION_OPTIONAL ) ); + public void deactivateOptionalProject(String selector) { + this.activations.add(new ProjectActivationSettings(selector, ActivationSettings.DEACTIVATION_OPTIONAL)); } - public boolean isEmpty() - { + public boolean isEmpty() { return this.activations.isEmpty(); } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ProjectDependencyGraph.java b/maven-core/src/main/java/org/apache/maven/execution/ProjectDependencyGraph.java index f28b502671..6f26ebc7a3 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ProjectDependencyGraph.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ProjectDependencyGraph.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.List; - import org.apache.maven.project.MavenProject; /** @@ -29,8 +27,7 @@ import org.apache.maven.project.MavenProject; * @author Benjamin Bentmann * @since 3.0-alpha */ -public interface ProjectDependencyGraph -{ +public interface ProjectDependencyGraph { /** * Gets all collected projects. @@ -58,7 +55,7 @@ public interface ProjectDependencyGraph * downstream projects. * @return The downstream projects in the build order, never {@code null}. */ - List getDownstreamProjects( MavenProject project, boolean transitive ); + List getDownstreamProjects(MavenProject project, boolean transitive); /** * Gets the upstream projects of the specified project. An upstream project is a project that directly or indirectly @@ -69,6 +66,5 @@ public interface ProjectDependencyGraph * upstream projects. * @return The upstream projects in the build order, never {@code null}. */ - List getUpstreamProjects( MavenProject project, boolean transitive ); - + List getUpstreamProjects(MavenProject project, boolean transitive); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionEvent.java b/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionEvent.java index 96cb2262dc..d19cb339cb 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionEvent.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import java.util.List; - import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; @@ -34,8 +32,7 @@ import org.apache.maven.project.MavenProject; * @see ProjectExecutionListener * @since 3.1.2 */ -public class ProjectExecutionEvent -{ +public class ProjectExecutionEvent { private final MavenSession session; @@ -45,48 +42,39 @@ public class ProjectExecutionEvent private final Throwable cause; - public ProjectExecutionEvent( MavenSession session, MavenProject project ) - { - this( session, project, null, null ); + public ProjectExecutionEvent(MavenSession session, MavenProject project) { + this(session, project, null, null); } - public ProjectExecutionEvent( MavenSession session, MavenProject project, List executionPlan ) - { - this( session, project, executionPlan, null ); + public ProjectExecutionEvent(MavenSession session, MavenProject project, List executionPlan) { + this(session, project, executionPlan, null); } - public ProjectExecutionEvent( MavenSession session, MavenProject project, Throwable cause ) - { - this( session, project, null, cause ); + public ProjectExecutionEvent(MavenSession session, MavenProject project, Throwable cause) { + this(session, project, null, cause); } - public ProjectExecutionEvent( MavenSession session, MavenProject project, List executionPlan, - Throwable cause ) - { + public ProjectExecutionEvent( + MavenSession session, MavenProject project, List executionPlan, Throwable cause) { this.session = session; this.project = project; this.executionPlan = executionPlan; this.cause = cause; } - public MavenSession getSession() - { + public MavenSession getSession() { return session; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public List getExecutionPlan() - { + public List getExecutionPlan() { return executionPlan; } - public Throwable getCause() - { + public Throwable getCause() { return cause; } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionListener.java b/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionListener.java index 279742505e..da17ce3c94 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; import org.apache.maven.lifecycle.LifecycleExecutionException; @@ -31,16 +30,12 @@ import org.apache.maven.lifecycle.LifecycleExecutionException; * @see MojoExecutionListener * @since 3.1.2 */ -public interface ProjectExecutionListener -{ - void beforeProjectExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException; +public interface ProjectExecutionListener { + void beforeProjectExecution(ProjectExecutionEvent event) throws LifecycleExecutionException; - void beforeProjectLifecycleExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException; + void beforeProjectLifecycleExecution(ProjectExecutionEvent event) throws LifecycleExecutionException; - void afterProjectExecutionSuccess( ProjectExecutionEvent event ) - throws LifecycleExecutionException; + void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException; - void afterProjectExecutionFailure( ProjectExecutionEvent event ); + void afterProjectExecutionFailure(ProjectExecutionEvent event); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/ReactorManager.java b/maven-core/src/main/java/org/apache/maven/execution/ReactorManager.java index 795ac349b2..7ece350eb3 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/ReactorManager.java +++ b/maven-core/src/main/java/org/apache/maven/execution/ReactorManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,7 +16,12 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.project.DuplicateProjectException; @@ -26,17 +29,11 @@ import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectSorter; import org.codehaus.plexus.util.dag.CycleDetectedException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * ReactorManager - unused */ @Deprecated -public class ReactorManager -{ +public class ReactorManager { public static final String FAIL_FAST = "fail-fast"; public static final String FAIL_AT_END = "fail-at-end"; @@ -62,129 +59,102 @@ public class ReactorManager private Map buildSuccessesByProject = new HashMap<>(); - public ReactorManager( List projects ) - throws CycleDetectedException, DuplicateProjectException - { - this.sorter = new ProjectSorter( projects ); + public ReactorManager(List projects) throws CycleDetectedException, DuplicateProjectException { + this.sorter = new ProjectSorter(projects); } - public Map getPluginContext( PluginDescriptor plugin, MavenProject project ) - { + public Map getPluginContext(PluginDescriptor plugin, MavenProject project) { Map pluginContextsByKey = - pluginContextsByProjectAndPluginKey.computeIfAbsent( project.getId(), k -> new HashMap<>() ); + pluginContextsByProjectAndPluginKey.computeIfAbsent(project.getId(), k -> new HashMap<>()); - return pluginContextsByKey.computeIfAbsent( plugin.getPluginLookupKey(), k -> new HashMap<>() ); + return pluginContextsByKey.computeIfAbsent(plugin.getPluginLookupKey(), k -> new HashMap<>()); } - public void setFailureBehavior( String failureBehavior ) - { - if ( failureBehavior == null ) - { + public void setFailureBehavior(String failureBehavior) { + if (failureBehavior == null) { this.failureBehavior = FAIL_FAST; // default return; } - if ( FAIL_FAST.equals( failureBehavior ) || FAIL_AT_END.equals( failureBehavior ) || FAIL_NEVER.equals( - failureBehavior ) ) - { + if (FAIL_FAST.equals(failureBehavior) + || FAIL_AT_END.equals(failureBehavior) + || FAIL_NEVER.equals(failureBehavior)) { this.failureBehavior = failureBehavior; - } - else - { - throw new IllegalArgumentException( - "Invalid failure behavior (must be one of: '" + FAIL_FAST + "', '" + FAIL_AT_END + "', '" - + FAIL_NEVER + "')." ); + } else { + throw new IllegalArgumentException("Invalid failure behavior (must be one of: '" + FAIL_FAST + "', '" + + FAIL_AT_END + "', '" + FAIL_NEVER + "')."); } } - public String getFailureBehavior() - { + public String getFailureBehavior() { return failureBehavior; } - public void blackList( MavenProject project ) - { - blackList( getProjectKey( project ) ); + public void blackList(MavenProject project) { + blackList(getProjectKey(project)); } - private void blackList( String id ) - { - if ( !blackList.contains( id ) ) - { - blackList.add( id ); + private void blackList(String id) { + if (!blackList.contains(id)) { + blackList.add(id); - List dependents = sorter.getDependents( id ); + List dependents = sorter.getDependents(id); - if ( dependents != null && !dependents.isEmpty() ) - { - for ( String dependentId : dependents ) - { - if ( !buildSuccessesByProject.containsKey( dependentId ) && !buildFailuresByProject.containsKey( - dependentId ) ) - { - blackList( dependentId ); + if (dependents != null && !dependents.isEmpty()) { + for (String dependentId : dependents) { + if (!buildSuccessesByProject.containsKey(dependentId) + && !buildFailuresByProject.containsKey(dependentId)) { + blackList(dependentId); } } } } } - public boolean isBlackListed( MavenProject project ) - { - return blackList.contains( getProjectKey( project ) ); + public boolean isBlackListed(MavenProject project) { + return blackList.contains(getProjectKey(project)); } - private static String getProjectKey( MavenProject project ) - { - return ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() ); + private static String getProjectKey(MavenProject project) { + return ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()); } - public void registerBuildFailure( MavenProject project, Exception error, String task, long time ) - { - buildFailuresByProject.put( getProjectKey( project ), new BuildFailure( project, time, error ) ); + public void registerBuildFailure(MavenProject project, Exception error, String task, long time) { + buildFailuresByProject.put(getProjectKey(project), new BuildFailure(project, time, error)); } - public boolean hasBuildFailures() - { + public boolean hasBuildFailures() { return !buildFailuresByProject.isEmpty(); } - public boolean hasBuildFailure( MavenProject project ) - { - return buildFailuresByProject.containsKey( getProjectKey( project ) ); + public boolean hasBuildFailure(MavenProject project) { + return buildFailuresByProject.containsKey(getProjectKey(project)); } - public boolean hasMultipleProjects() - { + public boolean hasMultipleProjects() { return sorter.hasMultipleProjects(); } - public List getSortedProjects() - { + public List getSortedProjects() { return sorter.getSortedProjects(); } - public boolean hasBuildSuccess( MavenProject project ) - { - return buildSuccessesByProject.containsKey( getProjectKey( project ) ); + public boolean hasBuildSuccess(MavenProject project) { + return buildSuccessesByProject.containsKey(getProjectKey(project)); } - public void registerBuildSuccess( MavenProject project, long time ) - { - buildSuccessesByProject.put( getProjectKey( project ), new BuildSuccess( project, time ) ); + public void registerBuildSuccess(MavenProject project, long time) { + buildSuccessesByProject.put(getProjectKey(project), new BuildSuccess(project, time)); } - public BuildFailure getBuildFailure( MavenProject project ) - { - return buildFailuresByProject.get( getProjectKey( project ) ); + public BuildFailure getBuildFailure(MavenProject project) { + return buildFailuresByProject.get(getProjectKey(project)); } - public BuildSuccess getBuildSuccess( MavenProject project ) - { - return buildSuccessesByProject.get( getProjectKey( project ) ); + public BuildSuccess getBuildSuccess(MavenProject project) { + return buildSuccessesByProject.get(getProjectKey(project)); } - public boolean executedMultipleProjects() - { + public boolean executedMultipleProjects() { return buildFailuresByProject.size() + buildSuccessesByProject.size() > 1; } } diff --git a/maven-core/src/main/java/org/apache/maven/execution/scope/MojoExecutionScoped.java b/maven-core/src/main/java/org/apache/maven/execution/scope/MojoExecutionScoped.java index 0dcbd16fd8..c7e84e8c67 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/scope/MojoExecutionScoped.java +++ b/maven-core/src/main/java/org/apache/maven/execution/scope/MojoExecutionScoped.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution.scope; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,15 @@ package org.apache.maven.execution.scope; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution.scope; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import com.google.inject.ScopeAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import com.google.inject.ScopeAnnotation; - /** * Indicates that annotated component should be instantiated before mojo execution starts and discarded after mojo * execution completes. @@ -34,9 +32,7 @@ import com.google.inject.ScopeAnnotation; * @author igor * @since 3.1.2 */ -@Target( { TYPE } ) -@Retention( RUNTIME ) +@Target({TYPE}) +@Retention(RUNTIME) @ScopeAnnotation -public @interface MojoExecutionScoped -{ -} +public @interface MojoExecutionScoped {} diff --git a/maven-core/src/main/java/org/apache/maven/execution/scope/WeakMojoExecutionListener.java b/maven-core/src/main/java/org/apache/maven/execution/scope/WeakMojoExecutionListener.java index da78de7ab8..d0643261c6 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/scope/WeakMojoExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/execution/scope/WeakMojoExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution.scope; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.execution.scope; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution.scope; import org.apache.maven.execution.MojoExecutionEvent; import org.apache.maven.plugin.MojoExecutionException; @@ -34,13 +33,10 @@ import org.apache.maven.plugin.MojoExecutionException; * @see org.apache.maven.execution.MojoExecutionListener * @since 3.1.2 */ -public interface WeakMojoExecutionListener -{ - void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException; +public interface WeakMojoExecutionListener { + void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException; - void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException; + void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException; - void afterExecutionFailure( MojoExecutionEvent event ); + void afterExecutionFailure(MojoExecutionEvent event); } diff --git a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java index 86d7c73a6e..ef937e9ad5 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java +++ b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution.scope.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,37 +16,32 @@ package org.apache.maven.execution.scope.internal; * specific language governing permissions and limitations * under the License. */ - -import java.util.Collection; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.LinkedList; -import java.util.Map; - -import org.apache.maven.execution.MojoExecutionEvent; -import org.apache.maven.execution.MojoExecutionListener; -import org.apache.maven.execution.scope.WeakMojoExecutionListener; -import org.apache.maven.plugin.MojoExecutionException; +package org.apache.maven.execution.scope.internal; import com.google.inject.Key; import com.google.inject.OutOfScopeException; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.util.Providers; +import java.util.Collection; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedList; +import java.util.Map; +import org.apache.maven.execution.MojoExecutionEvent; +import org.apache.maven.execution.MojoExecutionListener; +import org.apache.maven.execution.scope.WeakMojoExecutionListener; +import org.apache.maven.plugin.MojoExecutionException; /** * MojoExecutionScope */ -public class MojoExecutionScope - implements Scope, MojoExecutionListener -{ - private static final Provider SEEDED_KEY_PROVIDER = () -> - { +public class MojoExecutionScope implements Scope, MojoExecutionListener { + private static final Provider SEEDED_KEY_PROVIDER = () -> { throw new IllegalStateException(); }; - private static final class ScopeState - { + private static final class ScopeState { private final Map, Provider> seeded = new HashMap<>(); private final Map, Object> provided = new HashMap<>(); @@ -56,129 +49,99 @@ public class MojoExecutionScope private final ThreadLocal> values = new ThreadLocal<>(); - public MojoExecutionScope() - { - } + public MojoExecutionScope() {} - public void enter() - { + public void enter() { LinkedList stack = values.get(); - if ( stack == null ) - { + if (stack == null) { stack = new LinkedList<>(); - values.set( stack ); + values.set(stack); } - stack.addFirst( new ScopeState() ); + stack.addFirst(new ScopeState()); } - private ScopeState getScopeState() - { + private ScopeState getScopeState() { LinkedList stack = values.get(); - if ( stack == null || stack.isEmpty() ) - { + if (stack == null || stack.isEmpty()) { throw new IllegalStateException(); } return stack.getFirst(); } - public void exit() - throws MojoExecutionException - { + public void exit() throws MojoExecutionException { final LinkedList stack = values.get(); - if ( stack == null || stack.isEmpty() ) - { + if (stack == null || stack.isEmpty()) { throw new IllegalStateException(); } stack.removeFirst(); - if ( stack.isEmpty() ) - { + if (stack.isEmpty()) { values.remove(); } } - public void seed( Class clazz, Provider value ) - { - getScopeState().seeded.put( Key.get( clazz ), value ); + public void seed(Class clazz, Provider value) { + getScopeState().seeded.put(Key.get(clazz), value); } - public void seed( Class clazz, final T value ) - { - getScopeState().seeded.put( Key.get( clazz ), Providers.of( value ) ); + public void seed(Class clazz, final T value) { + getScopeState().seeded.put(Key.get(clazz), Providers.of(value)); } - public Provider scope( final Key key, final Provider unscoped ) - { - return () -> - { + public Provider scope(final Key key, final Provider unscoped) { + return () -> { LinkedList stack = values.get(); - if ( stack == null || stack.isEmpty() ) - { - throw new OutOfScopeException( "Cannot access " + key + " outside of a scoping block" ); + if (stack == null || stack.isEmpty()) { + throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block"); } ScopeState state = stack.getFirst(); - Provider seeded = state.seeded.get( key ); + Provider seeded = state.seeded.get(key); - if ( seeded != null ) - { + if (seeded != null) { return (T) seeded.get(); } - T provided = (T) state.provided.get( key ); - if ( provided == null && unscoped != null ) - { + T provided = (T) state.provided.get(key); + if (provided == null && unscoped != null) { provided = unscoped.get(); - state.provided.put( key, provided ); + state.provided.put(key, provided); } return provided; }; } - @SuppressWarnings( { "unchecked" } ) - public static Provider seededKeyProvider() - { + @SuppressWarnings({"unchecked"}) + public static Provider seededKeyProvider() { return (Provider) SEEDED_KEY_PROVIDER; } - public void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException - { - for ( WeakMojoExecutionListener provided : getProvidedListeners() ) - { - provided.beforeMojoExecution( event ); + public void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException { + for (WeakMojoExecutionListener provided : getProvidedListeners()) { + provided.beforeMojoExecution(event); } } - public void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException - { - for ( WeakMojoExecutionListener provided : getProvidedListeners() ) - { - provided.afterMojoExecutionSuccess( event ); + public void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException { + for (WeakMojoExecutionListener provided : getProvidedListeners()) { + provided.afterMojoExecutionSuccess(event); } } - public void afterExecutionFailure( MojoExecutionEvent event ) - { - for ( WeakMojoExecutionListener provided : getProvidedListeners() ) - { - provided.afterExecutionFailure( event ); + public void afterExecutionFailure(MojoExecutionEvent event) { + for (WeakMojoExecutionListener provided : getProvidedListeners()) { + provided.afterExecutionFailure(event); } } - private Collection getProvidedListeners() - { + private Collection getProvidedListeners() { // the same instance can be provided multiple times under different Key's // deduplicate instances to avoid redundant beforeXXX/afterXXX callbacks - IdentityHashMap listeners = - new IdentityHashMap<>(); - for ( Object provided : getScopeState().provided.values() ) - { - if ( provided instanceof WeakMojoExecutionListener ) - { - listeners.put( (WeakMojoExecutionListener) provided, null ); + IdentityHashMap listeners = new IdentityHashMap<>(); + for (Object provided : getScopeState().provided.values()) { + if (provided instanceof WeakMojoExecutionListener) { + listeners.put((WeakMojoExecutionListener) provided, null); } } return listeners.keySet(); diff --git a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeCoreModule.java b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeCoreModule.java index 79a18bd311..1365a3ba7c 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeCoreModule.java +++ b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeCoreModule.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution.scope.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution.scope.internal; * "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 + * 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 @@ -18,31 +16,26 @@ package org.apache.maven.execution.scope.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution.scope.internal; import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.execution.MojoExecutionListener; /** * MojoExecutionScopeCoreModule */ @Named -public class MojoExecutionScopeCoreModule - extends MojoExecutionScopeModule -{ +public class MojoExecutionScopeCoreModule extends MojoExecutionScopeModule { @Inject - public MojoExecutionScopeCoreModule() - { - super( new MojoExecutionScope() ); + public MojoExecutionScopeCoreModule() { + super(new MojoExecutionScope()); } @Override - protected void configure() - { + protected void configure() { super.configure(); - bind( MojoExecutionListener.class ).toInstance( scope ); + bind(MojoExecutionListener.class).toInstance(scope); } - } diff --git a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java index 0420b6054e..ed3625fafe 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java +++ b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution.scope.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution.scope.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.execution.scope.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution.scope.internal; import com.google.inject.AbstractModule; import org.apache.maven.api.plugin.Log; @@ -30,33 +29,33 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti /** * MojoExecutionScopeModule */ -public class MojoExecutionScopeModule - extends AbstractModule -{ +public class MojoExecutionScopeModule extends AbstractModule { protected final MojoExecutionScope scope; - public MojoExecutionScopeModule( PlexusContainer container ) - throws ComponentLookupException - { - this( container.lookup( MojoExecutionScope.class ) ); + public MojoExecutionScopeModule(PlexusContainer container) throws ComponentLookupException { + this(container.lookup(MojoExecutionScope.class)); } - protected MojoExecutionScopeModule( MojoExecutionScope scope ) - { + protected MojoExecutionScopeModule(MojoExecutionScope scope) { this.scope = scope; } @Override - protected void configure() - { - bindScope( MojoExecutionScoped.class, scope ); - bind( MojoExecutionScope.class ).toInstance( scope ); - bind( MavenProject.class ).toProvider( MojoExecutionScope.seededKeyProvider() ).in( scope ); - bind( MojoExecution.class ).toProvider( MojoExecutionScope.seededKeyProvider() ).in( scope ); - bind( Log.class ).toProvider( MojoExecutionScope.seededKeyProvider() ).in( scope ); - bind( org.apache.maven.api.Project.class ).toProvider( MojoExecutionScope.seededKeyProvider() ).in( scope ); - bind( org.apache.maven.api.MojoExecution.class ) - .toProvider( MojoExecutionScope.seededKeyProvider() ).in( scope ); + protected void configure() { + bindScope(MojoExecutionScoped.class, scope); + bind(MojoExecutionScope.class).toInstance(scope); + bind(MavenProject.class) + .toProvider(MojoExecutionScope.seededKeyProvider()) + .in(scope); + bind(MojoExecution.class) + .toProvider(MojoExecutionScope.seededKeyProvider()) + .in(scope); + bind(Log.class).toProvider(MojoExecutionScope.seededKeyProvider()).in(scope); + bind(org.apache.maven.api.Project.class) + .toProvider(MojoExecutionScope.seededKeyProvider()) + .in(scope); + bind(org.apache.maven.api.MojoExecution.class) + .toProvider(MojoExecutionScope.seededKeyProvider()) + .in(scope); } - } diff --git a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExports.java b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExports.java index 2d976ae0ef..4358d28d42 100644 --- a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExports.java +++ b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExports.java @@ -1,5 +1,3 @@ -package org.apache.maven.extension.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,56 +16,51 @@ package org.apache.maven.extension.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.extension.internal; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.toMap; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; - import org.codehaus.plexus.classworlds.realm.ClassRealm; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.collectingAndThen; -import static java.util.stream.Collectors.toMap; - /** * Provides information about artifacts (identified by groupId:artifactId string key) and classpath elements exported by * Maven core itself and loaded Maven core extensions. * * @since 3.3.0 */ -public class CoreExports -{ +public class CoreExports { private final Set artifacts; private final Map packages; - public CoreExports( CoreExtensionEntry entry ) - { - this( entry.getClassRealm(), entry.getExportedArtifacts(), entry.getExportedPackages() ); + public CoreExports(CoreExtensionEntry entry) { + this(entry.getClassRealm(), entry.getExportedArtifacts(), entry.getExportedPackages()); } - public CoreExports( ClassRealm realm, Set exportedArtifacts, Set exportedPackages ) - { - this.artifacts = Collections.unmodifiableSet( new HashSet<>( exportedArtifacts ) ); - this.packages = exportedPackages.stream().collect( - collectingAndThen( toMap( identity(), v -> realm ), Collections::unmodifiableMap ) ); + public CoreExports(ClassRealm realm, Set exportedArtifacts, Set exportedPackages) { + this.artifacts = Collections.unmodifiableSet(new HashSet<>(exportedArtifacts)); + this.packages = exportedPackages.stream() + .collect(collectingAndThen(toMap(identity(), v -> realm), Collections::unmodifiableMap)); } /** * Returns artifacts exported by Maven core and core extensions. Artifacts are identified by their * groupId:artifactId string key. */ - public Set getExportedArtifacts() - { + public Set getExportedArtifacts() { return artifacts; } /** * Returns packages exported by Maven core and core extensions. */ - public Map getExportedPackages() - { + public Map getExportedPackages() { return packages; } } diff --git a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExportsProvider.java b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExportsProvider.java index b1a30fe3c3..bb04a2ce2b 100644 --- a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExportsProvider.java +++ b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExportsProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.extension.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,13 @@ package org.apache.maven.extension.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.extension.internal; import java.util.Objects; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.codehaus.plexus.PlexusContainer; /** @@ -33,24 +30,20 @@ import org.codehaus.plexus.PlexusContainer; */ @Named @Singleton -public class CoreExportsProvider implements Provider -{ +public class CoreExportsProvider implements Provider { private final CoreExports exports; @Inject - public CoreExportsProvider( PlexusContainer container ) - { - this( new CoreExports( CoreExtensionEntry.discoverFrom( container.getContainerRealm() ) ) ); + public CoreExportsProvider(PlexusContainer container) { + this(new CoreExports(CoreExtensionEntry.discoverFrom(container.getContainerRealm()))); } - public CoreExportsProvider( CoreExports exports ) - { - this.exports = Objects.requireNonNull( exports ); + public CoreExportsProvider(CoreExports exports) { + this.exports = Objects.requireNonNull(exports); } - public CoreExports get() - { + public CoreExports get() { return exports; } } diff --git a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java index 50220f6ded..bac9136d35 100644 --- a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java +++ b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.extension.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,7 @@ package org.apache.maven.extension.internal; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.project.ExtensionDescriptor; -import org.apache.maven.project.ExtensionDescriptorBuilder; -import org.codehaus.plexus.classworlds.realm.ClassRealm; +package org.apache.maven.extension.internal; import java.io.File; import java.io.IOException; @@ -33,6 +28,9 @@ import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; +import org.apache.maven.project.ExtensionDescriptor; +import org.apache.maven.project.ExtensionDescriptorBuilder; +import org.codehaus.plexus.classworlds.realm.ClassRealm; /** * Provides information about artifacts (identified by groupId:artifactId string key) and classpath elements exported by @@ -40,97 +38,79 @@ import java.util.Set; * * @since 3.3.0 */ -public class CoreExtensionEntry -{ +public class CoreExtensionEntry { private final ClassRealm realm; private final Set artifacts; private final Set packages; - public CoreExtensionEntry( ClassRealm realm, Collection artifacts, Collection packages ) - { + public CoreExtensionEntry(ClassRealm realm, Collection artifacts, Collection packages) { this.realm = realm; - this.artifacts = Collections.unmodifiableSet( new HashSet<>( artifacts ) ); - this.packages = Collections.unmodifiableSet( new HashSet<>( packages ) ); + this.artifacts = Collections.unmodifiableSet(new HashSet<>(artifacts)); + this.packages = Collections.unmodifiableSet(new HashSet<>(packages)); } /** * Returns ClassLoader used to load extension classes. */ - public ClassRealm getClassRealm() - { + public ClassRealm getClassRealm() { return realm; } /** * Returns artifacts exported by the extension, identified by groupId:artifactId string key. */ - public Set getExportedArtifacts() - { + public Set getExportedArtifacts() { return artifacts; } /** * Returns classpath elements exported by the extension. */ - public Set getExportedPackages() - { + public Set getExportedPackages() { return packages; } private static final ExtensionDescriptorBuilder BUILDER = new ExtensionDescriptorBuilder(); - public static CoreExtensionEntry discoverFrom( ClassRealm loader ) - { + public static CoreExtensionEntry discoverFrom(ClassRealm loader) { Set artifacts = new LinkedHashSet<>(); Set packages = new LinkedHashSet<>(); - try - { - Enumeration urls = loader.getResources( BUILDER.getExtensionDescriptorLocation() ); - while ( urls.hasMoreElements() ) - { + try { + Enumeration urls = loader.getResources(BUILDER.getExtensionDescriptorLocation()); + while (urls.hasMoreElements()) { - try ( InputStream is = urls.nextElement().openStream() ) - { - ExtensionDescriptor descriptor = BUILDER.build( is ); - artifacts.addAll( descriptor.getExportedArtifacts() ); - packages.addAll( descriptor.getExportedPackages() ); + try (InputStream is = urls.nextElement().openStream()) { + ExtensionDescriptor descriptor = BUILDER.build(is); + artifacts.addAll(descriptor.getExportedArtifacts()); + packages.addAll(descriptor.getExportedPackages()); } } - } - catch ( IOException ignored ) - { + } catch (IOException ignored) { // exports descriptors are entirely optional } - return new CoreExtensionEntry( loader, artifacts, packages ); + return new CoreExtensionEntry(loader, artifacts, packages); } - public static CoreExtensionEntry discoverFrom( ClassRealm loader, Collection classpath ) - { + public static CoreExtensionEntry discoverFrom(ClassRealm loader, Collection classpath) { Set artifacts = new LinkedHashSet<>(); Set packages = new LinkedHashSet<>(); - try - { - for ( File entry : classpath ) - { - ExtensionDescriptor descriptor = BUILDER.build( entry ); - if ( descriptor != null ) - { - artifacts.addAll( descriptor.getExportedArtifacts() ); - packages.addAll( descriptor.getExportedPackages() ); + try { + for (File entry : classpath) { + ExtensionDescriptor descriptor = BUILDER.build(entry); + if (descriptor != null) { + artifacts.addAll(descriptor.getExportedArtifacts()); + packages.addAll(descriptor.getExportedPackages()); } } - } - catch ( IOException ignored ) - { + } catch (IOException ignored) { // exports descriptors are entirely optional } - return new CoreExtensionEntry( loader, artifacts, packages ); + return new CoreExtensionEntry(loader, artifacts, packages); } - } diff --git a/maven-core/src/main/java/org/apache/maven/graph/DefaultGraphBuilder.java b/maven-core/src/main/java/org/apache/maven/graph/DefaultGraphBuilder.java index 0d4f6ca45a..d7edbe7d0c 100644 --- a/maven-core/src/main/java/org/apache/maven/graph/DefaultGraphBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/graph/DefaultGraphBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.graph; + +import static java.util.Comparator.comparing; import java.io.File; import java.util.ArrayList; @@ -28,11 +29,9 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.MavenExecutionException; import org.apache.maven.ProjectCycleException; import org.apache.maven.artifact.ArtifactUtils; @@ -55,17 +54,13 @@ import org.codehaus.plexus.util.dag.CycleDetectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static java.util.Comparator.comparing; - /** * Builds the {@link ProjectDependencyGraph inter-dependencies graph} between projects in the reactor. */ -@Named( GraphBuilder.HINT ) +@Named(GraphBuilder.HINT) @Singleton -public class DefaultGraphBuilder - implements GraphBuilder -{ - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultGraphBuilder.class ); +public class DefaultGraphBuilder implements GraphBuilder { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultGraphBuilder.class); private final BuildResumptionDataRepository buildResumptionDataRepository; private final PomlessCollectionStrategy pomlessCollectionStrategy; @@ -74,11 +69,11 @@ public class DefaultGraphBuilder private final ProjectSelector projectSelector; @Inject - public DefaultGraphBuilder( BuildResumptionDataRepository buildResumptionDataRepository, - PomlessCollectionStrategy pomlessCollectionStrategy, - MultiModuleCollectionStrategy multiModuleCollectionStrategy, - RequestPomCollectionStrategy requestPomCollectionStrategy ) - { + public DefaultGraphBuilder( + BuildResumptionDataRepository buildResumptionDataRepository, + PomlessCollectionStrategy pomlessCollectionStrategy, + MultiModuleCollectionStrategy multiModuleCollectionStrategy, + RequestPomCollectionStrategy requestPomCollectionStrategy) { this.buildResumptionDataRepository = buildResumptionDataRepository; this.pomlessCollectionStrategy = pomlessCollectionStrategy; this.multiModuleCollectionStrategy = multiModuleCollectionStrategy; @@ -87,274 +82,243 @@ public class DefaultGraphBuilder } @Override - public Result build( MavenSession session ) - { - try - { - Result result = sessionDependencyGraph( session ); + public Result build(MavenSession session) { + try { + Result result = sessionDependencyGraph(session); - if ( result == null ) - { - final List projects = getProjectsForMavenReactor( session ); - validateProjects( projects, session.getRequest() ); - enrichRequestFromResumptionData( projects, session.getRequest() ); - result = reactorDependencyGraph( session, projects ); + if (result == null) { + final List projects = getProjectsForMavenReactor(session); + validateProjects(projects, session.getRequest()); + enrichRequestFromResumptionData(projects, session.getRequest()); + result = reactorDependencyGraph(session, projects); } return result; - } - catch ( final ProjectBuildingException | DuplicateProjectException | MavenExecutionException e ) - { - return Result.error( Collections.singletonList - ( new DefaultModelProblem ( null, null, null, null, 0, 0, e ) ) ); - } - catch ( final CycleDetectedException e ) - { + } catch (final ProjectBuildingException | DuplicateProjectException | MavenExecutionException e) { + return Result.error(Collections.singletonList(new DefaultModelProblem(null, null, null, null, 0, 0, e))); + } catch (final CycleDetectedException e) { String message = "The projects in the reactor contain a cyclic reference: " + e.getMessage(); - ProjectCycleException error = new ProjectCycleException( message, e ); - return Result.error( Collections.singletonList( - new DefaultModelProblem( null, null, null, null, 0, 0, error ) ) ); + ProjectCycleException error = new ProjectCycleException(message, e); + return Result.error( + Collections.singletonList(new DefaultModelProblem(null, null, null, null, 0, 0, error))); } } - private Result sessionDependencyGraph( final MavenSession session ) - throws CycleDetectedException, DuplicateProjectException - { + private Result sessionDependencyGraph(final MavenSession session) + throws CycleDetectedException, DuplicateProjectException { Result result = null; - if ( session.getProjectDependencyGraph() != null || session.getProjects() != null ) - { + if (session.getProjectDependencyGraph() != null || session.getProjects() != null) { final ProjectDependencyGraph graph = - new DefaultProjectDependencyGraph( session.getAllProjects(), session.getProjects() ); + new DefaultProjectDependencyGraph(session.getAllProjects(), session.getProjects()); - result = Result.success( graph ); + result = Result.success(graph); } return result; } - private Result reactorDependencyGraph( MavenSession session, List projects ) - throws CycleDetectedException, DuplicateProjectException, MavenExecutionException - { - ProjectDependencyGraph projectDependencyGraph = new DefaultProjectDependencyGraph( projects ); + private Result reactorDependencyGraph(MavenSession session, List projects) + throws CycleDetectedException, DuplicateProjectException, MavenExecutionException { + ProjectDependencyGraph projectDependencyGraph = new DefaultProjectDependencyGraph(projects); List activeProjects = projectDependencyGraph.getSortedProjects(); List allSortedProjects = projectDependencyGraph.getSortedProjects(); - activeProjects = trimProjectsToRequest( activeProjects, projectDependencyGraph, session.getRequest() ); - activeProjects = trimSelectedProjects( - activeProjects, allSortedProjects, projectDependencyGraph, session.getRequest() ); - activeProjects = trimResumedProjects( activeProjects, projectDependencyGraph, session.getRequest() ); - activeProjects = trimExcludedProjects( activeProjects, projectDependencyGraph, session.getRequest() ); + activeProjects = trimProjectsToRequest(activeProjects, projectDependencyGraph, session.getRequest()); + activeProjects = + trimSelectedProjects(activeProjects, allSortedProjects, projectDependencyGraph, session.getRequest()); + activeProjects = trimResumedProjects(activeProjects, projectDependencyGraph, session.getRequest()); + activeProjects = trimExcludedProjects(activeProjects, projectDependencyGraph, session.getRequest()); - if ( activeProjects.size() != projectDependencyGraph.getSortedProjects().size() ) - { - projectDependencyGraph = new FilteredProjectDependencyGraph( projectDependencyGraph, activeProjects ); + if (activeProjects.size() != projectDependencyGraph.getSortedProjects().size()) { + projectDependencyGraph = new FilteredProjectDependencyGraph(projectDependencyGraph, activeProjects); } - return Result.success( projectDependencyGraph ); + return Result.success(projectDependencyGraph); } - private List trimProjectsToRequest( List activeProjects, - ProjectDependencyGraph graph, - MavenExecutionRequest request ) - throws MavenExecutionException - { + private List trimProjectsToRequest( + List activeProjects, ProjectDependencyGraph graph, MavenExecutionRequest request) + throws MavenExecutionException { List result = activeProjects; - if ( request.getPom() != null ) - { - result = getProjectsInRequestScope( request, activeProjects ); + if (request.getPom() != null) { + result = getProjectsInRequestScope(request, activeProjects); List sortedProjects = graph.getSortedProjects(); - result.sort( comparing( sortedProjects::indexOf ) ); + result.sort(comparing(sortedProjects::indexOf)); - result = includeAlsoMakeTransitively( result, request, graph ); + result = includeAlsoMakeTransitively(result, request, graph); } return result; } - private List trimSelectedProjects( List projects, List allSortedProjects, - ProjectDependencyGraph graph, MavenExecutionRequest request ) - throws MavenExecutionException - { + private List trimSelectedProjects( + List projects, + List allSortedProjects, + ProjectDependencyGraph graph, + MavenExecutionRequest request) + throws MavenExecutionException { List result = projects; ProjectActivation projectActivation = request.getProjectActivation(); Set requiredSelectors = projectActivation.getRequiredActiveProjectSelectors(); Set optionalSelectors = projectActivation.getOptionalActiveProjectSelectors(); - if ( !requiredSelectors.isEmpty() || !optionalSelectors.isEmpty() ) - { - Set selectedProjects = new HashSet<>( requiredSelectors.size() + optionalSelectors.size() ); + if (!requiredSelectors.isEmpty() || !optionalSelectors.isEmpty()) { + Set selectedProjects = new HashSet<>(requiredSelectors.size() + optionalSelectors.size()); selectedProjects.addAll( - projectSelector.getRequiredProjectsBySelectors( request, allSortedProjects, requiredSelectors ) ); + projectSelector.getRequiredProjectsBySelectors(request, allSortedProjects, requiredSelectors)); selectedProjects.addAll( - projectSelector.getOptionalProjectsBySelectors( request, allSortedProjects, optionalSelectors ) ); + projectSelector.getOptionalProjectsBySelectors(request, allSortedProjects, optionalSelectors)); // it can be empty when an optional project is missing from the reactor, fallback to returning all projects - if ( !selectedProjects.isEmpty() ) - { - result = new ArrayList<>( selectedProjects ); + if (!selectedProjects.isEmpty()) { + result = new ArrayList<>(selectedProjects); - result = includeAlsoMakeTransitively( result, request, graph ); + result = includeAlsoMakeTransitively(result, request, graph); // Order the new list in the original order List sortedProjects = graph.getSortedProjects(); - result.sort( comparing( sortedProjects::indexOf ) ); + result.sort(comparing(sortedProjects::indexOf)); } } return result; } - private List trimResumedProjects( List projects, ProjectDependencyGraph graph, - MavenExecutionRequest request ) - throws MavenExecutionException - { + private List trimResumedProjects( + List projects, ProjectDependencyGraph graph, MavenExecutionRequest request) + throws MavenExecutionException { List result = projects; - if ( StringUtils.isNotEmpty( request.getResumeFrom() ) ) - { - File reactorDirectory = projectSelector.getBaseDirectoryFromRequest( request ); + if (StringUtils.isNotEmpty(request.getResumeFrom())) { + File reactorDirectory = projectSelector.getBaseDirectoryFromRequest(request); String selector = request.getResumeFrom(); MavenProject resumingFromProject = projects.stream() - .filter( project -> projectSelector.isMatchingProject( project, selector, reactorDirectory ) ) + .filter(project -> projectSelector.isMatchingProject(project, selector, reactorDirectory)) .findFirst() - .orElseThrow( () -> new MavenExecutionException( + .orElseThrow(() -> new MavenExecutionException( "Could not find project to resume reactor build from: " + selector + " vs " - + formatProjects( projects ), request.getPom() ) ); - int resumeFromProjectIndex = projects.indexOf( resumingFromProject ); - List retainingProjects = result.subList( resumeFromProjectIndex, projects.size() ); + + formatProjects(projects), + request.getPom())); + int resumeFromProjectIndex = projects.indexOf(resumingFromProject); + List retainingProjects = result.subList(resumeFromProjectIndex, projects.size()); - result = includeAlsoMakeTransitively( retainingProjects, request, graph ); + result = includeAlsoMakeTransitively(retainingProjects, request, graph); } return result; } - private List trimExcludedProjects( List projects, ProjectDependencyGraph graph, - MavenExecutionRequest request ) - throws MavenExecutionException - { + private List trimExcludedProjects( + List projects, ProjectDependencyGraph graph, MavenExecutionRequest request) + throws MavenExecutionException { List result = projects; ProjectActivation projectActivation = request.getProjectActivation(); Set requiredSelectors = projectActivation.getRequiredInactiveProjectSelectors(); Set optionalSelectors = projectActivation.getOptionalInactiveProjectSelectors(); - if ( !requiredSelectors.isEmpty() || !optionalSelectors.isEmpty() ) - { - Set excludedProjects = new HashSet<>( requiredSelectors.size() + optionalSelectors.size() ); + if (!requiredSelectors.isEmpty() || !optionalSelectors.isEmpty()) { + Set excludedProjects = new HashSet<>(requiredSelectors.size() + optionalSelectors.size()); List allProjects = graph.getAllProjects(); excludedProjects.addAll( - projectSelector.getRequiredProjectsBySelectors( request, allProjects, requiredSelectors ) ); + projectSelector.getRequiredProjectsBySelectors(request, allProjects, requiredSelectors)); excludedProjects.addAll( - projectSelector.getOptionalProjectsBySelectors( request, allProjects, optionalSelectors ) ); + projectSelector.getOptionalProjectsBySelectors(request, allProjects, optionalSelectors)); - result = new ArrayList<>( projects ); - result.removeAll( excludedProjects ); + result = new ArrayList<>(projects); + result.removeAll(excludedProjects); - if ( result.isEmpty() ) - { + if (result.isEmpty()) { boolean isPlural = excludedProjects.size() > 1; - String message = String.format( "The project exclusion%s in --projects/-pl resulted in an " - + "empty reactor, please correct %s.", isPlural ? "s" : "", isPlural ? "them" : "it" ); - throw new MavenExecutionException( message, request.getPom() ); + String message = String.format( + "The project exclusion%s in --projects/-pl resulted in an " + + "empty reactor, please correct %s.", + isPlural ? "s" : "", isPlural ? "them" : "it"); + throw new MavenExecutionException(message, request.getPom()); } } return result; } - private List includeAlsoMakeTransitively( List projects, MavenExecutionRequest request, - ProjectDependencyGraph graph ) - throws MavenExecutionException - { + private List includeAlsoMakeTransitively( + List projects, MavenExecutionRequest request, ProjectDependencyGraph graph) + throws MavenExecutionException { List result = projects; String makeBehavior = request.getMakeBehavior(); - boolean makeBoth = MavenExecutionRequest.REACTOR_MAKE_BOTH.equals( makeBehavior ); + boolean makeBoth = MavenExecutionRequest.REACTOR_MAKE_BOTH.equals(makeBehavior); - boolean makeUpstream = makeBoth || MavenExecutionRequest.REACTOR_MAKE_UPSTREAM.equals( makeBehavior ); - boolean makeDownstream = makeBoth || MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM.equals( makeBehavior ); + boolean makeUpstream = makeBoth || MavenExecutionRequest.REACTOR_MAKE_UPSTREAM.equals(makeBehavior); + boolean makeDownstream = makeBoth || MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM.equals(makeBehavior); - if ( StringUtils.isNotEmpty( makeBehavior ) && !makeUpstream && !makeDownstream ) - { - throw new MavenExecutionException( "Invalid reactor make behavior: " + makeBehavior, - request.getPom() ); + if (StringUtils.isNotEmpty(makeBehavior) && !makeUpstream && !makeDownstream) { + throw new MavenExecutionException("Invalid reactor make behavior: " + makeBehavior, request.getPom()); } - if ( makeUpstream || makeDownstream ) - { - Set projectsSet = new HashSet<>( projects ); + if (makeUpstream || makeDownstream) { + Set projectsSet = new HashSet<>(projects); - for ( MavenProject project : projects ) - { - if ( makeUpstream ) - { - projectsSet.addAll( graph.getUpstreamProjects( project, true ) ); + for (MavenProject project : projects) { + if (makeUpstream) { + projectsSet.addAll(graph.getUpstreamProjects(project, true)); } - if ( makeDownstream ) - { - projectsSet.addAll( graph.getDownstreamProjects( project, true ) ); + if (makeDownstream) { + projectsSet.addAll(graph.getDownstreamProjects(project, true)); } } - result = new ArrayList<>( projectsSet ); + result = new ArrayList<>(projectsSet); // Order the new list in the original order List sortedProjects = graph.getSortedProjects(); - result.sort( comparing( sortedProjects::indexOf ) ); + result.sort(comparing(sortedProjects::indexOf)); } return result; } - private void enrichRequestFromResumptionData( List projects, MavenExecutionRequest request ) - { - if ( request.isResume() ) - { + private void enrichRequestFromResumptionData(List projects, MavenExecutionRequest request) { + if (request.isResume()) { projects.stream() - .filter( MavenProject::isExecutionRoot ) + .filter(MavenProject::isExecutionRoot) .findFirst() - .ifPresent( rootProject -> - buildResumptionDataRepository.applyResumptionData( request, rootProject ) ); + .ifPresent(rootProject -> buildResumptionDataRepository.applyResumptionData(request, rootProject)); } } - private List getProjectsInRequestScope( MavenExecutionRequest request, List projects ) - throws MavenExecutionException - { - if ( request.getPom() == null ) - { + private List getProjectsInRequestScope(MavenExecutionRequest request, List projects) + throws MavenExecutionException { + if (request.getPom() == null) { return projects; } MavenProject requestPomProject = projects.stream() - .filter( project -> request.getPom().equals( project.getFile() ) ) + .filter(project -> request.getPom().equals(project.getFile())) .findFirst() - .orElseThrow( () -> new MavenExecutionException( - "Could not find a project in reactor matching the request POM", request.getPom() ) ); + .orElseThrow(() -> new MavenExecutionException( + "Could not find a project in reactor matching the request POM", request.getPom())); List modules = requestPomProject.getCollectedProjects() != null - ? requestPomProject.getCollectedProjects() : Collections.emptyList(); + ? requestPomProject.getCollectedProjects() + : Collections.emptyList(); - List result = new ArrayList<>( modules ); - result.add( requestPomProject ); + List result = new ArrayList<>(modules); + result.add(requestPomProject); return result; } - private String formatProjects( List projects ) - { + private String formatProjects(List projects) { StringBuilder projectNames = new StringBuilder(); Iterator iterator = projects.iterator(); - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { MavenProject project = iterator.next(); - projectNames.append( project.getGroupId() ).append( ":" ).append( project.getArtifactId() ); - if ( iterator.hasNext() ) - { - projectNames.append( ", " ); + projectNames.append(project.getGroupId()).append(":").append(project.getArtifactId()); + if (iterator.hasNext()) { + projectNames.append(", "); } } return projectNames.toString(); @@ -366,60 +330,52 @@ public class DefaultGraphBuilder // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - private List getProjectsForMavenReactor( MavenSession session ) - throws ProjectBuildingException - { + private List getProjectsForMavenReactor(MavenSession session) throws ProjectBuildingException { MavenExecutionRequest request = session.getRequest(); - request.getProjectBuildingRequest().setRepositorySession( session.getRepositorySession() ); + request.getProjectBuildingRequest().setRepositorySession(session.getRepositorySession()); // 1. Collect project for invocation without a POM. - if ( request.getPom() == null ) - { - return pomlessCollectionStrategy.collectProjects( request ); + if (request.getPom() == null) { + return pomlessCollectionStrategy.collectProjects(request); } // 2. Collect projects for all modules in the multi-module project. - List projects = multiModuleCollectionStrategy.collectProjects( request ); - if ( !projects.isEmpty() ) - { + List projects = multiModuleCollectionStrategy.collectProjects(request); + if (!projects.isEmpty()) { return projects; } // 3. Collect projects for explicitly requested POM. - return requestPomCollectionStrategy.collectProjects( request ); + return requestPomCollectionStrategy.collectProjects(request); } - private void validateProjects( List projects, MavenExecutionRequest request ) - throws MavenExecutionException - { + private void validateProjects(List projects, MavenExecutionRequest request) + throws MavenExecutionException { Map projectsMap = new HashMap<>(); - List projectsInRequestScope = getProjectsInRequestScope( request, projects ); - for ( MavenProject p : projectsInRequestScope ) - { - String projectKey = ArtifactUtils.key( p.getGroupId(), p.getArtifactId(), p.getVersion() ); + List projectsInRequestScope = getProjectsInRequestScope(request, projects); + for (MavenProject p : projectsInRequestScope) { + String projectKey = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion()); - projectsMap.put( projectKey, p ); + projectsMap.put(projectKey, p); } - for ( MavenProject project : projects ) - { + for (MavenProject project : projects) { // MNG-1911 / MNG-5572: Building plugins with extensions cannot be part of reactor - for ( Plugin plugin : project.getBuildPlugins() ) - { - if ( plugin.isExtensions() ) - { - String pluginKey = ArtifactUtils.key( plugin.getGroupId(), plugin.getArtifactId(), - plugin.getVersion() ); + for (Plugin plugin : project.getBuildPlugins()) { + if (plugin.isExtensions()) { + String pluginKey = + ArtifactUtils.key(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion()); - if ( projectsMap.containsKey( pluginKey ) ) - { - LOGGER.warn( "'{}' uses '{}' as extension which is not possible within the same reactor build. " - + "This plugin was pulled from the local repository!", project.getName(), plugin.getKey() ); + if (projectsMap.containsKey(pluginKey)) { + LOGGER.warn( + "'{}' uses '{}' as extension which is not possible within the same reactor build. " + + "This plugin was pulled from the local repository!", + project.getName(), + plugin.getKey()); } } } } } - } diff --git a/maven-core/src/main/java/org/apache/maven/graph/DefaultProjectDependencyGraph.java b/maven-core/src/main/java/org/apache/maven/graph/DefaultProjectDependencyGraph.java index c5553d9c83..233d56f7c0 100644 --- a/maven-core/src/main/java/org/apache/maven/graph/DefaultProjectDependencyGraph.java +++ b/maven-core/src/main/java/org/apache/maven/graph/DefaultProjectDependencyGraph.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.graph; import java.util.ArrayList; import java.util.Collection; @@ -30,7 +29,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; - import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.project.DuplicateProjectException; import org.apache.maven.project.MavenProject; @@ -42,9 +40,7 @@ import org.codehaus.plexus.util.dag.CycleDetectedException; * * @author Benjamin Bentmann */ -public class DefaultProjectDependencyGraph - implements ProjectDependencyGraph -{ +public class DefaultProjectDependencyGraph implements ProjectDependencyGraph { private final ProjectSorter sorter; @@ -61,10 +57,9 @@ public class DefaultProjectDependencyGraph * @throws DuplicateProjectException * @throws CycleDetectedException */ - public DefaultProjectDependencyGraph( Collection projects ) - throws CycleDetectedException, DuplicateProjectException - { - this( projects, projects ); + public DefaultProjectDependencyGraph(Collection projects) + throws CycleDetectedException, DuplicateProjectException { + this(projects, projects); } /** @@ -76,93 +71,77 @@ public class DefaultProjectDependencyGraph * @throws CycleDetectedException * @since 3.5.0 */ - public DefaultProjectDependencyGraph( Collection allProjects, - Collection projects ) - throws CycleDetectedException, DuplicateProjectException - { - this.allProjects = Collections.unmodifiableList( new ArrayList<>( allProjects ) ); - this.sorter = new ProjectSorter( projects ); + public DefaultProjectDependencyGraph(Collection allProjects, Collection projects) + throws CycleDetectedException, DuplicateProjectException { + this.allProjects = Collections.unmodifiableList(new ArrayList<>(allProjects)); + this.sorter = new ProjectSorter(projects); this.order = new HashMap<>(); this.projects = new HashMap<>(); List sorted = this.sorter.getSortedProjects(); - for ( int index = 0; index < sorted.size(); index++ ) - { - MavenProject project = sorted.get( index ); - String id = ProjectSorter.getId( project ); - this.projects.put( id, project ); - this.order.put( project, index ); + for (int index = 0; index < sorted.size(); index++) { + MavenProject project = sorted.get(index); + String id = ProjectSorter.getId(project); + this.projects.put(id, project); + this.order.put(project, index); } } /** * @since 3.5.0 */ - public List getAllProjects() - { + public List getAllProjects() { return this.allProjects; } - public List getSortedProjects() - { - return new ArrayList<>( sorter.getSortedProjects() ); + public List getSortedProjects() { + return new ArrayList<>(sorter.getSortedProjects()); } - public List getDownstreamProjects( MavenProject project, boolean transitive ) - { - Objects.requireNonNull( project, "project cannot be null" ); + public List getDownstreamProjects(MavenProject project, boolean transitive) { + Objects.requireNonNull(project, "project cannot be null"); Set projectIds = new HashSet<>(); - getDownstreamProjects( ProjectSorter.getId( project ), projectIds, transitive ); + getDownstreamProjects(ProjectSorter.getId(project), projectIds, transitive); - return getSortedProjects( projectIds ); + return getSortedProjects(projectIds); } - private void getDownstreamProjects( String projectId, Set projectIds, boolean transitive ) - { - for ( String id : sorter.getDependents( projectId ) ) - { - if ( projectIds.add( id ) && transitive ) - { - getDownstreamProjects( id, projectIds, transitive ); + private void getDownstreamProjects(String projectId, Set projectIds, boolean transitive) { + for (String id : sorter.getDependents(projectId)) { + if (projectIds.add(id) && transitive) { + getDownstreamProjects(id, projectIds, transitive); } } } - public List getUpstreamProjects( MavenProject project, boolean transitive ) - { - Objects.requireNonNull( project, "project cannot be null" ); + public List getUpstreamProjects(MavenProject project, boolean transitive) { + Objects.requireNonNull(project, "project cannot be null"); Set projectIds = new HashSet<>(); - getUpstreamProjects( ProjectSorter.getId( project ), projectIds, transitive ); + getUpstreamProjects(ProjectSorter.getId(project), projectIds, transitive); - return getSortedProjects( projectIds ); + return getSortedProjects(projectIds); } - private void getUpstreamProjects( String projectId, Collection projectIds, boolean transitive ) - { - for ( String id : sorter.getDependencies( projectId ) ) - { - if ( projectIds.add( id ) && transitive ) - { - getUpstreamProjects( id, projectIds, transitive ); + private void getUpstreamProjects(String projectId, Collection projectIds, boolean transitive) { + for (String id : sorter.getDependencies(projectId)) { + if (projectIds.add(id) && transitive) { + getUpstreamProjects(id, projectIds, transitive); } } } - private List getSortedProjects( Set projectIds ) - { + private List getSortedProjects(Set projectIds) { return projectIds.stream() - .map( projects::get ) - .sorted( Comparator.comparingInt( order::get ) ) - .collect( Collectors.toList() ); + .map(projects::get) + .sorted(Comparator.comparingInt(order::get)) + .collect(Collectors.toList()); } @Override - public String toString() - { + public String toString() { return sorter.getSortedProjects().toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/graph/FilteredProjectDependencyGraph.java b/maven-core/src/main/java/org/apache/maven/graph/FilteredProjectDependencyGraph.java index 97ba57e408..7229506cd1 100644 --- a/maven-core/src/main/java/org/apache/maven/graph/FilteredProjectDependencyGraph.java +++ b/maven-core/src/main/java/org/apache/maven/graph/FilteredProjectDependencyGraph.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.graph; import java.util.ArrayList; import java.util.Collection; @@ -25,7 +24,6 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; - import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.project.MavenProject; @@ -34,9 +32,7 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -class FilteredProjectDependencyGraph - implements ProjectDependencyGraph -{ +class FilteredProjectDependencyGraph implements ProjectDependencyGraph { private ProjectDependencyGraph projectDependencyGraph; @@ -50,57 +46,47 @@ class FilteredProjectDependencyGraph * @param projectDependencyGraph The project dependency graph to create a sub view from, must not be {@code null}. * @param whiteList The projects on which the dependency view should focus, must not be {@code null}. */ - FilteredProjectDependencyGraph( ProjectDependencyGraph projectDependencyGraph, - Collection whiteList ) - { + FilteredProjectDependencyGraph( + ProjectDependencyGraph projectDependencyGraph, Collection whiteList) { this.projectDependencyGraph = - Objects.requireNonNull( projectDependencyGraph, "projectDependencyGraph cannot be null" ); + Objects.requireNonNull(projectDependencyGraph, "projectDependencyGraph cannot be null"); this.whiteList = new IdentityHashMap<>(); - for ( MavenProject project : whiteList ) - { - this.whiteList.put( project, null ); + for (MavenProject project : whiteList) { + this.whiteList.put(project, null); } } /** * @since 3.5.0 */ - public List getAllProjects() - { + public List getAllProjects() { return this.projectDependencyGraph.getAllProjects(); } - public List getSortedProjects() - { - if ( sortedProjects == null ) - { - sortedProjects = applyFilter( projectDependencyGraph.getSortedProjects() ); + public List getSortedProjects() { + if (sortedProjects == null) { + sortedProjects = applyFilter(projectDependencyGraph.getSortedProjects()); } - return new ArrayList<>( sortedProjects ); + return new ArrayList<>(sortedProjects); } - public List getDownstreamProjects( MavenProject project, boolean transitive ) - { - return applyFilter( projectDependencyGraph.getDownstreamProjects( project, transitive ) ); + public List getDownstreamProjects(MavenProject project, boolean transitive) { + return applyFilter(projectDependencyGraph.getDownstreamProjects(project, transitive)); } - public List getUpstreamProjects( MavenProject project, boolean transitive ) - { - return applyFilter( projectDependencyGraph.getUpstreamProjects( project, transitive ) ); + public List getUpstreamProjects(MavenProject project, boolean transitive) { + return applyFilter(projectDependencyGraph.getUpstreamProjects(project, transitive)); } - private List applyFilter( Collection projects ) - { - List filtered = new ArrayList<>( projects.size() ); + private List applyFilter(Collection projects) { + List filtered = new ArrayList<>(projects.size()); - for ( MavenProject project : projects ) - { - if ( whiteList.containsKey( project ) ) - { - filtered.add( project ); + for (MavenProject project : projects) { + if (whiteList.containsKey(project)) { + filtered.add(project); } } @@ -108,9 +94,7 @@ class FilteredProjectDependencyGraph } @Override - public String toString() - { + public String toString() { return getSortedProjects().toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/graph/GraphBuilder.java b/maven-core/src/main/java/org/apache/maven/graph/GraphBuilder.java index 0f584d9203..b860781bdd 100644 --- a/maven-core/src/main/java/org/apache/maven/graph/GraphBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/graph/GraphBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.graph; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.graph; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ProjectDependencyGraph; @@ -28,9 +27,8 @@ import org.apache.maven.model.building.Result; * * @since 3.0-alpha */ -public interface GraphBuilder -{ +public interface GraphBuilder { String HINT = "graphBuilder"; - Result build( MavenSession session ); + Result build(MavenSession session); } diff --git a/maven-core/src/main/java/org/apache/maven/graph/ProjectSelector.java b/maven-core/src/main/java/org/apache/maven/graph/ProjectSelector.java index bc81abc2b7..7ee8cc691b 100644 --- a/maven-core/src/main/java/org/apache/maven/graph/ProjectSelector.java +++ b/maven-core/src/main/java/org/apache/maven/graph/ProjectSelector.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,7 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.MavenExecutionException; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.project.MavenProject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.apache.maven.graph; import java.io.File; import java.util.ArrayList; @@ -32,124 +25,107 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; +import org.apache.maven.MavenExecutionException; +import org.apache.maven.execution.MavenExecutionRequest; +import org.apache.maven.project.MavenProject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Utility class to extract {@link MavenProject} from the project graph during the execution phase based on optional or * required selectors. */ -public final class ProjectSelector -{ - private static final Logger LOGGER = LoggerFactory.getLogger( ProjectSelector.class ); +public final class ProjectSelector { + private static final Logger LOGGER = LoggerFactory.getLogger(ProjectSelector.class); - public Set getRequiredProjectsBySelectors( MavenExecutionRequest request, List projects, - Set projectSelectors ) - throws MavenExecutionException - { + public Set getRequiredProjectsBySelectors( + MavenExecutionRequest request, List projects, Set projectSelectors) + throws MavenExecutionException { Set selectedProjects = new LinkedHashSet<>(); - File baseDirectory = getBaseDirectoryFromRequest( request ); - for ( String selector : projectSelectors ) - { + File baseDirectory = getBaseDirectoryFromRequest(request); + for (String selector : projectSelectors) { Optional optSelectedProject = - findOptionalProjectBySelector( projects, baseDirectory, selector ); - if ( !optSelectedProject.isPresent() ) - { + findOptionalProjectBySelector(projects, baseDirectory, selector); + if (!optSelectedProject.isPresent()) { String message = "Could not find the selected project in the reactor: " + selector; - throw new MavenExecutionException( message, request.getPom() ); + throw new MavenExecutionException(message, request.getPom()); } MavenProject selectedProject = optSelectedProject.get(); - selectedProjects.add( selectedProject ); - selectedProjects.addAll( getChildProjects( selectedProject, request ) ); + selectedProjects.add(selectedProject); + selectedProjects.addAll(getChildProjects(selectedProject, request)); } return selectedProjects; } - public Set getOptionalProjectsBySelectors( MavenExecutionRequest request, List projects, - Set projectSelectors ) - { + public Set getOptionalProjectsBySelectors( + MavenExecutionRequest request, List projects, Set projectSelectors) { Set resolvedOptionalProjects = new LinkedHashSet<>(); Set unresolvedOptionalSelectors = new HashSet<>(); - File baseDirectory = getBaseDirectoryFromRequest( request ); - for ( String selector : projectSelectors ) - { + File baseDirectory = getBaseDirectoryFromRequest(request); + for (String selector : projectSelectors) { Optional optSelectedProject = - findOptionalProjectBySelector( projects, baseDirectory, selector ); - if ( optSelectedProject.isPresent() ) - { - resolvedOptionalProjects.add( optSelectedProject.get() ); - resolvedOptionalProjects.addAll( getChildProjects( optSelectedProject.get(), request ) ); - } - else - { - unresolvedOptionalSelectors.add( selector ); + findOptionalProjectBySelector(projects, baseDirectory, selector); + if (optSelectedProject.isPresent()) { + resolvedOptionalProjects.add(optSelectedProject.get()); + resolvedOptionalProjects.addAll(getChildProjects(optSelectedProject.get(), request)); + } else { + unresolvedOptionalSelectors.add(selector); } } - if ( !unresolvedOptionalSelectors.isEmpty() ) - { - LOGGER.info( "The requested optional projects {} do not exist.", unresolvedOptionalSelectors ); + if (!unresolvedOptionalSelectors.isEmpty()) { + LOGGER.info("The requested optional projects {} do not exist.", unresolvedOptionalSelectors); } return resolvedOptionalProjects; } - private List getChildProjects( MavenProject parent, MavenExecutionRequest request ) - { + private List getChildProjects(MavenProject parent, MavenExecutionRequest request) { final List children = parent.getCollectedProjects(); - if ( children != null && request.isRecursive() ) - { + if (children != null && request.isRecursive()) { return children; - } - else - { + } else { return new ArrayList<>(); } } - private Optional findOptionalProjectBySelector( List projects, File reactorDirectory, - String selector ) - { + private Optional findOptionalProjectBySelector( + List projects, File reactorDirectory, String selector) { return projects.stream() - .filter( project -> isMatchingProject( project, selector, reactorDirectory ) ) + .filter(project -> isMatchingProject(project, selector, reactorDirectory)) .findFirst(); } - File getBaseDirectoryFromRequest( MavenExecutionRequest request ) - { - return request.getBaseDirectory() != null ? new File( request.getBaseDirectory() ) : null; + File getBaseDirectoryFromRequest(MavenExecutionRequest request) { + return request.getBaseDirectory() != null ? new File(request.getBaseDirectory()) : null; } - boolean isMatchingProject( MavenProject project, String selector, File reactorDirectory ) - { + boolean isMatchingProject(MavenProject project, String selector, File reactorDirectory) { // [groupId]:artifactId - if ( selector.contains( ":" ) ) - { + if (selector.contains(":")) { String id = ':' + project.getArtifactId(); - if ( id.equals( selector ) ) - { + if (id.equals(selector)) { return true; } id = project.getGroupId() + id; - return id.equals( selector ); + return id.equals(selector); } // relative path, e.g. "sub", "../sub" or "." - else if ( reactorDirectory != null ) - { - File selectedProject = new File( new File( reactorDirectory, selector ).toURI().normalize() ); + else if (reactorDirectory != null) { + File selectedProject = + new File(new File(reactorDirectory, selector).toURI().normalize()); - if ( selectedProject.isFile() ) - { - return selectedProject.equals( project.getFile() ); - } - else if ( selectedProject.isDirectory() ) - { - return selectedProject.equals( project.getBasedir() ); + if (selectedProject.isFile()) { + return selectedProject.equals(project.getFile()); + } else if (selectedProject.isDirectory()) { + return selectedProject.equals(project.getBasedir()); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/MultilineMessageHelper.java b/maven-core/src/main/java/org/apache/maven/internal/MultilineMessageHelper.java index da158295ba..0e52e4c61a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/MultilineMessageHelper.java +++ b/maven-core/src/main/java/org/apache/maven/internal/MultilineMessageHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal; import java.util.ArrayList; import java.util.List; @@ -25,67 +24,57 @@ import java.util.List; /** * Helper class to format multiline messages to the console */ -public class MultilineMessageHelper -{ +public class MultilineMessageHelper { private static final int DEFAULT_MAX_SIZE = 65; private static final char BOX_CHAR = '*'; - public static String separatorLine() - { - StringBuilder sb = new StringBuilder( DEFAULT_MAX_SIZE ); - repeat( sb, '*', DEFAULT_MAX_SIZE ); + public static String separatorLine() { + StringBuilder sb = new StringBuilder(DEFAULT_MAX_SIZE); + repeat(sb, '*', DEFAULT_MAX_SIZE); return sb.toString(); } - public static List format( String... lines ) - { + public static List format(String... lines) { int size = DEFAULT_MAX_SIZE; int remainder = size - 4; // 4 chars = 2 box_char + 2 spaces List result = new ArrayList<>(); - StringBuilder sb = new StringBuilder( size ); + StringBuilder sb = new StringBuilder(size); // first line - sb.setLength( 0 ); - repeat( sb, BOX_CHAR, size ); - result.add( sb.toString() ); + sb.setLength(0); + repeat(sb, BOX_CHAR, size); + result.add(sb.toString()); // lines - for ( String line : lines ) - { - sb.setLength( 0 ); - String[] words = line.split( "\\s+" ); - for ( String word : words ) - { - if ( sb.length() >= remainder - word.length() - ( sb.length() > 0 ? 1 : 0 ) ) - { - repeat( sb, ' ', remainder - sb.length() ); - result.add( BOX_CHAR + " " + sb + " " + BOX_CHAR ); - sb.setLength( 0 ); + for (String line : lines) { + sb.setLength(0); + String[] words = line.split("\\s+"); + for (String word : words) { + if (sb.length() >= remainder - word.length() - (sb.length() > 0 ? 1 : 0)) { + repeat(sb, ' ', remainder - sb.length()); + result.add(BOX_CHAR + " " + sb + " " + BOX_CHAR); + sb.setLength(0); } - if ( sb.length() > 0 ) - { - sb.append( ' ' ); + if (sb.length() > 0) { + sb.append(' '); } - sb.append( word ); + sb.append(word); } - while ( sb.length() < remainder ) - { - sb.append( ' ' ); + while (sb.length() < remainder) { + sb.append(' '); } - result.add( BOX_CHAR + " " + sb + " " + BOX_CHAR ); + result.add(BOX_CHAR + " " + sb + " " + BOX_CHAR); } // last line - sb.setLength( 0 ); - repeat( sb, BOX_CHAR, size ); - result.add( sb.toString() ); + sb.setLength(0); + repeat(sb, BOX_CHAR, size); + result.add(sb.toString()); return result; } - private static void repeat( StringBuilder sb, char c, int nb ) - { - for ( int i = 0; i < nb; i++ ) - { - sb.append( c ); + private static void repeat(StringBuilder sb, char c, int nb) { + for (int i = 0; i < nb; i++) { + sb.append(c); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformer.java b/maven-core/src/main/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformer.java index c1e1144144..e680b0de2b 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformer.java +++ b/maven-core/src/main/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformer.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ package org.apache.maven.internal.aether; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.aether; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; - import org.apache.maven.model.building.DefaultBuildPomXMLFilterFactory; import org.apache.maven.model.building.TransformerContext; import org.apache.maven.model.transform.RawToConsumerPomXMLFilterFactory; @@ -35,18 +33,14 @@ import org.codehaus.plexus.util.xml.pull.MXParser; import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -class ConsumerModelSourceTransformer -{ - public InputStream transform( Path pomFile, TransformerContext context ) - throws IOException, XmlPullParserException - { - XmlStreamReader reader = ReaderFactory.newXmlReader( Files.newInputStream( pomFile ) ); - XmlPullParser parser = new MXParser( EntityReplacementMap.defaultEntityReplacementMap ); - parser.setInput( reader ); - parser = new RawToConsumerPomXMLFilterFactory( new DefaultBuildPomXMLFilterFactory( context, true ) ) - .get( parser, pomFile ); +class ConsumerModelSourceTransformer { + public InputStream transform(Path pomFile, TransformerContext context) throws IOException, XmlPullParserException { + XmlStreamReader reader = ReaderFactory.newXmlReader(Files.newInputStream(pomFile)); + XmlPullParser parser = new MXParser(EntityReplacementMap.defaultEntityReplacementMap); + parser.setInput(reader); + parser = new RawToConsumerPomXMLFilterFactory(new DefaultBuildPomXMLFilterFactory(context, true)) + .get(parser, pomFile); - return XmlUtils.writeDocument( reader, parser ); + return XmlUtils.writeDocument(reader, parser); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java b/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java index df013251c6..2a546c6ec7 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.internal.aether; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.aether; import java.io.File; import java.io.IOException; @@ -30,10 +29,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.RepositoryUtils; import org.apache.maven.api.xml.Dom; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; @@ -82,8 +79,7 @@ import org.slf4j.LoggerFactory; * @since 3.3.0 */ @Named -public class DefaultRepositorySystemSessionFactory -{ +public class DefaultRepositorySystemSessionFactory { private static final String MAVEN_RESOLVER_TRANSPORT_KEY = "maven.resolver.transport"; private static final String MAVEN_RESOLVER_TRANSPORT_DEFAULT = "default"; @@ -100,9 +96,9 @@ public class DefaultRepositorySystemSessionFactory private static final String NATIVE_FILE_TRANSPORTER_PRIORITY_KEY = "aether.priority.FileTransporterFactory"; - private static final String RESOLVER_MAX_PRIORITY = String.valueOf( Float.MAX_VALUE ); + private static final String RESOLVER_MAX_PRIORITY = String.valueOf(Float.MAX_VALUE); - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final ArtifactHandlerManager artifactHandlerManager; @@ -120,18 +116,17 @@ public class DefaultRepositorySystemSessionFactory private final RuntimeInformation runtimeInformation; - @SuppressWarnings( "checkstyle:ParameterNumber" ) + @SuppressWarnings("checkstyle:ParameterNumber") @Inject public DefaultRepositorySystemSessionFactory( ArtifactHandlerManager artifactHandlerManager, RepositorySystem repoSystem, - @Nullable @Named( "simple" ) LocalRepositoryManagerFactory simpleLocalRepoMgrFactory, - @Nullable @Named( "ide" ) WorkspaceReader workspaceRepository, + @Nullable @Named("simple") LocalRepositoryManagerFactory simpleLocalRepoMgrFactory, + @Nullable @Named("ide") WorkspaceReader workspaceRepository, SettingsDecrypter settingsDecrypter, EventSpyDispatcher eventSpyDispatcher, MavenRepositorySystem mavenRepositorySystem, - RuntimeInformation runtimeInformation ) - { + RuntimeInformation runtimeInformation) { this.artifactHandlerManager = artifactHandlerManager; this.repoSystem = repoSystem; this.simpleLocalRepoMgrFactory = simpleLocalRepoMgrFactory; @@ -142,100 +137,102 @@ public class DefaultRepositorySystemSessionFactory this.runtimeInformation = runtimeInformation; } - @SuppressWarnings( "checkstyle:methodLength" ) - public DefaultRepositorySystemSession newRepositorySession( MavenExecutionRequest request ) - { + @SuppressWarnings("checkstyle:methodLength") + public DefaultRepositorySystemSession newRepositorySession(MavenExecutionRequest request) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - session.setCache( request.getRepositoryCache() ); + session.setCache(request.getRepositoryCache()); Map configProps = new LinkedHashMap<>(); - configProps.put( ConfigurationProperties.USER_AGENT, getUserAgent() ); - configProps.put( ConfigurationProperties.INTERACTIVE, request.isInteractiveMode() ); - configProps.put( "maven.startTime", request.getStartTime() ); + configProps.put(ConfigurationProperties.USER_AGENT, getUserAgent()); + configProps.put(ConfigurationProperties.INTERACTIVE, request.isInteractiveMode()); + configProps.put("maven.startTime", request.getStartTime()); // First add properties populated from settings.xml - configProps.putAll( getPropertiesFromRequestedProfiles( request ) ); + configProps.putAll(getPropertiesFromRequestedProfiles(request)); // Resolver's ConfigUtils solely rely on config properties, that is why we need to add both here as well. - configProps.putAll( request.getSystemProperties() ); - configProps.putAll( request.getUserProperties() ); + configProps.putAll(request.getSystemProperties()); + configProps.putAll(request.getUserProperties()); - session.setOffline( request.isOffline() ); - session.setChecksumPolicy( request.getGlobalChecksumPolicy() ); - session.setUpdatePolicy( request.isNoSnapshotUpdates() - ? RepositoryPolicy.UPDATE_POLICY_NEVER - : request.isUpdateSnapshots() ? RepositoryPolicy.UPDATE_POLICY_ALWAYS : null ); + session.setOffline(request.isOffline()); + session.setChecksumPolicy(request.getGlobalChecksumPolicy()); + session.setUpdatePolicy( + request.isNoSnapshotUpdates() + ? RepositoryPolicy.UPDATE_POLICY_NEVER + : request.isUpdateSnapshots() ? RepositoryPolicy.UPDATE_POLICY_ALWAYS : null); int errorPolicy = 0; - errorPolicy |= request.isCacheNotFound() ? ResolutionErrorPolicy.CACHE_NOT_FOUND - : ResolutionErrorPolicy.CACHE_DISABLED; - errorPolicy |= request.isCacheTransferError() ? ResolutionErrorPolicy.CACHE_TRANSFER_ERROR - : ResolutionErrorPolicy.CACHE_DISABLED; + errorPolicy |= request.isCacheNotFound() + ? ResolutionErrorPolicy.CACHE_NOT_FOUND + : ResolutionErrorPolicy.CACHE_DISABLED; + errorPolicy |= request.isCacheTransferError() + ? ResolutionErrorPolicy.CACHE_TRANSFER_ERROR + : ResolutionErrorPolicy.CACHE_DISABLED; session.setResolutionErrorPolicy( - new SimpleResolutionErrorPolicy( errorPolicy, errorPolicy | ResolutionErrorPolicy.CACHE_NOT_FOUND ) ); + new SimpleResolutionErrorPolicy(errorPolicy, errorPolicy | ResolutionErrorPolicy.CACHE_NOT_FOUND)); - session.setArtifactTypeRegistry( RepositoryUtils.newArtifactTypeRegistry( artifactHandlerManager ) ); + session.setArtifactTypeRegistry(RepositoryUtils.newArtifactTypeRegistry(artifactHandlerManager)); session.setWorkspaceReader( - request.getWorkspaceReader() != null ? request.getWorkspaceReader() : workspaceRepository ); + request.getWorkspaceReader() != null ? request.getWorkspaceReader() : workspaceRepository); DefaultSettingsDecryptionRequest decrypt = new DefaultSettingsDecryptionRequest(); - decrypt.setProxies( request.getProxies() ); - decrypt.setServers( request.getServers() ); - SettingsDecryptionResult decrypted = settingsDecrypter.decrypt( decrypt ); + decrypt.setProxies(request.getProxies()); + decrypt.setServers(request.getServers()); + SettingsDecryptionResult decrypted = settingsDecrypter.decrypt(decrypt); - if ( logger.isDebugEnabled() ) - { - for ( SettingsProblem problem : decrypted.getProblems() ) - { - logger.debug( problem.getMessage(), problem.getException() ); + if (logger.isDebugEnabled()) { + for (SettingsProblem problem : decrypted.getProblems()) { + logger.debug(problem.getMessage(), problem.getException()); } } DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector(); - for ( Mirror mirror : request.getMirrors() ) - { - mirrorSelector.add( mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.isBlocked(), - mirror.getMirrorOf(), mirror.getMirrorOfLayouts() ); + for (Mirror mirror : request.getMirrors()) { + mirrorSelector.add( + mirror.getId(), + mirror.getUrl(), + mirror.getLayout(), + false, + mirror.isBlocked(), + mirror.getMirrorOf(), + mirror.getMirrorOfLayouts()); } - session.setMirrorSelector( mirrorSelector ); + session.setMirrorSelector(mirrorSelector); DefaultProxySelector proxySelector = new DefaultProxySelector(); - for ( Proxy proxy : decrypted.getProxies() ) - { + for (Proxy proxy : decrypted.getProxies()) { AuthenticationBuilder authBuilder = new AuthenticationBuilder(); - authBuilder.addUsername( proxy.getUsername() ).addPassword( proxy.getPassword() ); + authBuilder.addUsername(proxy.getUsername()).addPassword(proxy.getPassword()); proxySelector.add( - new org.eclipse.aether.repository.Proxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), - authBuilder.build() ), proxy.getNonProxyHosts() ); + new org.eclipse.aether.repository.Proxy( + proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authBuilder.build()), + proxy.getNonProxyHosts()); } - session.setProxySelector( proxySelector ); + session.setProxySelector(proxySelector); DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector(); - for ( Server server : decrypted.getServers() ) - { + for (Server server : decrypted.getServers()) { AuthenticationBuilder authBuilder = new AuthenticationBuilder(); - authBuilder.addUsername( server.getUsername() ).addPassword( server.getPassword() ); - authBuilder.addPrivateKey( server.getPrivateKey(), server.getPassphrase() ); - authSelector.add( server.getId(), authBuilder.build() ); + authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword()); + authBuilder.addPrivateKey(server.getPrivateKey(), server.getPassphrase()); + authSelector.add(server.getId(), authBuilder.build()); - if ( server.getConfiguration() != null ) - { - Dom dom = ( ( org.codehaus.plexus.util.xml.Xpp3Dom ) server.getConfiguration() ).getDom(); + if (server.getConfiguration() != null) { + Dom dom = ((org.codehaus.plexus.util.xml.Xpp3Dom) server.getConfiguration()).getDom(); List children = dom.getChildren().stream() - .filter( c -> !"wagonProvider".equals( c.getName() ) ) - .collect( Collectors.toList() ); - dom = new Xpp3Dom( dom.getName(), null, null, children, null ); - PlexusConfiguration config = XmlPlexusConfiguration.toPlexusConfiguration( dom ); - configProps.put( "aether.connector.wagon.config." + server.getId(), config ); + .filter(c -> !"wagonProvider".equals(c.getName())) + .collect(Collectors.toList()); + dom = new Xpp3Dom(dom.getName(), null, null, children, null); + PlexusConfiguration config = XmlPlexusConfiguration.toPlexusConfiguration(dom); + configProps.put("aether.connector.wagon.config." + server.getId(), config); } - configProps.put( "aether.connector.perms.fileMode." + server.getId(), server.getFilePermissions() ); - configProps.put( "aether.connector.perms.dirMode." + server.getId(), server.getDirectoryPermissions() ); + configProps.put("aether.connector.perms.fileMode." + server.getId(), server.getFilePermissions()); + configProps.put("aether.connector.perms.dirMode." + server.getId(), server.getDirectoryPermissions()); } - session.setAuthenticationSelector( authSelector ); + session.setAuthenticationSelector(authSelector); - Object transport = configProps.getOrDefault( MAVEN_RESOLVER_TRANSPORT_KEY, MAVEN_RESOLVER_TRANSPORT_DEFAULT ); - if ( MAVEN_RESOLVER_TRANSPORT_DEFAULT.equals( transport ) ) - { + Object transport = configProps.getOrDefault(MAVEN_RESOLVER_TRANSPORT_KEY, MAVEN_RESOLVER_TRANSPORT_DEFAULT); + if (MAVEN_RESOLVER_TRANSPORT_DEFAULT.equals(transport)) { // The "default" mode (user did not set anything) needs to tweak resolver default priorities // that are coded like this (default values): // @@ -252,131 +249,106 @@ public class DefaultRepositorySystemSessionFactory // old behavior. Also, this "default" mode is different from "auto" setting, // as it does not alter resolver priorities at all, and uses priorities as is. - configProps.put( WAGON_TRANSPORTER_PRIORITY_KEY, "6" ); - } - else if ( MAVEN_RESOLVER_TRANSPORT_NATIVE.equals( transport ) ) - { + configProps.put(WAGON_TRANSPORTER_PRIORITY_KEY, "6"); + } else if (MAVEN_RESOLVER_TRANSPORT_NATIVE.equals(transport)) { // Make sure (whatever extra priority is set) that resolver native is selected - configProps.put( NATIVE_FILE_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY ); - configProps.put( NATIVE_HTTP_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY ); - } - else if ( MAVEN_RESOLVER_TRANSPORT_WAGON.equals( transport ) ) - { + configProps.put(NATIVE_FILE_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY); + configProps.put(NATIVE_HTTP_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY); + } else if (MAVEN_RESOLVER_TRANSPORT_WAGON.equals(transport)) { // Make sure (whatever extra priority is set) that wagon is selected - configProps.put( WAGON_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY ); - } - else if ( !MAVEN_RESOLVER_TRANSPORT_AUTO.equals( transport ) ) - { - throw new IllegalArgumentException( "Unknown resolver transport '" + transport + configProps.put(WAGON_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY); + } else if (!MAVEN_RESOLVER_TRANSPORT_AUTO.equals(transport)) { + throw new IllegalArgumentException("Unknown resolver transport '" + transport + "'. Supported transports are: " + MAVEN_RESOLVER_TRANSPORT_WAGON + ", " - + MAVEN_RESOLVER_TRANSPORT_NATIVE + ", " + MAVEN_RESOLVER_TRANSPORT_AUTO ); + + MAVEN_RESOLVER_TRANSPORT_NATIVE + ", " + MAVEN_RESOLVER_TRANSPORT_AUTO); } - session.setUserProperties( request.getUserProperties() ); - session.setSystemProperties( request.getSystemProperties() ); - session.setConfigProperties( configProps ); + session.setUserProperties(request.getUserProperties()); + session.setSystemProperties(request.getSystemProperties()); + session.setConfigProperties(configProps); - session.setTransferListener( request.getTransferListener() ); + session.setTransferListener(request.getTransferListener()); - session.setRepositoryListener( eventSpyDispatcher.chainListener( new LoggingRepositoryListener( logger ) ) ); + session.setRepositoryListener(eventSpyDispatcher.chainListener(new LoggingRepositoryListener(logger))); - mavenRepositorySystem.injectMirror( request.getRemoteRepositories(), request.getMirrors() ); - mavenRepositorySystem.injectProxy( session, request.getRemoteRepositories() ); - mavenRepositorySystem.injectAuthentication( session, request.getRemoteRepositories() ); + mavenRepositorySystem.injectMirror(request.getRemoteRepositories(), request.getMirrors()); + mavenRepositorySystem.injectProxy(session, request.getRemoteRepositories()); + mavenRepositorySystem.injectAuthentication(session, request.getRemoteRepositories()); - mavenRepositorySystem.injectMirror( request.getPluginArtifactRepositories(), request.getMirrors() ); - mavenRepositorySystem.injectProxy( session, request.getPluginArtifactRepositories() ); - mavenRepositorySystem.injectAuthentication( session, request.getPluginArtifactRepositories() ); + mavenRepositorySystem.injectMirror(request.getPluginArtifactRepositories(), request.getMirrors()); + mavenRepositorySystem.injectProxy(session, request.getPluginArtifactRepositories()); + mavenRepositorySystem.injectAuthentication(session, request.getPluginArtifactRepositories()); - setUpLocalRepositoryManager( request, session ); + setUpLocalRepositoryManager(request, session); - if ( Features.buildConsumer( request.getUserProperties() ).isActive() ) - { - session.setFileTransformerManager( a -> getTransformersForArtifact( a, session.getData() ) ); + if (Features.buildConsumer(request.getUserProperties()).isActive()) { + session.setFileTransformerManager(a -> getTransformersForArtifact(a, session.getData())); } return session; } - private void setUpLocalRepositoryManager( MavenExecutionRequest request, DefaultRepositorySystemSession session ) - { - LocalRepository localRepo = new LocalRepository( request.getLocalRepository().getBasedir() ); + private void setUpLocalRepositoryManager(MavenExecutionRequest request, DefaultRepositorySystemSession session) { + LocalRepository localRepo = + new LocalRepository(request.getLocalRepository().getBasedir()); - if ( request.isUseLegacyLocalRepository() ) - { - try - { - session.setLocalRepositoryManager( simpleLocalRepoMgrFactory.newInstance( session, localRepo ) ); - logger.info( "Disabling enhanced local repository: using legacy is strongly discouraged to ensure" - + " build reproducibility." ); + if (request.isUseLegacyLocalRepository()) { + try { + session.setLocalRepositoryManager(simpleLocalRepoMgrFactory.newInstance(session, localRepo)); + logger.info("Disabling enhanced local repository: using legacy is strongly discouraged to ensure" + + " build reproducibility."); + } catch (NoLocalRepositoryManagerException e) { + logger.error("Failed to configure legacy local repository: falling back to default"); + session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo)); } - catch ( NoLocalRepositoryManagerException e ) - { - logger.error( "Failed to configure legacy local repository: falling back to default" ); - session.setLocalRepositoryManager( repoSystem.newLocalRepositoryManager( session, localRepo ) ); - } - } - else - { - session.setLocalRepositoryManager( repoSystem.newLocalRepositoryManager( session, localRepo ) ); + } else { + session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo)); } } - private Map getPropertiesFromRequestedProfiles( MavenExecutionRequest request ) - { + private Map getPropertiesFromRequestedProfiles(MavenExecutionRequest request) { - HashSet activeProfileId = new HashSet<>( request.getProfileActivation().getRequiredActiveProfileIds() ); - activeProfileId.addAll( request.getProfileActivation().getOptionalActiveProfileIds() ); + HashSet activeProfileId = + new HashSet<>(request.getProfileActivation().getRequiredActiveProfileIds()); + activeProfileId.addAll(request.getProfileActivation().getOptionalActiveProfileIds()); return request.getProfiles().stream() - .filter( profile -> activeProfileId.contains( profile.getId() ) ) - .map( ModelBase::getProperties ) - .flatMap( properties -> properties.entrySet().stream() ) - .collect( - Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, ( k1, k2 ) -> k2 ) ); + .filter(profile -> activeProfileId.contains(profile.getId())) + .map(ModelBase::getProperties) + .flatMap(properties -> properties.entrySet().stream()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k2)); } - private String getUserAgent() - { + private String getUserAgent() { String version = runtimeInformation.getMavenVersion(); version = version.isEmpty() ? version : "/" + version; - return "Apache-Maven" + version + " (Java " + System.getProperty( "java.version" ) + "; " - + System.getProperty( "os.name" ) + " " + System.getProperty( "os.version" ) + ")"; + return "Apache-Maven" + version + " (Java " + System.getProperty("java.version") + "; " + + System.getProperty("os.name") + " " + System.getProperty("os.version") + ")"; } - private Collection getTransformersForArtifact( final Artifact artifact, - final SessionData sessionData ) - { - TransformerContext context = (TransformerContext) sessionData.get( TransformerContext.KEY ); + private Collection getTransformersForArtifact( + final Artifact artifact, final SessionData sessionData) { + TransformerContext context = (TransformerContext) sessionData.get(TransformerContext.KEY); Collection transformers = new ArrayList<>(); // In case of install:install-file there's no transformer context, as the goal is unrelated to the lifecycle. - if ( "pom".equals( artifact.getExtension() ) && context != null ) - { - transformers.add( new FileTransformer() - { + if ("pom".equals(artifact.getExtension()) && context != null) { + transformers.add(new FileTransformer() { @Override - public InputStream transformData( File pomFile ) - throws IOException, TransformException - { - try - { - return new ConsumerModelSourceTransformer().transform( pomFile.toPath(), context ); - } - catch ( XmlPullParserException e ) - { - throw new TransformException( e ); + public InputStream transformData(File pomFile) throws IOException, TransformException { + try { + return new ConsumerModelSourceTransformer().transform(pomFile.toPath(), context); + } catch (XmlPullParserException e) { + throw new TransformException(e); } } @Override - public Artifact transformArtifact( Artifact artifact ) - { + public Artifact transformArtifact(Artifact artifact) { return artifact; } - } ); + }); } - return Collections.unmodifiableCollection( transformers ); + return Collections.unmodifiableCollection(transformers); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/aether/LoggingRepositoryListener.java b/maven-core/src/main/java/org/apache/maven/internal/aether/LoggingRepositoryListener.java index 340a3b6e3a..1066064b53 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/aether/LoggingRepositoryListener.java +++ b/maven-core/src/main/java/org/apache/maven/internal/aether/LoggingRepositoryListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.internal.aether; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.aether; import java.io.FileNotFoundException; - import org.eclipse.aether.AbstractRepositoryListener; import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.transfer.MetadataNotFoundException; @@ -29,113 +27,84 @@ import org.slf4j.Logger; /** * @author Benjamin Bentmann */ -class LoggingRepositoryListener - extends AbstractRepositoryListener -{ +class LoggingRepositoryListener extends AbstractRepositoryListener { private final Logger logger; - LoggingRepositoryListener( Logger logger ) - { + LoggingRepositoryListener(Logger logger) { this.logger = logger; } @Override - public void artifactInstalling( RepositoryEvent event ) - { - logger.info( "Installing " + event.getArtifact().getFile() + " to " + event.getFile() ); + public void artifactInstalling(RepositoryEvent event) { + logger.info("Installing " + event.getArtifact().getFile() + " to " + event.getFile()); } @Override - public void metadataInstalling( RepositoryEvent event ) - { - logger.debug( "Installing " + event.getMetadata() + " to " + event.getFile() ); + public void metadataInstalling(RepositoryEvent event) { + logger.debug("Installing " + event.getMetadata() + " to " + event.getFile()); } @Override - public void metadataResolved( RepositoryEvent event ) - { + public void metadataResolved(RepositoryEvent event) { Exception e = event.getException(); - if ( e != null ) - { - if ( e instanceof MetadataNotFoundException ) - { - logger.debug( e.getMessage() ); - } - else if ( logger.isDebugEnabled() ) - { - logger.warn( e.getMessage(), e ); - } - else - { - logger.warn( e.getMessage() ); + if (e != null) { + if (e instanceof MetadataNotFoundException) { + logger.debug(e.getMessage()); + } else if (logger.isDebugEnabled()) { + logger.warn(e.getMessage(), e); + } else { + logger.warn(e.getMessage()); } } } @Override - public void metadataInvalid( RepositoryEvent event ) - { + public void metadataInvalid(RepositoryEvent event) { Exception exception = event.getException(); - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "The metadata " ); - if ( event.getMetadata().getFile() != null ) - { - buffer.append( event.getMetadata().getFile() ); - } - else - { - buffer.append( event.getMetadata() ); + StringBuilder buffer = new StringBuilder(256); + buffer.append("The metadata "); + if (event.getMetadata().getFile() != null) { + buffer.append(event.getMetadata().getFile()); + } else { + buffer.append(event.getMetadata()); } - if ( exception instanceof FileNotFoundException ) - { - buffer.append( " is inaccessible" ); - } - else - { - buffer.append( " is invalid" ); + if (exception instanceof FileNotFoundException) { + buffer.append(" is inaccessible"); + } else { + buffer.append(" is invalid"); } - if ( exception != null ) - { - buffer.append( ": " ); - buffer.append( exception.getMessage() ); + if (exception != null) { + buffer.append(": "); + buffer.append(exception.getMessage()); } - if ( logger.isDebugEnabled() ) - { - logger.warn( buffer.toString(), exception ); - } - else - { - logger.warn( buffer.toString() ); + if (logger.isDebugEnabled()) { + logger.warn(buffer.toString(), exception); + } else { + logger.warn(buffer.toString()); } } @Override - public void artifactDescriptorInvalid( RepositoryEvent event ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "The POM for " ); - buffer.append( event.getArtifact() ); - buffer.append( " is invalid, transitive dependencies (if any) will not be available" ); + public void artifactDescriptorInvalid(RepositoryEvent event) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("The POM for "); + buffer.append(event.getArtifact()); + buffer.append(" is invalid, transitive dependencies (if any) will not be available"); - if ( logger.isDebugEnabled() ) - { - logger.warn( buffer + ": " + event.getException().getMessage() ); - } - else - { - logger.warn( buffer + ", enable verbose output (-X) for more details" ); + if (logger.isDebugEnabled()) { + logger.warn(buffer + ": " + event.getException().getMessage()); + } else { + logger.warn(buffer + ", enable verbose output (-X) for more details"); } } @Override - public void artifactDescriptorMissing( RepositoryEvent event ) - { - logger.warn( "The POM for " + event.getArtifact() + " is missing, no dependency information available" ); + public void artifactDescriptorMissing(RepositoryEvent event) { + logger.warn("The POM for " + event.getArtifact() + " is missing, no dependency information available"); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/aether/MavenChainedWorkspaceReader.java b/maven-core/src/main/java/org/apache/maven/internal/aether/MavenChainedWorkspaceReader.java index 4bc16a9271..05e3c781eb 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/aether/MavenChainedWorkspaceReader.java +++ b/maven-core/src/main/java/org/apache/maven/internal/aether/MavenChainedWorkspaceReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.internal.aether; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.aether; import java.io.File; import java.util.Collection; import java.util.List; - import org.apache.maven.model.Model; import org.apache.maven.repository.internal.MavenWorkspaceReader; import org.eclipse.aether.artifact.Artifact; @@ -33,9 +31,7 @@ import org.eclipse.aether.util.repository.ChainedWorkspaceReader; /** * A maven workspace reader that delegates to a chain of other readers, effectively aggregating their contents. */ -public final class MavenChainedWorkspaceReader - implements MavenWorkspaceReader -{ +public final class MavenChainedWorkspaceReader implements MavenWorkspaceReader { private ChainedWorkspaceReader delegate; @@ -43,25 +39,20 @@ public final class MavenChainedWorkspaceReader /** * Creates a new workspace reader by chaining the specified readers. - * + * * @param readers The readers to chain must not be {@code null}. */ - private MavenChainedWorkspaceReader( WorkspaceReader... readers ) - { - this.delegate = new ChainedWorkspaceReader( readers ); + private MavenChainedWorkspaceReader(WorkspaceReader... readers) { + this.delegate = new ChainedWorkspaceReader(readers); this.readers = readers; } @Override - public Model findModel( Artifact artifact ) - { - for ( WorkspaceReader workspaceReader : readers ) - { - if ( workspaceReader instanceof MavenWorkspaceReader ) - { - Model model = ( (MavenWorkspaceReader) workspaceReader ).findModel( artifact ); - if ( model != null ) - { + public Model findModel(Artifact artifact) { + for (WorkspaceReader workspaceReader : readers) { + if (workspaceReader instanceof MavenWorkspaceReader) { + Model model = ((MavenWorkspaceReader) workspaceReader).findModel(artifact); + if (model != null) { return model; } } @@ -70,21 +61,18 @@ public final class MavenChainedWorkspaceReader } @Override - public WorkspaceRepository getRepository() - { + public WorkspaceRepository getRepository() { return delegate.getRepository(); } @Override - public File findArtifact( Artifact artifact ) - { - return delegate.findArtifact( artifact ); + public File findArtifact(Artifact artifact) { + return delegate.findArtifact(artifact); } @Override - public List findVersions( Artifact artifact ) - { - return delegate.findVersions( artifact ); + public List findVersions(Artifact artifact) { + return delegate.findVersions(artifact); } /** @@ -93,14 +81,11 @@ public final class MavenChainedWorkspaceReader * @return if the collection contains only one item returns the single item, otherwise creates a new * {@link MavenChainedWorkspaceReader} chaining all readers in the order of the given collection. */ - public static WorkspaceReader of( Collection workspaceReaderCollection ) - { - WorkspaceReader[] readers = workspaceReaderCollection.toArray( new WorkspaceReader[0] ); - if ( readers.length == 1 ) - { + public static WorkspaceReader of(Collection workspaceReaderCollection) { + WorkspaceReader[] readers = workspaceReaderCollection.toArray(new WorkspaceReader[0]); + if (readers.length == 1) { return readers[0]; } - return new MavenChainedWorkspaceReader( readers ); + return new MavenChainedWorkspaceReader(readers); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractNode.java b/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractNode.java index 199d722216..fcbced9511 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractNode.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractNode.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,69 +16,59 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.maven.api.Node; import org.apache.maven.api.NodeVisitor; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; -public abstract class AbstractNode implements Node -{ +public abstract class AbstractNode implements Node { abstract org.eclipse.aether.graph.DependencyNode getDependencyNode(); @Override - public boolean accept( NodeVisitor visitor ) - { - if ( visitor.enter( this ) ) - { - for ( Node child : getChildren() ) - { - if ( !child.accept( visitor ) ) - { + public boolean accept(NodeVisitor visitor) { + if (visitor.enter(this)) { + for (Node child : getChildren()) { + if (!child.accept(visitor)) { break; } } } - return visitor.leave( this ); + return visitor.leave(this); } @Override - public Node filter( Predicate filter ) - { - List children = getChildren().stream().filter( filter ) - .map( n -> n.filter( filter ) ) - .collect( Collectors.toList() ); - return new WrapperNode( this, Collections.unmodifiableList( children ) ); + public Node filter(Predicate filter) { + List children = + getChildren().stream().filter(filter).map(n -> n.filter(filter)).collect(Collectors.toList()); + return new WrapperNode(this, Collections.unmodifiableList(children)); } @Override - public String asString() - { + public String asString() { StringBuilder sb = new StringBuilder(); DependencyNode node = getDependencyNode(); Artifact artifact = node.getArtifact(); - sb.append( artifact ); + sb.append(artifact); Dependency dependency = node.getDependency(); - if ( dependency != null ) - { - sb.append( ":" ).append( dependency.getScope() ); + if (dependency != null) { + sb.append(":").append(dependency.getScope()); } return sb.toString(); } @Override - public String toString() - { + public String toString() { return getDependencyNode().toString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractSession.java b/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractSession.java index 11738ba066..3a8a03523a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractSession.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/AbstractSession.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,6 +16,9 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import java.io.File; import java.nio.file.Path; @@ -32,7 +33,6 @@ import java.util.WeakHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.apache.maven.api.Artifact; import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.Dependency; @@ -65,128 +65,103 @@ import org.apache.maven.api.services.VersionParser; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.project.MavenProject; -import static org.apache.maven.internal.impl.Utils.nonNull; - -public abstract class AbstractSession implements Session -{ +public abstract class AbstractSession implements Session { private final List listeners = new CopyOnWriteArrayList<>(); - private final Map allNodes - = Collections.synchronizedMap( new WeakHashMap<>() ); - private final Map allArtifacts - = Collections.synchronizedMap( new WeakHashMap<>() ); - private final Map allRepositories - = Collections.synchronizedMap( new WeakHashMap<>() ); - private final Map allProjects - = Collections.synchronizedMap( new WeakHashMap<>() ); - private final Map allDependencies - = Collections.synchronizedMap( new WeakHashMap<>() ); + private final Map allNodes = + Collections.synchronizedMap(new WeakHashMap<>()); + private final Map allArtifacts = + Collections.synchronizedMap(new WeakHashMap<>()); + private final Map allRepositories = + Collections.synchronizedMap(new WeakHashMap<>()); + private final Map allProjects = Collections.synchronizedMap(new WeakHashMap<>()); + private final Map allDependencies = + Collections.synchronizedMap(new WeakHashMap<>()); - public RemoteRepository getRemoteRepository( org.eclipse.aether.repository.RemoteRepository repository ) - { - return allRepositories.computeIfAbsent( repository, DefaultRemoteRepository::new ); + public RemoteRepository getRemoteRepository(org.eclipse.aether.repository.RemoteRepository repository) { + return allRepositories.computeIfAbsent(repository, DefaultRemoteRepository::new); } - public Node getNode( org.eclipse.aether.graph.DependencyNode node ) - { - return getNode( node, false ); + public Node getNode(org.eclipse.aether.graph.DependencyNode node) { + return getNode(node, false); } - public Node getNode( org.eclipse.aether.graph.DependencyNode node, boolean verbose ) - { - return allNodes.computeIfAbsent( node, n -> new DefaultNode( this, n, verbose ) ); + public Node getNode(org.eclipse.aether.graph.DependencyNode node, boolean verbose) { + return allNodes.computeIfAbsent(node, n -> new DefaultNode(this, n, verbose)); } @Nonnull - public Artifact getArtifact( @Nonnull org.eclipse.aether.artifact.Artifact artifact ) - { - return allArtifacts.computeIfAbsent( artifact, a -> new DefaultArtifact( this, a ) ); + public Artifact getArtifact(@Nonnull org.eclipse.aether.artifact.Artifact artifact) { + return allArtifacts.computeIfAbsent(artifact, a -> new DefaultArtifact(this, a)); } @Nonnull - public Dependency getDependency( @Nonnull org.eclipse.aether.graph.Dependency dependency ) - { - return allDependencies.computeIfAbsent( dependency, d -> new DefaultDependency( this, d ) ); + public Dependency getDependency(@Nonnull org.eclipse.aether.graph.Dependency dependency) { + return allDependencies.computeIfAbsent(dependency, d -> new DefaultDependency(this, d)); } - public List getProjects( List projects ) - { - return projects == null ? null : projects.stream() - .map( this::getProject ) - .collect( Collectors.toList() ); + public List getProjects(List projects) { + return projects == null ? null : projects.stream().map(this::getProject).collect(Collectors.toList()); } - public Project getProject( MavenProject project ) - { - return allProjects.computeIfAbsent( project.getId(), id -> new DefaultProject( this, project ) ); + public Project getProject(MavenProject project) { + return allProjects.computeIfAbsent(project.getId(), id -> new DefaultProject(this, project)); } - public List toRepositories( List repositories ) - { - return repositories == null ? null : repositories.stream() - .map( this::toRepository ) - .collect( Collectors.toList() ); + public List toRepositories(List repositories) { + return repositories == null + ? null + : repositories.stream().map(this::toRepository).collect(Collectors.toList()); } - public org.eclipse.aether.repository.RemoteRepository toRepository( RemoteRepository repository ) - { - if ( repository instanceof DefaultRemoteRepository ) - { - return ( (DefaultRemoteRepository) repository ).getRepository(); - } - else - { + public org.eclipse.aether.repository.RemoteRepository toRepository(RemoteRepository repository) { + if (repository instanceof DefaultRemoteRepository) { + return ((DefaultRemoteRepository) repository).getRepository(); + } else { // TODO - throw new UnsupportedOperationException( "Not implemented yet" ); + throw new UnsupportedOperationException("Not implemented yet"); } } - public org.eclipse.aether.repository.LocalRepository toRepository( LocalRepository repository ) - { - if ( repository instanceof DefaultLocalRepository ) - { - return ( (DefaultLocalRepository) repository ).getRepository(); - } - else - { + public org.eclipse.aether.repository.LocalRepository toRepository(LocalRepository repository) { + if (repository instanceof DefaultLocalRepository) { + return ((DefaultLocalRepository) repository).getRepository(); + } else { // TODO - throw new UnsupportedOperationException( "Not implemented yet" ); + throw new UnsupportedOperationException("Not implemented yet"); } } - public List toArtifactRepositories( List repositories ) - { - return repositories == null ? null : repositories.stream() - .map( this::toArtifactRepository ) - .collect( Collectors.toList() ); + public List toArtifactRepositories(List repositories) { + return repositories == null + ? null + : repositories.stream().map(this::toArtifactRepository).collect(Collectors.toList()); } - public abstract ArtifactRepository toArtifactRepository( RemoteRepository repository ); + public abstract ArtifactRepository toArtifactRepository(RemoteRepository repository); - public List toDependencies( Collection dependencies ) - { - return dependencies == null ? null : dependencies.stream() - .map( this::toDependency ) - .collect( Collectors.toList() ); + public List toDependencies(Collection dependencies) { + return dependencies == null + ? null + : dependencies.stream().map(this::toDependency).collect(Collectors.toList()); } - public abstract org.eclipse.aether.graph.Dependency toDependency( DependencyCoordinate dependency ); + public abstract org.eclipse.aether.graph.Dependency toDependency(DependencyCoordinate dependency); - public List toArtifacts( Collection artifacts ) - { - return artifacts == null ? null : artifacts.stream() - .map( this::toArtifact ) - .collect( Collectors.toList() ); + public List toArtifacts(Collection artifacts) { + return artifacts == null + ? null + : artifacts.stream().map(this::toArtifact).collect(Collectors.toList()); } - public org.eclipse.aether.artifact.Artifact toArtifact( Artifact artifact ) - { - File file = getService( ArtifactManager.class ).getPath( artifact ).map( Path::toFile ).orElse( null ); - if ( artifact instanceof DefaultArtifact ) - { - org.eclipse.aether.artifact.Artifact a = ( (DefaultArtifact) artifact ).getArtifact(); - if ( Objects.equals( file, a.getFile() ) ) - { + public org.eclipse.aether.artifact.Artifact toArtifact(Artifact artifact) { + File file = getService(ArtifactManager.class) + .getPath(artifact) + .map(Path::toFile) + .orElse(null); + if (artifact instanceof DefaultArtifact) { + org.eclipse.aether.artifact.Artifact a = ((DefaultArtifact) artifact).getArtifact(); + if (Objects.equals(file, a.getFile())) { return a; } } @@ -197,15 +172,12 @@ public abstract class AbstractSession implements Session artifact.getExtension(), artifact.getVersion().toString(), null, - file - ); + file); } - public org.eclipse.aether.artifact.Artifact toArtifact( ArtifactCoordinate coord ) - { - if ( coord instanceof DefaultArtifactCoordinate ) - { - return ( (DefaultArtifactCoordinate) coord ).getCoordinate(); + public org.eclipse.aether.artifact.Artifact toArtifact(ArtifactCoordinate coord) { + if (coord instanceof DefaultArtifactCoordinate) { + return ((DefaultArtifactCoordinate) coord).getCoordinate(); } return new org.eclipse.aether.artifact.DefaultArtifact( coord.getGroupId(), @@ -214,27 +186,23 @@ public abstract class AbstractSession implements Session coord.getExtension(), coord.getVersion().toString(), null, - (File) null - ); + (File) null); } @Override - public void registerListener( @Nonnull Listener listener ) - { - listeners.add( nonNull( listener ) ); + public void registerListener(@Nonnull Listener listener) { + listeners.add(nonNull(listener)); } @Override - public void unregisterListener( @Nonnull Listener listener ) - { - listeners.remove( nonNull( listener ) ); + public void unregisterListener(@Nonnull Listener listener) { + listeners.remove(nonNull(listener)); } @Nonnull @Override - public Collection getListeners() - { - return Collections.unmodifiableCollection( listeners ); + public Collection getListeners() { + return Collections.unmodifiableCollection(listeners); } // @@ -247,9 +215,8 @@ public abstract class AbstractSession implements Session * @see RepositoryFactory#createLocal(Path) */ @Override - public LocalRepository createLocalRepository( Path path ) - { - return getService( RepositoryFactory.class ).createLocal( path ); + public LocalRepository createLocalRepository(Path path) { + return getService(RepositoryFactory.class).createLocal(path); } /** @@ -259,10 +226,8 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public RemoteRepository createRemoteRepository( @Nonnull String id, @Nonnull String url ) - { - return getService( RepositoryFactory.class ) - .createRemote( id, url ); + public RemoteRepository createRemoteRepository(@Nonnull String id, @Nonnull String url) { + return getService(RepositoryFactory.class).createRemote(id, url); } /** @@ -272,10 +237,8 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public RemoteRepository createRemoteRepository( @Nonnull Repository repository ) - { - return getService( RepositoryFactory.class ) - .createRemote( repository ); + public RemoteRepository createRemoteRepository(@Nonnull Repository repository) { + return getService(RepositoryFactory.class).createRemote(repository); } /** @@ -284,11 +247,9 @@ public abstract class AbstractSession implements Session * @see ArtifactFactory#create(Session, String, String, String, String) */ @Override - public ArtifactCoordinate createArtifactCoordinate( String groupId, String artifactId, - String version, String extension ) - { - return getService( ArtifactCoordinateFactory.class ) - .create( this, groupId, artifactId, version, extension ); + public ArtifactCoordinate createArtifactCoordinate( + String groupId, String artifactId, String version, String extension) { + return getService(ArtifactCoordinateFactory.class).create(this, groupId, artifactId, version, extension); } /** @@ -297,11 +258,10 @@ public abstract class AbstractSession implements Session * @see ArtifactCoordinateFactory#create(Session, String, String, String, String, String, String) */ @Override - public ArtifactCoordinate createArtifactCoordinate( String groupId, String artifactId, String version, - String classifier, String extension, String type ) - { - return getService( ArtifactCoordinateFactory.class ) - .create( this, groupId, artifactId, version, classifier, extension, type ); + public ArtifactCoordinate createArtifactCoordinate( + String groupId, String artifactId, String version, String classifier, String extension, String type) { + return getService(ArtifactCoordinateFactory.class) + .create(this, groupId, artifactId, version, classifier, extension, type); } /** @@ -310,11 +270,16 @@ public abstract class AbstractSession implements Session * @see ArtifactCoordinateFactory#create(Session, String, String, String, String, String, String) */ @Override - public ArtifactCoordinate createArtifactCoordinate( Artifact artifact ) - { - return getService( ArtifactCoordinateFactory.class ) - .create( this, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion().asString(), - artifact.getClassifier(), artifact.getExtension(), null ); + public ArtifactCoordinate createArtifactCoordinate(Artifact artifact) { + return getService(ArtifactCoordinateFactory.class) + .create( + this, + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion().asString(), + artifact.getClassifier(), + artifact.getExtension(), + null); } /** @@ -323,10 +288,8 @@ public abstract class AbstractSession implements Session * @see ArtifactFactory#create(Session, String, String, String, String) */ @Override - public Artifact createArtifact( String groupId, String artifactId, String version, String extension ) - { - return getService( ArtifactFactory.class ) - .create( this, groupId, artifactId, version, extension ); + public Artifact createArtifact(String groupId, String artifactId, String version, String extension) { + return getService(ArtifactFactory.class).create(this, groupId, artifactId, version, extension); } /** @@ -335,11 +298,10 @@ public abstract class AbstractSession implements Session * @see ArtifactFactory#create(Session, String, String, String, String, String, String) */ @Override - public Artifact createArtifact( String groupId, String artifactId, String version, String classifier, - String extension, String type ) - { - return getService( ArtifactFactory.class ) - .create( this, groupId, artifactId, version, classifier, extension, type ); + public Artifact createArtifact( + String groupId, String artifactId, String version, String classifier, String extension, String type) { + return getService(ArtifactFactory.class) + .create(this, groupId, artifactId, version, classifier, extension, type); } /** @@ -349,11 +311,13 @@ public abstract class AbstractSession implements Session * @see ArtifactResolver#resolve(Session, Collection) */ @Override - public Artifact resolveArtifact( ArtifactCoordinate coordinate ) - { - return getService( ArtifactResolver.class ) - .resolve( this, Collections.singletonList( coordinate ) ) - .getArtifacts().keySet().iterator().next(); + public Artifact resolveArtifact(ArtifactCoordinate coordinate) { + return getService(ArtifactResolver.class) + .resolve(this, Collections.singletonList(coordinate)) + .getArtifacts() + .keySet() + .iterator() + .next(); } /** @@ -363,9 +327,8 @@ public abstract class AbstractSession implements Session * @see ArtifactResolver#resolve(Session, Collection) */ @Override - public Collection resolveArtifacts( ArtifactCoordinate... coordinates ) - { - return resolveArtifacts( Arrays.asList( coordinates ) ); + public Collection resolveArtifacts(ArtifactCoordinate... coordinates) { + return resolveArtifacts(Arrays.asList(coordinates)); } /** @@ -375,11 +338,11 @@ public abstract class AbstractSession implements Session * @see ArtifactResolver#resolve(Session, Collection) */ @Override - public Collection resolveArtifacts( Collection coordinates ) - { - return getService( ArtifactResolver.class ) - .resolve( this, coordinates ) - .getArtifacts().keySet(); + public Collection resolveArtifacts(Collection coordinates) { + return getService(ArtifactResolver.class) + .resolve(this, coordinates) + .getArtifacts() + .keySet(); } /** @@ -389,21 +352,18 @@ public abstract class AbstractSession implements Session * @see ArtifactResolver#resolve(Session, Collection) */ @Override - public Artifact resolveArtifact( Artifact artifact ) - { - ArtifactCoordinate coordinate = getService( ArtifactCoordinateFactory.class ) - .create( this, artifact ); - return resolveArtifact( coordinate ); + public Artifact resolveArtifact(Artifact artifact) { + ArtifactCoordinate coordinate = + getService(ArtifactCoordinateFactory.class).create(this, artifact); + return resolveArtifact(coordinate); } @Override - public Collection resolveArtifacts( Artifact... artifacts ) - { - ArtifactCoordinateFactory acf = getService( ArtifactCoordinateFactory.class ); - ArtifactCoordinate[] coords = Stream.of( artifacts ) - .map( a -> acf.create( this, a ) ) - .toArray( ArtifactCoordinate[]::new ); - return resolveArtifacts( coords ); + public Collection resolveArtifacts(Artifact... artifacts) { + ArtifactCoordinateFactory acf = getService(ArtifactCoordinateFactory.class); + ArtifactCoordinate[] coords = + Stream.of(artifacts).map(a -> acf.create(this, a)).toArray(ArtifactCoordinate[]::new); + return resolveArtifacts(coords); } /** @@ -413,9 +373,8 @@ public abstract class AbstractSession implements Session * @see ArtifactInstaller#install(Session, Collection) */ @Override - public void installArtifacts( Artifact... artifacts ) - { - installArtifacts( Arrays.asList( artifacts ) ); + public void installArtifacts(Artifact... artifacts) { + installArtifacts(Arrays.asList(artifacts)); } /** @@ -425,10 +384,8 @@ public abstract class AbstractSession implements Session * @see ArtifactInstaller#install(Session, Collection) */ @Override - public void installArtifacts( Collection artifacts ) - { - getService( ArtifactInstaller.class ) - .install( this, artifacts ); + public void installArtifacts(Collection artifacts) { + getService(ArtifactInstaller.class).install(this, artifacts); } /** @@ -438,10 +395,8 @@ public abstract class AbstractSession implements Session * @see ArtifactDeployer#deploy(Session, RemoteRepository, Collection) */ @Override - public void deployArtifact( RemoteRepository repository, Artifact... artifacts ) - { - getService( ArtifactDeployer.class ) - .deploy( this, repository, Arrays.asList( artifacts ) ); + public void deployArtifact(RemoteRepository repository, Artifact... artifacts) { + getService(ArtifactDeployer.class).deploy(this, repository, Arrays.asList(artifacts)); } /** @@ -450,10 +405,8 @@ public abstract class AbstractSession implements Session * @see ArtifactManager#setPath(Artifact, Path) */ @Override - public void setArtifactPath( @Nonnull Artifact artifact, @Nonnull Path path ) - { - getService( ArtifactManager.class ) - .setPath( artifact, path ); + public void setArtifactPath(@Nonnull Artifact artifact, @Nonnull Path path) { + getService(ArtifactManager.class).setPath(artifact, path); } /** @@ -463,10 +416,8 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public Optional getArtifactPath( @Nonnull Artifact artifact ) - { - return getService( ArtifactManager.class ) - .getPath( artifact ); + public Optional getArtifactPath(@Nonnull Artifact artifact) { + return getService(ArtifactManager.class).getPath(artifact); } /** @@ -475,10 +426,8 @@ public abstract class AbstractSession implements Session * @see VersionParser#isSnapshot(String) */ @Override - public boolean isVersionSnapshot( @Nonnull String version ) - { - return getService( VersionParser.class ) - .isSnapshot( version ); + public boolean isVersionSnapshot(@Nonnull String version) { + return getService(VersionParser.class).isSnapshot(version); } /** @@ -488,10 +437,8 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public DependencyCoordinate createDependencyCoordinate( @Nonnull ArtifactCoordinate coordinate ) - { - return getService( DependencyCoordinateFactory.class ) - .create( this, coordinate ); + public DependencyCoordinate createDependencyCoordinate(@Nonnull ArtifactCoordinate coordinate) { + return getService(DependencyCoordinateFactory.class).create(this, coordinate); } /** @@ -500,10 +447,8 @@ public abstract class AbstractSession implements Session * @see DependencyCoordinateFactory#create(Session, ArtifactCoordinate) */ @Nonnull - public DependencyCoordinate createDependencyCoordinate( @Nonnull Dependency dependency ) - { - return getService( DependencyCoordinateFactory.class ) - .create( this, dependency ); + public DependencyCoordinate createDependencyCoordinate(@Nonnull Dependency dependency) { + return getService(DependencyCoordinateFactory.class).create(this, dependency); } /** @@ -514,11 +459,8 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public Node collectDependencies( @Nonnull Artifact artifact ) - { - return getService( DependencyCollector.class ) - .collect( this, artifact ) - .getRoot(); + public Node collectDependencies(@Nonnull Artifact artifact) { + return getService(DependencyCollector.class).collect(this, artifact).getRoot(); } /** @@ -529,11 +471,8 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public Node collectDependencies( @Nonnull Project project ) - { - return getService( DependencyCollector.class ) - .collect( this, project ) - .getRoot(); + public Node collectDependencies(@Nonnull Project project) { + return getService(DependencyCollector.class).collect(this, project).getRoot(); } /** @@ -544,38 +483,28 @@ public abstract class AbstractSession implements Session */ @Nonnull @Override - public Node collectDependencies( @Nonnull DependencyCoordinate dependency ) - { - return getService( DependencyCollector.class ) - .collect( this, dependency ) - .getRoot(); + public Node collectDependencies(@Nonnull DependencyCoordinate dependency) { + return getService(DependencyCollector.class).collect(this, dependency).getRoot(); } @Override - public Path getPathForLocalArtifact( @Nonnull Artifact artifact ) - { - return getService( LocalRepositoryManager.class ) - .getPathForLocalArtifact( this, getLocalRepository(), artifact ); + public Path getPathForLocalArtifact(@Nonnull Artifact artifact) { + return getService(LocalRepositoryManager.class).getPathForLocalArtifact(this, getLocalRepository(), artifact); } @Override - public Path getPathForRemoteArtifact( RemoteRepository remote, Artifact artifact ) - { - return getService( LocalRepositoryManager.class ) - .getPathForRemoteArtifact( this, getLocalRepository(), remote, artifact ); + public Path getPathForRemoteArtifact(RemoteRepository remote, Artifact artifact) { + return getService(LocalRepositoryManager.class) + .getPathForRemoteArtifact(this, getLocalRepository(), remote, artifact); } @Override - public Version parseVersion( String version ) - { - return getService( VersionParser.class ) - .parseVersion( version ); + public Version parseVersion(String version) { + return getService(VersionParser.class).parseVersion(version); } @Override - public VersionRange parseVersionRange( String versionRange ) - { - return getService( VersionParser.class ) - .parseVersionRange( versionRange ); + public VersionRange parseVersionRange(String versionRange) { + return getService(VersionParser.class).parseVersionRange(versionRange); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifact.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifact.java index 54b5ff3725..b68bbcd16f 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifact.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,111 +16,99 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import java.util.Objects; - import org.apache.maven.api.Artifact; import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.Version; import org.apache.maven.api.annotations.Nonnull; -import static org.apache.maven.internal.impl.Utils.nonNull; - /** * A wrapper class around a maven resolver artifact. */ -public class DefaultArtifact implements Artifact -{ +public class DefaultArtifact implements Artifact { private final @Nonnull AbstractSession session; private final @Nonnull org.eclipse.aether.artifact.Artifact artifact; private final String id; - public DefaultArtifact( @Nonnull AbstractSession session, @Nonnull org.eclipse.aether.artifact.Artifact artifact ) - { - this.session = nonNull( session, "session can not be null" ); - this.artifact = nonNull( artifact, "artifact can not be null" ); + public DefaultArtifact(@Nonnull AbstractSession session, @Nonnull org.eclipse.aether.artifact.Artifact artifact) { + this.session = nonNull(session, "session can not be null"); + this.artifact = nonNull(artifact, "artifact can not be null"); this.id = getGroupId() - + ':' + getArtifactId() - + ':' + getExtension() - + ( getClassifier().length() > 0 ? ":" + getClassifier() : "" ) - + ':' + getVersion(); + + ':' + + getArtifactId() + + ':' + + getExtension() + + (getClassifier().length() > 0 ? ":" + getClassifier() : "") + + ':' + + getVersion(); } - public org.eclipse.aether.artifact.Artifact getArtifact() - { + public org.eclipse.aether.artifact.Artifact getArtifact() { return artifact; } @Override - public String key() - { + public String key() { return id; } @Nonnull @Override - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } @Nonnull @Override - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } @Nonnull @Override - public Version getVersion() - { - return session.parseVersion( artifact.getVersion() ); + public Version getVersion() { + return session.parseVersion(artifact.getVersion()); } @Nonnull @Override - public String getExtension() - { + public String getExtension() { return artifact.getExtension(); } @Nonnull @Override - public String getClassifier() - { + public String getClassifier() { return artifact.getClassifier(); } @Override - public boolean isSnapshot() - { - return DefaultVersionParser.checkSnapshot( artifact.getVersion() ); + public boolean isSnapshot() { + return DefaultVersionParser.checkSnapshot(artifact.getVersion()); } @Nonnull @Override - public ArtifactCoordinate toCoordinate() - { - return session.createArtifactCoordinate( this ); + public ArtifactCoordinate toCoordinate() { + return session.createArtifactCoordinate(this); } @Override - public boolean equals( Object o ) - { - return o instanceof DefaultArtifact - && Objects.equals( id, ( (DefaultArtifact) o ).id ); + public boolean equals(Object o) { + return o instanceof DefaultArtifact && Objects.equals(id, ((DefaultArtifact) o).id); } @Override - public int hashCode() - { + public int hashCode() { return id.hashCode(); } @Override - public String toString() - { + public String toString() { return artifact.toString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinate.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinate.java index 3386ff56e5..3a5f69a3b1 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinate.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinate.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,96 +16,83 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import java.util.Objects; - import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.VersionRange; import org.apache.maven.api.annotations.Nonnull; -import static org.apache.maven.internal.impl.Utils.nonNull; - /** * A wrapper class around a maven resolver artifact. */ -public class DefaultArtifactCoordinate implements ArtifactCoordinate -{ +public class DefaultArtifactCoordinate implements ArtifactCoordinate { private final @Nonnull AbstractSession session; private final @Nonnull org.eclipse.aether.artifact.Artifact coordinate; - public DefaultArtifactCoordinate( @Nonnull AbstractSession session, - @Nonnull org.eclipse.aether.artifact.Artifact coordinate ) - { - this.session = nonNull( session, "session can not be null" ); - this.coordinate = nonNull( coordinate, "coordinate can not be null" ); + public DefaultArtifactCoordinate( + @Nonnull AbstractSession session, @Nonnull org.eclipse.aether.artifact.Artifact coordinate) { + this.session = nonNull(session, "session can not be null"); + this.coordinate = nonNull(coordinate, "coordinate can not be null"); } - public org.eclipse.aether.artifact.Artifact getCoordinate() - { + public org.eclipse.aether.artifact.Artifact getCoordinate() { return coordinate; } @Nonnull @Override - public String getGroupId() - { + public String getGroupId() { return coordinate.getGroupId(); } @Nonnull @Override - public String getArtifactId() - { + public String getArtifactId() { return coordinate.getArtifactId(); } @Nonnull @Override - public VersionRange getVersion() - { - return session.parseVersionRange( coordinate.getVersion() ); + public VersionRange getVersion() { + return session.parseVersionRange(coordinate.getVersion()); } @Override - public String getExtension() - { + public String getExtension() { return coordinate.getExtension(); } @Nonnull @Override - public String getClassifier() - { + public String getClassifier() { return coordinate.getClassifier(); } @Override - 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; } DefaultArtifactCoordinate that = (DefaultArtifactCoordinate) o; - return Objects.equals( this.getGroupId(), that.getGroupId() ) - && Objects.equals( this.getArtifactId(), that.getArtifactId() ) - && Objects.equals( this.getVersion(), that.getVersion() ) - && Objects.equals( this.getClassifier(), that.getClassifier() ); + return Objects.equals(this.getGroupId(), that.getGroupId()) + && Objects.equals(this.getArtifactId(), that.getArtifactId()) + && Objects.equals(this.getVersion(), that.getVersion()) + && Objects.equals(this.getClassifier(), that.getClassifier()); } @Override - public int hashCode() - { - return Objects.hash( getGroupId(), getArtifactId(), getVersion(), getClassifier() ); + public int hashCode() { + return Objects.hash(getGroupId(), getArtifactId(), getVersion(), getClassifier()); } @Override - public String toString() - { + public String toString() { return coordinate.toString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinateFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinateFactory.java index 3412c07e77..b2ba486ef5 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinateFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinateFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,10 +16,13 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.ArtifactCoordinateFactory; @@ -29,36 +30,32 @@ import org.apache.maven.api.services.ArtifactCoordinateFactoryRequest; import org.apache.maven.shared.utils.StringUtils; import org.eclipse.aether.artifact.ArtifactType; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultArtifactCoordinateFactory implements ArtifactCoordinateFactory -{ +public class DefaultArtifactCoordinateFactory implements ArtifactCoordinateFactory { @Override - public ArtifactCoordinate create( @Nonnull ArtifactCoordinateFactoryRequest request ) - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); + public ArtifactCoordinate create(@Nonnull ArtifactCoordinateFactoryRequest request) { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); ArtifactType type = null; - if ( request.getType() != null ) - { - type = session.getSession().getArtifactTypeRegistry().get( request.getType() ); + if (request.getType() != null) { + type = session.getSession().getArtifactTypeRegistry().get(request.getType()); } - String classifier = StringUtils.isNotEmpty( request.getClassifier() ) - ? request.getClassifier() : type != null ? type.getClassifier() : ""; - String extension = StringUtils.isNotEmpty( request.getExtension() ) - ? request.getExtension() : type != null ? type.getExtension() : ""; + String classifier = StringUtils.isNotEmpty(request.getClassifier()) + ? request.getClassifier() + : type != null ? type.getClassifier() : ""; + String extension = StringUtils.isNotEmpty(request.getExtension()) + ? request.getExtension() + : type != null ? type.getExtension() : ""; return new DefaultArtifactCoordinate( session, new org.eclipse.aether.artifact.DefaultArtifact( - request.getGroupId(), - request.getArtifactId(), - classifier, - extension, - request.getVersion(), - type ) ); + request.getGroupId(), + request.getArtifactId(), + classifier, + extension, + request.getVersion(), + type)); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactDeployer.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactDeployer.java index c117b84d55..ee2379b37d 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactDeployer.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactDeployer.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,16 +16,18 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import org.apache.maven.api.Artifact; -import org.apache.maven.api.RemoteRepository; -import org.apache.maven.api.annotations.Nonnull; +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; + +import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - -import java.util.Collection; - +import org.apache.maven.api.Artifact; +import org.apache.maven.api.RemoteRepository; +import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.ArtifactDeployer; import org.apache.maven.api.services.ArtifactDeployerException; import org.apache.maven.api.services.ArtifactDeployerRequest; @@ -36,43 +36,34 @@ import org.eclipse.aether.deployment.DeployRequest; import org.eclipse.aether.deployment.DeployResult; import org.eclipse.aether.deployment.DeploymentException; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - /** * Implementation of {@link ArtifactDeployer} service. */ @Named @Singleton -public class DefaultArtifactDeployer implements ArtifactDeployer -{ +public class DefaultArtifactDeployer implements ArtifactDeployer { private final @Nonnull RepositorySystem repositorySystem; @Inject - DefaultArtifactDeployer( @Nonnull RepositorySystem repositorySystem ) - { - this.repositorySystem = nonNull( repositorySystem, "repositorySystem can not be null" ); + DefaultArtifactDeployer(@Nonnull RepositorySystem repositorySystem) { + this.repositorySystem = nonNull(repositorySystem, "repositorySystem can not be null"); } @Override - public void deploy( @Nonnull ArtifactDeployerRequest request ) - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); - Collection artifacts = nonNull( request.getArtifacts(), "request.artifacts can not be null" ); - RemoteRepository repository = nonNull( request.getRepository(), "request.repository can not be null" ); - try - { + public void deploy(@Nonnull ArtifactDeployerRequest request) { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); + Collection artifacts = nonNull(request.getArtifacts(), "request.artifacts can not be null"); + RemoteRepository repository = nonNull(request.getRepository(), "request.repository can not be null"); + try { DeployRequest deployRequest = new DeployRequest() - .setRepository( session.toRepository( repository ) ) - .setArtifacts( session.toArtifacts( artifacts ) ); + .setRepository(session.toRepository(repository)) + .setArtifacts(session.toArtifacts(artifacts)); - DeployResult result = repositorySystem.deploy( session.getSession(), deployRequest ); - } - catch ( DeploymentException e ) - { - throw new ArtifactDeployerException( "Unable to deploy artifacts", e ); + DeployResult result = repositorySystem.deploy(session.getSession(), deployRequest); + } catch (DeploymentException e) { + throw new ArtifactDeployerException("Unable to deploy artifacts", e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactFactory.java index 25d98185d3..1c38e21c73 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,10 +16,13 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.Artifact; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.ArtifactFactory; @@ -29,37 +30,32 @@ import org.apache.maven.api.services.ArtifactFactoryRequest; import org.apache.maven.shared.utils.StringUtils; import org.eclipse.aether.artifact.ArtifactType; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultArtifactFactory implements ArtifactFactory -{ +public class DefaultArtifactFactory implements ArtifactFactory { @Override - public Artifact create( @Nonnull ArtifactFactoryRequest request ) - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); + public Artifact create(@Nonnull ArtifactFactoryRequest request) { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); ArtifactType type = null; - if ( request.getType() != null ) - { - type = session.getSession().getArtifactTypeRegistry().get( request.getType() ); + if (request.getType() != null) { + type = session.getSession().getArtifactTypeRegistry().get(request.getType()); } - String classifier = StringUtils.isNotEmpty( request.getClassifier() ) - ? request.getClassifier() - : type != null ? type.getClassifier() : null; - String extension = StringUtils.isNotEmpty( request.getExtension() ) - ? request.getExtension() : type != null ? type.getExtension() : null; + String classifier = StringUtils.isNotEmpty(request.getClassifier()) + ? request.getClassifier() + : type != null ? type.getClassifier() : null; + String extension = StringUtils.isNotEmpty(request.getExtension()) + ? request.getExtension() + : type != null ? type.getExtension() : null; return new DefaultArtifact( session, new org.eclipse.aether.artifact.DefaultArtifact( - request.getGroupId(), - request.getArtifactId(), - classifier, - extension, - request.getVersion(), - type ) ); + request.getGroupId(), + request.getArtifactId(), + classifier, + extension, + request.getVersion(), + type)); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactInstaller.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactInstaller.java index abe910a2e4..77e5152b54 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactInstaller.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactInstaller.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,11 +16,14 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.ArtifactInstaller; import org.apache.maven.api.services.ArtifactInstallerException; @@ -32,38 +33,29 @@ import org.eclipse.aether.installation.InstallRequest; import org.eclipse.aether.installation.InstallResult; import org.eclipse.aether.installation.InstallationException; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultArtifactInstaller implements ArtifactInstaller -{ +public class DefaultArtifactInstaller implements ArtifactInstaller { private final RepositorySystem repositorySystem; @Inject - DefaultArtifactInstaller( @Nonnull RepositorySystem repositorySystem ) - { - this.repositorySystem = nonNull( repositorySystem ); + DefaultArtifactInstaller(@Nonnull RepositorySystem repositorySystem) { + this.repositorySystem = nonNull(repositorySystem); } @Override - public void install( ArtifactInstallerRequest request ) throws ArtifactInstallerException, IllegalArgumentException - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); - try - { - InstallRequest installRequest = new InstallRequest() - .setArtifacts( session.toArtifacts( request.getArtifacts() ) ); + public void install(ArtifactInstallerRequest request) throws ArtifactInstallerException, IllegalArgumentException { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); + try { + InstallRequest installRequest = + new InstallRequest().setArtifacts(session.toArtifacts(request.getArtifacts())); - InstallResult result = repositorySystem.install( session.getSession(), installRequest ); - } - catch ( InstallationException e ) - { - throw new ArtifactInstallerException( e.getMessage(), e ); + InstallResult result = repositorySystem.install(session.getSession(), installRequest); + } catch (InstallationException e) { + throw new ArtifactInstallerException(e.getMessage(), e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactManager.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactManager.java index 829c71474b..d9208455d9 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactManager.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; +package org.apache.maven.internal.impl; import java.io.File; import java.nio.file.Path; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; - +import javax.inject.Inject; +import javax.inject.Named; import org.apache.maven.SessionScoped; import org.apache.maven.api.Artifact; import org.apache.maven.api.annotations.Nonnull; @@ -36,84 +33,69 @@ import org.apache.maven.project.MavenProject; @Named @SessionScoped -public class DefaultArtifactManager implements ArtifactManager -{ +public class DefaultArtifactManager implements ArtifactManager { @Nonnull private final DefaultSession session; + private final Map paths = new ConcurrentHashMap<>(); @Inject - public DefaultArtifactManager( @Nonnull DefaultSession session ) - { + public DefaultArtifactManager(@Nonnull DefaultSession session) { this.session = session; } @Nonnull @Override - public Optional getPath( @Nonnull Artifact artifact ) - { - String id = id( artifact ); - if ( session.getMavenSession().getAllProjects() != null ) - { - for ( MavenProject project : session.getMavenSession().getAllProjects() ) - { - if ( id.equals( id( project.getArtifact() ) ) && project.getArtifact().getFile() != null ) - { - return Optional.of( project.getArtifact().getFile().toPath() ); + public Optional getPath(@Nonnull Artifact artifact) { + String id = id(artifact); + if (session.getMavenSession().getAllProjects() != null) { + for (MavenProject project : session.getMavenSession().getAllProjects()) { + if (id.equals(id(project.getArtifact())) + && project.getArtifact().getFile() != null) { + return Optional.of(project.getArtifact().getFile().toPath()); } } } - Path path = paths.get( id ); - if ( path == null && artifact instanceof DefaultArtifact ) - { - File file = ( (DefaultArtifact) artifact ).getArtifact().getFile(); - if ( file != null ) - { + Path path = paths.get(id); + if (path == null && artifact instanceof DefaultArtifact) { + File file = ((DefaultArtifact) artifact).getArtifact().getFile(); + if (file != null) { path = file.toPath(); } } - return Optional.ofNullable( path ); + return Optional.ofNullable(path); } @Override - public void setPath( @Nonnull Artifact artifact, Path path ) - { - String id = id( artifact ); - if ( session.getMavenSession().getAllProjects() != null ) - { - for ( MavenProject project : session.getMavenSession().getAllProjects() ) - { - if ( id.equals( id( project.getArtifact() ) ) ) - { - project.getArtifact().setFile( path != null ? path.toFile() : null ); + public void setPath(@Nonnull Artifact artifact, Path path) { + String id = id(artifact); + if (session.getMavenSession().getAllProjects() != null) { + for (MavenProject project : session.getMavenSession().getAllProjects()) { + if (id.equals(id(project.getArtifact()))) { + project.getArtifact().setFile(path != null ? path.toFile() : null); break; } } } - if ( path == null ) - { - paths.remove( id ); - } - else - { - paths.put( id, path ); + if (path == null) { + paths.remove(id); + } else { + paths.put(id, path); } } - private String id( org.apache.maven.artifact.Artifact artifact ) - { + private String id(org.apache.maven.artifact.Artifact artifact) { return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getType() - + ( artifact.getClassifier() == null || artifact.getClassifier().isEmpty() - ? "" : ":" + artifact.getClassifier() ) + + (artifact.getClassifier() == null || artifact.getClassifier().isEmpty() + ? "" + : ":" + artifact.getClassifier()) + ":" + artifact.getVersion(); } - private String id( Artifact artifact ) - { + private String id(Artifact artifact) { return artifact.key(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactResolver.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactResolver.java index ac1a163a56..051794bb80 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactResolver.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,19 +16,21 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import org.apache.maven.api.annotations.Nonnull; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.Artifact; +import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.ArtifactManager; import org.apache.maven.api.services.ArtifactResolver; import org.apache.maven.api.services.ArtifactResolverException; @@ -42,56 +42,43 @@ import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultArtifactResolver implements ArtifactResolver -{ +public class DefaultArtifactResolver implements ArtifactResolver { private final RepositorySystem repositorySystem; @Inject - DefaultArtifactResolver( @Nonnull RepositorySystem repositorySystem ) - { - this.repositorySystem = nonNull( repositorySystem, "repositorySystem can not be null" ); + DefaultArtifactResolver(@Nonnull RepositorySystem repositorySystem) { + this.repositorySystem = nonNull(repositorySystem, "repositorySystem can not be null"); } @Override - public ArtifactResolverResult resolve( ArtifactResolverRequest request ) - throws ArtifactResolverException, IllegalArgumentException - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); - try - { - List repositories = session.toRepositories( session.getRemoteRepositories() ); + public ArtifactResolverResult resolve(ArtifactResolverRequest request) + throws ArtifactResolverException, IllegalArgumentException { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); + try { + List repositories = session.toRepositories(session.getRemoteRepositories()); List requests = request.getCoordinates().stream() - .map( coord -> new ArtifactRequest( session.toArtifact( coord ), repositories, null ) ) - .collect( Collectors.toList() ); - List results = repositorySystem.resolveArtifacts( session.getSession(), requests ); + .map(coord -> new ArtifactRequest(session.toArtifact(coord), repositories, null)) + .collect(Collectors.toList()); + List results = repositorySystem.resolveArtifacts(session.getSession(), requests); Map paths = new HashMap<>(); - for ( ArtifactResult result : results ) - { - Artifact artifact = session.getArtifact( result.getArtifact() ); + for (ArtifactResult result : results) { + Artifact artifact = session.getArtifact(result.getArtifact()); Path path = result.getArtifact().getFile().toPath(); - session.getService( ArtifactManager.class ).setPath( artifact, path ); - paths.put( artifact, path ); + session.getService(ArtifactManager.class).setPath(artifact, path); + paths.put(artifact, path); } - return new ArtifactResolverResult() - { + return new ArtifactResolverResult() { @Override - public Map getArtifacts() - { + public Map getArtifacts() { return paths; } }; - } - catch ( ArtifactResolutionException e ) - { - throw new ArtifactResolverException( "Unable to resolve artifact", e ); + } catch (ArtifactResolutionException e) { + throw new ArtifactResolverException("Unable to resolve artifact", e); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependency.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependency.java index 78b6eaddd8..a4ad39299a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependency.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependency.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,9 +16,11 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import java.util.Objects; - import org.apache.maven.api.Dependency; import org.apache.maven.api.DependencyCoordinate; import org.apache.maven.api.Scope; @@ -31,119 +31,103 @@ import org.apache.maven.api.annotations.Nullable; import org.apache.maven.api.services.TypeRegistry; import org.eclipse.aether.artifact.ArtifactProperties; -import static org.apache.maven.internal.impl.Utils.nonNull; - -public class DefaultDependency implements Dependency -{ +public class DefaultDependency implements Dependency { private final AbstractSession session; private final org.eclipse.aether.graph.Dependency dependency; private final String key; - public DefaultDependency( @Nonnull AbstractSession session, - @Nonnull org.eclipse.aether.graph.Dependency dependency ) - { - this.session = nonNull( session, "session" ); - this.dependency = nonNull( dependency, "dependency" ); + public DefaultDependency( + @Nonnull AbstractSession session, @Nonnull org.eclipse.aether.graph.Dependency dependency) { + this.session = nonNull(session, "session"); + this.dependency = nonNull(dependency, "dependency"); this.key = getGroupId() - + ':' + getArtifactId() - + ':' + getExtension() - + ( getClassifier().length() > 0 ? ":" + getClassifier() : "" ) - + ':' + getVersion(); + + ':' + + getArtifactId() + + ':' + + getExtension() + + (getClassifier().length() > 0 ? ":" + getClassifier() : "") + + ':' + + getVersion(); } @Override - public String key() - { + public String key() { return key; } @Nonnull - public org.eclipse.aether.graph.Dependency getDependency() - { + public org.eclipse.aether.graph.Dependency getDependency() { return dependency; } @Override - public String getGroupId() - { + public String getGroupId() { return dependency.getArtifact().getGroupId(); } @Override - public String getArtifactId() - { + public String getArtifactId() { return dependency.getArtifact().getArtifactId(); } @Override - public String getClassifier() - { + public String getClassifier() { return dependency.getArtifact().getClassifier(); } @Override - public Version getVersion() - { - return session.parseVersion( dependency.getArtifact().getVersion() ); + public Version getVersion() { + return session.parseVersion(dependency.getArtifact().getVersion()); } @Override - public String getExtension() - { + public String getExtension() { return dependency.getArtifact().getExtension(); } @Override - public Type getType() - { - String type = dependency.getArtifact().getProperty( ArtifactProperties.TYPE, - dependency.getArtifact().getExtension() ); - return session.getService( TypeRegistry.class ).getType( type ); + public Type getType() { + String type = dependency + .getArtifact() + .getProperty(ArtifactProperties.TYPE, dependency.getArtifact().getExtension()); + return session.getService(TypeRegistry.class).getType(type); } @Override - public boolean isSnapshot() - { - return DefaultVersionParser.checkSnapshot( dependency.getArtifact().getVersion() ); + public boolean isSnapshot() { + return DefaultVersionParser.checkSnapshot(dependency.getArtifact().getVersion()); } @Nonnull @Override - public Scope getScope() - { - return Scope.get( dependency.getScope() ); + public Scope getScope() { + return Scope.get(dependency.getScope()); } @Nullable @Override - public boolean isOptional() - { + public boolean isOptional() { return dependency.isOptional(); } @Nonnull @Override - public DependencyCoordinate toCoordinate() - { - return session.createDependencyCoordinate( this ); + public DependencyCoordinate toCoordinate() { + return session.createDependencyCoordinate(this); } @Override - public boolean equals( Object o ) - { - return o instanceof DefaultDependency - && Objects.equals( key, ( (DefaultDependency) o ).key ); + public boolean equals(Object o) { + return o instanceof DefaultDependency && Objects.equals(key, ((DefaultDependency) o).key); } @Override - public int hashCode() - { + public int hashCode() { return key.hashCode(); } @Override - public String toString() - { + public String toString() { return dependency.toString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCollector.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCollector.java index 8cf4b181a4..289593fcce 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCollector.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCollector.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,15 +16,17 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import org.apache.maven.api.annotations.Nonnull; +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; + +import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - -import java.util.List; - import org.apache.maven.api.Node; +import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.DependencyCollector; import org.apache.maven.api.services.DependencyCollectorException; import org.apache.maven.api.services.DependencyCollectorRequest; @@ -42,71 +42,57 @@ import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.util.graph.manager.DependencyManagerUtils; import org.eclipse.aether.util.graph.transformer.ConflictResolver; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultDependencyCollector implements DependencyCollector -{ +public class DefaultDependencyCollector implements DependencyCollector { private final RepositorySystem repositorySystem; @Inject - DefaultDependencyCollector( @Nonnull RepositorySystem repositorySystem ) - { + DefaultDependencyCollector(@Nonnull RepositorySystem repositorySystem) { this.repositorySystem = repositorySystem; } @Nonnull @Override - public DependencyCollectorResult collect( @Nonnull DependencyCollectorRequest request ) - throws DependencyCollectorException, IllegalArgumentException - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); + public DependencyCollectorResult collect(@Nonnull DependencyCollectorRequest request) + throws DependencyCollectorException, IllegalArgumentException { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); - Artifact rootArtifact = request.getRootArtifact().map( session::toArtifact ).orElse( null ); - Dependency root = request.getRoot().map( session::toDependency ).orElse( null ); + Artifact rootArtifact = + request.getRootArtifact().map(session::toArtifact).orElse(null); + Dependency root = request.getRoot().map(session::toDependency).orElse(null); CollectRequest collectRequest = new CollectRequest() - .setRootArtifact( rootArtifact ) - .setRoot( root ) - .setDependencies( session.toDependencies( request.getDependencies() ) ) - .setManagedDependencies( session.toDependencies( request.getManagedDependencies() ) ) - .setRepositories( session.toRepositories( session.getRemoteRepositories() ) ); + .setRootArtifact(rootArtifact) + .setRoot(root) + .setDependencies(session.toDependencies(request.getDependencies())) + .setManagedDependencies(session.toDependencies(request.getManagedDependencies())) + .setRepositories(session.toRepositories(session.getRemoteRepositories())); RepositorySystemSession systemSession = session.getSession(); - if ( request.getVerbose() ) - { - systemSession = new DefaultRepositorySystemSession( systemSession ) - .setConfigProperty( ConflictResolver.CONFIG_PROP_VERBOSE, true ) - .setConfigProperty( DependencyManagerUtils.CONFIG_PROP_VERBOSE, true ); + if (request.getVerbose()) { + systemSession = new DefaultRepositorySystemSession(systemSession) + .setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true) + .setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); } - try - { - final CollectResult - result = repositorySystem.collectDependencies( systemSession, collectRequest ); - return new DependencyCollectorResult() - { + try { + final CollectResult result = repositorySystem.collectDependencies(systemSession, collectRequest); + return new DependencyCollectorResult() { @Override - public List getExceptions() - { + public List getExceptions() { return result.getExceptions(); } @Override - public Node getRoot() - { - return session.getNode( result.getRoot(), request.getVerbose() ); + public Node getRoot() { + return session.getNode(result.getRoot(), request.getVerbose()); } }; - } - catch ( DependencyCollectionException e ) - { - throw new DependencyCollectorException( "Unable to collect dependencies", e ); + } catch (DependencyCollectionException e) { + throw new DependencyCollectorException("Unable to collect dependencies", e); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinate.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinate.java index f6b7862f0a..2b9d2af005 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinate.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinate.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,9 +16,11 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import java.util.Collection; - import org.apache.maven.api.DependencyCoordinate; import org.apache.maven.api.Exclusion; import org.apache.maven.api.Scope; @@ -31,100 +31,83 @@ import org.apache.maven.api.annotations.Nullable; import org.apache.maven.api.services.TypeRegistry; import org.eclipse.aether.artifact.ArtifactProperties; -import static org.apache.maven.internal.impl.Utils.nonNull; - -public class DefaultDependencyCoordinate implements DependencyCoordinate -{ +public class DefaultDependencyCoordinate implements DependencyCoordinate { private final AbstractSession session; private final org.eclipse.aether.graph.Dependency dependency; - public DefaultDependencyCoordinate( @Nonnull AbstractSession session, - @Nonnull org.eclipse.aether.graph.Dependency dependency ) - { - this.session = nonNull( session, "session" ); - this.dependency = nonNull( dependency, "dependency" ); + public DefaultDependencyCoordinate( + @Nonnull AbstractSession session, @Nonnull org.eclipse.aether.graph.Dependency dependency) { + this.session = nonNull(session, "session"); + this.dependency = nonNull(dependency, "dependency"); } @Nonnull - public org.eclipse.aether.graph.Dependency getDependency() - { + public org.eclipse.aether.graph.Dependency getDependency() { return dependency; } @Override - public String getGroupId() - { + public String getGroupId() { return dependency.getArtifact().getGroupId(); } @Override - public String getArtifactId() - { + public String getArtifactId() { return dependency.getArtifact().getArtifactId(); } @Override - public String getClassifier() - { + public String getClassifier() { return dependency.getArtifact().getClassifier(); } @Override - public VersionRange getVersion() - { - return session.parseVersionRange( dependency.getArtifact().getVersion() ); + public VersionRange getVersion() { + return session.parseVersionRange(dependency.getArtifact().getVersion()); } @Override - public String getExtension() - { + public String getExtension() { return dependency.getArtifact().getExtension(); } @Override - public Type getType() - { - String type = dependency.getArtifact().getProperty( ArtifactProperties.TYPE, - dependency.getArtifact().getExtension() ); - return session.getService( TypeRegistry.class ).getType( type ); + public Type getType() { + String type = dependency + .getArtifact() + .getProperty(ArtifactProperties.TYPE, dependency.getArtifact().getExtension()); + return session.getService(TypeRegistry.class).getType(type); } @Nonnull @Override - public Scope getScope() - { - return Scope.get( dependency.getScope() ); + public Scope getScope() { + return Scope.get(dependency.getScope()); } @Nullable @Override - public Boolean getOptional() - { + public Boolean getOptional() { return dependency.getOptional(); } @Nonnull @Override - public Collection getExclusions() - { - return new MappedCollection<>( dependency.getExclusions(), this::toExclusion ); + public Collection getExclusions() { + return new MappedCollection<>(dependency.getExclusions(), this::toExclusion); } - private Exclusion toExclusion( org.eclipse.aether.graph.Exclusion exclusion ) - { - return new Exclusion() - { + private Exclusion toExclusion(org.eclipse.aether.graph.Exclusion exclusion) { + return new Exclusion() { @Nullable @Override - public String getGroupId() - { + public String getGroupId() { return exclusion.getGroupId(); } @Nullable @Override - public String getArtifactId() - { + public String getArtifactId() { return exclusion.getArtifactId(); } }; diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinateFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinateFactory.java index 06e0da3144..7438719050 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinateFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinateFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,12 +16,14 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import javax.inject.Named; -import javax.inject.Singleton; +import static org.apache.maven.internal.impl.Utils.cast; +import static org.apache.maven.internal.impl.Utils.nonNull; import java.util.stream.Collectors; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.DependencyCoordinate; import org.apache.maven.api.Exclusion; import org.apache.maven.api.annotations.Nonnull; @@ -31,26 +31,20 @@ import org.apache.maven.api.services.DependencyCoordinateFactory; import org.apache.maven.api.services.DependencyCoordinateFactoryRequest; import org.eclipse.aether.artifact.ArtifactType; -import static org.apache.maven.internal.impl.Utils.cast; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultDependencyCoordinateFactory implements DependencyCoordinateFactory -{ +public class DefaultDependencyCoordinateFactory implements DependencyCoordinateFactory { @Nonnull @Override - public DependencyCoordinate create( @Nonnull DependencyCoordinateFactoryRequest request ) - { - nonNull( request, "request can not be null" ); - DefaultSession session = cast( DefaultSession.class, request.getSession(), - "request.session should be a " + DefaultSession.class ); + public DependencyCoordinate create(@Nonnull DependencyCoordinateFactoryRequest request) { + nonNull(request, "request can not be null"); + DefaultSession session = + cast(DefaultSession.class, request.getSession(), "request.session should be a " + DefaultSession.class); ArtifactType type = null; - if ( request.getType() != null ) - { - type = session.getSession().getArtifactTypeRegistry().get( request.getType() ); + if (request.getType() != null) { + type = session.getSession().getArtifactTypeRegistry().get(request.getType()); } return new DefaultDependencyCoordinate( session, @@ -61,17 +55,13 @@ public class DefaultDependencyCoordinateFactory implements DependencyCoordinateF request.getClassifier(), request.getExtension(), request.getVersion(), - type - ), + type), request.getScope(), request.isOptional(), - request.getExclusions().stream().map( this::toExclusion ).collect( Collectors.toList() ) ) ); + request.getExclusions().stream().map(this::toExclusion).collect(Collectors.toList()))); } - private org.eclipse.aether.graph.Exclusion toExclusion( Exclusion exclusion ) - { - return new org.eclipse.aether.graph.Exclusion( - exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*" ); + private org.eclipse.aether.graph.Exclusion toExclusion(Exclusion exclusion) { + return new org.eclipse.aether.graph.Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*"); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultEvent.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultEvent.java index 12f047fec6..bd1546e575 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultEvent.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.Optional; - import org.apache.maven.api.Event; import org.apache.maven.api.EventType; import org.apache.maven.api.MojoExecution; @@ -28,44 +26,37 @@ import org.apache.maven.api.Project; import org.apache.maven.api.Session; import org.apache.maven.execution.ExecutionEvent; -public class DefaultEvent implements Event -{ +public class DefaultEvent implements Event { private final AbstractSession session; private final ExecutionEvent delegate; - public DefaultEvent( AbstractSession session, ExecutionEvent delegate ) - { + public DefaultEvent(AbstractSession session, ExecutionEvent delegate) { this.session = session; this.delegate = delegate; } @Override - public EventType getType() - { - return EventType.valueOf( delegate.getType().name() ); + public EventType getType() { + return EventType.valueOf(delegate.getType().name()); } @Override - public Session getSession() - { + public Session getSession() { return session; } @Override - public Optional getProject() - { - return Optional.ofNullable( delegate.getProject() ).map( session::getProject ); + public Optional getProject() { + return Optional.ofNullable(delegate.getProject()).map(session::getProject); } @Override - public Optional getMojoExecution() - { - return Optional.ofNullable( delegate.getMojoExecution() ).map( DefaultMojoExecution::new ); + public Optional getMojoExecution() { + return Optional.ofNullable(delegate.getMojoExecution()).map(DefaultMojoExecution::new); } @Override - public Optional getException() - { + public Optional getException() { return Optional.empty(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepository.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepository.java index 618333e1c8..9d0eecfc69 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepository.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,52 +16,44 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.api.annotations.Nonnull; -import javax.inject.Inject; - -import java.nio.file.Path; - -import org.apache.maven.api.LocalRepository; +package org.apache.maven.internal.impl; import static org.apache.maven.internal.impl.Utils.nonNull; -public class DefaultLocalRepository implements LocalRepository -{ +import java.nio.file.Path; +import javax.inject.Inject; +import org.apache.maven.api.LocalRepository; +import org.apache.maven.api.annotations.Nonnull; + +public class DefaultLocalRepository implements LocalRepository { private final @Nonnull org.eclipse.aether.repository.LocalRepository repository; @Inject - public DefaultLocalRepository( @Nonnull org.eclipse.aether.repository.LocalRepository repository ) - { - this.repository = nonNull( repository, "repository can not be null" ); + public DefaultLocalRepository(@Nonnull org.eclipse.aether.repository.LocalRepository repository) { + this.repository = nonNull(repository, "repository can not be null"); } @Nonnull - public org.eclipse.aether.repository.LocalRepository getRepository() - { + public org.eclipse.aether.repository.LocalRepository getRepository() { return repository; } @Nonnull @Override - public String getId() - { + public String getId() { return repository.getId(); } @Nonnull @Override - public String getType() - { + public String getType() { return repository.getContentType(); } @Nonnull @Override - public Path getPath() - { + public Path getPath() { return repository.getBasedir().toPath(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepositoryManager.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepositoryManager.java index 95a7883919..de04cbe585 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepositoryManager.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,12 +16,11 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.nio.file.Path; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.Artifact; import org.apache.maven.api.LocalRepository; import org.apache.maven.api.RemoteRepository; @@ -32,36 +29,30 @@ import org.apache.maven.api.services.LocalRepositoryManager; @Named @Singleton -public class DefaultLocalRepositoryManager implements LocalRepositoryManager -{ +public class DefaultLocalRepositoryManager implements LocalRepositoryManager { @Override - public Path getPathForLocalArtifact( Session session, LocalRepository local, Artifact artifact ) - { + public Path getPathForLocalArtifact(Session session, LocalRepository local, Artifact artifact) { DefaultSession s = (DefaultSession) session; - String path = getManager( s, local ).getPathForLocalArtifact( s.toArtifact( artifact ) ); - return local.getPath().resolve( path ); + String path = getManager(s, local).getPathForLocalArtifact(s.toArtifact(artifact)); + return local.getPath().resolve(path); } @Override - public Path getPathForRemoteArtifact( Session session, LocalRepository local, - RemoteRepository remote, Artifact artifact ) - { + public Path getPathForRemoteArtifact( + Session session, LocalRepository local, RemoteRepository remote, Artifact artifact) { DefaultSession s = (DefaultSession) session; - String path = getManager( s, local ).getPathForRemoteArtifact( - s.toArtifact( artifact ), s.toRepository( remote ), null ); - return local.getPath().resolve( path ); + String path = + getManager(s, local).getPathForRemoteArtifact(s.toArtifact(artifact), s.toRepository(remote), null); + return local.getPath().resolve(path); } private org.eclipse.aether.repository.LocalRepositoryManager getManager( - DefaultSession session, LocalRepository local ) - { - org.eclipse.aether.repository.LocalRepository repository = session.toRepository( local ); - if ( "enhanced".equals( repository.getContentType() ) ) - { - repository = new org.eclipse.aether.repository.LocalRepository( repository.getBasedir(), "" ); + DefaultSession session, LocalRepository local) { + org.eclipse.aether.repository.LocalRepository repository = session.toRepository(local); + if ("enhanced".equals(repository.getContentType())) { + repository = new org.eclipse.aether.repository.LocalRepository(repository.getBasedir(), ""); } - return session.getRepositorySystem().newLocalRepositoryManager( session.getSession(), repository ); + return session.getRepositorySystem().newLocalRepositoryManager(session.getSession(), repository); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java index 0f04460919..1807716416 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,193 +16,157 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import java.util.function.Supplier; - -import org.apache.maven.api.plugin.Log; -import org.slf4j.Logger; +package org.apache.maven.internal.impl; import static java.util.Objects.requireNonNull; -public class DefaultLog implements Log -{ +import java.util.function.Supplier; +import org.apache.maven.api.plugin.Log; +import org.slf4j.Logger; + +public class DefaultLog implements Log { private final Logger logger; - public DefaultLog( Logger logger ) - { - this.logger = requireNonNull( logger ); + public DefaultLog(Logger logger) { + this.logger = requireNonNull(logger); } - public void debug( CharSequence content ) - { - logger.debug( toString( content ) ); + public void debug(CharSequence content) { + logger.debug(toString(content)); } @Override - public void debug( CharSequence content, Throwable error ) - { - logger.debug( toString( content ), error ); + public void debug(CharSequence content, Throwable error) { + logger.debug(toString(content), error); } @Override - public void debug( Throwable error ) - { - logger.debug( "", error ); + public void debug(Throwable error) { + logger.debug("", error); } @Override - public void debug( Supplier content ) - { - if ( isDebugEnabled() ) - { - logger.debug( content.get() ); + public void debug(Supplier content) { + if (isDebugEnabled()) { + logger.debug(content.get()); } } @Override - public void debug( Supplier content, Throwable error ) - { - if ( isDebugEnabled() ) - { - logger.debug( content.get(), error ); + public void debug(Supplier content, Throwable error) { + if (isDebugEnabled()) { + logger.debug(content.get(), error); } } @Override - public void info( CharSequence content ) - { - logger.info( toString( content ) ); + public void info(CharSequence content) { + logger.info(toString(content)); } @Override - public void info( CharSequence content, Throwable error ) - { - logger.info( toString( content ), error ); + public void info(CharSequence content, Throwable error) { + logger.info(toString(content), error); } @Override - public void info( Throwable error ) - { - logger.info( "", error ); + public void info(Throwable error) { + logger.info("", error); } @Override - public void info( Supplier content ) - { - if ( isInfoEnabled() ) - { - logger.info( content.get() ); + public void info(Supplier content) { + if (isInfoEnabled()) { + logger.info(content.get()); } } @Override - public void info( Supplier content, Throwable error ) - { - if ( isInfoEnabled() ) - { - logger.info( content.get(), error ); + public void info(Supplier content, Throwable error) { + if (isInfoEnabled()) { + logger.info(content.get(), error); } } @Override - public void warn( CharSequence content ) - { - logger.warn( toString( content ) ); + public void warn(CharSequence content) { + logger.warn(toString(content)); } @Override - public void warn( CharSequence content, Throwable error ) - { - logger.warn( toString( content ), error ); + public void warn(CharSequence content, Throwable error) { + logger.warn(toString(content), error); } @Override - public void warn( Throwable error ) - { - logger.warn( "", error ); + public void warn(Throwable error) { + logger.warn("", error); } @Override - public void warn( Supplier content ) - { - if ( isWarnEnabled() ) - { - logger.warn( content.get() ); + public void warn(Supplier content) { + if (isWarnEnabled()) { + logger.warn(content.get()); } } @Override - public void warn( Supplier content, Throwable error ) - { - if ( isWarnEnabled() ) - { - logger.info( content.get(), error ); + public void warn(Supplier content, Throwable error) { + if (isWarnEnabled()) { + logger.info(content.get(), error); } } @Override - public void error( CharSequence content ) - { - logger.error( toString( content ) ); + public void error(CharSequence content) { + logger.error(toString(content)); } @Override - public void error( CharSequence content, Throwable error ) - { - logger.error( toString( content ), error ); + public void error(CharSequence content, Throwable error) { + logger.error(toString(content), error); } @Override - public void error( Throwable error ) - { - logger.error( "", error ); + public void error(Throwable error) { + logger.error("", error); } @Override - public void error( Supplier content ) - { - if ( isErrorEnabled() ) - { - logger.error( content.get() ); + public void error(Supplier content) { + if (isErrorEnabled()) { + logger.error(content.get()); } } @Override - public void error( Supplier content, Throwable error ) - { - if ( isErrorEnabled() ) - { - logger.error( content.get(), error ); + public void error(Supplier content, Throwable error) { + if (isErrorEnabled()) { + logger.error(content.get(), error); } } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return logger.isErrorEnabled(); } - private String toString( CharSequence content ) - { + private String toString(CharSequence content) { return content != null ? content.toString() : ""; } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLookup.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLookup.java index 1273066f54..c91ac8a54d 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLookup.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLookup.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.util.List; import java.util.Map; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.services.Lookup; import org.apache.maven.api.services.LookupException; import org.codehaus.plexus.PlexusContainer; @@ -33,66 +30,48 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti @Named @Singleton -public class DefaultLookup implements Lookup -{ +public class DefaultLookup implements Lookup { private final PlexusContainer container; @Inject - public DefaultLookup( PlexusContainer container ) - { + public DefaultLookup(PlexusContainer container) { this.container = container; } @Override - public T lookup( Class type ) - { - try - { - return container.lookup( type ); - } - catch ( ComponentLookupException e ) - { - throw new LookupException( e ); + public T lookup(Class type) { + try { + return container.lookup(type); + } catch (ComponentLookupException e) { + throw new LookupException(e); } } @Override - public T lookup( Class type, String name ) - { - try - { - return container.lookup( type, name ); - } - catch ( ComponentLookupException e ) - { - throw new LookupException( e ); + public T lookup(Class type, String name) { + try { + return container.lookup(type, name); + } catch (ComponentLookupException e) { + throw new LookupException(e); } } @Override - public List lookupList( Class type ) - { - try - { - return container.lookupList( type ); - } - catch ( ComponentLookupException e ) - { - throw new LookupException( e ); + public List lookupList(Class type) { + try { + return container.lookupList(type); + } catch (ComponentLookupException e) { + throw new LookupException(e); } } @Override - public Map lookupMap( Class type ) - { - try - { - return container.lookupMap( type ); - } - catch ( ComponentLookupException e ) - { - throw new LookupException( e ); + public Map lookupMap(Class type) { + try { + return container.lookupMap(type); + } catch (ComponentLookupException e) { + throw new LookupException(e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilder.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilder.java index 088258f011..74f3729cc4 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,129 +16,114 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import org.apache.maven.api.annotations.Experimental; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.MessageBuilder; @Experimental -public class DefaultMessageBuilder implements MessageBuilder -{ +public class DefaultMessageBuilder implements MessageBuilder { private final @Nonnull org.apache.maven.shared.utils.logging.MessageBuilder delegate; - public DefaultMessageBuilder( @Nonnull org.apache.maven.shared.utils.logging.MessageBuilder delegate ) - { + public DefaultMessageBuilder(@Nonnull org.apache.maven.shared.utils.logging.MessageBuilder delegate) { this.delegate = delegate; } @Override @Nonnull - public MessageBuilder success( Object o ) - { - delegate.success( o ); + public MessageBuilder success(Object o) { + delegate.success(o); return this; } @Override @Nonnull - public MessageBuilder warning( Object o ) - { - delegate.warning( o ); + public MessageBuilder warning(Object o) { + delegate.warning(o); return this; } @Override @Nonnull - public MessageBuilder failure( Object o ) - { - delegate.failure( o ); + public MessageBuilder failure(Object o) { + delegate.failure(o); return this; } @Override @Nonnull - public MessageBuilder strong( Object o ) - { - delegate.strong( o ); + public MessageBuilder strong(Object o) { + delegate.strong(o); return this; } @Override @Nonnull - public MessageBuilder mojo( Object o ) - { - delegate.mojo( o ); + public MessageBuilder mojo(Object o) { + delegate.mojo(o); return this; } @Override @Nonnull - public MessageBuilder project( Object o ) - { - delegate.project( o ); + public MessageBuilder project(Object o) { + delegate.project(o); return this; } @Override @Nonnull - public MessageBuilder a( char[] chars, int i, int i1 ) - { - delegate.a( chars, i, i1 ); + public MessageBuilder a(char[] chars, int i, int i1) { + delegate.a(chars, i, i1); return this; } @Override @Nonnull - public MessageBuilder a( char[] chars ) - { - delegate.a( chars ); + public MessageBuilder a(char[] chars) { + delegate.a(chars); return this; } @Override @Nonnull - public MessageBuilder a( CharSequence charSequence, int i, int i1 ) - { - delegate.a( charSequence, i, i1 ); + public MessageBuilder a(CharSequence charSequence, int i, int i1) { + delegate.a(charSequence, i, i1); return this; } @Override @Nonnull - public MessageBuilder a( CharSequence charSequence ) - { - delegate.a( charSequence ); + public MessageBuilder a(CharSequence charSequence) { + delegate.a(charSequence); return this; } @Override @Nonnull - public MessageBuilder a( Object o ) - { - delegate.a( o ); + public MessageBuilder a(Object o) { + delegate.a(o); return this; } @Override @Nonnull - public MessageBuilder newline() - { + public MessageBuilder newline() { delegate.newline(); return this; } @Override @Nonnull - public MessageBuilder format( String s, Object... objects ) - { - delegate.format( s, objects ); + public MessageBuilder format(String s, Object... objects) { + delegate.format(s, objects); return this; } @Override @Nonnull - public String build() - { + public String build() { return delegate.toString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilderFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilderFactory.java index f04f3087ef..e9b6578c4a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilderFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMessageBuilderFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,12 +16,11 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.util.Objects; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.annotations.Experimental; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.MessageBuilder; @@ -33,33 +30,27 @@ import org.apache.maven.shared.utils.logging.MessageUtils; @Experimental @Named @Singleton -public class DefaultMessageBuilderFactory implements MessageBuilderFactory -{ +public class DefaultMessageBuilderFactory implements MessageBuilderFactory { @Override - public boolean isColorEnabled() - { + public boolean isColorEnabled() { return MessageUtils.isColorEnabled(); } @Override - public int getTerminalWidth() - { + public int getTerminalWidth() { return MessageUtils.getTerminalWidth(); } @Override @Nonnull - public MessageBuilder builder() - { - return new DefaultMessageBuilder( MessageUtils.buffer() ); + public MessageBuilder builder() { + return new DefaultMessageBuilder(MessageUtils.buffer()); } @Override @Nonnull - public MessageBuilder builder( @Nonnull StringBuilder stringBuilder ) - { - return new DefaultMessageBuilder( MessageUtils.buffer( Objects.requireNonNull( stringBuilder ) ) ); + public MessageBuilder builder(@Nonnull StringBuilder stringBuilder) { + return new DefaultMessageBuilder(MessageUtils.buffer(Objects.requireNonNull(stringBuilder))); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultModelXmlFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultModelXmlFactory.java index ccb69a8b99..619d63d02d 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultModelXmlFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultModelXmlFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import javax.inject.Named; -import javax.inject.Singleton; +import static org.apache.maven.internal.impl.Utils.nonNull; import java.io.InputStream; import java.io.OutputStream; @@ -29,7 +27,8 @@ import java.io.Writer; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.model.InputSource; import org.apache.maven.api.model.Model; @@ -42,87 +41,61 @@ import org.apache.maven.model.v4.MavenXpp3ReaderEx; import org.apache.maven.model.v4.MavenXpp3WriterEx; import org.codehaus.plexus.util.ReaderFactory; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultModelXmlFactory - implements ModelXmlFactory -{ +public class DefaultModelXmlFactory implements ModelXmlFactory { @Override - public Model read( @Nonnull XmlReaderRequest request ) throws XmlReaderException - { - nonNull( request, "request can not be null" ); + public Model read(@Nonnull XmlReaderRequest request) throws XmlReaderException { + nonNull(request, "request can not be null"); Path path = request.getPath(); URL url = request.getURL(); Reader reader = request.getReader(); InputStream inputStream = request.getInputStream(); - if ( path == null && url == null && reader == null && inputStream == null ) - { - throw new IllegalArgumentException( "path, url, reader or inputStream must be non null" ); + if (path == null && url == null && reader == null && inputStream == null) { + throw new IllegalArgumentException("path, url, reader or inputStream must be non null"); } - try - { + try { InputSource source = null; - if ( request.getModelId() != null || request.getLocation() != null ) - { - source = new InputSource( request.getModelId(), request.getLocation() ); + if (request.getModelId() != null || request.getLocation() != null) { + source = new InputSource(request.getModelId(), request.getLocation()); } MavenXpp3ReaderEx xml = new MavenXpp3ReaderEx(); - xml.setAddDefaultEntities( request.isAddDefaultEntities() ); - if ( path != null ) - { - reader = ReaderFactory.newXmlReader( path.toFile() ); + xml.setAddDefaultEntities(request.isAddDefaultEntities()); + if (path != null) { + reader = ReaderFactory.newXmlReader(path.toFile()); + } else if (url != null) { + reader = ReaderFactory.newXmlReader(url); + } else if (inputStream != null) { + reader = ReaderFactory.newXmlReader(inputStream); } - else if ( url != null ) - { - reader = ReaderFactory.newXmlReader( url ); - } - else if ( inputStream != null ) - { - reader = ReaderFactory.newXmlReader( inputStream ); - } - return xml.read( reader, request.isStrict(), source ); - } - catch ( Exception e ) - { - throw new XmlReaderException( "Unable to read model", e ); + return xml.read(reader, request.isStrict(), source); + } catch (Exception e) { + throw new XmlReaderException("Unable to read model", e); } } @Override - public void write( XmlWriterRequest request ) throws XmlWriterException - { - nonNull( request, "request can not be null" ); - Model content = nonNull( request.getContent(), "content can not be null" ); + public void write(XmlWriterRequest request) throws XmlWriterException { + nonNull(request, "request can not be null"); + Model content = nonNull(request.getContent(), "content can not be null"); Path path = request.getPath(); OutputStream outputStream = request.getOutputStream(); Writer writer = request.getWriter(); - if ( writer == null && outputStream == null && path == null ) - { - throw new IllegalArgumentException( "writer, outputStream or path must be non null" ); + if (writer == null && outputStream == null && path == null) { + throw new IllegalArgumentException("writer, outputStream or path must be non null"); } - try - { - if ( writer != null ) - { - new MavenXpp3WriterEx().write( writer, content ); - } - else if ( outputStream != null ) - { - new MavenXpp3WriterEx().write( outputStream, content ); - } - else - { - try ( OutputStream os = Files.newOutputStream( path ) ) - { - new MavenXpp3WriterEx().write( outputStream, content ); + try { + if (writer != null) { + new MavenXpp3WriterEx().write(writer, content); + } else if (outputStream != null) { + new MavenXpp3WriterEx().write(outputStream, content); + } else { + try (OutputStream os = Files.newOutputStream(path)) { + new MavenXpp3WriterEx().write(outputStream, content); } } - } - catch ( Exception e ) - { - throw new XmlWriterException( "Unable to write model", e ); + } catch (Exception e) { + throw new XmlWriterException("Unable to write model", e); } } @@ -134,9 +107,8 @@ public class DefaultModelXmlFactory * @throws XmlReaderException if an error occurs during the parsing * @see #toXmlString(Object) */ - public static Model fromXml( @Nonnull String xml ) throws XmlReaderException - { - return new DefaultModelXmlFactory().fromXmlString( xml ); + public static Model fromXml(@Nonnull String xml) throws XmlReaderException { + return new DefaultModelXmlFactory().fromXmlString(xml); } /** @@ -147,9 +119,7 @@ public class DefaultModelXmlFactory * @throws XmlWriterException if an error occurs during the transformation * @see #fromXmlString(String) */ - public static String toXml( @Nonnull Model content ) throws XmlWriterException - { - return new DefaultModelXmlFactory().toXmlString( content ); + public static String toXml(@Nonnull Model content) throws XmlWriterException { + return new DefaultModelXmlFactory().toXmlString(content); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java index c0ec2bebf1..a6910e1a48 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,56 +16,47 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.Optional; - import org.apache.maven.api.MojoExecution; import org.apache.maven.api.model.Plugin; import org.apache.maven.api.xml.Dom; import org.codehaus.plexus.util.xml.Xpp3Dom; -public class DefaultMojoExecution - implements MojoExecution -{ +public class DefaultMojoExecution implements MojoExecution { private final org.apache.maven.plugin.MojoExecution delegate; - public DefaultMojoExecution( org.apache.maven.plugin.MojoExecution delegate ) - { + public DefaultMojoExecution(org.apache.maven.plugin.MojoExecution delegate) { this.delegate = delegate; } - public org.apache.maven.plugin.MojoExecution getDelegate() - { + public org.apache.maven.plugin.MojoExecution getDelegate() { return delegate; } @Override - public Plugin getPlugin() - { + public Plugin getPlugin() { return delegate.getPlugin().getDelegate(); } @Override - public String getExecutionId() - { + public String getExecutionId() { return delegate.getExecutionId(); } @Override - public String getGoal() - { + public String getGoal() { return delegate.getGoal(); } @Override - public Optional getConfiguration() - { - return Optional.of( delegate.getConfiguration() ).map( Xpp3Dom::getDom ); + public Optional getConfiguration() { + return Optional.of(delegate.getConfiguration()).map(Xpp3Dom::getDom); } @Override - public String toString() - { + public String toString() { return delegate.toString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultNode.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultNode.java index 787d76c22f..ef3fc6ddcb 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultNode.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultNode.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,12 +16,12 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; - import org.apache.maven.api.Dependency; import org.apache.maven.api.Node; import org.apache.maven.api.RemoteRepository; @@ -32,60 +30,50 @@ import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.util.graph.manager.DependencyManagerUtils; import org.eclipse.aether.util.graph.transformer.ConflictResolver; -public class DefaultNode extends AbstractNode -{ +public class DefaultNode extends AbstractNode { protected final @Nonnull AbstractSession session; protected final @Nonnull org.eclipse.aether.graph.DependencyNode node; protected final boolean verbose; - public DefaultNode( @Nonnull AbstractSession session, - @Nonnull org.eclipse.aether.graph.DependencyNode node, - boolean verbose ) - { + public DefaultNode( + @Nonnull AbstractSession session, @Nonnull org.eclipse.aether.graph.DependencyNode node, boolean verbose) { this.session = session; this.node = node; this.verbose = verbose; } @Override - DependencyNode getDependencyNode() - { + DependencyNode getDependencyNode() { return node; } @Override - public Dependency getDependency() - { - return node.getDependency() != null ? session.getDependency( node.getDependency() ) : null; + public Dependency getDependency() { + return node.getDependency() != null ? session.getDependency(node.getDependency()) : null; } @Override - public List getChildren() - { - return new MappedList<>( node.getChildren(), n -> session.getNode( n, verbose ) ); + public List getChildren() { + return new MappedList<>(node.getChildren(), n -> session.getNode(n, verbose)); } @Override - public List getRemoteRepositories() - { - return new MappedList<>( node.getRepositories(), session::getRemoteRepository ); + public List getRemoteRepositories() { + return new MappedList<>(node.getRepositories(), session::getRemoteRepository); } @Override - public Optional getRepository() - { + public Optional getRepository() { // TODO - throw new UnsupportedOperationException( "Not implemented yet" ); + throw new UnsupportedOperationException("Not implemented yet"); } @Override - public String asString() - { + public String asString() { String nodeString = super.asString(); - if ( !verbose ) - { + if (!verbose) { return nodeString; } @@ -94,80 +82,62 @@ public class DefaultNode extends AbstractNode List details = new ArrayList<>(); org.eclipse.aether.graph.DependencyNode winner = - (org.eclipse.aether.graph.DependencyNode) node.getData().get( ConflictResolver.NODE_DATA_WINNER ); + (org.eclipse.aether.graph.DependencyNode) node.getData().get(ConflictResolver.NODE_DATA_WINNER); String winnerVersion = winner != null ? winner.getArtifact().getBaseVersion() : null; - boolean included = ( winnerVersion == null ); + boolean included = (winnerVersion == null); - String preManagedVersion = DependencyManagerUtils.getPremanagedVersion( node ); - if ( preManagedVersion != null ) - { - details.add( "version managed from " + preManagedVersion ); + String preManagedVersion = DependencyManagerUtils.getPremanagedVersion(node); + if (preManagedVersion != null) { + details.add("version managed from " + preManagedVersion); } - String preManagedScope = DependencyManagerUtils.getPremanagedScope( node ); - if ( preManagedScope != null ) - { - details.add( "scope managed from " + preManagedScope ); + String preManagedScope = DependencyManagerUtils.getPremanagedScope(node); + if (preManagedScope != null) { + details.add("scope managed from " + preManagedScope); } - String originalScope = (String) node.getData().get( ConflictResolver.NODE_DATA_ORIGINAL_SCOPE ); - if ( originalScope != null && !originalScope.equals( node.getDependency().getScope() ) ) - { - details.add( "scope updated from " + originalScope ); + String originalScope = (String) node.getData().get(ConflictResolver.NODE_DATA_ORIGINAL_SCOPE); + if (originalScope != null && !originalScope.equals(node.getDependency().getScope())) { + details.add("scope updated from " + originalScope); } - if ( !included ) - { - if ( Objects.equals( winnerVersion, node.getArtifact().getVersion() ) ) - { - details.add( "omitted for duplicate" ); - } - else - { - details.add( "omitted for conflict with " + winnerVersion ); + if (!included) { + if (Objects.equals(winnerVersion, node.getArtifact().getVersion())) { + details.add("omitted for duplicate"); + } else { + details.add("omitted for conflict with " + winnerVersion); } } StringBuilder buffer = new StringBuilder(); - if ( included ) - { - buffer.append( nodeString ); - if ( !details.isEmpty() ) - { - buffer.append( " (" ); - join( buffer, details, "; " ); - buffer.append( ")" ); + if (included) { + buffer.append(nodeString); + if (!details.isEmpty()) { + buffer.append(" ("); + join(buffer, details, "; "); + buffer.append(")"); } - } - else - { - buffer.append( "(" ); - buffer.append( nodeString ); - if ( !details.isEmpty() ) - { - buffer.append( " - " ); - join( buffer, details, "; " ); + } else { + buffer.append("("); + buffer.append(nodeString); + if (!details.isEmpty()) { + buffer.append(" - "); + join(buffer, details, "; "); } - buffer.append( ")" ); + buffer.append(")"); } return buffer.toString(); } - private static void join( StringBuilder buffer, List details, String separator ) - { + private static void join(StringBuilder buffer, List details, String separator) { boolean first = true; - for ( String detail : details ) - { - if ( first ) - { + for (String detail : details) { + if (first) { first = false; + } else { + buffer.append(separator); } - else - { - buffer.append( separator ); - } - buffer.append( detail ); + buffer.append(detail); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProject.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProject.java index 50e083dd0b..cf8bb874ec 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProject.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProject.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,13 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.api.RemoteRepository; -import org.apache.maven.api.Scope; -import org.apache.maven.api.Type; -import org.apache.maven.api.VersionRange; -import org.apache.maven.api.annotations.Nonnull; -import org.apache.maven.api.annotations.Nullable; +package org.apache.maven.internal.impl; import java.io.File; import java.nio.file.Path; @@ -32,215 +24,188 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; - import org.apache.maven.RepositoryUtils; import org.apache.maven.api.Artifact; import org.apache.maven.api.DependencyCoordinate; import org.apache.maven.api.Exclusion; import org.apache.maven.api.Project; +import org.apache.maven.api.RemoteRepository; +import org.apache.maven.api.Scope; +import org.apache.maven.api.Type; +import org.apache.maven.api.VersionRange; +import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.annotations.Nullable; import org.apache.maven.api.model.DependencyManagement; import org.apache.maven.api.model.Model; import org.apache.maven.api.services.ArtifactManager; import org.apache.maven.api.services.TypeRegistry; import org.apache.maven.project.MavenProject; -public class DefaultProject implements Project -{ +public class DefaultProject implements Project { private final AbstractSession session; private final MavenProject project; - public DefaultProject( AbstractSession session, MavenProject project ) - { + public DefaultProject(AbstractSession session, MavenProject project) { this.session = session; this.project = project; } - public AbstractSession getSession() - { + public AbstractSession getSession() { return session; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } @Nonnull @Override - public String getGroupId() - { + public String getGroupId() { return project.getGroupId(); } @Nonnull @Override - public String getArtifactId() - { + public String getArtifactId() { return project.getArtifactId(); } @Nonnull @Override - public String getVersion() - { + public String getVersion() { return project.getVersion(); } @Nonnull @Override - public Artifact getArtifact() - { - org.eclipse.aether.artifact.Artifact resolverArtifact = RepositoryUtils.toArtifact( project.getArtifact() ); - Artifact artifact = session.getArtifact( resolverArtifact ); - Path path = resolverArtifact.getFile() != null ? resolverArtifact.getFile().toPath() : null; - session.getService( ArtifactManager.class ).setPath( artifact, path ); + public Artifact getArtifact() { + org.eclipse.aether.artifact.Artifact resolverArtifact = RepositoryUtils.toArtifact(project.getArtifact()); + Artifact artifact = session.getArtifact(resolverArtifact); + Path path = + resolverArtifact.getFile() != null ? resolverArtifact.getFile().toPath() : null; + session.getService(ArtifactManager.class).setPath(artifact, path); return artifact; } @Nonnull @Override - public String getPackaging() - { + public String getPackaging() { return project.getPackaging(); } @Nonnull @Override - public Model getModel() - { + public Model getModel() { return project.getModel().getDelegate(); } @Nonnull @Override - public Optional getPomPath() - { + public Optional getPomPath() { File file = project.getFile(); - return Optional.ofNullable( file ).map( File::toPath ); + return Optional.ofNullable(file).map(File::toPath); } @Nonnull @Override - public List getDependencies() - { - return new MappedList<>( getModel().getDependencies(), this::toDependency ); + public List getDependencies() { + return new MappedList<>(getModel().getDependencies(), this::toDependency); } @Nonnull @Override - public List getManagedDependencies() - { + public List getManagedDependencies() { DependencyManagement dependencyManagement = getModel().getDependencyManagement(); - if ( dependencyManagement != null ) - { - return new MappedList<>( dependencyManagement.getDependencies(), this::toDependency ); + if (dependencyManagement != null) { + return new MappedList<>(dependencyManagement.getDependencies(), this::toDependency); } return Collections.emptyList(); } @Override - public boolean isExecutionRoot() - { + public boolean isExecutionRoot() { return project.isExecutionRoot(); } @Override - public Optional getParent() - { + public Optional getParent() { MavenProject parent = project.getParent(); - return parent != null ? Optional.of( session.getProject( parent ) ) : Optional.empty(); + return parent != null ? Optional.of(session.getProject(parent)) : Optional.empty(); } @Override - public List getRemoteProjectRepositories() - { - return new MappedList<>( project.getRemoteProjectRepositories(), session::getRemoteRepository ); + public List getRemoteProjectRepositories() { + return new MappedList<>(project.getRemoteProjectRepositories(), session::getRemoteRepository); } @Override - public List getRemotePluginRepositories() - { - return new MappedList<>( project.getRemotePluginRepositories(), session::getRemoteRepository ); + public List getRemotePluginRepositories() { + return new MappedList<>(project.getRemotePluginRepositories(), session::getRemoteRepository); } @Nonnull - private DependencyCoordinate toDependency( org.apache.maven.api.model.Dependency dependency ) - { - return new DependencyCoordinate() - { + private DependencyCoordinate toDependency(org.apache.maven.api.model.Dependency dependency) { + return new DependencyCoordinate() { @Override - public String getGroupId() - { + public String getGroupId() { return dependency.getGroupId(); } @Override - public String getArtifactId() - { + public String getArtifactId() { return dependency.getArtifactId(); } @Override - public String getClassifier() - { + public String getClassifier() { return dependency.getClassifier(); } @Override - public VersionRange getVersion() - { - return session.parseVersionRange( dependency.getVersion() ); + public VersionRange getVersion() { + return session.parseVersionRange(dependency.getVersion()); } @Override - public String getExtension() - { + public String getExtension() { return getType().getExtension(); } @Override - public Type getType() - { + public Type getType() { String type = dependency.getType(); - return session.getService( TypeRegistry.class ).getType( type ); + return session.getService(TypeRegistry.class).getType(type); } @Nonnull @Override - public Scope getScope() - { - return Scope.get( dependency.getScope() ); + public Scope getScope() { + return Scope.get(dependency.getScope()); } @Override - public Boolean getOptional() - { + public Boolean getOptional() { return dependency.isOptional(); } @Nonnull @Override - public Collection getExclusions() - { - return new MappedCollection<>( dependency.getExclusions(), this::toExclusion ); + public Collection getExclusions() { + return new MappedCollection<>(dependency.getExclusions(), this::toExclusion); } - private Exclusion toExclusion( org.apache.maven.api.model.Exclusion exclusion ) - { - return new Exclusion() - { + private Exclusion toExclusion(org.apache.maven.api.model.Exclusion exclusion) { + return new Exclusion() { @Nullable @Override - public String getGroupId() - { + public String getGroupId() { return exclusion.getGroupId(); } @Nullable @Override - public String getArtifactId() - { + public String getArtifactId() { return exclusion.getArtifactId(); } }; diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectBuilder.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectBuilder.java index 4944df1354..466153d71a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,10 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.io.File; import java.io.IOException; @@ -30,17 +25,19 @@ import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Optional; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.RepositoryUtils; import org.apache.maven.api.Artifact; import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.Node; import org.apache.maven.api.Project; import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.services.BuilderProblem; import org.apache.maven.api.services.DependencyCollectorResult; import org.apache.maven.api.services.ProjectBuilder; import org.apache.maven.api.services.ProjectBuilderException; -import org.apache.maven.api.services.BuilderProblem; import org.apache.maven.api.services.ProjectBuilderRequest; import org.apache.maven.api.services.ProjectBuilderResult; import org.apache.maven.api.services.Source; @@ -55,216 +52,178 @@ import org.apache.maven.project.ProjectBuildingResult; @Named @Singleton -public class DefaultProjectBuilder implements ProjectBuilder -{ +public class DefaultProjectBuilder implements ProjectBuilder { private final org.apache.maven.project.ProjectBuilder builder; @Inject - public DefaultProjectBuilder( org.apache.maven.project.ProjectBuilder builder ) - { + public DefaultProjectBuilder(org.apache.maven.project.ProjectBuilder builder) { this.builder = builder; } - @SuppressWarnings( "MethodLength" ) + @SuppressWarnings("MethodLength") @Nonnull @Override - public ProjectBuilderResult build( ProjectBuilderRequest request ) - throws ProjectBuilderException, IllegalArgumentException - { - DefaultSession session = ( DefaultSession ) request.getSession(); - try - { - List repositories = - session.toArtifactRepositories( session.getRemoteRepositories() ); + public ProjectBuilderResult build(ProjectBuilderRequest request) + throws ProjectBuilderException, IllegalArgumentException { + DefaultSession session = (DefaultSession) request.getSession(); + try { + List repositories = session.toArtifactRepositories(session.getRemoteRepositories()); ProjectBuildingRequest req = new DefaultProjectBuildingRequest() - .setRepositorySession( session.getSession() ) - .setRemoteRepositories( repositories ) - .setPluginArtifactRepositories( repositories ) - .setProcessPlugins( request.isProcessPlugins() ); + .setRepositorySession(session.getSession()) + .setRemoteRepositories(repositories) + .setPluginArtifactRepositories(repositories) + .setProcessPlugins(request.isProcessPlugins()); ProjectBuildingResult res; - if ( request.getPath().isPresent() ) - { + if (request.getPath().isPresent()) { Path path = request.getPath().get(); - res = builder.build( path.toFile(), req ); - } - else if ( request.getSource().isPresent() ) - { + res = builder.build(path.toFile(), req); + } else if (request.getSource().isPresent()) { Source source = request.getSource().get(); - ModelSource modelSource = new ModelSource() - { + ModelSource modelSource = new ModelSource() { @Override - public InputStream getInputStream() throws IOException - { + public InputStream getInputStream() throws IOException { return source.getInputStream(); } @Override - public String getLocation() - { + public String getLocation() { return source.getLocation(); } }; - res = builder.build( modelSource, req ); - } - else if ( request.getArtifact().isPresent() ) - { + res = builder.build(modelSource, req); + } else if (request.getArtifact().isPresent()) { Artifact a = request.getArtifact().get(); - org.eclipse.aether.artifact.Artifact aetherArtifact = session.toArtifact( a ); - org.apache.maven.artifact.Artifact artifact = RepositoryUtils.toArtifact( aetherArtifact ); - res = builder.build( artifact, request.isAllowStubModel(), req ); - } - else if ( request.getCoordinate().isPresent() ) - { + org.eclipse.aether.artifact.Artifact aetherArtifact = session.toArtifact(a); + org.apache.maven.artifact.Artifact artifact = RepositoryUtils.toArtifact(aetherArtifact); + res = builder.build(artifact, request.isAllowStubModel(), req); + } else if (request.getCoordinate().isPresent()) { ArtifactCoordinate c = request.getCoordinate().get(); org.apache.maven.artifact.Artifact artifact = new DefaultArtifact( - c.getGroupId(), c.getArtifactId(), c.getVersion().asString(), null, - c.getExtension(), c.getClassifier(), null ); - res = builder.build( artifact, request.isAllowStubModel(), req ); + c.getGroupId(), + c.getArtifactId(), + c.getVersion().asString(), + null, + c.getExtension(), + c.getClassifier(), + null); + res = builder.build(artifact, request.isAllowStubModel(), req); + } else { + throw new IllegalArgumentException("Invalid request"); } - else - { - throw new IllegalArgumentException( "Invalid request" ); - } - return new ProjectBuilderResult() - { + return new ProjectBuilderResult() { @Nonnull @Override - public String getProjectId() - { + public String getProjectId() { return res.getProjectId(); } @Nonnull @Override - public Optional getPomFile() - { - return Optional.ofNullable( res.getPomFile() ).map( File::toPath ); + public Optional getPomFile() { + return Optional.ofNullable(res.getPomFile()).map(File::toPath); } @Nonnull @Override - public Optional getProject() - { - return Optional.ofNullable( res.getProject() ) - .map( session::getProject ); + public Optional getProject() { + return Optional.ofNullable(res.getProject()).map(session::getProject); } @Nonnull @Override - public Collection getProblems() - { - return new MappedCollection<>( res.getProblems(), this::toProblem ); + public Collection getProblems() { + return new MappedCollection<>(res.getProblems(), this::toProblem); } - private BuilderProblem toProblem( ModelProblem problem ) - { - return new BuilderProblem() - { + private BuilderProblem toProblem(ModelProblem problem) { + return new BuilderProblem() { @Override - public String getSource() - { + public String getSource() { return problem.getSource(); } @Override - public int getLineNumber() - { + public int getLineNumber() { return problem.getLineNumber(); } @Override - public int getColumnNumber() - { + public int getColumnNumber() { return problem.getColumnNumber(); } @Override - public String getLocation() - { - StringBuilder buffer = new StringBuilder( 256 ); + public String getLocation() { + StringBuilder buffer = new StringBuilder(256); - if ( getSource().length() > 0 ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + if (getSource().length() > 0) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( getSource() ); + buffer.append(getSource()); } - if ( getLineNumber() > 0 ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + if (getLineNumber() > 0) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( "line " ).append( getLineNumber() ); + buffer.append("line ").append(getLineNumber()); } - if ( getColumnNumber() > 0 ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + if (getColumnNumber() > 0) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( "column " ).append( getColumnNumber() ); + buffer.append("column ").append(getColumnNumber()); } return buffer.toString(); } @Override - public Exception getException() - { + public Exception getException() { return problem.getException(); } @Override - public String getMessage() - { + public String getMessage() { return problem.getMessage(); } @Override - public Severity getSeverity() - { - return Severity.valueOf( problem.getSeverity().name() ); + public Severity getSeverity() { + return Severity.valueOf(problem.getSeverity().name()); } }; } @Nonnull @Override - public Optional getDependencyResolverResult() - { - return Optional.ofNullable( res.getDependencyResolutionResult() ) - .map( r -> new DependencyCollectorResult() - { + public Optional getDependencyResolverResult() { + return Optional.ofNullable(res.getDependencyResolutionResult()) + .map(r -> new DependencyCollectorResult() { @Override - public List getExceptions() - { + public List getExceptions() { return r.getCollectionErrors(); } @Override - public Node getRoot() - { - return session.getNode( r.getDependencyGraph() ); + public Node getRoot() { + return session.getNode(r.getDependencyGraph()); } -// @Override -// public List getArtifactResults() -// { -// return Collections.emptyList(); -// } - } ); + // @Override + // public List + // getArtifactResults() + // { + // return Collections.emptyList(); + // } + }); } }; - } - catch ( ProjectBuildingException e ) - { - throw new ProjectBuilderException( "Unable to build project", e ); + } catch (ProjectBuildingException e) { + throw new ProjectBuilderException("Unable to build project", e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectManager.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectManager.java index 6f0855ba9a..6e35e1e5c3 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectManager.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,9 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; +package org.apache.maven.internal.impl; import java.nio.file.Path; import java.util.Collection; @@ -29,7 +25,8 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; - +import javax.inject.Inject; +import javax.inject.Named; import org.apache.maven.RepositoryUtils; import org.apache.maven.SessionScoped; import org.apache.maven.api.Artifact; @@ -51,18 +48,14 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti @Named @SessionScoped -public class DefaultProjectManager implements ProjectManager -{ +public class DefaultProjectManager implements ProjectManager { private final Session session; private final ArtifactManager artifactManager; private final PlexusContainer container; @Inject - public DefaultProjectManager( Session session, - ArtifactManager artifactManager, - PlexusContainer container ) - { + public DefaultProjectManager(Session session, ArtifactManager artifactManager, PlexusContainer container) { this.session = session; this.artifactManager = artifactManager; this.container = container; @@ -70,115 +63,98 @@ public class DefaultProjectManager implements ProjectManager @Nonnull @Override - public Optional getPath( Project project ) - { + public Optional getPath(Project project) { // TODO: apiv4 - throw new UnsupportedOperationException( "Not implemented yet" ); + throw new UnsupportedOperationException("Not implemented yet"); } @Nonnull @Override - public Collection getAttachedArtifacts( Project project ) - { - AbstractSession session = ( (DefaultProject ) project ).getSession(); - Collection attached = getMavenProject( project ).getAttachedArtifacts().stream() - .map( RepositoryUtils::toArtifact ) - .map( session::getArtifact ) - .collect( Collectors.toList() ); - return Collections.unmodifiableCollection( attached ); + public Collection getAttachedArtifacts(Project project) { + AbstractSession session = ((DefaultProject) project).getSession(); + Collection attached = getMavenProject(project).getAttachedArtifacts().stream() + .map(RepositoryUtils::toArtifact) + .map(session::getArtifact) + .collect(Collectors.toList()); + return Collections.unmodifiableCollection(attached); } @Override - public void attachArtifact( Project project, Artifact artifact, Path path ) - { - getMavenProject( project ).addAttachedArtifact( - RepositoryUtils.toArtifact( ( ( DefaultProject ) project ).getSession().toArtifact( artifact ) ) ); - artifactManager.setPath( artifact, path ); + public void attachArtifact(Project project, Artifact artifact, Path path) { + getMavenProject(project) + .addAttachedArtifact(RepositoryUtils.toArtifact( + ((DefaultProject) project).getSession().toArtifact(artifact))); + artifactManager.setPath(artifact, path); } @Override - public List getCompileSourceRoots( Project project ) - { - List roots = getMavenProject( project ).getCompileSourceRoots(); - return Collections.unmodifiableList( roots ); + public List getCompileSourceRoots(Project project) { + List roots = getMavenProject(project).getCompileSourceRoots(); + return Collections.unmodifiableList(roots); } @Override - public void addCompileSourceRoot( Project project, String sourceRoot ) - { - List roots = getMavenProject( project ).getCompileSourceRoots(); - roots.add( sourceRoot ); + public void addCompileSourceRoot(Project project, String sourceRoot) { + List roots = getMavenProject(project).getCompileSourceRoots(); + roots.add(sourceRoot); } @Override - public List getTestCompileSourceRoots( Project project ) - { - List roots = getMavenProject( project ).getTestCompileSourceRoots(); - return Collections.unmodifiableList( roots ); + public List getTestCompileSourceRoots(Project project) { + List roots = getMavenProject(project).getTestCompileSourceRoots(); + return Collections.unmodifiableList(roots); } @Override - public void addTestCompileSourceRoot( Project project, String sourceRoot ) - { - List roots = getMavenProject( project ).getTestCompileSourceRoots(); - roots.add( sourceRoot ); + public void addTestCompileSourceRoot(Project project, String sourceRoot) { + List roots = getMavenProject(project).getTestCompileSourceRoots(); + roots.add(sourceRoot); } @Override - public List getRepositories( Project project ) - { + public List getRepositories(Project project) { // TODO: apiv4 - throw new UnsupportedOperationException( "Not implemented yet" ); + throw new UnsupportedOperationException("Not implemented yet"); } @Override - public List getResolvedDependencies( Project project, ResolutionScope scope ) - { - Collection toResolve = toScopes( scope ); - try - { + public List getResolvedDependencies(Project project, ResolutionScope scope) { + Collection toResolve = toScopes(scope); + try { LifecycleDependencyResolver lifecycleDependencyResolver = - container.lookup( LifecycleDependencyResolver.class ); + container.lookup(LifecycleDependencyResolver.class); Set artifacts = lifecycleDependencyResolver.resolveProjectArtifacts( - getMavenProject( project ), + getMavenProject(project), toResolve, toResolve, - ( ( DefaultSession ) session ).getMavenSession(), + ((DefaultSession) session).getMavenSession(), false, - Collections.emptySet() - ); + Collections.emptySet()); return artifacts.stream() - .map( RepositoryUtils::toArtifact ) - .map( ( ( DefaultSession ) session )::getArtifact ) - .collect( Collectors.toList() ); - } - catch ( LifecycleExecutionException | ComponentLookupException e ) - { - throw new MavenException( "Unable to resolve project dependencies", e ); + .map(RepositoryUtils::toArtifact) + .map(((DefaultSession) session)::getArtifact) + .collect(Collectors.toList()); + } catch (LifecycleExecutionException | ComponentLookupException e) { + throw new MavenException("Unable to resolve project dependencies", e); } } @Override - public Node getCollectedDependencies( Project project, ResolutionScope scope ) - { + public Node getCollectedDependencies(Project project, ResolutionScope scope) { // TODO: apiv4 - throw new UnsupportedOperationException( "Not implemented yet" ); + throw new UnsupportedOperationException("Not implemented yet"); } @Override - public void setProperty( Project project, String key, String value ) - { - getMavenProject( project ).getProperties().setProperty( key, value ); + public void setProperty(Project project, String key, String value) { + getMavenProject(project).getProperties().setProperty(key, value); } - private MavenProject getMavenProject( Project project ) - { - return ( ( DefaultProject ) project ).getProject(); + private MavenProject getMavenProject(Project project) { + return ((DefaultProject) project).getProject(); } - private Collection toScopes( ResolutionScope scope ) - { - return scope.scopes().stream().map( Scope::id ).collect( Collectors.toList() ); + private Collection toScopes(ResolutionScope scope) { + return scope.scopes().stream().map(Scope::id).collect(Collectors.toList()); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPrompter.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPrompter.java index 2bb6421240..97b31397db 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPrompter.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPrompter.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,77 +16,62 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.lang.reflect.Method; import java.util.List; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.services.Prompter; import org.apache.maven.api.services.PrompterException; import org.codehaus.plexus.PlexusContainer; @Named @Singleton -public class DefaultPrompter implements Prompter -{ +public class DefaultPrompter implements Prompter { private static final String PROMPTER_CLASS = "org.codehaus.plexus.components.interactivity.Prompter"; private final PlexusContainer container; @Inject - public DefaultPrompter( PlexusContainer container ) - { + public DefaultPrompter(PlexusContainer container) { this.container = container; } @Override - public String prompt( String message, List possibleValues, String defaultReply ) throws PrompterException - { - try - { - Class clazz = container.getContainerRealm().loadClass( PROMPTER_CLASS ); - Object instance = container.lookup( clazz ); - Method method = clazz.getMethod( "prompt", String.class, List.class, String.class ); - return (String) method.invoke( instance, message, possibleValues, defaultReply ); - } - catch ( Exception e ) - { - throw new PrompterException( "Unable to call prompter", e ); + public String prompt(String message, List possibleValues, String defaultReply) throws PrompterException { + try { + Class clazz = container.getContainerRealm().loadClass(PROMPTER_CLASS); + Object instance = container.lookup(clazz); + Method method = clazz.getMethod("prompt", String.class, List.class, String.class); + return (String) method.invoke(instance, message, possibleValues, defaultReply); + } catch (Exception e) { + throw new PrompterException("Unable to call prompter", e); } } @Override - public String promptForPassword( String message ) throws PrompterException - { - try - { - Class clazz = container.getContainerRealm().loadClass( PROMPTER_CLASS ); - Object instance = container.lookup( clazz ); - Method method = clazz.getMethod( "promptForPassword", String.class ); - return (String) method.invoke( instance, message ); - } - catch ( Exception e ) - { - throw new PrompterException( "Unable to call prompter", e ); + public String promptForPassword(String message) throws PrompterException { + try { + Class clazz = container.getContainerRealm().loadClass(PROMPTER_CLASS); + Object instance = container.lookup(clazz); + Method method = clazz.getMethod("promptForPassword", String.class); + return (String) method.invoke(instance, message); + } catch (Exception e) { + throw new PrompterException("Unable to call prompter", e); } } @Override - public void showMessage( String message ) throws PrompterException - { - try - { - Class clazz = container.getContainerRealm().loadClass( PROMPTER_CLASS ); - Object instance = container.lookup( clazz ); - Method method = clazz.getMethod( "showMessage", String.class ); - method.invoke( instance, message ); - } - catch ( Exception e ) - { - throw new PrompterException( "Unable to call prompter", e ); + public void showMessage(String message) throws PrompterException { + try { + Class clazz = container.getContainerRealm().loadClass(PROMPTER_CLASS); + Object instance = container.lookup(clazz); + Method method = clazz.getMethod("showMessage", String.class); + method.invoke(instance, message); + } catch (Exception e) { + throw new PrompterException("Unable to call prompter", e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRemoteRepository.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRemoteRepository.java index e56d54280a..6a279f675f 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRemoteRepository.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRemoteRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,50 +16,43 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.api.annotations.Nonnull; +package org.apache.maven.internal.impl; import org.apache.maven.api.RemoteRepository; +import org.apache.maven.api.annotations.Nonnull; -public class DefaultRemoteRepository implements RemoteRepository -{ +public class DefaultRemoteRepository implements RemoteRepository { private final org.eclipse.aether.repository.RemoteRepository repository; - public DefaultRemoteRepository( org.eclipse.aether.repository.RemoteRepository repository ) - { + public DefaultRemoteRepository(org.eclipse.aether.repository.RemoteRepository repository) { this.repository = repository; } - public org.eclipse.aether.repository.RemoteRepository getRepository() - { + public org.eclipse.aether.repository.RemoteRepository getRepository() { return repository; } @Nonnull @Override - public String getId() - { + public String getId() { return repository.getId(); } @Nonnull @Override - public String getType() - { + public String getType() { return repository.getContentType(); } @Nonnull @Override - public String getUrl() - { + public String getUrl() { return repository.getUrl(); } @Nonnull @Override - public String getProtocol() - { + public String getProtocol() { return repository.getProtocol(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRepositoryFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRepositoryFactory.java index e3abff1db3..60852866c0 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRepositoryFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRepositoryFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,78 +16,64 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; +import java.nio.file.Path; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - -import java.nio.file.Path; - import org.apache.maven.api.LocalRepository; import org.apache.maven.api.RemoteRepository; -import org.apache.maven.api.services.RepositoryFactory; import org.apache.maven.api.model.Repository; +import org.apache.maven.api.services.RepositoryFactory; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.repository.RepositoryPolicy; @Named @Singleton -public class DefaultRepositoryFactory implements RepositoryFactory -{ +public class DefaultRepositoryFactory implements RepositoryFactory { private final RepositorySystem repositorySystem; @Inject - public DefaultRepositoryFactory( RepositorySystem repositorySystem ) - { + public DefaultRepositoryFactory(RepositorySystem repositorySystem) { this.repositorySystem = repositorySystem; } @Override - public LocalRepository createLocal( Path path ) - { - return new DefaultLocalRepository( new org.eclipse.aether.repository.LocalRepository( path.toFile() ) ); + public LocalRepository createLocal(Path path) { + return new DefaultLocalRepository(new org.eclipse.aether.repository.LocalRepository(path.toFile())); } @Override - public RemoteRepository createRemote( String id, String url ) - { + public RemoteRepository createRemote(String id, String url) { return new DefaultRemoteRepository( - new org.eclipse.aether.repository.RemoteRepository.Builder( id, "default", url ) - .build() ); + new org.eclipse.aether.repository.RemoteRepository.Builder(id, "default", url).build()); } @Override - public RemoteRepository createRemote( Repository repository ) - throws IllegalArgumentException - { - return new DefaultRemoteRepository( - new org.eclipse.aether.repository.RemoteRepository.Builder( - repository.getId(), repository.getLayout(), repository.getUrl() ) - .setReleasePolicy( buildRepositoryPolicy( repository.getReleases() ) ) - .setSnapshotPolicy( buildRepositoryPolicy( repository.getSnapshots() ) ) - .build() ); + public RemoteRepository createRemote(Repository repository) throws IllegalArgumentException { + return new DefaultRemoteRepository(new org.eclipse.aether.repository.RemoteRepository.Builder( + repository.getId(), repository.getLayout(), repository.getUrl()) + .setReleasePolicy(buildRepositoryPolicy(repository.getReleases())) + .setSnapshotPolicy(buildRepositoryPolicy(repository.getSnapshots())) + .build()); } public static org.eclipse.aether.repository.RepositoryPolicy buildRepositoryPolicy( - org.apache.maven.api.model.RepositoryPolicy policy ) - { + org.apache.maven.api.model.RepositoryPolicy policy) { boolean enabled = true; String updatePolicy = RepositoryPolicy.UPDATE_POLICY_DAILY; String checksumPolicy = RepositoryPolicy.CHECKSUM_POLICY_FAIL; - if ( policy != null ) - { + if (policy != null) { enabled = policy.isEnabled(); - if ( policy.getUpdatePolicy() != null ) - { + if (policy.getUpdatePolicy() != null) { updatePolicy = policy.getUpdatePolicy(); } - if ( policy.getChecksumPolicy() != null ) - { + if (policy.getChecksumPolicy() != null) { checksumPolicy = policy.getChecksumPolicy(); } } - return new org.eclipse.aether.repository.RepositoryPolicy( - enabled, updatePolicy, checksumPolicy ); + return new org.eclipse.aether.repository.RepositoryPolicy(enabled, updatePolicy, checksumPolicy); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSession.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSession.java index 6d5b7c6ef0..0483f5b636 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSession.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSession.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,6 +16,9 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import java.nio.file.Path; import java.nio.file.Paths; @@ -30,7 +31,6 @@ import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Collectors; - import org.apache.maven.RepositoryUtils; import org.apache.maven.api.DependencyCoordinate; import org.apache.maven.api.LocalRepository; @@ -56,10 +56,7 @@ import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; -import static org.apache.maven.internal.impl.Utils.nonNull; - -public class DefaultSession extends AbstractSession -{ +public class DefaultSession extends AbstractSession { private final MavenSession mavenSession; private final RepositorySystemSession session; @@ -70,270 +67,225 @@ public class DefaultSession extends AbstractSession private final RuntimeInformation runtimeInformation; private final Map, Service> services = new HashMap<>(); - @SuppressWarnings( "checkstyle:ParameterNumber" ) - public DefaultSession( @Nonnull MavenSession session, - @Nonnull RepositorySystem repositorySystem, - @Nullable List repositories, - @Nonnull MavenRepositorySystem mavenRepositorySystem, - @Nonnull PlexusContainer container, - @Nonnull RuntimeInformation runtimeInformation ) - { - this.mavenSession = nonNull( session ); + @SuppressWarnings("checkstyle:ParameterNumber") + public DefaultSession( + @Nonnull MavenSession session, + @Nonnull RepositorySystem repositorySystem, + @Nullable List repositories, + @Nonnull MavenRepositorySystem mavenRepositorySystem, + @Nonnull PlexusContainer container, + @Nonnull RuntimeInformation runtimeInformation) { + this.mavenSession = nonNull(session); this.session = mavenSession.getRepositorySession(); - this.repositorySystem = nonNull( repositorySystem ); + this.repositorySystem = nonNull(repositorySystem); this.repositories = repositories != null ? repositories : mavenSession.getRequest().getRemoteRepositories().stream() - .map( RepositoryUtils::toRepo ).map( this::getRemoteRepository ).collect( Collectors.toList() ); + .map(RepositoryUtils::toRepo) + .map(this::getRemoteRepository) + .collect(Collectors.toList()); this.mavenRepositorySystem = mavenRepositorySystem; this.container = container; this.runtimeInformation = runtimeInformation; } - public MavenSession getMavenSession() - { + public MavenSession getMavenSession() { return mavenSession; } @Nonnull @Override - public LocalRepository getLocalRepository() - { - return new DefaultLocalRepository( session.getLocalRepository() ); + public LocalRepository getLocalRepository() { + return new DefaultLocalRepository(session.getLocalRepository()); } @Nonnull @Override - public List getRemoteRepositories() - { - return Collections.unmodifiableList( repositories ); + public List getRemoteRepositories() { + return Collections.unmodifiableList(repositories); } @Nonnull @Override - public Settings getSettings() - { + public Settings getSettings() { return mavenSession.getSettings().getDelegate(); } @Nonnull @Override - public Map getUserProperties() - { - return new PropertiesAsMap( mavenSession.getUserProperties() ); + public Map getUserProperties() { + return new PropertiesAsMap(mavenSession.getUserProperties()); } @Nonnull @Override - public Map getSystemProperties() - { - return new PropertiesAsMap( mavenSession.getSystemProperties() ); + public Map getSystemProperties() { + return new PropertiesAsMap(mavenSession.getSystemProperties()); } @Nonnull @Override - public String getMavenVersion() - { + public String getMavenVersion() { return runtimeInformation.getMavenVersion(); } @Override - public int getDegreeOfConcurrency() - { + public int getDegreeOfConcurrency() { return mavenSession.getRequest().getDegreeOfConcurrency(); } @Nonnull @Override - public Instant getStartTime() - { + public Instant getStartTime() { return mavenSession.getStartTime().toInstant(); } @Nonnull @Override - public Path getMultiModuleProjectDirectory() - { + public Path getMultiModuleProjectDirectory() { return mavenSession.getRequest().getMultiModuleProjectDirectory().toPath(); } @Nonnull @Override - public Path getExecutionRootDirectory() - { - return Paths.get( mavenSession.getRequest().getBaseDirectory() ); + public Path getExecutionRootDirectory() { + return Paths.get(mavenSession.getRequest().getBaseDirectory()); } @Nonnull @Override - public List getProjects() - { - return getProjects( mavenSession.getProjects() ); + public List getProjects() { + return getProjects(mavenSession.getProjects()); } @Nonnull @Override - public Map getPluginContext( Project project ) - { - nonNull( project, "project" ); - try - { - MojoExecution mojoExecution = container.lookup( MojoExecution.class ); + public Map getPluginContext(Project project) { + nonNull(project, "project"); + try { + MojoExecution mojoExecution = container.lookup(MojoExecution.class); MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); - return mavenSession.getPluginContext( pluginDescriptor, ( ( DefaultProject ) project ).getProject() ); - } - catch ( ComponentLookupException e ) - { - throw new MavenException( "The PluginContext is only available during a mojo execution", e ); + return mavenSession.getPluginContext(pluginDescriptor, ((DefaultProject) project).getProject()); + } catch (ComponentLookupException e) { + throw new MavenException("The PluginContext is only available during a mojo execution", e); } } @Nonnull @Override - public SessionData getData() - { + public SessionData getData() { org.eclipse.aether.SessionData data = session.getData(); - return new SessionData() - { + return new SessionData() { @Override - public void set( @Nonnull Object key, @Nullable Object value ) - { - data.set( key, value ); + public void set(@Nonnull Object key, @Nullable Object value) { + data.set(key, value); } @Override - public boolean set( @Nonnull Object key, @Nullable Object oldValue, @Nullable Object newValue ) - { - return data.set( key, oldValue, newValue ); + public boolean set(@Nonnull Object key, @Nullable Object oldValue, @Nullable Object newValue) { + return data.set(key, oldValue, newValue); } @Nullable @Override - public Object get( @Nonnull Object key ) - { - return data.get( key ); + public Object get(@Nonnull Object key) { + return data.get(key); } @Nullable @Override - public Object computeIfAbsent( @Nonnull Object key, @Nonnull Supplier supplier ) - { - return data.computeIfAbsent( key, supplier ); + public Object computeIfAbsent(@Nonnull Object key, @Nonnull Supplier supplier) { + return data.computeIfAbsent(key, supplier); } }; } @Nonnull @Override - public Session withLocalRepository( @Nonnull LocalRepository localRepository ) - { - nonNull( localRepository, "localRepository" ); - if ( session.getLocalRepository() != null - && Objects.equals( session.getLocalRepository().getBasedir().toPath(), - localRepository.getPath() ) ) - { + public Session withLocalRepository(@Nonnull LocalRepository localRepository) { + nonNull(localRepository, "localRepository"); + if (session.getLocalRepository() != null + && Objects.equals(session.getLocalRepository().getBasedir().toPath(), localRepository.getPath())) { return this; } - org.eclipse.aether.repository.LocalRepository repository = toRepository( localRepository ); - org.eclipse.aether.repository.LocalRepositoryManager localRepositoryManager - = repositorySystem.newLocalRepositoryManager( session, repository ); + org.eclipse.aether.repository.LocalRepository repository = toRepository(localRepository); + org.eclipse.aether.repository.LocalRepositoryManager localRepositoryManager = + repositorySystem.newLocalRepositoryManager(session, repository); - RepositorySystemSession repoSession = new DefaultRepositorySystemSession( session ) - .setLocalRepositoryManager( localRepositoryManager ); - MavenSession newSession = new MavenSession( mavenSession.getContainer(), repoSession, - mavenSession.getRequest(), mavenSession.getResult() ); - return new DefaultSession( newSession, repositorySystem, repositories, - mavenRepositorySystem, container, runtimeInformation ); + RepositorySystemSession repoSession = + new DefaultRepositorySystemSession(session).setLocalRepositoryManager(localRepositoryManager); + MavenSession newSession = new MavenSession( + mavenSession.getContainer(), repoSession, mavenSession.getRequest(), mavenSession.getResult()); + return new DefaultSession( + newSession, repositorySystem, repositories, mavenRepositorySystem, container, runtimeInformation); } @Nonnull @Override - public Session withRemoteRepositories( @Nonnull List repositories ) - { - return new DefaultSession( mavenSession, repositorySystem, repositories, - mavenRepositorySystem, container, runtimeInformation ); + public Session withRemoteRepositories(@Nonnull List repositories) { + return new DefaultSession( + mavenSession, repositorySystem, repositories, mavenRepositorySystem, container, runtimeInformation); } @Nonnull @Override - @SuppressWarnings( "unchecked" ) - public T getService( Class clazz ) throws NoSuchElementException - { - T t = (T) services.computeIfAbsent( clazz, this::lookup ); - if ( t == null ) - { - throw new NoSuchElementException( clazz.getName() ); + @SuppressWarnings("unchecked") + public T getService(Class clazz) throws NoSuchElementException { + T t = (T) services.computeIfAbsent(clazz, this::lookup); + if (t == null) { + throw new NoSuchElementException(clazz.getName()); } return t; } - private Service lookup( Class c ) - { - try - { - return container.lookup( c ); - } - catch ( ComponentLookupException e ) - { - NoSuchElementException nsee = new NoSuchElementException( c.getName() ); - e.initCause( e ); + private Service lookup(Class c) { + try { + return container.lookup(c); + } catch (ComponentLookupException e) { + NoSuchElementException nsee = new NoSuchElementException(c.getName()); + e.initCause(e); throw nsee; } } @Nonnull - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } @Nonnull - public RepositorySystem getRepositorySystem() - { + public RepositorySystem getRepositorySystem() { return repositorySystem; } - public ArtifactRepository toArtifactRepository( RemoteRepository repository ) - { - if ( repository instanceof DefaultRemoteRepository ) - { - org.eclipse.aether.repository.RemoteRepository rr - = ( (DefaultRemoteRepository) repository ).getRepository(); + public ArtifactRepository toArtifactRepository(RemoteRepository repository) { + if (repository instanceof DefaultRemoteRepository) { + org.eclipse.aether.repository.RemoteRepository rr = ((DefaultRemoteRepository) repository).getRepository(); - try - { + try { return mavenRepositorySystem.createRepository( rr.getUrl(), rr.getId(), - rr.getPolicy( false ).isEnabled(), - rr.getPolicy( false ).getUpdatePolicy(), - rr.getPolicy( true ).isEnabled(), - rr.getPolicy( true ).getUpdatePolicy(), - rr.getPolicy( false ).getChecksumPolicy() + rr.getPolicy(false).isEnabled(), + rr.getPolicy(false).getUpdatePolicy(), + rr.getPolicy(true).isEnabled(), + rr.getPolicy(true).getUpdatePolicy(), + rr.getPolicy(false).getChecksumPolicy()); - ); + } catch (Exception e) { + throw new RuntimeException("Unable to create repository", e); } - catch ( Exception e ) - { - throw new RuntimeException( "Unable to create repository", e ); - } - } - else - { + } else { // TODO - throw new UnsupportedOperationException( "Not yet implemented" ); + throw new UnsupportedOperationException("Not yet implemented"); } } - public org.eclipse.aether.graph.Dependency toDependency( DependencyCoordinate dependency ) - { - if ( dependency instanceof DefaultDependencyCoordinate ) - { - return ( (DefaultDependencyCoordinate) dependency ).getDependency(); - } - else - { + public org.eclipse.aether.graph.Dependency toDependency(DependencyCoordinate dependency) { + if (dependency instanceof DefaultDependencyCoordinate) { + return ((DefaultDependencyCoordinate) dependency).getDependency(); + } else { return new org.eclipse.aether.graph.Dependency( new org.eclipse.aether.artifact.DefaultArtifact( dependency.getGroupId(), @@ -341,9 +293,8 @@ public class DefaultSession extends AbstractSession dependency.getClassifier(), dependency.getType().getExtension(), dependency.getVersion().toString(), - null ), - dependency.getScope().id() ); + null), + dependency.getScope().id()); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSessionFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSessionFactory.java index b0cb18d760..d2883d6fa7 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSessionFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSessionFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.Session; import org.apache.maven.bridge.MavenRepositorySystem; import org.apache.maven.execution.MavenSession; @@ -33,36 +31,32 @@ import org.eclipse.aether.SessionData; @Singleton @Named -public class DefaultSessionFactory -{ +public class DefaultSessionFactory { private final RepositorySystem repositorySystem; private final MavenRepositorySystem mavenRepositorySystem; private final PlexusContainer plexusContainer; private final RuntimeInformation runtimeInformation; @Inject - @SuppressWarnings( "checkstyle:ParameterNumber" ) - public DefaultSessionFactory( RepositorySystem repositorySystem, - MavenRepositorySystem mavenRepositorySystem, - PlexusContainer plexusContainer, - RuntimeInformation runtimeInformation ) - { + @SuppressWarnings("checkstyle:ParameterNumber") + public DefaultSessionFactory( + RepositorySystem repositorySystem, + MavenRepositorySystem mavenRepositorySystem, + PlexusContainer plexusContainer, + RuntimeInformation runtimeInformation) { this.repositorySystem = repositorySystem; this.mavenRepositorySystem = mavenRepositorySystem; this.plexusContainer = plexusContainer; this.runtimeInformation = runtimeInformation; } - public Session getSession( MavenSession mavenSession ) - { + public Session getSession(MavenSession mavenSession) { SessionData data = mavenSession.getRepositorySession().getData(); - return ( Session ) data.computeIfAbsent( DefaultSession.class, () -> newSession( mavenSession ) ); + return (Session) data.computeIfAbsent(DefaultSession.class, () -> newSession(mavenSession)); } - private Session newSession( MavenSession mavenSession ) - { + private Session newSession(MavenSession mavenSession) { return new DefaultSession( - mavenSession, repositorySystem, null, - mavenRepositorySystem, plexusContainer, runtimeInformation ); + mavenSession, repositorySystem, null, mavenRepositorySystem, plexusContainer, runtimeInformation); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsBuilder.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsBuilder.java index 8b7f598cb0..533b2959c9 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.BuilderProblem; import org.apache.maven.api.services.SettingsBuilder; @@ -45,144 +42,119 @@ import org.apache.maven.settings.building.SettingsSource; @Named @Singleton -public class DefaultSettingsBuilder implements SettingsBuilder -{ +public class DefaultSettingsBuilder implements SettingsBuilder { private final org.apache.maven.settings.building.SettingsBuilder builder; @Inject - public DefaultSettingsBuilder( org.apache.maven.settings.building.SettingsBuilder builder ) - { + public DefaultSettingsBuilder(org.apache.maven.settings.building.SettingsBuilder builder) { this.builder = builder; } @Nonnull @Override - public SettingsBuilderResult build( SettingsBuilderRequest request ) - throws SettingsBuilderException, IllegalArgumentException - { - DefaultSession session = ( DefaultSession ) request.getSession(); - try - { + public SettingsBuilderResult build(SettingsBuilderRequest request) + throws SettingsBuilderException, IllegalArgumentException { + DefaultSession session = (DefaultSession) request.getSession(); + try { DefaultSettingsBuildingRequest req = new DefaultSettingsBuildingRequest(); - req.setUserProperties( toProperties( session.getUserProperties() ) ); - req.setSystemProperties( toProperties( session.getSystemProperties() ) ); - if ( request.getGlobalSettingsSource().isPresent() ) - { - req.setGlobalSettingsSource( new MappedSettingsSource( request.getGlobalSettingsSource().get() ) ); + req.setUserProperties(toProperties(session.getUserProperties())); + req.setSystemProperties(toProperties(session.getSystemProperties())); + if (request.getGlobalSettingsSource().isPresent()) { + req.setGlobalSettingsSource(new MappedSettingsSource( + request.getGlobalSettingsSource().get())); } - if ( request.getGlobalSettingsPath().isPresent() ) - { - req.setGlobalSettingsFile( request.getGlobalSettingsPath().get().toFile() ); + if (request.getGlobalSettingsPath().isPresent()) { + req.setGlobalSettingsFile(request.getGlobalSettingsPath().get().toFile()); } - if ( request.getUserSettingsSource().isPresent() ) - { - req.setUserSettingsSource( new MappedSettingsSource( request.getUserSettingsSource().get() ) ); + if (request.getUserSettingsSource().isPresent()) { + req.setUserSettingsSource( + new MappedSettingsSource(request.getUserSettingsSource().get())); } - if ( request.getUserSettingsPath().isPresent() ) - { - req.setUserSettingsFile( request.getUserSettingsPath().get().toFile() ); + if (request.getUserSettingsPath().isPresent()) { + req.setUserSettingsFile(request.getUserSettingsPath().get().toFile()); } - SettingsBuildingResult result = builder.build( req ); - return new SettingsBuilderResult() - { + SettingsBuildingResult result = builder.build(req); + return new SettingsBuilderResult() { @Override - public Settings getEffectiveSettings() - { + public Settings getEffectiveSettings() { return result.getEffectiveSettings().getDelegate(); } @Override - public List getProblems() - { - return new MappedList<>( result.getProblems(), MappedBuilderProblem::new ); + public List getProblems() { + return new MappedList<>(result.getProblems(), MappedBuilderProblem::new); } }; - } - catch ( SettingsBuildingException e ) - { - throw new SettingsBuilderException( "Unable to build settings", e ); + } catch (SettingsBuildingException e) { + throw new SettingsBuilderException("Unable to build settings", e); } } - private Properties toProperties( Map map ) - { + private Properties toProperties(Map map) { Properties properties = new Properties(); - properties.putAll( map ); + properties.putAll(map); return properties; } - private static class MappedSettingsSource implements SettingsSource - { + private static class MappedSettingsSource implements SettingsSource { private final Source source; - MappedSettingsSource( Source source ) - { + MappedSettingsSource(Source source) { this.source = source; } @Override - public InputStream getInputStream() throws IOException - { + public InputStream getInputStream() throws IOException { return source.getInputStream(); } @Override - public String getLocation() - { + public String getLocation() { return source.getLocation(); } } - private static class MappedBuilderProblem implements BuilderProblem - { + private static class MappedBuilderProblem implements BuilderProblem { private final SettingsProblem problem; - MappedBuilderProblem( SettingsProblem problem ) - { + MappedBuilderProblem(SettingsProblem problem) { this.problem = problem; } @Override - public String getSource() - { + public String getSource() { return problem.getSource(); } @Override - public int getLineNumber() - { + public int getLineNumber() { return problem.getLineNumber(); } @Override - public int getColumnNumber() - { + public int getColumnNumber() { return problem.getColumnNumber(); } @Override - public String getLocation() - { + public String getLocation() { return problem.getLocation(); } @Override - public Exception getException() - { + public Exception getException() { return problem.getException(); } @Override - public String getMessage() - { + public String getMessage() { return problem.getMessage(); } @Override - public Severity getSeverity() - { - return Severity.valueOf( problem.getSeverity().name() ); + public Severity getSeverity() { + return Severity.valueOf(problem.getSeverity().name()); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsXmlFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsXmlFactory.java index a1f636a0e6..9b3dbe532a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsXmlFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultSettingsXmlFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,91 +16,71 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Objects; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.model.InputSource; import org.apache.maven.api.services.xml.SettingsXmlFactory; import org.apache.maven.api.services.xml.XmlReaderException; import org.apache.maven.api.services.xml.XmlReaderRequest; import org.apache.maven.api.services.xml.XmlWriterException; import org.apache.maven.api.services.xml.XmlWriterRequest; -import org.apache.maven.api.model.InputSource; import org.apache.maven.api.settings.Settings; import org.apache.maven.settings.v4.SettingsXpp3Reader; import org.apache.maven.settings.v4.SettingsXpp3Writer; @Named @Singleton -public class DefaultSettingsXmlFactory - implements SettingsXmlFactory -{ +public class DefaultSettingsXmlFactory implements SettingsXmlFactory { @Override - public Settings read( @Nonnull XmlReaderRequest request ) throws XmlReaderException - { - Objects.requireNonNull( request, "request can not be null" ); + public Settings read(@Nonnull XmlReaderRequest request) throws XmlReaderException { + Objects.requireNonNull(request, "request can not be null"); Reader reader = request.getReader(); InputStream inputStream = request.getInputStream(); - if ( reader == null && inputStream == null ) - { - throw new IllegalArgumentException( "reader or inputStream must be non null" ); + if (reader == null && inputStream == null) { + throw new IllegalArgumentException("reader or inputStream must be non null"); } - try - { + try { InputSource source = null; - if ( request.getModelId() != null || request.getLocation() != null ) - { - source = new InputSource( request.getModelId(), request.getLocation() ); + if (request.getModelId() != null || request.getLocation() != null) { + source = new InputSource(request.getModelId(), request.getLocation()); } SettingsXpp3Reader xml = new SettingsXpp3Reader(); - xml.setAddDefaultEntities( request.isAddDefaultEntities() ); - if ( reader != null ) - { - return xml.read( reader, request.isStrict() ); + xml.setAddDefaultEntities(request.isAddDefaultEntities()); + if (reader != null) { + return xml.read(reader, request.isStrict()); + } else { + return xml.read(inputStream, request.isStrict()); } - else - { - return xml.read( inputStream, request.isStrict() ); - } - } - catch ( Exception e ) - { - throw new XmlReaderException( "Unable to read settings", e ); + } catch (Exception e) { + throw new XmlReaderException("Unable to read settings", e); } } @Override - public void write( XmlWriterRequest request ) throws XmlWriterException - { - Objects.requireNonNull( request, "request can not be null" ); - Settings content = Objects.requireNonNull( request.getContent(), "content can not be null" ); + public void write(XmlWriterRequest request) throws XmlWriterException { + Objects.requireNonNull(request, "request can not be null"); + Settings content = Objects.requireNonNull(request.getContent(), "content can not be null"); OutputStream outputStream = request.getOutputStream(); Writer writer = request.getWriter(); - if ( writer == null && outputStream == null ) - { - throw new IllegalArgumentException( "writer or outputStream must be non null" ); + if (writer == null && outputStream == null) { + throw new IllegalArgumentException("writer or outputStream must be non null"); } - try - { - if ( writer != null ) - { - new SettingsXpp3Writer().write( writer, content ); + try { + if (writer != null) { + new SettingsXpp3Writer().write(writer, content); + } else { + new SettingsXpp3Writer().write(outputStream, content); } - else - { - new SettingsXpp3Writer().write( outputStream, content ); - } - } - catch ( Exception e ) - { - throw new XmlWriterException( "Unable to write settings", e ); + } catch (Exception e) { + throw new XmlWriterException("Unable to write settings", e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainManager.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainManager.java index 5348c48418..1541e596e4 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainManager.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.Session; import org.apache.maven.api.Toolchain; import org.apache.maven.api.services.ToolchainManager; @@ -39,91 +36,74 @@ import org.apache.maven.toolchain.ToolchainPrivate; @Named @Singleton -public class DefaultToolchainManager implements ToolchainManager -{ +public class DefaultToolchainManager implements ToolchainManager { private final DefaultToolchainManagerPrivate toolchainManagerPrivate; @Inject - public DefaultToolchainManager( DefaultToolchainManagerPrivate toolchainManagerPrivate ) - { + public DefaultToolchainManager(DefaultToolchainManagerPrivate toolchainManagerPrivate) { this.toolchainManagerPrivate = toolchainManagerPrivate; } @Override - public List getToolchains( Session session, String type, Map requirements ) - throws ToolchainManagerException - { - MavenSession s = ( ( DefaultSession ) session ).getMavenSession(); + public List getToolchains(Session session, String type, Map requirements) + throws ToolchainManagerException { + MavenSession s = ((DefaultSession) session).getMavenSession(); List toolchains = - toolchainManagerPrivate.getToolchains( s, type, requirements ); - return new MappedList<>( toolchains, this::toToolchain ); + toolchainManagerPrivate.getToolchains(s, type, requirements); + return new MappedList<>(toolchains, this::toToolchain); } @Override - public Optional getToolchainFromBuildContext( Session session, String type ) - throws ToolchainManagerException - { - MavenSession s = ( ( DefaultSession ) session ).getMavenSession(); - return Optional.ofNullable( toolchainManagerPrivate.getToolchainFromBuildContext( type, s ) ) - .map( this::toToolchain ); + public Optional getToolchainFromBuildContext(Session session, String type) + throws ToolchainManagerException { + MavenSession s = ((DefaultSession) session).getMavenSession(); + return Optional.ofNullable(toolchainManagerPrivate.getToolchainFromBuildContext(type, s)) + .map(this::toToolchain); } @Override - public List getToolchainsForType( Session session, String type ) - throws ToolchainManagerException - { - try - { - MavenSession s = ( (DefaultSession) session ).getMavenSession(); - ToolchainPrivate[] toolchains = toolchainManagerPrivate.getToolchainsForType( type, s ); - return new MappedList<>( Arrays.asList( toolchains ), this::toToolchain ); - } - catch ( MisconfiguredToolchainException e ) - { - throw new ToolchainManagerException( "Unable to get toochains for type " + type, e ); + public List getToolchainsForType(Session session, String type) throws ToolchainManagerException { + try { + MavenSession s = ((DefaultSession) session).getMavenSession(); + ToolchainPrivate[] toolchains = toolchainManagerPrivate.getToolchainsForType(type, s); + return new MappedList<>(Arrays.asList(toolchains), this::toToolchain); + } catch (MisconfiguredToolchainException e) { + throw new ToolchainManagerException("Unable to get toochains for type " + type, e); } } @Override - public void storeToolchainToBuildContext( Session session, Toolchain toolchain ) - throws ToolchainManagerException - { - MavenSession s = ( ( DefaultSession ) session ).getMavenSession(); + public void storeToolchainToBuildContext(Session session, Toolchain toolchain) throws ToolchainManagerException { + MavenSession s = ((DefaultSession) session).getMavenSession(); org.apache.maven.toolchain.ToolchainPrivate tc = - (org.apache.maven.toolchain.ToolchainPrivate) ( (ToolchainWrapper) toolchain ).toolchain; - toolchainManagerPrivate.storeToolchainToBuildContext( tc, s ); + (org.apache.maven.toolchain.ToolchainPrivate) ((ToolchainWrapper) toolchain).toolchain; + toolchainManagerPrivate.storeToolchainToBuildContext(tc, s); } - private Toolchain toToolchain( org.apache.maven.toolchain.Toolchain toolchain ) - { - return new ToolchainWrapper( toolchain ); + private Toolchain toToolchain(org.apache.maven.toolchain.Toolchain toolchain) { + return new ToolchainWrapper(toolchain); } - private static class ToolchainWrapper implements Toolchain - { + private static class ToolchainWrapper implements Toolchain { private final org.apache.maven.toolchain.Toolchain toolchain; - ToolchainWrapper( org.apache.maven.toolchain.Toolchain toolchain ) - { + ToolchainWrapper(org.apache.maven.toolchain.Toolchain toolchain) { this.toolchain = toolchain; } @Override - public String getType() - { + public String getType() { return toolchain.getType(); } @Override - public String findTool( String toolName ) - { - return toolchain.findTool( toolName ); + public String findTool(String toolName) { + return toolchain.findTool(toolName); } @Override - public boolean matchesRequirements( Map requirements ) - { - return ( (ToolchainPrivate) toolchain ).matchesRequirements( requirements ); + public boolean matchesRequirements(Map requirements) { + return ((ToolchainPrivate) toolchain).matchesRequirements(requirements); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsBuilder.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsBuilder.java index ef75abd4ce..076f0de85d 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,170 +16,141 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.BuilderProblem; +import org.apache.maven.api.services.Source; import org.apache.maven.api.services.ToolchainsBuilder; import org.apache.maven.api.services.ToolchainsBuilderException; import org.apache.maven.api.services.ToolchainsBuilderRequest; import org.apache.maven.api.services.ToolchainsBuilderResult; -import org.apache.maven.api.services.Source; +import org.apache.maven.api.toolchain.PersistedToolchains; import org.apache.maven.toolchain.building.DefaultToolchainsBuildingRequest; import org.apache.maven.toolchain.building.ToolchainsBuildingException; import org.apache.maven.toolchain.building.ToolchainsBuildingResult; -import org.apache.maven.api.toolchain.PersistedToolchains; @Named @Singleton -public class DefaultToolchainsBuilder implements ToolchainsBuilder -{ +public class DefaultToolchainsBuilder implements ToolchainsBuilder { private final org.apache.maven.toolchain.building.ToolchainsBuilder builder; @Inject - public DefaultToolchainsBuilder( org.apache.maven.toolchain.building.ToolchainsBuilder builder ) - { + public DefaultToolchainsBuilder(org.apache.maven.toolchain.building.ToolchainsBuilder builder) { this.builder = builder; } @Nonnull @Override - public ToolchainsBuilderResult build( ToolchainsBuilderRequest request ) - throws ToolchainsBuilderException, IllegalArgumentException - { - DefaultSession session = ( DefaultSession ) request.getSession(); - try - { + public ToolchainsBuilderResult build(ToolchainsBuilderRequest request) + throws ToolchainsBuilderException, IllegalArgumentException { + DefaultSession session = (DefaultSession) request.getSession(); + try { DefaultToolchainsBuildingRequest req = new DefaultToolchainsBuildingRequest(); - if ( request.getGlobalToolchainsSource().isPresent() ) - { - req.setGlobalToolchainsSource( - new MappedToolchainsSource( request.getGlobalToolchainsSource().get() ) ); + if (request.getGlobalToolchainsSource().isPresent()) { + req.setGlobalToolchainsSource(new MappedToolchainsSource( + request.getGlobalToolchainsSource().get())); + } else if (request.getGlobalToolchainsPath().isPresent()) { + req.setGlobalToolchainsSource(new org.apache.maven.building.FileSource( + request.getGlobalToolchainsPath().get().toFile())); } - else if ( request.getGlobalToolchainsPath().isPresent() ) - { - req.setGlobalToolchainsSource( new org.apache.maven.building.FileSource( - request.getGlobalToolchainsPath().get().toFile() ) ); + if (request.getUserToolchainsSource().isPresent()) { + req.setUserToolchainsSource(new MappedToolchainsSource( + request.getUserToolchainsSource().get())); + } else if (request.getUserToolchainsPath().isPresent()) { + req.setUserToolchainsSource(new org.apache.maven.building.FileSource( + request.getUserToolchainsPath().get().toFile())); } - if ( request.getUserToolchainsSource().isPresent() ) - { - req.setUserToolchainsSource( new MappedToolchainsSource( request.getUserToolchainsSource().get() ) ); - } - else if ( request.getUserToolchainsPath().isPresent() ) - { - req.setUserToolchainsSource( new org.apache.maven.building.FileSource( - request.getUserToolchainsPath().get().toFile() ) ); - } - ToolchainsBuildingResult result = builder.build( req ); - return new ToolchainsBuilderResult() - { + ToolchainsBuildingResult result = builder.build(req); + return new ToolchainsBuilderResult() { @Override - public PersistedToolchains getEffectiveToolchains() - { + public PersistedToolchains getEffectiveToolchains() { return result.getEffectiveToolchains().getDelegate(); } @Override - public List getProblems() - { - return new MappedList<>( result.getProblems(), MappedBuilderProblem::new ); + public List getProblems() { + return new MappedList<>(result.getProblems(), MappedBuilderProblem::new); } }; - } - catch ( ToolchainsBuildingException e ) - { - throw new ToolchainsBuilderException( "Unable to build Toolchains", e ); + } catch (ToolchainsBuildingException e) { + throw new ToolchainsBuilderException("Unable to build Toolchains", e); } } - private Properties toProperties( Map map ) - { + private Properties toProperties(Map map) { Properties properties = new Properties(); - properties.putAll( map ); + properties.putAll(map); return properties; } - private static class MappedToolchainsSource implements org.apache.maven.building.Source - { + private static class MappedToolchainsSource implements org.apache.maven.building.Source { private final Source source; - MappedToolchainsSource( Source source ) - { + MappedToolchainsSource(Source source) { this.source = source; } @Override - public InputStream getInputStream() throws IOException - { + public InputStream getInputStream() throws IOException { return source.getInputStream(); } @Override - public String getLocation() - { + public String getLocation() { return source.getLocation(); } } - private static class MappedBuilderProblem implements BuilderProblem - { + private static class MappedBuilderProblem implements BuilderProblem { private final org.apache.maven.building.Problem problem; - MappedBuilderProblem( org.apache.maven.building.Problem problem ) - { + MappedBuilderProblem(org.apache.maven.building.Problem problem) { this.problem = problem; } @Override - public String getSource() - { + public String getSource() { return problem.getSource(); } @Override - public int getLineNumber() - { + public int getLineNumber() { return problem.getLineNumber(); } @Override - public int getColumnNumber() - { + public int getColumnNumber() { return problem.getColumnNumber(); } @Override - public String getLocation() - { + public String getLocation() { return problem.getLocation(); } @Override - public Exception getException() - { + public Exception getException() { return problem.getException(); } @Override - public String getMessage() - { + public String getMessage() { return problem.getMessage(); } @Override - public Severity getSeverity() - { - return Severity.valueOf( problem.getSeverity().name() ); + public Severity getSeverity() { + return Severity.valueOf(problem.getSeverity().name()); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsXmlFactory.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsXmlFactory.java index 21b499c79b..2d1b80bff6 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsXmlFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsXmlFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,92 +16,71 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Objects; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.model.InputSource; import org.apache.maven.api.services.xml.ToolchainsXmlFactory; import org.apache.maven.api.services.xml.XmlReaderException; import org.apache.maven.api.services.xml.XmlReaderRequest; import org.apache.maven.api.services.xml.XmlWriterException; import org.apache.maven.api.services.xml.XmlWriterRequest; -import org.apache.maven.api.model.InputSource; import org.apache.maven.api.toolchain.PersistedToolchains; import org.apache.maven.toolchain.v4.MavenToolchainsXpp3Reader; import org.apache.maven.toolchain.v4.MavenToolchainsXpp3Writer; - @Named @Singleton -public class DefaultToolchainsXmlFactory - implements ToolchainsXmlFactory -{ +public class DefaultToolchainsXmlFactory implements ToolchainsXmlFactory { @Override - public PersistedToolchains read( @Nonnull XmlReaderRequest request ) throws XmlReaderException - { - Objects.requireNonNull( request, "request can not be null" ); + public PersistedToolchains read(@Nonnull XmlReaderRequest request) throws XmlReaderException { + Objects.requireNonNull(request, "request can not be null"); Reader reader = request.getReader(); InputStream inputStream = request.getInputStream(); - if ( reader == null && inputStream == null ) - { - throw new IllegalArgumentException( "reader or inputStream must be non null" ); + if (reader == null && inputStream == null) { + throw new IllegalArgumentException("reader or inputStream must be non null"); } - try - { + try { InputSource source = null; - if ( request.getModelId() != null || request.getLocation() != null ) - { - source = new InputSource( request.getModelId(), request.getLocation() ); + if (request.getModelId() != null || request.getLocation() != null) { + source = new InputSource(request.getModelId(), request.getLocation()); } MavenToolchainsXpp3Reader xml = new MavenToolchainsXpp3Reader(); - xml.setAddDefaultEntities( request.isAddDefaultEntities() ); - if ( reader != null ) - { - return xml.read( reader, request.isStrict() ); + xml.setAddDefaultEntities(request.isAddDefaultEntities()); + if (reader != null) { + return xml.read(reader, request.isStrict()); + } else { + return xml.read(inputStream, request.isStrict()); } - else - { - return xml.read( inputStream, request.isStrict() ); - } - } - catch ( Exception e ) - { - throw new XmlReaderException( "Unable to read toolchains", e ); + } catch (Exception e) { + throw new XmlReaderException("Unable to read toolchains", e); } } @Override - public void write( XmlWriterRequest request ) throws XmlWriterException - { - Objects.requireNonNull( request, "request can not be null" ); - PersistedToolchains content = Objects.requireNonNull( request.getContent(), "content can not be null" ); + public void write(XmlWriterRequest request) throws XmlWriterException { + Objects.requireNonNull(request, "request can not be null"); + PersistedToolchains content = Objects.requireNonNull(request.getContent(), "content can not be null"); OutputStream outputStream = request.getOutputStream(); Writer writer = request.getWriter(); - if ( writer == null && outputStream == null ) - { - throw new IllegalArgumentException( "writer or outputStream must be non null" ); + if (writer == null && outputStream == null) { + throw new IllegalArgumentException("writer or outputStream must be non null"); } - try - { - if ( writer != null ) - { - new MavenToolchainsXpp3Writer().write( writer, content ); + try { + if (writer != null) { + new MavenToolchainsXpp3Writer().write(writer, content); + } else { + new MavenToolchainsXpp3Writer().write(outputStream, content); } - else - { - new MavenToolchainsXpp3Writer().write( outputStream, content ); - } - } - catch ( Exception e ) - { - throw new XmlWriterException( "Unable to write toolchains", e ); + } catch (Exception e) { + throw new XmlWriterException("Unable to write toolchains", e); } } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultTypeRegistry.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultTypeRegistry.java index 691e64588e..fc058ec30a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultTypeRegistry.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultTypeRegistry.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,74 +16,64 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; + +import static org.apache.maven.internal.impl.Utils.nonNull; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.Type; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.services.TypeRegistry; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultTypeRegistry implements TypeRegistry -{ +public class DefaultTypeRegistry implements TypeRegistry { private final ArtifactHandlerManager manager; @Inject - public DefaultTypeRegistry( ArtifactHandlerManager manager ) - { - this.manager = nonNull( manager, "artifactHandlerManager" ); + public DefaultTypeRegistry(ArtifactHandlerManager manager) { + this.manager = nonNull(manager, "artifactHandlerManager"); } @Override @Nonnull - public Type getType( String id ) - { + public Type getType(String id) { // Copy data as the ArtifacHandler is not immutable, but Type should be. - ArtifactHandler handler = manager.getArtifactHandler( nonNull( id , "id" ) ); + ArtifactHandler handler = manager.getArtifactHandler(nonNull(id, "id")); String extension = handler.getExtension(); String classifier = handler.getClassifier(); boolean includeDependencies = handler.isIncludesDependencies(); boolean addedToClasspath = handler.isAddedToClasspath(); - return new Type() - { + return new Type() { @Override - public String getName() - { + public String getName() { return id; } @Override - public String getExtension() - { + public String getExtension() { return extension; } @Override - public String getClassifier() - { + public String getClassifier() { return classifier; } @Override - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return includeDependencies; } @Override - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return addedToClasspath; } }; } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultVersionParser.java b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultVersionParser.java index 9ea1cb209d..a3fd719837 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultVersionParser.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultVersionParser.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,13 +16,15 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import javax.inject.Named; -import javax.inject.Singleton; +import static org.apache.maven.artifact.versioning.VersionRange.createFromVersionSpec; +import static org.apache.maven.internal.impl.Utils.nonNull; import java.util.Objects; import java.util.regex.Pattern; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.Version; import org.apache.maven.api.VersionRange; import org.apache.maven.api.services.VersionParser; @@ -33,133 +33,102 @@ import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; -import static org.apache.maven.artifact.versioning.VersionRange.createFromVersionSpec; -import static org.apache.maven.internal.impl.Utils.nonNull; - @Named @Singleton -public class DefaultVersionParser implements VersionParser -{ +public class DefaultVersionParser implements VersionParser { private static final String SNAPSHOT = "SNAPSHOT"; - private static final Pattern SNAPSHOT_TIMESTAMP = Pattern.compile( "^(.*-)?([0-9]{8}\\.[0-9]{6}-[0-9]+)$" ); + private static final Pattern SNAPSHOT_TIMESTAMP = Pattern.compile("^(.*-)?([0-9]{8}\\.[0-9]{6}-[0-9]+)$"); @Override - public Version parseVersion( String version ) - { - return new DefaultVersion( new DefaultArtifactVersion( nonNull( version, "version" ) ) ); + public Version parseVersion(String version) { + return new DefaultVersion(new DefaultArtifactVersion(nonNull(version, "version"))); } @Override - public VersionRange parseVersionRange( String range ) - { - try - { - return new DefaultVersionRange( createFromVersionSpec( nonNull( range, "version" ) ) ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new VersionParserException( "Unable to parse version range: " + range, e ); + public VersionRange parseVersionRange(String range) { + try { + return new DefaultVersionRange(createFromVersionSpec(nonNull(range, "version"))); + } catch (InvalidVersionSpecificationException e) { + throw new VersionParserException("Unable to parse version range: " + range, e); } } @Override - public boolean isSnapshot( String version ) - { - return checkSnapshot( version ); + public boolean isSnapshot(String version) { + return checkSnapshot(version); } - static boolean checkSnapshot( String version ) - { - return version.endsWith( SNAPSHOT ) || SNAPSHOT_TIMESTAMP.matcher( version ).matches(); + static boolean checkSnapshot(String version) { + return version.endsWith(SNAPSHOT) || SNAPSHOT_TIMESTAMP.matcher(version).matches(); } - static class DefaultVersion implements Version - { + static class DefaultVersion implements Version { private final ArtifactVersion delegate; - DefaultVersion( ArtifactVersion delegate ) - { + DefaultVersion(ArtifactVersion delegate) { this.delegate = delegate; } @Override - public int compareTo( Version o ) - { - if ( o instanceof DefaultVersion ) - { - return delegate.compareTo( ( ( DefaultVersion ) o ).delegate ); - } - else - { - return delegate.compareTo( new DefaultArtifactVersion( o.toString() ) ); + public int compareTo(Version o) { + if (o instanceof DefaultVersion) { + return delegate.compareTo(((DefaultVersion) o).delegate); + } else { + return delegate.compareTo(new DefaultArtifactVersion(o.toString())); } } @Override - 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; } DefaultVersion that = (DefaultVersion) o; - return delegate.equals( that.delegate ); + return delegate.equals(that.delegate); } @Override - public int hashCode() - { - return Objects.hash( delegate ); + public int hashCode() { + return Objects.hash(delegate); } @Override - public String asString() - { + public String asString() { return delegate.toString(); } @Override - public String toString() - { + public String toString() { return asString(); } } - static class DefaultVersionRange implements VersionRange - { + static class DefaultVersionRange implements VersionRange { private final org.apache.maven.artifact.versioning.VersionRange delegate; - DefaultVersionRange( org.apache.maven.artifact.versioning.VersionRange delegate ) - { + DefaultVersionRange(org.apache.maven.artifact.versioning.VersionRange delegate) { this.delegate = delegate; } @Override - public boolean contains( Version version ) - { - if ( version instanceof DefaultVersion ) - { - return delegate.containsVersion( ( ( DefaultVersion ) version ).delegate ); - } - else - { - return delegate.containsVersion( new DefaultArtifactVersion( version.toString() ) ); + public boolean contains(Version version) { + if (version instanceof DefaultVersion) { + return delegate.containsVersion(((DefaultVersion) version).delegate); + } else { + return delegate.containsVersion(new DefaultArtifactVersion(version.toString())); } } @Override - public String asString() - { + public String asString() { return delegate.toString(); } @Override - public String toString() - { + public String toString() { return asString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java b/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java index 255625e491..4edaef3acc 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,13 +16,12 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; +import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - -import java.util.Collection; - import org.apache.maven.api.Event; import org.apache.maven.api.Listener; import org.apache.maven.eventspy.EventSpy; @@ -32,44 +29,33 @@ import org.apache.maven.execution.ExecutionEvent; @Named @Singleton -public class EventSpyImpl implements EventSpy -{ +public class EventSpyImpl implements EventSpy { private DefaultSessionFactory sessionFactory; @Inject - EventSpyImpl( DefaultSessionFactory sessionFactory ) - { + EventSpyImpl(DefaultSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override - public void init( Context context ) throws Exception - { - } + public void init(Context context) throws Exception {} @Override - public void onEvent( Object arg ) throws Exception - { - if ( arg instanceof ExecutionEvent ) - { + public void onEvent(Object arg) throws Exception { + if (arg instanceof ExecutionEvent) { ExecutionEvent ee = (ExecutionEvent) arg; - AbstractSession session = ( AbstractSession ) sessionFactory.getSession( ee.getSession() ); + AbstractSession session = (AbstractSession) sessionFactory.getSession(ee.getSession()); Collection listeners = session.getListeners(); - if ( !listeners.isEmpty() ) - { - Event event = new DefaultEvent( session, ee ); - for ( Listener listener : listeners ) - { - listener.onEvent( event ); + if (!listeners.isEmpty()) { + Event event = new DefaultEvent(session, ee); + for (Listener listener : listeners) { + listener.onEvent(event); } } } } @Override - public void close() throws Exception - { - } - + public void close() throws Exception {} } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/MappedCollection.java b/maven-core/src/main/java/org/apache/maven/internal/impl/MappedCollection.java index 32310800f6..3492e9c6a3 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/MappedCollection.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/MappedCollection.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,46 +16,40 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.function.Function; -public class MappedCollection extends AbstractCollection -{ +public class MappedCollection extends AbstractCollection { private final Collection list; private final Function mapper; - public MappedCollection( Collection list, Function mapper ) - { + public MappedCollection(Collection list, Function mapper) { this.list = list; this.mapper = mapper; } @Override - public Iterator iterator() - { + public Iterator iterator() { Iterator it = list.iterator(); - return new Iterator() - { + return new Iterator() { @Override - public boolean hasNext() - { + public boolean hasNext() { return it.hasNext(); } @Override - public U next() - { - return mapper.apply( it.next() ); + public U next() { + return mapper.apply(it.next()); } }; } @Override - public int size() - { + public int size() { return list.size(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/MappedList.java b/maven-core/src/main/java/org/apache/maven/internal/impl/MappedList.java index e68f25941c..78e590338e 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/MappedList.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/MappedList.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,31 +16,28 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.AbstractList; import java.util.List; import java.util.function.Function; -public class MappedList extends AbstractList -{ +public class MappedList extends AbstractList { private final List list; private final Function mapper; - public MappedList( List list, Function mapper ) - { + public MappedList(List list, Function mapper) { this.list = list; this.mapper = mapper; } @Override - public U get( int index ) - { - return mapper.apply( list.get( index ) ); + public U get(int index) { + return mapper.apply(list.get(index)); } @Override - public int size() - { + public int size() { return list.size(); } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java b/maven-core/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java index 78fd841f11..dbb383556a 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.AbstractMap; import java.util.AbstractSet; @@ -26,59 +25,46 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; -class PropertiesAsMap extends AbstractMap -{ +class PropertiesAsMap extends AbstractMap { private final Map properties; - PropertiesAsMap( Map properties ) - { + PropertiesAsMap(Map properties) { this.properties = properties; } @Override - public Set> entrySet() - { - return new AbstractSet>() - { + public Set> entrySet() { + return new AbstractSet>() { @Override - public Iterator> iterator() - { + public Iterator> iterator() { Iterator> iterator = properties.entrySet().iterator(); - return new Iterator>() - { + return new Iterator>() { Entry next; { advance(); } - private void advance() - { + private void advance() { next = null; - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { Entry e = iterator.next(); - if ( PropertiesAsMap.matches( e ) ) - { - next = new Entry() - { + if (PropertiesAsMap.matches(e)) { + next = new Entry() { @Override - public String getKey() - { + public String getKey() { return (String) e.getKey(); } @Override - public String getValue() - { + public String getValue() { return (String) e.getValue(); } @Override - public String setValue( String value ) - { - return (String) e.setValue( value ); + public String setValue(String value) { + return (String) e.setValue(value); } }; break; @@ -87,17 +73,14 @@ class PropertiesAsMap extends AbstractMap } @Override - public boolean hasNext() - { + public boolean hasNext() { return next != null; } @Override - public Entry next() - { + public Entry next() { Entry item = next; - if ( item == null ) - { + if (item == null) { throw new NoSuchElementException(); } advance(); @@ -107,18 +90,15 @@ class PropertiesAsMap extends AbstractMap } @Override - public int size() - { - return (int) properties.entrySet() - .stream().filter( PropertiesAsMap::matches ) + public int size() { + return (int) properties.entrySet().stream() + .filter(PropertiesAsMap::matches) .count(); } }; } - private static boolean matches( Entry entry ) - { - return entry.getKey() instanceof String - && entry.getValue() instanceof String; + private static boolean matches(Entry entry) { + return entry.getKey() instanceof String && entry.getValue() instanceof String; } } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/Utils.java b/maven-core/src/main/java/org/apache/maven/internal/impl/Utils.java index 675f397017..e96a807fcd 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/Utils.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/Utils.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,34 +16,27 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -class Utils -{ - static T nonNull( T t ) - { - if ( t == null ) - { +class Utils { + static T nonNull(T t) { + if (t == null) { throw new IllegalArgumentException(); } return t; } - static T nonNull( T t, String message ) - { - if ( t == null ) - { - throw new IllegalArgumentException( message ); + static T nonNull(T t, String message) { + if (t == null) { + throw new IllegalArgumentException(message); } return t; } - static T cast( Class clazz, Object o, String message ) - { - if ( ! clazz.isInstance( o ) ) - { - throw new IllegalArgumentException( message ); + static T cast(Class clazz, Object o, String message) { + if (!clazz.isInstance(o)) { + throw new IllegalArgumentException(message); } - return clazz.cast( o ); + return clazz.cast(o); } - } diff --git a/maven-core/src/main/java/org/apache/maven/internal/impl/WrapperNode.java b/maven-core/src/main/java/org/apache/maven/internal/impl/WrapperNode.java index 066df38fa4..6f3cdb8887 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/impl/WrapperNode.java +++ b/maven-core/src/main/java/org/apache/maven/internal/impl/WrapperNode.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.impl; * "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 + * 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 @@ -18,64 +16,56 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import java.util.List; import java.util.Optional; - import org.apache.maven.api.Dependency; import org.apache.maven.api.Node; import org.apache.maven.api.RemoteRepository; import org.apache.maven.api.annotations.Nonnull; import org.eclipse.aether.graph.DependencyNode; -class WrapperNode extends AbstractNode -{ +class WrapperNode extends AbstractNode { protected final Node delegate; protected final List children; - WrapperNode( Node delegate, List children ) - { + WrapperNode(Node delegate, List children) { this.delegate = delegate; this.children = children; } @Override - DependencyNode getDependencyNode() - { - return Utils.cast( AbstractNode.class, delegate, - "delegate is not an instance of AbstractNode" ).getDependencyNode(); + DependencyNode getDependencyNode() { + return Utils.cast(AbstractNode.class, delegate, "delegate is not an instance of AbstractNode") + .getDependencyNode(); } @Override - public List getChildren() - { + public List getChildren() { return children; } @Override - public Dependency getDependency() - { + public Dependency getDependency() { return delegate.getDependency(); } @Override @Nonnull - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return delegate.getRemoteRepositories(); } @Override @Nonnull - public Optional getRepository() - { + public Optional getRepository() { return delegate.getRepository(); } @Override @Nonnull - public String asString() - { + public String asString() { return delegate.asString(); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycleExecutor.java b/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycleExecutor.java index c8b4c2d766..c43ea01768 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycleExecutor.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycleExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,15 +16,14 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.Arrays; import java.util.List; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.LifecycleExecutionPlanCalculator; import org.apache.maven.lifecycle.internal.LifecycleStarter; @@ -58,9 +55,7 @@ import org.apache.maven.project.MavenProject; */ @Named @Singleton -public class DefaultLifecycleExecutor - implements LifecycleExecutor -{ +public class DefaultLifecycleExecutor implements LifecycleExecutor { private final LifeCyclePluginAnalyzer lifeCyclePluginAnalyzer; private final DefaultLifecycles defaultLifeCycles; @@ -78,8 +73,7 @@ public class DefaultLifecycleExecutor LifecycleExecutionPlanCalculator lifecycleExecutionPlanCalculator, MojoExecutor mojoExecutor, LifecycleStarter lifecycleStarter, - MojoDescriptorCreator mojoDescriptorCreator ) - { + MojoDescriptorCreator mojoDescriptorCreator) { this.lifeCyclePluginAnalyzer = lifeCyclePluginAnalyzer; this.defaultLifeCycles = defaultLifeCycles; this.lifecycleTaskSegmentCalculator = lifecycleTaskSegmentCalculator; @@ -89,9 +83,8 @@ public class DefaultLifecycleExecutor this.mojoDescriptorCreator = mojoDescriptorCreator; } - public void execute( MavenSession session ) - { - lifecycleStarter.execute( session ); + public void execute(MavenSession session) { + lifecycleStarter.execute(session); } // These methods deal with construction intact Plugin object that look like they come from a standard @@ -106,58 +99,50 @@ public class DefaultLifecycleExecutor // TODO This whole method could probably removed by injecting lifeCyclePluginAnalyzer straight into client site. // TODO But for some reason the whole plexus appcontext refuses to start when I try this. - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { - return lifeCyclePluginAnalyzer.getPluginsBoundByDefaultToAllLifecycles( packaging ); + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { + return lifeCyclePluginAnalyzer.getPluginsBoundByDefaultToAllLifecycles(packaging); } // Used by m2eclipse - @SuppressWarnings( { "UnusedDeclaration" } ) - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, boolean setup, String... tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, - PluginVersionResolutionException - { + @SuppressWarnings({"UnusedDeclaration"}) + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, boolean setup, String... tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, + PluginVersionResolutionException { List taskSegments = - lifecycleTaskSegmentCalculator.calculateTaskSegments( session, Arrays.asList( tasks ) ); + lifecycleTaskSegmentCalculator.calculateTaskSegments(session, Arrays.asList(tasks)); - TaskSegment mergedSegment = new TaskSegment( false ); + TaskSegment mergedSegment = new TaskSegment(false); - for ( TaskSegment taskSegment : taskSegments ) - { - mergedSegment.getTasks().addAll( taskSegment.getTasks() ); + for (TaskSegment taskSegment : taskSegments) { + mergedSegment.getTasks().addAll(taskSegment.getTasks()); } - return lifecycleExecutionPlanCalculator.calculateExecutionPlan( session, session.getCurrentProject(), - mergedSegment.getTasks(), setup ); + return lifecycleExecutionPlanCalculator.calculateExecutionPlan( + session, session.getCurrentProject(), mergedSegment.getTasks(), setup); } - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, String... tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, - PluginVersionResolutionException - { - return calculateExecutionPlan( session, true, tasks ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, String... tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, + PluginVersionResolutionException { + return calculateExecutionPlan(session, true, tasks); } // Site 3.x - public void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { - lifecycleExecutionPlanCalculator.calculateForkedExecutions( mojoExecution, session ); + public void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { + lifecycleExecutionPlanCalculator.calculateForkedExecutions(mojoExecution, session); } // Site 3.x - public List executeForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws LifecycleExecutionException - { - return mojoExecutor.executeForkedExecutions( mojoExecution, session, - new ProjectIndex( session.getProjects() ) ); + public List executeForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws LifecycleExecutionException { + return mojoExecutor.executeForkedExecutions(mojoExecution, session, new ProjectIndex(session.getProjects())); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycles.java b/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycles.java index c29791119a..2c3af74a73 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycles.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/DefaultLifecycles.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.Arrays; import java.util.Comparator; @@ -26,11 +25,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.slf4j.Logger; @@ -45,24 +42,21 @@ import org.slf4j.LoggerFactory; // wiring and reference and external source for the lifecycle configuration. @Named @Singleton -public class DefaultLifecycles -{ - public static final String[] STANDARD_LIFECYCLES = { "clean", "default", "site", "wrapper" }; +public class DefaultLifecycles { + public static final String[] STANDARD_LIFECYCLES = {"clean", "default", "site", "wrapper"}; - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); // @Configuration(source="org/apache/maven/lifecycle/lifecycles.xml") private final PlexusContainer plexusContainer; - public DefaultLifecycles() - { + public DefaultLifecycles() { this.plexusContainer = null; } @Inject - public DefaultLifecycles( PlexusContainer plexusContainer ) - { + public DefaultLifecycles(PlexusContainer plexusContainer) { this.plexusContainer = plexusContainer; } @@ -72,9 +66,8 @@ public class DefaultLifecycles * @param phase * @return */ - public Lifecycle get( String phase ) - { - return getPhaseToLifecycleMap().get( phase ); + public Lifecycle get(String phase) { + return getPhaseToLifecycleMap().get(phase); } /** @@ -83,32 +76,25 @@ public class DefaultLifecycles * * @return A map of lifecycles, indexed on id */ - public Map getPhaseToLifecycleMap() - { + public Map getPhaseToLifecycleMap() { // If people are going to make their own lifecycles then we need to tell people how to namespace them correctly // so that they don't interfere with internally defined lifecycles. Map phaseToLifecycleMap = new HashMap<>(); - for ( Lifecycle lifecycle : getLifeCycles() ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Lifecycle " + lifecycle ); + for (Lifecycle lifecycle : getLifeCycles()) { + if (logger.isDebugEnabled()) { + logger.debug("Lifecycle " + lifecycle); } - for ( String phase : lifecycle.getPhases() ) - { + for (String phase : lifecycle.getPhases()) { // The first definition wins. - if ( !phaseToLifecycleMap.containsKey( phase ) ) - { - phaseToLifecycleMap.put( phase, lifecycle ); - } - else - { - Lifecycle original = phaseToLifecycleMap.get( phase ); - logger.warn( "Duplicated lifecycle phase " + phase + ". Defined in " + original.getId() - + " but also in " + lifecycle.getId() ); + if (!phaseToLifecycleMap.containsKey(phase)) { + phaseToLifecycleMap.put(phase, lifecycle); + } else { + Lifecycle original = phaseToLifecycleMap.get(phase); + logger.warn("Duplicated lifecycle phase " + phase + ". Defined in " + original.getId() + + " but also in " + lifecycle.getId()); } } } @@ -119,21 +105,16 @@ public class DefaultLifecycles /** * Returns an ordered list of lifecycles */ - public List getLifeCycles() - { - List lifecycleIds = Arrays.asList( STANDARD_LIFECYCLES ); + public List getLifeCycles() { + List lifecycleIds = Arrays.asList(STANDARD_LIFECYCLES); - Comparator comparator = ( l, r ) -> - { - int lx = lifecycleIds.indexOf( l ); - int rx = lifecycleIds.indexOf( r ); + Comparator comparator = (l, r) -> { + int lx = lifecycleIds.indexOf(l); + int rx = lifecycleIds.indexOf(r); - if ( lx < 0 || rx < 0 ) - { + if (lx < 0 || rx < 0) { return rx - lx; - } - else - { + } else { return lx - rx; } }; @@ -142,36 +123,27 @@ public class DefaultLifecycles // ensure canonical order of standard lifecycles return lifecyclesMap.values().stream() - .peek( l -> Objects.requireNonNull( l.getId(), "A lifecycle must have an id." ) ) - .sorted( Comparator.comparing( Lifecycle::getId, comparator ) ) - .collect( Collectors.toList() ); + .peek(l -> Objects.requireNonNull(l.getId(), "A lifecycle must have an id.")) + .sorted(Comparator.comparing(Lifecycle::getId, comparator)) + .collect(Collectors.toList()); } - private Map lookupLifecycles() - { + private Map lookupLifecycles() { // TODO: Remove the following code when maven-compat is gone // This code is here to ensure maven-compat's EmptyLifecycleExecutor keeps on working. - if ( plexusContainer == null ) - { + if (plexusContainer == null) { return new HashMap<>(); } // Lifecycles cannot be cached as extensions might add custom lifecycles later in the execution. - try - { - return plexusContainer.lookupMap( Lifecycle.class ); - } - catch ( ComponentLookupException e ) - { - throw new IllegalStateException( "Unable to lookup lifecycles from the plexus container", e ); + try { + return plexusContainer.lookupMap(Lifecycle.class); + } catch (ComponentLookupException e) { + throw new IllegalStateException("Unable to lookup lifecycles from the plexus container", e); } } - public String getLifecyclePhaseList() - { - return getLifeCycles().stream() - .flatMap( l -> l.getPhases().stream() ) - .collect( Collectors.joining( ", " ) ); + public String getLifecyclePhaseList() { + return getLifeCycles().stream().flatMap(l -> l.getPhases().stream()).collect(Collectors.joining(", ")); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/LifeCyclePluginAnalyzer.java b/maven-core/src/main/java/org/apache/maven/lifecycle/LifeCyclePluginAnalyzer.java index ed07c1d5e7..d16e9a44ef 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/LifeCyclePluginAnalyzer.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/LifeCyclePluginAnalyzer.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.Set; import org.apache.maven.model.Plugin; @@ -26,7 +25,6 @@ import org.apache.maven.model.Plugin; * @since 3.0 * @author Kristian Rosenvold */ -public interface LifeCyclePluginAnalyzer -{ - Set getPluginsBoundByDefaultToAllLifecycles( String packaging ); +public interface LifeCyclePluginAnalyzer { + Set getPluginsBoundByDefaultToAllLifecycles(String packaging); } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/Lifecycle.java b/maven-core/src/main/java/org/apache/maven/lifecycle/Lifecycle.java index 43a674e743..190071ba72 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/Lifecycle.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/Lifecycle.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,23 +16,19 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.List; import java.util.Map; - import org.apache.maven.lifecycle.mapping.LifecyclePhase; /** * Lifecycle definition, with eventual plugin bindings (when they are not packaging-specific). */ -public class Lifecycle -{ - public Lifecycle() - { - } +public class Lifecycle { + public Lifecycle() {} - public Lifecycle( String id, List phases, Map defaultPhases ) - { + public Lifecycle(String id, List phases, Map defaultPhases) { this.id = id; this.phases = phases; this.defaultPhases = defaultPhases; @@ -58,31 +52,25 @@ public class Lifecycle private Map defaultPhases; - public String getId() - { + public String getId() { return this.id; } - public List getPhases() - { + public List getPhases() { return this.phases; } - public Map getDefaultLifecyclePhases() - { + public Map getDefaultLifecyclePhases() { return defaultPhases; } @Deprecated - public Map getDefaultPhases() - { - return LifecyclePhase.toLegacyMap( getDefaultLifecyclePhases() ); + public Map getDefaultPhases() { + return LifecyclePhase.toLegacyMap(getDefaultLifecyclePhases()); } @Override - public String toString() - { + public String toString() { return id + " -> " + phases; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutionException.java b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutionException.java index 0831a4f901..2bbc050424 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutionException.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; @@ -28,80 +27,70 @@ import org.apache.maven.shared.utils.logging.MessageBuilder; /** * @author Jason van Zyl */ -public class LifecycleExecutionException - extends Exception -{ +public class LifecycleExecutionException extends Exception { private MavenProject project; - public LifecycleExecutionException( String message ) - { - super( message ); + public LifecycleExecutionException(String message) { + super(message); } - public LifecycleExecutionException( Throwable cause ) - { - super( cause ); + public LifecycleExecutionException(Throwable cause) { + super(cause); } - public LifecycleExecutionException( String message, Throwable cause ) - { - super( message, cause ); + public LifecycleExecutionException(String message, Throwable cause) { + super(message, cause); } - public LifecycleExecutionException( String message, MavenProject project ) - { - super( message ); + public LifecycleExecutionException(String message, MavenProject project) { + super(message); this.project = project; } - public LifecycleExecutionException( String message, MojoExecution execution, MavenProject project ) - { - super( message ); + public LifecycleExecutionException(String message, MojoExecution execution, MavenProject project) { + super(message); this.project = project; } - public LifecycleExecutionException( String message, MojoExecution execution, MavenProject project, Throwable cause ) - { - super( message, cause ); + public LifecycleExecutionException(String message, MojoExecution execution, MavenProject project, Throwable cause) { + super(message, cause); this.project = project; } - public LifecycleExecutionException( MojoExecution execution, MavenProject project, Throwable cause ) - { - this( createMessage( execution, project, cause ), execution, project, cause ); + public LifecycleExecutionException(MojoExecution execution, MavenProject project, Throwable cause) { + this(createMessage(execution, project, cause), execution, project, cause); } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - private static String createMessage( MojoExecution execution, MavenProject project, Throwable cause ) - { - MessageBuilder buffer = buffer( 256 ); + private static String createMessage(MojoExecution execution, MavenProject project, Throwable cause) { + MessageBuilder buffer = buffer(256); - buffer.a( "Failed to execute goal" ); + buffer.a("Failed to execute goal"); - if ( execution != null ) - { - buffer.a( ' ' ); - buffer.mojo( execution.getGroupId() + ':' + execution.getArtifactId() + ':' + execution.getVersion() + ':' - + execution.getGoal() ); - buffer.a( ' ' ).strong( '(' + execution.getExecutionId() + ')' ); + if (execution != null) { + buffer.a(' '); + buffer.mojo(execution.getGroupId() + + ':' + + execution.getArtifactId() + + ':' + + execution.getVersion() + + ':' + + execution.getGoal()); + buffer.a(' ').strong('(' + execution.getExecutionId() + ')'); } - if ( project != null ) - { - buffer.a( " on project " ); - buffer.project( project.getArtifactId() ); + if (project != null) { + buffer.a(" on project "); + buffer.project(project.getArtifactId()); } - if ( cause != null ) - { - buffer.a( ": " ).failure( cause.getMessage() ); + if (cause != null) { + buffer.a(": ").failure(cause.getMessage()); } return buffer.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutor.java b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutor.java index 26156db07d..88dea239ac 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutor.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,7 +16,10 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; +import java.util.List; +import java.util.Set; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.InvalidPluginDescriptorException; @@ -32,16 +33,12 @@ import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; -import java.util.List; -import java.util.Set; - /** * A facade that provides lifecycle services to components outside Maven core. * * @author Jason van Zyl */ -public interface LifecycleExecutor -{ +public interface LifecycleExecutor { // USED BY MAVEN HELP PLUGIN @Deprecated @@ -61,29 +58,29 @@ public interface LifecycleExecutor * @return The plugins bound to the lifecycles of the specified packaging or {@code null} if the packaging is * unknown. */ - Set getPluginsBoundByDefaultToAllLifecycles( String packaging ); + Set getPluginsBoundByDefaultToAllLifecycles(String packaging); - MavenExecutionPlan calculateExecutionPlan( MavenSession session, String... tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, - PluginVersionResolutionException; + MavenExecutionPlan calculateExecutionPlan(MavenSession session, String... tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, + PluginVersionResolutionException; - MavenExecutionPlan calculateExecutionPlan( MavenSession session, boolean setup, String... tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, - PluginVersionResolutionException; + MavenExecutionPlan calculateExecutionPlan(MavenSession session, boolean setup, String... tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginManagerException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, + PluginVersionResolutionException; - void execute( MavenSession session ); + void execute(MavenSession session); // used by the site plugin 3.x - void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; + void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; // used by the site plugin 3.x - List executeForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws LifecycleExecutionException; + List executeForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws LifecycleExecutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleMappingDelegate.java b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleMappingDelegate.java index f070198712..e1ac0a8c00 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleMappingDelegate.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleMappingDelegate.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.List; import java.util.Map; - import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.InvalidPluginDescriptorException; import org.apache.maven.plugin.MojoExecution; @@ -43,10 +41,9 @@ import org.apache.maven.project.MavenProject; * @see org.apache.maven.lifecycle.internal.DefaultLifecycleMappingDelegate * @author ifedorenko */ -public interface LifecycleMappingDelegate -{ - Map> calculateLifecycleMappings( MavenSession session, MavenProject project, - Lifecycle lifecycle, String lifecyclePhase ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException; +public interface LifecycleMappingDelegate { + Map> calculateLifecycleMappings( + MavenSession session, MavenProject project, Lifecycle lifecycle, String lifecyclePhase) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleNotFoundException.java b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleNotFoundException.java index e9ff0c2080..f38ea2c3ba 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleNotFoundException.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecycleNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,14 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; /** * Signals a failure to locate a lifecycle. * * @author Benjamin Bentmann */ -public class LifecycleNotFoundException - extends Exception -{ +public class LifecycleNotFoundException extends Exception { private final String lifecycleId; @@ -35,10 +32,9 @@ public class LifecycleNotFoundException * * @param lifecycleId The identifier of the lifecycle that could not be located, may be {@code null}. */ - public LifecycleNotFoundException( String lifecycleId ) - { - super( "Unknown lifecycle " + lifecycleId ); - this.lifecycleId = ( lifecycleId != null ) ? lifecycleId : ""; + public LifecycleNotFoundException(String lifecycleId) { + super("Unknown lifecycle " + lifecycleId); + this.lifecycleId = (lifecycleId != null) ? lifecycleId : ""; } /** @@ -46,9 +42,7 @@ public class LifecycleNotFoundException * * @return The identifier of the lifecycle that was not found, never {@code null}. */ - public String getLifecycleId() - { + public String getLifecycleId() { return lifecycleId; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecyclePhaseNotFoundException.java b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecyclePhaseNotFoundException.java index fab1d2f2c5..7055d93649 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/LifecyclePhaseNotFoundException.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/LifecyclePhaseNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,14 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; /** * Signals a failure to locate the lifecycle for some phase. * * @author Benjamin Bentmann */ -public class LifecyclePhaseNotFoundException - extends Exception -{ +public class LifecyclePhaseNotFoundException extends Exception { private final String lifecyclePhase; @@ -36,10 +33,9 @@ public class LifecyclePhaseNotFoundException * @param message The detail message, may be {@code null}. * @param lifecyclePhase The name of the lifecycle phase that could not be located, may be {@code null}. */ - public LifecyclePhaseNotFoundException( String message, String lifecyclePhase ) - { - super( message ); - this.lifecyclePhase = ( lifecyclePhase != null ) ? lifecyclePhase : ""; + public LifecyclePhaseNotFoundException(String message, String lifecyclePhase) { + super(message); + this.lifecyclePhase = (lifecyclePhase != null) ? lifecyclePhase : ""; } /** @@ -47,9 +43,7 @@ public class LifecyclePhaseNotFoundException * * @return The lifecycle phase that was not found, never {@code null}. */ - public String getLifecyclePhase() - { + public String getLifecyclePhase() { return lifecyclePhase; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/MavenExecutionPlan.java b/maven-core/src/main/java/org/apache/maven/lifecycle/MavenExecutionPlan.java index aecf264111..8c3bcaf90d 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/MavenExecutionPlan.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/MavenExecutionPlan.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.ArrayList; import java.util.HashMap; @@ -28,35 +27,32 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.lifecycle.internal.ExecutionPlanItem; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.descriptor.MojoDescriptor; -//TODO lifecycles being executed -//TODO what runs in each phase -//TODO plugins that need downloading -//TODO project dependencies that need downloading -//TODO unfortunately the plugins need to be downloaded in order to get the plugin.xml file. need to externalize this +// TODO lifecycles being executed +// TODO what runs in each phase +// TODO plugins that need downloading +// TODO project dependencies that need downloading +// TODO unfortunately the plugins need to be downloaded in order to get the plugin.xml file. need to externalize this // from the plugin archive. -//TODO this will be the class that people get in IDEs to modify +// TODO this will be the class that people get in IDEs to modify /** * MavenExecutionPlan */ -public class MavenExecutionPlan - implements Iterable -{ +public class MavenExecutionPlan implements Iterable { /* - At the moment, this class is totally immutable, and this is in line with thoughts about the - pre-calculated execution plan that stays the same during the execution. + At the moment, this class is totally immutable, and this is in line with thoughts about the + pre-calculated execution plan that stays the same during the execution. - If deciding to add mutable state to this class, it should be at least considered to - separate this into a separate mutable structure. + If deciding to add mutable state to this class, it should be at least considered to + separate this into a separate mutable structure. - */ + */ private final List planItem; @@ -64,48 +60,40 @@ public class MavenExecutionPlan final List phasesInExecutionPlan; - public MavenExecutionPlan( List planItem, DefaultLifecycles defaultLifecycles ) - { + public MavenExecutionPlan(List planItem, DefaultLifecycles defaultLifecycles) { this.planItem = planItem; lastMojoExecutionForAllPhases = new LinkedHashMap<>(); LinkedHashSet totalPhaseSet = new LinkedHashSet<>(); - if ( defaultLifecycles != null ) - { - for ( String phase : getDistinctPhasesInOrderOfExecutionPlanAppearance( planItem ) ) - { - final Lifecycle lifecycle = defaultLifecycles.get( phase ); - if ( lifecycle != null ) - { - totalPhaseSet.addAll( lifecycle.getPhases() ); + if (defaultLifecycles != null) { + for (String phase : getDistinctPhasesInOrderOfExecutionPlanAppearance(planItem)) { + final Lifecycle lifecycle = defaultLifecycles.get(phase); + if (lifecycle != null) { + totalPhaseSet.addAll(lifecycle.getPhases()); } } } - this.phasesInExecutionPlan = new ArrayList<>( totalPhaseSet ); + this.phasesInExecutionPlan = new ArrayList<>(totalPhaseSet); Map lastInExistingPhases = new HashMap<>(); - for ( ExecutionPlanItem executionPlanItem : getExecutionPlanItems() ) - { - lastInExistingPhases.put( executionPlanItem.getLifecyclePhase(), executionPlanItem ); + for (ExecutionPlanItem executionPlanItem : getExecutionPlanItems()) { + lastInExistingPhases.put(executionPlanItem.getLifecyclePhase(), executionPlanItem); } ExecutionPlanItem lastSeenExecutionPlanItem = null; - for ( String phase : totalPhaseSet ) - { - ExecutionPlanItem forThisPhase = lastInExistingPhases.get( phase ); - if ( forThisPhase != null ) - { + for (String phase : totalPhaseSet) { + ExecutionPlanItem forThisPhase = lastInExistingPhases.get(phase); + if (forThisPhase != null) { lastSeenExecutionPlanItem = forThisPhase; } - lastMojoExecutionForAllPhases.put( phase, lastSeenExecutionPlanItem ); + lastMojoExecutionForAllPhases.put(phase, lastSeenExecutionPlanItem); } } - public Iterator iterator() - { + public Iterator iterator() { return getExecutionPlanItems().iterator(); } @@ -117,37 +105,30 @@ public class MavenExecutionPlan * The execution plan item * @return The ExecutionPlanItem or null if none can be found */ - public ExecutionPlanItem findLastInPhase( String requestedPhase ) - { - return lastMojoExecutionForAllPhases.get( requestedPhase ); + public ExecutionPlanItem findLastInPhase(String requestedPhase) { + return lastMojoExecutionForAllPhases.get(requestedPhase); } - private List getExecutionPlanItems() - { + private List getExecutionPlanItems() { return planItem; } private static Iterable getDistinctPhasesInOrderOfExecutionPlanAppearance( - List planItems ) - { + List planItems) { LinkedHashSet result = new LinkedHashSet<>(); - for ( ExecutionPlanItem executionPlanItem : planItems ) - { + for (ExecutionPlanItem executionPlanItem : planItems) { final String phase = executionPlanItem.getLifecyclePhase(); - if ( !result.contains( phase ) ) - { - result.add( phase ); + if (!result.contains(phase)) { + result.add(phase); } } return result; } - public List getMojoExecutions() - { + public List getMojoExecutions() { List result = new ArrayList<>(); - for ( ExecutionPlanItem executionPlanItem : planItem ) - { - result.add( executionPlanItem.getMojoExecution() ); + for (ExecutionPlanItem executionPlanItem : planItem) { + result.add(executionPlanItem.getMojoExecution()); } return result; } @@ -157,15 +138,12 @@ public class MavenExecutionPlan * * @return the set of plugins (without info on which goal is concerned) */ - public Set getNonThreadSafePlugins() - { + public Set getNonThreadSafePlugins() { Set plugins = new HashSet<>(); - for ( ExecutionPlanItem executionPlanItem : planItem ) - { + for (ExecutionPlanItem executionPlanItem : planItem) { final MojoExecution mojoExecution = executionPlanItem.getMojoExecution(); - if ( !mojoExecution.getMojoDescriptor().isThreadSafe() ) - { - plugins.add( mojoExecution.getPlugin() ); + if (!mojoExecution.getMojoDescriptor().isThreadSafe()) { + plugins.add(mojoExecution.getPlugin()); } } return plugins; @@ -176,15 +154,12 @@ public class MavenExecutionPlan * * @return the set of mojo descriptors */ - public Set getNonThreadSafeMojos() - { + public Set getNonThreadSafeMojos() { Set mojos = new HashSet<>(); - for ( ExecutionPlanItem executionPlanItem : planItem ) - { + for (ExecutionPlanItem executionPlanItem : planItem) { final MojoExecution mojoExecution = executionPlanItem.getMojoExecution(); - if ( !mojoExecution.getMojoDescriptor().isThreadSafe() ) - { - mojos.add( mojoExecution.getMojoDescriptor() ); + if (!mojoExecution.getMojoDescriptor().isThreadSafe()) { + mojos.add(mojoExecution.getMojoDescriptor()); } } return mojos; @@ -192,14 +167,11 @@ public class MavenExecutionPlan // Used by m2e but will be removed, really. @Deprecated - public List getExecutions() - { + public List getExecutions() { return getMojoExecutions(); } - public int size() - { + public int size() { return planItem.size(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/MissingProjectException.java b/maven-core/src/main/java/org/apache/maven/lifecycle/MissingProjectException.java index 571e1d2bc6..b67ca44a76 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/MissingProjectException.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/MissingProjectException.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,21 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; /** * Signals a failure to execute a lifecycle phase or mojo because a project is required but not present. * * @author Benjamin Bentmann */ -public class MissingProjectException - extends Exception -{ +public class MissingProjectException extends Exception { /** * Creates a new exception. * * @param message The detail message, may be {@code null}. */ - public MissingProjectException( String message ) - { - super( message ); + public MissingProjectException(String message) { + super(message); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/MojoExecutionConfigurator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/MojoExecutionConfigurator.java index 07219b22b5..6376631288 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/MojoExecutionConfigurator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/MojoExecutionConfigurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; @@ -31,8 +30,7 @@ import org.apache.maven.project.MavenProject; * @author Jason van Zyl * @since 3.3.1, MNG-5753 */ -public interface MojoExecutionConfigurator -{ +public interface MojoExecutionConfigurator { /** * Create the MojoExecution configuration based on configuration for a Mojo in the MavenProject and the * default configuration for the Mojo from the containing plugin's plugin.xml descriptor. @@ -41,5 +39,5 @@ public interface MojoExecutionConfigurator * @param mojoExecution * @param allowPluginLevelConfig */ - void configure( MavenProject project, MojoExecution mojoExecution, boolean allowPluginLevelConfig ); + void configure(MavenProject project, MojoExecution mojoExecution, boolean allowPluginLevelConfig); } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/NoGoalSpecifiedException.java b/maven-core/src/main/java/org/apache/maven/lifecycle/NoGoalSpecifiedException.java index 2ac9638a65..33339a854b 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/NoGoalSpecifiedException.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/NoGoalSpecifiedException.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,21 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; /** * Signals a failure to build because no goal was specified. * * @author Benjamin Bentmann */ -public class NoGoalSpecifiedException - extends Exception -{ +public class NoGoalSpecifiedException extends Exception { /** * Creates a new exception. * * @param message The detail message, may be {@code null}. */ - public NoGoalSpecifiedException( String message ) - { - super( message ); + public NoGoalSpecifiedException(String message) { + super(message); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java index b30b560c81..36a23e1e9b 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.builder.BuilderCommon; import org.apache.maven.project.MavenProject; @@ -38,43 +35,33 @@ import org.apache.maven.project.MavenProject; */ @Named @Singleton -public class BuildListCalculator -{ - public ProjectBuildList calculateProjectBuilds( MavenSession session, List taskSegments ) - { +public class BuildListCalculator { + public ProjectBuildList calculateProjectBuilds(MavenSession session, List taskSegments) { List projectBuilds = new ArrayList<>(); MavenProject rootProject = session.getTopLevelProject(); - for ( TaskSegment taskSegment : taskSegments ) - { + for (TaskSegment taskSegment : taskSegments) { List projects; - if ( taskSegment.isAggregating() ) - { - projects = Collections.singletonList( rootProject ); - } - else - { + if (taskSegment.isAggregating()) { + projects = Collections.singletonList(rootProject); + } else { projects = session.getProjects(); } - for ( MavenProject project : projects ) - { + for (MavenProject project : projects) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); MavenProject currentProject = session.getCurrentProject(); - try - { - BuilderCommon.attachToThread( project ); // Not totally sure if this is needed for anything - session.setCurrentProject( project ); - projectBuilds.add( new ProjectSegment( project, taskSegment, session ) ); - } - finally - { - session.setCurrentProject( currentProject ); - Thread.currentThread().setContextClassLoader( tccl ); + try { + BuilderCommon.attachToThread(project); // Not totally sure if this is needed for anything + session.setCurrentProject(project); + projectBuilds.add(new ProjectSegment(project, taskSegment, session)); + } finally { + session.setCurrentProject(currentProject); + Thread.currentThread().setContextClassLoader(tccl); } } } - return new ProjectBuildList( projectBuilds ); + return new ProjectBuildList(projectBuilds); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildThreadFactory.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildThreadFactory.java index bf6e637f73..f0886b61e9 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildThreadFactory.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildThreadFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; @@ -25,15 +24,12 @@ import java.util.concurrent.atomic.AtomicInteger; /** * Simple {@link ThreadFactory} implementation that ensures the corresponding threads have a meaningful name. */ -public class BuildThreadFactory - implements ThreadFactory -{ +public class BuildThreadFactory implements ThreadFactory { private final AtomicInteger id = new AtomicInteger(); private static final String PREFIX = "BuilderThread"; - public Thread newThread( Runnable r ) - { - return new Thread( r, String.format( "%s-%d", PREFIX, id.getAndIncrement() ) ); + public Thread newThread(Runnable r) { + return new Thread(r, String.format("%s-%d", PREFIX, id.getAndIncrement())); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/CompoundProjectExecutionListener.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/CompoundProjectExecutionListener.java index 48474e6582..197c04f6de 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/CompoundProjectExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/CompoundProjectExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,55 +16,41 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.Collection; - import org.apache.maven.execution.ProjectExecutionEvent; import org.apache.maven.execution.ProjectExecutionListener; import org.apache.maven.lifecycle.LifecycleExecutionException; -class CompoundProjectExecutionListener - implements ProjectExecutionListener -{ +class CompoundProjectExecutionListener implements ProjectExecutionListener { private final Collection listeners; - CompoundProjectExecutionListener( Collection listeners ) - { + CompoundProjectExecutionListener(Collection listeners) { this.listeners = listeners; // NB this is live injected collection } - public void beforeProjectExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.beforeProjectExecution( event ); + public void beforeProjectExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { + for (ProjectExecutionListener listener : listeners) { + listener.beforeProjectExecution(event); } } - public void beforeProjectLifecycleExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.beforeProjectLifecycleExecution( event ); + public void beforeProjectLifecycleExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { + for (ProjectExecutionListener listener : listeners) { + listener.beforeProjectLifecycleExecution(event); } } - public void afterProjectExecutionSuccess( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.afterProjectExecutionSuccess( event ); + public void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException { + for (ProjectExecutionListener listener : listeners) { + listener.afterProjectExecutionSuccess(event); } } - public void afterProjectExecutionFailure( ProjectExecutionEvent event ) - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.afterProjectExecutionFailure( event ); + public void afterProjectExecutionFailure(ProjectExecutionEvent event) { + for (ProjectExecutionListener listener : listeners) { + listener.afterProjectExecutionFailure(event); } } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEvent.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEvent.java index 109087154b..dc0dccdd13 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEvent.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.execution.MavenSession; @@ -29,9 +28,7 @@ import org.apache.maven.project.MavenProject; * * @author Benjamin Bentmann */ -class DefaultExecutionEvent - implements ExecutionEvent -{ +class DefaultExecutionEvent implements ExecutionEvent { private final Type type; @@ -41,37 +38,30 @@ class DefaultExecutionEvent private final Exception exception; - DefaultExecutionEvent( Type type, MavenSession session, MojoExecution mojoExecution, Exception exception ) - { + DefaultExecutionEvent(Type type, MavenSession session, MojoExecution mojoExecution, Exception exception) { this.type = type; this.session = session; this.mojoExecution = mojoExecution; this.exception = exception; } - public Type getType() - { + public Type getType() { return type; } - public MavenSession getSession() - { + public MavenSession getSession() { return session; } - public MavenProject getProject() - { + public MavenProject getProject() { return session.getCurrentProject(); } - public MojoExecution getMojoExecution() - { + public MojoExecution getMojoExecution() { return mojoExecution; } - public Exception getException() - { + public Exception getException() { return exception; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult.java index 94948bc518..a90255ebce 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.execution.ExecutionListener; import org.apache.maven.execution.MavenSession; @@ -36,87 +34,80 @@ import org.apache.maven.plugin.MojoExecution; */ @Named @Singleton -public class DefaultExecutionEventCatapult - implements ExecutionEventCatapult -{ +public class DefaultExecutionEventCatapult implements ExecutionEventCatapult { - public void fire( ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution ) - { - fire( eventType, session, mojoExecution, null ); + public void fire(ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution) { + fire(eventType, session, mojoExecution, null); } - public void fire( ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution, - Exception exception ) - { + public void fire( + ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution, Exception exception) { ExecutionListener listener = session.getRequest().getExecutionListener(); - if ( listener != null ) - { - ExecutionEvent event = new DefaultExecutionEvent( eventType, session, mojoExecution, exception ); + if (listener != null) { + ExecutionEvent event = new DefaultExecutionEvent(eventType, session, mojoExecution, exception); - switch ( eventType ) - { + switch (eventType) { case ProjectDiscoveryStarted: - listener.projectDiscoveryStarted( event ); + listener.projectDiscoveryStarted(event); break; case SessionStarted: - listener.sessionStarted( event ); + listener.sessionStarted(event); break; case SessionEnded: - listener.sessionEnded( event ); + listener.sessionEnded(event); break; case ProjectSkipped: - listener.projectSkipped( event ); + listener.projectSkipped(event); break; case ProjectStarted: - listener.projectStarted( event ); + listener.projectStarted(event); break; case ProjectSucceeded: - listener.projectSucceeded( event ); + listener.projectSucceeded(event); break; case ProjectFailed: - listener.projectFailed( event ); + listener.projectFailed(event); break; case MojoSkipped: - listener.mojoSkipped( event ); + listener.mojoSkipped(event); break; case MojoStarted: - listener.mojoStarted( event ); + listener.mojoStarted(event); break; case MojoSucceeded: - listener.mojoSucceeded( event ); + listener.mojoSucceeded(event); break; case MojoFailed: - listener.mojoFailed( event ); + listener.mojoFailed(event); break; case ForkStarted: - listener.forkStarted( event ); + listener.forkStarted(event); break; case ForkSucceeded: - listener.forkSucceeded( event ); + listener.forkSucceeded(event); break; case ForkFailed: - listener.forkFailed( event ); + listener.forkFailed(event); break; case ForkedProjectStarted: - listener.forkedProjectStarted( event ); + listener.forkedProjectStarted(event); break; case ForkedProjectSucceeded: - listener.forkedProjectSucceeded( event ); + listener.forkedProjectSucceeded(event); break; case ForkedProjectFailed: - listener.forkedProjectFailed( event ); + listener.forkedProjectFailed(event); break; default: - throw new IllegalStateException( "Unknown execution event type " + eventType ); + throw new IllegalStateException("Unknown execution event type " + eventType); } } } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleExecutionPlanCalculator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleExecutionPlanCalculator.java index cb560462e4..e37da743ff 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleExecutionPlanCalculator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleExecutionPlanCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.io.IOException; import java.util.ArrayList; @@ -29,11 +28,9 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.xml.Dom; import org.apache.maven.execution.MavenSession; import org.apache.maven.internal.xml.Xpp3Dom; @@ -63,7 +60,6 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; - /** * NOTE: This class is not part of any public api and can be changed or deleted without prior notice. * @@ -73,9 +69,7 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; */ @Named @Singleton -public class DefaultLifecycleExecutionPlanCalculator - implements LifecycleExecutionPlanCalculator -{ +public class DefaultLifecycleExecutionPlanCalculator implements LifecycleExecutionPlanCalculator { private final BuildPluginManager pluginManager; @@ -97,10 +91,9 @@ public class DefaultLifecycleExecutionPlanCalculator DefaultLifecycles defaultLifecycles, MojoDescriptorCreator mojoDescriptorCreator, LifecyclePluginResolver lifecyclePluginResolver, - @Named( DefaultLifecycleMappingDelegate.HINT ) LifecycleMappingDelegate standardDelegate, + @Named(DefaultLifecycleMappingDelegate.HINT) LifecycleMappingDelegate standardDelegate, Map delegates, - Map mojoExecutionConfigurators ) - { + Map mojoExecutionConfigurators) { this.pluginManager = pluginManager; this.defaultLifecycles = defaultLifecycles; this.mojoDescriptorCreator = mojoDescriptorCreator; @@ -111,198 +104,178 @@ public class DefaultLifecycleExecutionPlanCalculator } // Only used for testing - public DefaultLifecycleExecutionPlanCalculator( BuildPluginManager pluginManager, - DefaultLifecycles defaultLifecycles, - MojoDescriptorCreator mojoDescriptorCreator, - LifecyclePluginResolver lifecyclePluginResolver ) - { + public DefaultLifecycleExecutionPlanCalculator( + BuildPluginManager pluginManager, + DefaultLifecycles defaultLifecycles, + MojoDescriptorCreator mojoDescriptorCreator, + LifecyclePluginResolver lifecyclePluginResolver) { this.pluginManager = pluginManager; this.defaultLifecycles = defaultLifecycles; this.mojoDescriptorCreator = mojoDescriptorCreator; this.lifecyclePluginResolver = lifecyclePluginResolver; this.standardDelegate = null; this.delegates = null; - this.mojoExecutionConfigurators = Collections.singletonMap( - "default", (MojoExecutionConfigurator) new DefaultMojoExecutionConfigurator() ); + this.mojoExecutionConfigurators = + Collections.singletonMap("default", (MojoExecutionConfigurator) new DefaultMojoExecutionConfigurator()); } @Override - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List tasks, - boolean setup ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException - { - lifecyclePluginResolver.resolveMissingPluginVersions( project, session ); + public MavenExecutionPlan calculateExecutionPlan( + MavenSession session, MavenProject project, List tasks, boolean setup) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException { + lifecyclePluginResolver.resolveMissingPluginVersions(project, session); - final List executions = calculateMojoExecutions( session, project, tasks ); + final List executions = calculateMojoExecutions(session, project, tasks); - if ( setup ) - { - setupMojoExecutions( session, project, executions ); + if (setup) { + setupMojoExecutions(session, project, executions); } - final List planItem = ExecutionPlanItem.createExecutionPlanItems( project, executions ); + final List planItem = ExecutionPlanItem.createExecutionPlanItems(project, executions); - return new MavenExecutionPlan( planItem, defaultLifecycles ); + return new MavenExecutionPlan(planItem, defaultLifecycles); } @Override - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List tasks ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException - { - return calculateExecutionPlan( session, project, tasks, true ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, MavenProject project, List tasks) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException { + return calculateExecutionPlan(session, project, tasks, true); } - private void setupMojoExecutions( MavenSession session, MavenProject project, List mojoExecutions ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { - Set alreadyPlannedExecutions = fillMojoDescriptors( session, project, mojoExecutions ); + private void setupMojoExecutions(MavenSession session, MavenProject project, List mojoExecutions) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { + Set alreadyPlannedExecutions = fillMojoDescriptors(session, project, mojoExecutions); - for ( MojoExecution mojoExecution : mojoExecutions ) - { - setupMojoExecution( session, project, mojoExecution, alreadyPlannedExecutions ); + for (MojoExecution mojoExecution : mojoExecutions) { + setupMojoExecution(session, project, mojoExecution, alreadyPlannedExecutions); } } - private Set fillMojoDescriptors( MavenSession session, MavenProject project, - List mojoExecutions ) + private Set fillMojoDescriptors( + MavenSession session, MavenProject project, List mojoExecutions) throws InvalidPluginDescriptorException, MojoNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, PluginNotFoundException - { - Set descriptors = new HashSet<>( mojoExecutions.size() ); + PluginDescriptorParsingException, PluginNotFoundException { + Set descriptors = new HashSet<>(mojoExecutions.size()); - for ( MojoExecution execution : mojoExecutions ) - { - MojoDescriptor mojoDescriptor = fillMojoDescriptor( session, project, execution ); - descriptors.add( mojoDescriptor ); + for (MojoExecution execution : mojoExecutions) { + MojoDescriptor mojoDescriptor = fillMojoDescriptor(session, project, execution); + descriptors.add(mojoDescriptor); } return descriptors; } - private MojoDescriptor fillMojoDescriptor( MavenSession session, MavenProject project, MojoExecution execution ) + private MojoDescriptor fillMojoDescriptor(MavenSession session, MavenProject project, MojoExecution execution) throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException - { + MojoNotFoundException, InvalidPluginDescriptorException { MojoDescriptor mojoDescriptor = execution.getMojoDescriptor(); - if ( mojoDescriptor == null ) - { - mojoDescriptor = - pluginManager.getMojoDescriptor( execution.getPlugin(), execution.getGoal(), - project.getRemotePluginRepositories(), - session.getRepositorySession() ); + if (mojoDescriptor == null) { + mojoDescriptor = pluginManager.getMojoDescriptor( + execution.getPlugin(), + execution.getGoal(), + project.getRemotePluginRepositories(), + session.getRepositorySession()); - execution.setMojoDescriptor( mojoDescriptor ); + execution.setMojoDescriptor(mojoDescriptor); } return mojoDescriptor; } @Override - public void setupMojoExecution( MavenSession session, MavenProject project, MojoExecution mojoExecution, - Set alreadyPlannedExecutions ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { - fillMojoDescriptor( session, project, mojoExecution ); + public void setupMojoExecution( + MavenSession session, + MavenProject project, + MojoExecution mojoExecution, + Set alreadyPlannedExecutions) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { + fillMojoDescriptor(session, project, mojoExecution); - mojoExecutionConfigurator( mojoExecution ).configure( project, - mojoExecution, - MojoExecution.Source.CLI.equals( mojoExecution.getSource() ) ); + mojoExecutionConfigurator(mojoExecution) + .configure(project, mojoExecution, MojoExecution.Source.CLI.equals(mojoExecution.getSource())); - finalizeMojoConfiguration( mojoExecution ); + finalizeMojoConfiguration(mojoExecution); - calculateForkedExecutions( mojoExecution, session, project, alreadyPlannedExecutions ); + calculateForkedExecutions(mojoExecution, session, project, alreadyPlannedExecutions); } - public List calculateMojoExecutions( MavenSession session, MavenProject project, List tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException, LifecyclePhaseNotFoundException - { + public List calculateMojoExecutions(MavenSession session, MavenProject project, List tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException, LifecyclePhaseNotFoundException { final List mojoExecutions = new ArrayList<>(); - for ( Object task : tasks ) - { - if ( task instanceof GoalTask ) - { - String pluginGoal = ( (GoalTask) task ).pluginGoal; + for (Object task : tasks) { + if (task instanceof GoalTask) { + String pluginGoal = ((GoalTask) task).pluginGoal; String executionId = "default-cli"; - int executionIdx = pluginGoal.indexOf( '@' ); - if ( executionIdx > 0 ) - { - executionId = pluginGoal.substring( executionIdx + 1 ); + int executionIdx = pluginGoal.indexOf('@'); + if (executionIdx > 0) { + executionId = pluginGoal.substring(executionIdx + 1); } - MojoDescriptor mojoDescriptor = mojoDescriptorCreator.getMojoDescriptor( pluginGoal, session, project ); + MojoDescriptor mojoDescriptor = mojoDescriptorCreator.getMojoDescriptor(pluginGoal, session, project); - MojoExecution mojoExecution = new MojoExecution( mojoDescriptor, executionId, - MojoExecution.Source.CLI ); + MojoExecution mojoExecution = new MojoExecution(mojoDescriptor, executionId, MojoExecution.Source.CLI); - mojoExecutions.add( mojoExecution ); - } - else if ( task instanceof LifecycleTask ) - { - String lifecyclePhase = ( (LifecycleTask) task ).getLifecyclePhase(); + mojoExecutions.add(mojoExecution); + } else if (task instanceof LifecycleTask) { + String lifecyclePhase = ((LifecycleTask) task).getLifecyclePhase(); Map> phaseToMojoMapping = - calculateLifecycleMappings( session, project, lifecyclePhase ); + calculateLifecycleMappings(session, project, lifecyclePhase); - for ( List mojoExecutionsFromLifecycle : phaseToMojoMapping.values() ) - { - mojoExecutions.addAll( mojoExecutionsFromLifecycle ); + for (List mojoExecutionsFromLifecycle : phaseToMojoMapping.values()) { + mojoExecutions.addAll(mojoExecutionsFromLifecycle); } - } - else - { - throw new IllegalStateException( "unexpected task " + task ); + } else { + throw new IllegalStateException("unexpected task " + task); } } return mojoExecutions; } - private Map> calculateLifecycleMappings( MavenSession session, MavenProject project, - String lifecyclePhase ) - throws LifecyclePhaseNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException - { + private Map> calculateLifecycleMappings( + MavenSession session, MavenProject project, String lifecyclePhase) + throws LifecyclePhaseNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException { /* * Determine the lifecycle that corresponds to the given phase. */ - Lifecycle lifecycle = defaultLifecycles.get( lifecyclePhase ); + Lifecycle lifecycle = defaultLifecycles.get(lifecyclePhase); - if ( lifecycle == null ) - { - throw new LifecyclePhaseNotFoundException( "Unknown lifecycle phase \"" + lifecyclePhase - + "\". You must specify a valid lifecycle phase" + " or a goal in the format : or" - + " :[:]:. Available lifecycle phases are: " - + defaultLifecycles.getLifecyclePhaseList() + ".", lifecyclePhase ); + if (lifecycle == null) { + throw new LifecyclePhaseNotFoundException( + "Unknown lifecycle phase \"" + lifecyclePhase + + "\". You must specify a valid lifecycle phase" + + " or a goal in the format : or" + + " :[:]:. Available lifecycle phases are: " + + defaultLifecycles.getLifecyclePhaseList() + ".", + lifecyclePhase); } LifecycleMappingDelegate delegate; - if ( Arrays.binarySearch( DefaultLifecycles.STANDARD_LIFECYCLES, lifecycle.getId() ) >= 0 ) - { + if (Arrays.binarySearch(DefaultLifecycles.STANDARD_LIFECYCLES, lifecycle.getId()) >= 0) { delegate = standardDelegate; - } - else - { - delegate = delegates.get( lifecycle.getId() ); - if ( delegate == null ) - { + } else { + delegate = delegates.get(lifecycle.getId()); + if (delegate == null) { delegate = standardDelegate; } } - return delegate.calculateLifecycleMappings( session, project, lifecycle, lifecyclePhase ); + return delegate.calculateLifecycleMappings(session, project, lifecycle, lifecyclePhase); } /** @@ -312,172 +285,152 @@ public class DefaultLifecycleExecutionPlanCalculator * * @param mojoExecution The mojo execution whose configuration should be finalized, must not be {@code null}. */ - private void finalizeMojoConfiguration( MojoExecution mojoExecution ) - { + private void finalizeMojoConfiguration(MojoExecution mojoExecution) { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); org.codehaus.plexus.util.xml.Xpp3Dom config = mojoExecution.getConfiguration(); Dom executionConfiguration = config != null ? config.getDom() : null; - if ( executionConfiguration == null ) - { - executionConfiguration = new Xpp3Dom( "configuration" ); + if (executionConfiguration == null) { + executionConfiguration = new Xpp3Dom("configuration"); } - Dom defaultConfiguration = getMojoConfiguration( mojoDescriptor ); + Dom defaultConfiguration = getMojoConfiguration(mojoDescriptor); List children = new ArrayList<>(); - if ( mojoDescriptor.getParameters() != null ) - { - for ( Parameter parameter : mojoDescriptor.getParameters() ) - { - Dom parameterConfiguration = executionConfiguration.getChild( parameter.getName() ); + if (mojoDescriptor.getParameters() != null) { + for (Parameter parameter : mojoDescriptor.getParameters()) { + Dom parameterConfiguration = executionConfiguration.getChild(parameter.getName()); - if ( parameterConfiguration == null ) - { - parameterConfiguration = executionConfiguration.getChild( parameter.getAlias() ); + if (parameterConfiguration == null) { + parameterConfiguration = executionConfiguration.getChild(parameter.getAlias()); } - Dom parameterDefaults = defaultConfiguration.getChild( parameter.getName() ); + Dom parameterDefaults = defaultConfiguration.getChild(parameter.getName()); - if ( parameterConfiguration != null ) - { - parameterConfiguration = parameterConfiguration.merge( parameterDefaults, Boolean.TRUE ); - } - else - { + if (parameterConfiguration != null) { + parameterConfiguration = parameterConfiguration.merge(parameterDefaults, Boolean.TRUE); + } else { parameterConfiguration = parameterDefaults; } - if ( parameterConfiguration != null ) - { - Map attributes = new HashMap<>( parameterConfiguration.getAttributes() ); + if (parameterConfiguration != null) { + Map attributes = new HashMap<>(parameterConfiguration.getAttributes()); - if ( StringUtils.isEmpty( parameterConfiguration.getAttribute( "implementation" ) ) - && StringUtils.isNotEmpty( parameter.getImplementation() ) ) - { - attributes.put( "implementation", parameter.getImplementation() ); + if (StringUtils.isEmpty(parameterConfiguration.getAttribute("implementation")) + && StringUtils.isNotEmpty(parameter.getImplementation())) { + attributes.put("implementation", parameter.getImplementation()); } - parameterConfiguration = new Xpp3Dom( parameter.getName(), parameterConfiguration.getValue(), - attributes, parameterConfiguration.getChildren(), - parameterConfiguration.getInputLocation() ); + parameterConfiguration = new Xpp3Dom( + parameter.getName(), + parameterConfiguration.getValue(), + attributes, + parameterConfiguration.getChildren(), + parameterConfiguration.getInputLocation()); - children.add( parameterConfiguration ); + children.add(parameterConfiguration); } } } - Dom finalConfiguration = new Xpp3Dom( "configuration", null, null, children, null ); + Dom finalConfiguration = new Xpp3Dom("configuration", null, null, children, null); - mojoExecution.setConfiguration( finalConfiguration ); + mojoExecution.setConfiguration(finalConfiguration); } - private Dom getMojoConfiguration( MojoDescriptor mojoDescriptor ) - { - return MojoDescriptorCreator.convert( mojoDescriptor ).getDom(); + private Dom getMojoConfiguration(MojoDescriptor mojoDescriptor) { + return MojoDescriptorCreator.convert(mojoDescriptor).getDom(); } @Override - public void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { - calculateForkedExecutions( mojoExecution, session, session.getCurrentProject(), new HashSet<>() ); + public void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { + calculateForkedExecutions(mojoExecution, session, session.getCurrentProject(), new HashSet<>()); } - private void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session, MavenProject project, - Collection alreadyPlannedExecutions ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { + private void calculateForkedExecutions( + MojoExecution mojoExecution, + MavenSession session, + MavenProject project, + Collection alreadyPlannedExecutions) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); - if ( !mojoDescriptor.isForking() ) - { + if (!mojoDescriptor.isForking()) { return; } - alreadyPlannedExecutions.add( mojoDescriptor ); + alreadyPlannedExecutions.add(mojoDescriptor); List forkedProjects = - LifecycleDependencyResolver.getProjects( project, session, mojoDescriptor.isAggregator() ); + LifecycleDependencyResolver.getProjects(project, session, mojoDescriptor.isAggregator()); - for ( MavenProject forkedProject : forkedProjects ) - { - if ( forkedProject != project ) - { - lifecyclePluginResolver.resolveMissingPluginVersions( forkedProject, session ); + for (MavenProject forkedProject : forkedProjects) { + if (forkedProject != project) { + lifecyclePluginResolver.resolveMissingPluginVersions(forkedProject, session); } List forkedExecutions; - if ( StringUtils.isNotEmpty( mojoDescriptor.getExecutePhase() ) ) - { + if (StringUtils.isNotEmpty(mojoDescriptor.getExecutePhase())) { forkedExecutions = - calculateForkedLifecycle( mojoExecution, session, forkedProject, alreadyPlannedExecutions ); - } - else - { - forkedExecutions = calculateForkedGoal( mojoExecution, session, forkedProject, - alreadyPlannedExecutions ); + calculateForkedLifecycle(mojoExecution, session, forkedProject, alreadyPlannedExecutions); + } else { + forkedExecutions = calculateForkedGoal(mojoExecution, session, forkedProject, alreadyPlannedExecutions); } // This List can be empty when the executions are already present in the plan - if ( !forkedExecutions.isEmpty() ) - { - mojoExecution.setForkedExecutions( BuilderCommon.getKey( forkedProject ), forkedExecutions ); + if (!forkedExecutions.isEmpty()) { + mojoExecution.setForkedExecutions(BuilderCommon.getKey(forkedProject), forkedExecutions); } } } - private List calculateForkedLifecycle( MojoExecution mojoExecution, MavenSession session, - MavenProject project, - Collection alreadyPlannedExecutions ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { + private List calculateForkedLifecycle( + MojoExecution mojoExecution, + MavenSession session, + MavenProject project, + Collection alreadyPlannedExecutions) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); String forkedPhase = mojoDescriptor.getExecutePhase(); - Map> lifecycleMappings = calculateLifecycleMappings( session, project, - forkedPhase ); + Map> lifecycleMappings = calculateLifecycleMappings(session, project, forkedPhase); - for ( List forkedExecutions : lifecycleMappings.values() ) - { - for ( MojoExecution forkedExecution : forkedExecutions ) - { - if ( forkedExecution.getMojoDescriptor() == null ) - { - MojoDescriptor forkedMojoDescriptor = - pluginManager.getMojoDescriptor( forkedExecution.getPlugin(), forkedExecution.getGoal(), - project.getRemotePluginRepositories(), - session.getRepositorySession() ); + for (List forkedExecutions : lifecycleMappings.values()) { + for (MojoExecution forkedExecution : forkedExecutions) { + if (forkedExecution.getMojoDescriptor() == null) { + MojoDescriptor forkedMojoDescriptor = pluginManager.getMojoDescriptor( + forkedExecution.getPlugin(), + forkedExecution.getGoal(), + project.getRemotePluginRepositories(), + session.getRepositorySession()); - forkedExecution.setMojoDescriptor( forkedMojoDescriptor ); + forkedExecution.setMojoDescriptor(forkedMojoDescriptor); } - mojoExecutionConfigurator( forkedExecution ).configure( project, forkedExecution, false ); + mojoExecutionConfigurator(forkedExecution).configure(project, forkedExecution, false); } } - injectLifecycleOverlay( lifecycleMappings, mojoExecution, session, project ); + injectLifecycleOverlay(lifecycleMappings, mojoExecution, session, project); List mojoExecutions = new ArrayList<>(); - for ( List forkedExecutions : lifecycleMappings.values() ) - { - for ( MojoExecution forkedExecution : forkedExecutions ) - { - if ( !alreadyPlannedExecutions.contains( forkedExecution.getMojoDescriptor() ) ) - { - finalizeMojoConfiguration( forkedExecution ); + for (List forkedExecutions : lifecycleMappings.values()) { + for (MojoExecution forkedExecution : forkedExecutions) { + if (!alreadyPlannedExecutions.contains(forkedExecution.getMojoDescriptor())) { + finalizeMojoConfiguration(forkedExecution); - calculateForkedExecutions( forkedExecution, session, project, alreadyPlannedExecutions ); + calculateForkedExecutions(forkedExecution, session, project, alreadyPlannedExecutions); - mojoExecutions.add( forkedExecution ); + mojoExecutions.add(forkedExecution); } } } @@ -485,92 +438,78 @@ public class DefaultLifecycleExecutionPlanCalculator return mojoExecutions; } - private void injectLifecycleOverlay( Map> lifecycleMappings, - MojoExecution mojoExecution, MavenSession session, MavenProject project ) - throws PluginDescriptorParsingException, LifecycleNotFoundException, MojoNotFoundException, - PluginNotFoundException, PluginResolutionException, NoPluginFoundForPrefixException, - InvalidPluginDescriptorException, PluginVersionResolutionException - { + private void injectLifecycleOverlay( + Map> lifecycleMappings, + MojoExecution mojoExecution, + MavenSession session, + MavenProject project) + throws PluginDescriptorParsingException, LifecycleNotFoundException, MojoNotFoundException, + PluginNotFoundException, PluginResolutionException, NoPluginFoundForPrefixException, + InvalidPluginDescriptorException, PluginVersionResolutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); String forkedLifecycle = mojoDescriptor.getExecuteLifecycle(); - if ( StringUtils.isEmpty( forkedLifecycle ) ) - { + if (StringUtils.isEmpty(forkedLifecycle)) { return; } org.apache.maven.plugin.lifecycle.Lifecycle lifecycleOverlay; - try - { - lifecycleOverlay = pluginDescriptor.getLifecycleMapping( forkedLifecycle ); - } - catch ( IOException | XmlPullParserException e ) - { - throw new PluginDescriptorParsingException( pluginDescriptor.getPlugin(), pluginDescriptor.getSource(), e ); + try { + lifecycleOverlay = pluginDescriptor.getLifecycleMapping(forkedLifecycle); + } catch (IOException | XmlPullParserException e) { + throw new PluginDescriptorParsingException(pluginDescriptor.getPlugin(), pluginDescriptor.getSource(), e); } - if ( lifecycleOverlay == null ) - { - throw new LifecycleNotFoundException( forkedLifecycle ); + if (lifecycleOverlay == null) { + throw new LifecycleNotFoundException(forkedLifecycle); } - for ( Phase phase : lifecycleOverlay.getPhases() ) - { - List forkedExecutions = lifecycleMappings.get( phase.getId() ); + for (Phase phase : lifecycleOverlay.getPhases()) { + List forkedExecutions = lifecycleMappings.get(phase.getId()); - if ( forkedExecutions != null ) - { - for ( Execution execution : phase.getExecutions() ) - { - for ( String goal : execution.getGoals() ) - { + if (forkedExecutions != null) { + for (Execution execution : phase.getExecutions()) { + for (String goal : execution.getGoals()) { MojoDescriptor forkedMojoDescriptor; - if ( goal.indexOf( ':' ) < 0 ) - { - forkedMojoDescriptor = pluginDescriptor.getMojo( goal ); - if ( forkedMojoDescriptor == null ) - { - throw new MojoNotFoundException( goal, pluginDescriptor ); + if (goal.indexOf(':') < 0) { + forkedMojoDescriptor = pluginDescriptor.getMojo(goal); + if (forkedMojoDescriptor == null) { + throw new MojoNotFoundException(goal, pluginDescriptor); } - } - else - { - forkedMojoDescriptor = mojoDescriptorCreator.getMojoDescriptor( goal, session, project ); + } else { + forkedMojoDescriptor = mojoDescriptorCreator.getMojoDescriptor(goal, session, project); } MojoExecution forkedExecution = - new MojoExecution( forkedMojoDescriptor, mojoExecution.getExecutionId() ); + new MojoExecution(forkedMojoDescriptor, mojoExecution.getExecutionId()); Xpp3Dom forkedConfiguration = (Xpp3Dom) execution.getConfiguration(); - forkedExecution.setConfiguration( forkedConfiguration ); + forkedExecution.setConfiguration(forkedConfiguration); - mojoExecutionConfigurator( forkedExecution ).configure( project, forkedExecution, true ); + mojoExecutionConfigurator(forkedExecution).configure(project, forkedExecution, true); - forkedExecutions.add( forkedExecution ); + forkedExecutions.add(forkedExecution); } } Xpp3Dom phaseConfiguration = (Xpp3Dom) phase.getConfiguration(); - if ( phaseConfiguration != null ) - { - for ( MojoExecution forkedExecution : forkedExecutions ) - { + if (phaseConfiguration != null) { + for (MojoExecution forkedExecution : forkedExecutions) { org.codehaus.plexus.util.xml.Xpp3Dom config = forkedExecution.getConfiguration(); - if ( config != null ) - { + if (config != null) { Dom forkedConfiguration = config.getDom(); - forkedConfiguration = phaseConfiguration.merge( forkedConfiguration ); + forkedConfiguration = phaseConfiguration.merge(forkedConfiguration); - forkedExecution.setConfiguration( forkedConfiguration ); + forkedExecution.setConfiguration(forkedConfiguration); } } } @@ -583,58 +522,54 @@ public class DefaultLifecycleExecutionPlanCalculator // TODO collect at the root of the repository, read the one at the root, and fetch remote if something is missing // or the user forces the issue - private List calculateForkedGoal( MojoExecution mojoExecution, MavenSession session, - MavenProject project, - Collection alreadyPlannedExecutions ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { + private List calculateForkedGoal( + MojoExecution mojoExecution, + MavenSession session, + MavenProject project, + Collection alreadyPlannedExecutions) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); String forkedGoal = mojoDescriptor.getExecuteGoal(); - MojoDescriptor forkedMojoDescriptor = pluginDescriptor.getMojo( forkedGoal ); - if ( forkedMojoDescriptor == null ) - { - throw new MojoNotFoundException( forkedGoal, pluginDescriptor ); + MojoDescriptor forkedMojoDescriptor = pluginDescriptor.getMojo(forkedGoal); + if (forkedMojoDescriptor == null) { + throw new MojoNotFoundException(forkedGoal, pluginDescriptor); } - if ( alreadyPlannedExecutions.contains( forkedMojoDescriptor ) ) - { + if (alreadyPlannedExecutions.contains(forkedMojoDescriptor)) { return Collections.emptyList(); } - MojoExecution forkedExecution = new MojoExecution( forkedMojoDescriptor, forkedGoal ); + MojoExecution forkedExecution = new MojoExecution(forkedMojoDescriptor, forkedGoal); - mojoExecutionConfigurator( forkedExecution ).configure( project, forkedExecution, true ); + mojoExecutionConfigurator(forkedExecution).configure(project, forkedExecution, true); - finalizeMojoConfiguration( forkedExecution ); + finalizeMojoConfiguration(forkedExecution); - calculateForkedExecutions( forkedExecution, session, project, alreadyPlannedExecutions ); + calculateForkedExecutions(forkedExecution, session, project, alreadyPlannedExecutions); - return Collections.singletonList( forkedExecution ); + return Collections.singletonList(forkedExecution); } - private MojoExecutionConfigurator mojoExecutionConfigurator( MojoExecution mojoExecution ) - { + private MojoExecutionConfigurator mojoExecutionConfigurator(MojoExecution mojoExecution) { String configuratorId = mojoExecution.getMojoDescriptor().getComponentConfigurator(); - if ( configuratorId == null ) - { + if (configuratorId == null) { configuratorId = "default"; } - MojoExecutionConfigurator mojoExecutionConfigurator = mojoExecutionConfigurators.get( configuratorId ); + MojoExecutionConfigurator mojoExecutionConfigurator = mojoExecutionConfigurators.get(configuratorId); - if ( mojoExecutionConfigurator == null ) - { + if (mojoExecutionConfigurator == null) { // // The plugin has a custom component configurator but does not have a custom mojo execution configurator // so fall back to the default mojo execution configurator. // - mojoExecutionConfigurator = mojoExecutionConfigurators.get( "default" ); + mojoExecutionConfigurator = mojoExecutionConfigurators.get("default"); } return mojoExecutionConfigurator; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleMappingDelegate.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleMappingDelegate.java index cd7c812668..2187a4ea80 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleMappingDelegate.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleMappingDelegate.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.Lifecycle; import org.apache.maven.lifecycle.LifecycleMappingDelegate; @@ -49,42 +46,35 @@ import org.apache.maven.project.MavenProject; * lifecycle phase. Standard lifecycles use plugin execution {@code } or mojo default lifecycle phase to * calculate the execution plan, but custom lifecycles can use alternative mapping strategies. */ -@Named( DefaultLifecycleMappingDelegate.HINT ) +@Named(DefaultLifecycleMappingDelegate.HINT) @Singleton -public class DefaultLifecycleMappingDelegate - implements LifecycleMappingDelegate -{ +public class DefaultLifecycleMappingDelegate implements LifecycleMappingDelegate { public static final String HINT = "default"; private final BuildPluginManager pluginManager; @Inject - public DefaultLifecycleMappingDelegate( BuildPluginManager pluginManager ) - { + public DefaultLifecycleMappingDelegate(BuildPluginManager pluginManager) { this.pluginManager = pluginManager; } - public Map> calculateLifecycleMappings( MavenSession session, MavenProject project, - Lifecycle lifecycle, String lifecyclePhase ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException - { + public Map> calculateLifecycleMappings( + MavenSession session, MavenProject project, Lifecycle lifecycle, String lifecyclePhase) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException { /* * Initialize mapping from lifecycle phase to bound mojos. The key set of this map denotes the phases the caller * is interested in, i.e. all phases up to and including the specified phase. */ - Map>> mappings = - new LinkedHashMap<>(); + Map>> mappings = new LinkedHashMap<>(); - for ( String phase : lifecycle.getPhases() ) - { + for (String phase : lifecycle.getPhases()) { Map> phaseBindings = new TreeMap<>(); - mappings.put( phase, phaseBindings ); + mappings.put(phase, phaseBindings); - if ( phase.equals( lifecyclePhase ) ) - { + if (phase.equals(lifecyclePhase)) { break; } } @@ -96,40 +86,31 @@ public class DefaultLifecycleMappingDelegate * not interested in any of the executions bound to it. */ - for ( Plugin plugin : project.getBuild().getPlugins() ) - { - for ( PluginExecution execution : plugin.getExecutions() ) - { + for (Plugin plugin : project.getBuild().getPlugins()) { + for (PluginExecution execution : plugin.getExecutions()) { // if the phase is specified then I don't have to go fetch the plugin yet and pull it down // to examine the phase it is associated to. - if ( execution.getPhase() != null ) - { - Map> phaseBindings = mappings.get( execution.getPhase() ); - if ( phaseBindings != null ) - { - for ( String goal : execution.getGoals() ) - { - MojoExecution mojoExecution = new MojoExecution( plugin, goal, execution.getId() ); - mojoExecution.setLifecyclePhase( execution.getPhase() ); - addMojoExecution( phaseBindings, mojoExecution, execution.getPriority() ); + if (execution.getPhase() != null) { + Map> phaseBindings = mappings.get(execution.getPhase()); + if (phaseBindings != null) { + for (String goal : execution.getGoals()) { + MojoExecution mojoExecution = new MojoExecution(plugin, goal, execution.getId()); + mojoExecution.setLifecyclePhase(execution.getPhase()); + addMojoExecution(phaseBindings, mojoExecution, execution.getPriority()); } } } // if not then I need to grab the mojo descriptor and look at the phase that is specified - else - { - for ( String goal : execution.getGoals() ) - { - MojoDescriptor mojoDescriptor = - pluginManager.getMojoDescriptor( plugin, goal, project.getRemotePluginRepositories(), - session.getRepositorySession() ); + else { + for (String goal : execution.getGoals()) { + MojoDescriptor mojoDescriptor = pluginManager.getMojoDescriptor( + plugin, goal, project.getRemotePluginRepositories(), session.getRepositorySession()); - Map> phaseBindings = mappings.get( mojoDescriptor.getPhase() ); - if ( phaseBindings != null ) - { - MojoExecution mojoExecution = new MojoExecution( mojoDescriptor, execution.getId() ); - mojoExecution.setLifecyclePhase( mojoDescriptor.getPhase() ); - addMojoExecution( phaseBindings, mojoExecution, execution.getPriority() ); + Map> phaseBindings = mappings.get(mojoDescriptor.getPhase()); + if (phaseBindings != null) { + MojoExecution mojoExecution = new MojoExecution(mojoDescriptor, execution.getId()); + mojoExecution.setLifecyclePhase(mojoDescriptor.getPhase()); + addMojoExecution(phaseBindings, mojoExecution, execution.getPriority()); } } } @@ -138,28 +119,23 @@ public class DefaultLifecycleMappingDelegate Map> lifecycleMappings = new LinkedHashMap<>(); - for ( Map.Entry>> entry : mappings.entrySet() ) - { + for (Map.Entry>> entry : mappings.entrySet()) { List mojoExecutions = new ArrayList<>(); - for ( List executions : entry.getValue().values() ) - { - mojoExecutions.addAll( executions ); + for (List executions : entry.getValue().values()) { + mojoExecutions.addAll(executions); } - lifecycleMappings.put( entry.getKey(), mojoExecutions ); + lifecycleMappings.put(entry.getKey(), mojoExecutions); } return lifecycleMappings; - } - private void addMojoExecution( Map> phaseBindings, MojoExecution mojoExecution, - int priority ) - { - List mojoExecutions = phaseBindings.computeIfAbsent( priority, k -> new ArrayList<>() ); + private void addMojoExecution( + Map> phaseBindings, MojoExecution mojoExecution, int priority) { + List mojoExecutions = phaseBindings.computeIfAbsent(priority, k -> new ArrayList<>()); - mojoExecutions.add( mojoExecution ); + mojoExecutions.add(mojoExecution); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer.java index c52eda83a5..c71fe01f1a 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,9 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; + +import static java.util.Objects.requireNonNull; import java.util.HashSet; import java.util.LinkedHashMap; @@ -25,7 +26,9 @@ import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.xml.Dom; import org.apache.maven.lifecycle.DefaultLifecycles; import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer; @@ -44,12 +47,6 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import static java.util.Objects.requireNonNull; - /** * NOTE: This class is not part of any public api and can be changed or deleted without prior notice. * @@ -61,24 +58,22 @@ import static java.util.Objects.requireNonNull; */ @Singleton @Named -public class DefaultLifecyclePluginAnalyzer - implements LifeCyclePluginAnalyzer -{ +public class DefaultLifecyclePluginAnalyzer implements LifeCyclePluginAnalyzer { public static final String DEFAULTLIFECYCLEBINDINGS_MODELID = "org.apache.maven:maven-core:" - + DefaultLifecyclePluginAnalyzer.class.getPackage().getImplementationVersion() + ":default-lifecycle-bindings"; + + DefaultLifecyclePluginAnalyzer.class.getPackage().getImplementationVersion() + + ":default-lifecycle-bindings"; - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final PlexusContainer plexusContainer; private final DefaultLifecycles defaultLifeCycles; @Inject - public DefaultLifecyclePluginAnalyzer( final PlexusContainer plexusContainer, - final DefaultLifecycles defaultLifeCycles ) - { - this.plexusContainer = requireNonNull( plexusContainer ); - this.defaultLifeCycles = requireNonNull( defaultLifeCycles ); + public DefaultLifecyclePluginAnalyzer( + final PlexusContainer plexusContainer, final DefaultLifecycles defaultLifeCycles) { + this.plexusContainer = requireNonNull(plexusContainer); + this.defaultLifeCycles = requireNonNull(defaultLifeCycles); } // These methods deal with construction intact Plugin object that look like they come from a standard @@ -92,48 +87,38 @@ public class DefaultLifecyclePluginAnalyzer // @Override - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Looking up lifecycle mappings for packaging " + packaging + " from " - + Thread.currentThread().getContextClassLoader() ); + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { + if (logger.isDebugEnabled()) { + logger.debug("Looking up lifecycle mappings for packaging " + packaging + " from " + + Thread.currentThread().getContextClassLoader()); } - LifecycleMapping lifecycleMappingForPackaging = lookupLifecycleMapping( packaging ); + LifecycleMapping lifecycleMappingForPackaging = lookupLifecycleMapping(packaging); - if ( lifecycleMappingForPackaging == null ) - { + if (lifecycleMappingForPackaging == null) { return null; } Map plugins = new LinkedHashMap<>(); - for ( Lifecycle lifecycle : defaultLifeCycles.getLifeCycles() ) - { + for (Lifecycle lifecycle : defaultLifeCycles.getLifeCycles()) { org.apache.maven.lifecycle.mapping.Lifecycle lifecycleConfiguration = - lifecycleMappingForPackaging.getLifecycles().get( lifecycle.getId() ); + lifecycleMappingForPackaging.getLifecycles().get(lifecycle.getId()); Map phaseToGoalMapping = null; - if ( lifecycleConfiguration != null ) - { + if (lifecycleConfiguration != null) { phaseToGoalMapping = lifecycleConfiguration.getLifecyclePhases(); - } - else if ( lifecycle.getDefaultLifecyclePhases() != null ) - { + } else if (lifecycle.getDefaultLifecyclePhases() != null) { phaseToGoalMapping = lifecycle.getDefaultLifecyclePhases(); } - if ( phaseToGoalMapping != null ) - { - for ( Map.Entry goalsForLifecyclePhase : phaseToGoalMapping.entrySet() ) - { + if (phaseToGoalMapping != null) { + for (Map.Entry goalsForLifecyclePhase : phaseToGoalMapping.entrySet()) { String phase = goalsForLifecyclePhase.getKey(); LifecyclePhase goals = goalsForLifecyclePhase.getValue(); - if ( goals != null ) - { - parseLifecyclePhaseDefinitions( plugins, phase, goals ); + if (goals != null) { + parseLifecyclePhaseDefinitions(plugins, phase, goals); } } } @@ -146,120 +131,99 @@ public class DefaultLifecyclePluginAnalyzer * Performs a lookup using Plexus API to make sure we can look up only "visible" (see Maven classloading) components * from current module and for example not extensions coming from other modules. */ - private LifecycleMapping lookupLifecycleMapping( final String packaging ) - { - try - { - return plexusContainer.lookup( LifecycleMapping.class, packaging ); - } - catch ( ComponentLookupException e ) - { - if ( e.getCause() instanceof NoSuchElementException ) - { + private LifecycleMapping lookupLifecycleMapping(final String packaging) { + try { + return plexusContainer.lookup(LifecycleMapping.class, packaging); + } catch (ComponentLookupException e) { + if (e.getCause() instanceof NoSuchElementException) { return null; } - throw new RuntimeException( e ); + throw new RuntimeException(e); } } - private void parseLifecyclePhaseDefinitions( Map plugins, String phase, LifecyclePhase goals ) - { + private void parseLifecyclePhaseDefinitions(Map plugins, String phase, LifecyclePhase goals) { InputSource inputSource = new InputSource(); - inputSource.setModelId( DEFAULTLIFECYCLEBINDINGS_MODELID ); - InputLocation location = new InputLocation( -1, -1, inputSource ); - location.setLocation( 0, location ); + inputSource.setModelId(DEFAULTLIFECYCLEBINDINGS_MODELID); + InputLocation location = new InputLocation(-1, -1, inputSource); + location.setLocation(0, location); List mojos = goals.getMojos(); - if ( mojos != null ) - { + if (mojos != null) { - for ( int i = 0; i < mojos.size(); i++ ) - { - LifecycleMojo mojo = mojos.get( i ); + for (int i = 0; i < mojos.size(); i++) { + LifecycleMojo mojo = mojos.get(i); - GoalSpec gs = parseGoalSpec( mojo.getGoal() ); + GoalSpec gs = parseGoalSpec(mojo.getGoal()); - if ( gs == null ) - { - logger.warn( "Ignored invalid goal specification '" + mojo.getGoal() - + "' from lifecycle mapping for phase " + phase ); + if (gs == null) { + logger.warn("Ignored invalid goal specification '" + mojo.getGoal() + + "' from lifecycle mapping for phase " + phase); continue; } Plugin plugin = new Plugin(); - plugin.setGroupId( gs.groupId ); - plugin.setArtifactId( gs.artifactId ); - plugin.setVersion( gs.version ); + plugin.setGroupId(gs.groupId); + plugin.setArtifactId(gs.artifactId); + plugin.setVersion(gs.version); - plugin.setLocation( "", location ); - plugin.setLocation( "groupId", location ); - plugin.setLocation( "artifactId", location ); - plugin.setLocation( "version", location ); + plugin.setLocation("", location); + plugin.setLocation("groupId", location); + plugin.setLocation("artifactId", location); + plugin.setLocation("version", location); - Plugin existing = plugins.get( plugin ); - if ( existing != null ) - { - if ( existing.getVersion() == null ) - { - existing.setVersion( plugin.getVersion() ); - existing.setLocation( "version", location ); + Plugin existing = plugins.get(plugin); + if (existing != null) { + if (existing.getVersion() == null) { + existing.setVersion(plugin.getVersion()); + existing.setLocation("version", location); } plugin = existing; - } - else - { - plugins.put( plugin, plugin ); + } else { + plugins.put(plugin, plugin); } PluginExecution execution = new PluginExecution(); - execution.setId( getExecutionId( plugin, gs.goal ) ); - execution.setPhase( phase ); - execution.setPriority( i - mojos.size() ); - execution.getGoals().add( gs.goal ); + execution.setId(getExecutionId(plugin, gs.goal)); + execution.setPhase(phase); + execution.setPriority(i - mojos.size()); + execution.getGoals().add(gs.goal); - execution.setLocation( "", location ); - execution.setLocation( "id", location ); - execution.setLocation( "phase", location ); - execution.setLocation( "goals", location ); + execution.setLocation("", location); + execution.setLocation("id", location); + execution.setLocation("phase", location); + execution.setLocation("goals", location); Dom lifecycleConfiguration = mojo.getConfiguration(); - if ( lifecycleConfiguration != null ) - { - execution.setConfiguration( new Xpp3Dom( lifecycleConfiguration ) ); + if (lifecycleConfiguration != null) { + execution.setConfiguration(new Xpp3Dom(lifecycleConfiguration)); } - if ( mojo.getDependencies() != null ) - { - plugin.setDependencies( mojo.getDependencies() ); + if (mojo.getDependencies() != null) { + plugin.setDependencies(mojo.getDependencies()); } - plugin.getExecutions().add( execution ); + plugin.getExecutions().add(execution); } } } - private GoalSpec parseGoalSpec( String goalSpec ) - { + private GoalSpec parseGoalSpec(String goalSpec) { GoalSpec gs = new GoalSpec(); - String[] p = StringUtils.split( goalSpec.trim(), ":" ); + String[] p = StringUtils.split(goalSpec.trim(), ":"); - if ( p.length == 3 ) - { + if (p.length == 3) { // :: gs.groupId = p[0]; gs.artifactId = p[1]; gs.goal = p[2]; - } - else if ( p.length == 4 ) - { + } else if (p.length == 4) { // ::: gs.groupId = p[0]; gs.artifactId = p[1]; gs.version = p[2]; gs.goal = p[3]; - } - else - { + } else { // invalid gs = null; } @@ -267,27 +231,23 @@ public class DefaultLifecyclePluginAnalyzer return gs; } - private String getExecutionId( Plugin plugin, String goal ) - { + private String getExecutionId(Plugin plugin, String goal) { Set existingIds = new HashSet<>(); - for ( PluginExecution execution : plugin.getExecutions() ) - { - existingIds.add( execution.getId() ); + for (PluginExecution execution : plugin.getExecutions()) { + existingIds.add(execution.getId()); } String base = "default-" + goal; String id = base; - for ( int index = 1; existingIds.contains( id ); index++ ) - { + for (int index = 1; existingIds.contains(id); index++) { id = base + '-' + index; } return id; } - static class GoalSpec - { + static class GoalSpec { String groupId; @@ -296,7 +256,5 @@ public class DefaultLifecyclePluginAnalyzer String version; String goal; - } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleTaskSegmentCalculator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleTaskSegmentCalculator.java index 01686f0212..83c73f61f2 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleTaskSegmentCalculator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultLifecycleTaskSegmentCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,15 +16,14 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleNotFoundException; import org.apache.maven.lifecycle.LifecyclePhaseNotFoundException; @@ -55,96 +52,79 @@ import org.codehaus.plexus.util.StringUtils; */ @Named @Singleton -public class DefaultLifecycleTaskSegmentCalculator - implements LifecycleTaskSegmentCalculator -{ +public class DefaultLifecycleTaskSegmentCalculator implements LifecycleTaskSegmentCalculator { private final MojoDescriptorCreator mojoDescriptorCreator; private final LifecyclePluginResolver lifecyclePluginResolver; @Inject public DefaultLifecycleTaskSegmentCalculator( - MojoDescriptorCreator mojoDescriptorCreator, - LifecyclePluginResolver lifecyclePluginResolver ) - { + MojoDescriptorCreator mojoDescriptorCreator, LifecyclePluginResolver lifecyclePluginResolver) { this.mojoDescriptorCreator = mojoDescriptorCreator; this.lifecyclePluginResolver = lifecyclePluginResolver; } - public List calculateTaskSegments( MavenSession session ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + public List calculateTaskSegments(MavenSession session) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { MavenProject rootProject = session.getTopLevelProject(); List tasks = session.getGoals(); - if ( ( tasks == null || tasks.isEmpty() ) && !StringUtils.isEmpty( rootProject.getDefaultGoal() ) ) - { - tasks = Arrays.asList( StringUtils.split( rootProject.getDefaultGoal() ) ); + if ((tasks == null || tasks.isEmpty()) && !StringUtils.isEmpty(rootProject.getDefaultGoal())) { + tasks = Arrays.asList(StringUtils.split(rootProject.getDefaultGoal())); } - return calculateTaskSegments( session, tasks ); + return calculateTaskSegments(session, tasks); } - public List calculateTaskSegments( MavenSession session, List tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException - { - List taskSegments = new ArrayList<>( tasks.size() ); + public List calculateTaskSegments(MavenSession session, List tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException { + List taskSegments = new ArrayList<>(tasks.size()); TaskSegment currentSegment = null; - for ( String task : tasks ) - { - if ( isGoalSpecification( task ) ) - { + for (String task : tasks) { + if (isGoalSpecification(task)) { // "pluginPrefix[:version]:goal" or "groupId:artifactId[:version]:goal" - lifecyclePluginResolver.resolveMissingPluginVersions( session.getTopLevelProject(), session ); + lifecyclePluginResolver.resolveMissingPluginVersions(session.getTopLevelProject(), session); MojoDescriptor mojoDescriptor = - mojoDescriptorCreator.getMojoDescriptor( task, session, session.getTopLevelProject() ); + mojoDescriptorCreator.getMojoDescriptor(task, session, session.getTopLevelProject()); boolean aggregating = mojoDescriptor.isAggregator() || !mojoDescriptor.isProjectRequired(); - if ( currentSegment == null || currentSegment.isAggregating() != aggregating ) - { - currentSegment = new TaskSegment( aggregating ); - taskSegments.add( currentSegment ); + if (currentSegment == null || currentSegment.isAggregating() != aggregating) { + currentSegment = new TaskSegment(aggregating); + taskSegments.add(currentSegment); } - currentSegment.getTasks().add( new GoalTask( task ) ); - } - else - { + currentSegment.getTasks().add(new GoalTask(task)); + } else { // lifecycle phase - if ( currentSegment == null || currentSegment.isAggregating() ) - { - currentSegment = new TaskSegment( false ); - taskSegments.add( currentSegment ); + if (currentSegment == null || currentSegment.isAggregating()) { + currentSegment = new TaskSegment(false); + taskSegments.add(currentSegment); } - currentSegment.getTasks().add( new LifecycleTask( task ) ); + currentSegment.getTasks().add(new LifecycleTask(task)); } } return taskSegments; } - public boolean requiresProject( MavenSession session ) - { + public boolean requiresProject(MavenSession session) { List goals = session.getGoals(); - if ( goals != null ) - { - for ( String goal : goals ) - { - if ( !isGoalSpecification( goal ) ) - { + if (goals != null) { + for (String goal : goals) { + if (!isGoalSpecification(goal)) { return true; } } @@ -152,10 +132,7 @@ public class DefaultLifecycleTaskSegmentCalculator return false; } - - private boolean isGoalSpecification( String task ) - { - return task.indexOf( ':' ) >= 0; + private boolean isGoalSpecification(String task) { + return task.indexOf(':') >= 0; } - -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator.java index 9e362d252b..c9154146e8 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,16 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; + +import static java.util.Arrays.stream; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.xml.Dom; import org.apache.maven.internal.xml.Xpp3Dom; import org.apache.maven.lifecycle.MojoExecutionConfigurator; @@ -42,65 +41,53 @@ import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static java.util.Arrays.stream; - /** * @since 3.3.1, MNG-5753 */ @Named @Singleton -public class DefaultMojoExecutionConfigurator - implements MojoExecutionConfigurator -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultMojoExecutionConfigurator implements MojoExecutionConfigurator { + private final Logger logger = LoggerFactory.getLogger(getClass()); @Override - public void configure( MavenProject project, MojoExecution mojoExecution, boolean allowPluginLevelConfig ) - { + public void configure(MavenProject project, MojoExecution mojoExecution, boolean allowPluginLevelConfig) { String g = mojoExecution.getPlugin().getGroupId(); String a = mojoExecution.getPlugin().getArtifactId(); - Plugin plugin = findPlugin( g, a, project.getBuildPlugins() ); + Plugin plugin = findPlugin(g, a, project.getBuildPlugins()); - if ( plugin == null && project.getPluginManagement() != null ) - { - plugin = findPlugin( g, a, project.getPluginManagement().getPlugins() ); + if (plugin == null && project.getPluginManagement() != null) { + plugin = findPlugin(g, a, project.getPluginManagement().getPlugins()); } - if ( plugin != null ) - { + if (plugin != null) { PluginExecution pluginExecution = - findPluginExecution( mojoExecution.getExecutionId(), plugin.getExecutions() ); + findPluginExecution(mojoExecution.getExecutionId(), plugin.getExecutions()); Dom pomConfiguration = null; - if ( pluginExecution != null ) - { + if (pluginExecution != null) { pomConfiguration = pluginExecution.getDelegate().getConfiguration(); - } - else if ( allowPluginLevelConfig ) - { + } else if (allowPluginLevelConfig) { pomConfiguration = plugin.getDelegate().getConfiguration(); } Dom mojoConfiguration = mojoExecution.getConfiguration() != null - ? mojoExecution.getConfiguration().getDom() : null; + ? mojoExecution.getConfiguration().getDom() + : null; - Dom mergedConfiguration = Xpp3Dom.merge( mojoConfiguration, pomConfiguration ); + Dom mergedConfiguration = Xpp3Dom.merge(mojoConfiguration, pomConfiguration); - mojoExecution.setConfiguration( mergedConfiguration ); + mojoExecution.setConfiguration(mergedConfiguration); - checkUnknownMojoConfigurationParameters( mojoExecution ); + checkUnknownMojoConfigurationParameters(mojoExecution); } } - private Plugin findPlugin( String groupId, String artifactId, Collection plugins ) - { - for ( Plugin plugin : plugins ) - { - if ( artifactId.equals( plugin.getArtifactId() ) && groupId.equals( plugin.getGroupId() ) ) - { + private Plugin findPlugin(String groupId, String artifactId, Collection plugins) { + for (Plugin plugin : plugins) { + if (artifactId.equals(plugin.getArtifactId()) && groupId.equals(plugin.getGroupId())) { return plugin; } } @@ -108,14 +95,10 @@ public class DefaultMojoExecutionConfigurator return null; } - private PluginExecution findPluginExecution( String executionId, Collection executions ) - { - if ( StringUtils.isNotEmpty( executionId ) ) - { - for ( PluginExecution execution : executions ) - { - if ( executionId.equals( execution.getId() ) ) - { + private PluginExecution findPluginExecution(String executionId, Collection executions) { + if (StringUtils.isNotEmpty(executionId)) { + for (PluginExecution execution : executions) { + if (executionId.equals(execution.getId())) { return execution; } } @@ -124,10 +107,9 @@ public class DefaultMojoExecutionConfigurator return null; } - private void checkUnknownMojoConfigurationParameters( MojoExecution mojoExecution ) - { - if ( mojoExecution.getConfiguration() == null || mojoExecution.getConfiguration().getChildCount() == 0 ) - { + private void checkUnknownMojoConfigurationParameters(MojoExecution mojoExecution) { + if (mojoExecution.getConfiguration() == null + || mojoExecution.getConfiguration().getChildCount() == 0) { return; } @@ -135,66 +117,58 @@ public class DefaultMojoExecutionConfigurator // in first step get parameter names of current goal Set parametersNamesGoal = mojoDescriptor.getParameters().stream() - .flatMap( this::getParameterNames ) - .collect( Collectors.toSet() ); + .flatMap(this::getParameterNames) + .collect(Collectors.toSet()); - Set unknownParameters = getUnknownParameters( mojoExecution, parametersNamesGoal ); + Set unknownParameters = getUnknownParameters(mojoExecution, parametersNamesGoal); - if ( unknownParameters.isEmpty() ) - { + if (unknownParameters.isEmpty()) { return; } // second step get parameter names of all plugin goals Set parametersNamesAll = mojoDescriptor.getPluginDescriptor().getMojos().stream() - .flatMap( m -> m.getParameters().stream() ) - .flatMap( this::getParameterNames ) - .collect( Collectors.toSet() ); + .flatMap(m -> m.getParameters().stream()) + .flatMap(this::getParameterNames) + .collect(Collectors.toSet()); - unknownParameters = getUnknownParameters( mojoExecution, parametersNamesAll ); + unknownParameters = getUnknownParameters(mojoExecution, parametersNamesAll); - unknownParameters.forEach( - name -> - { - MessageBuilder messageBuilder = MessageUtils.buffer() - .warning( "Parameter '" ) - .warning( name ) - .warning( "' is unknown for plugin '" ) - .warning( mojoExecution.getArtifactId() ).warning( ":" ) - .warning( mojoExecution.getVersion() ).warning( ":" ) - .warning( mojoExecution.getGoal() ); + unknownParameters.forEach(name -> { + MessageBuilder messageBuilder = MessageUtils.buffer() + .warning("Parameter '") + .warning(name) + .warning("' is unknown for plugin '") + .warning(mojoExecution.getArtifactId()) + .warning(":") + .warning(mojoExecution.getVersion()) + .warning(":") + .warning(mojoExecution.getGoal()); - if ( mojoExecution.getExecutionId() != null ) - { - messageBuilder.warning( " (" ); - messageBuilder.warning( mojoExecution.getExecutionId() ); - messageBuilder.warning( ")" ); - } + if (mojoExecution.getExecutionId() != null) { + messageBuilder.warning(" ("); + messageBuilder.warning(mojoExecution.getExecutionId()); + messageBuilder.warning(")"); + } - messageBuilder.warning( "'" ); + messageBuilder.warning("'"); - logger.warn( messageBuilder.toString() ); - } ); + logger.warn(messageBuilder.toString()); + }); } - private Stream getParameterNames( Parameter parameter ) - { - if ( parameter.getAlias() != null ) - { - return Stream.of( parameter.getName(), parameter.getAlias() ); - } - else - { - return Stream.of( parameter.getName() ); + private Stream getParameterNames(Parameter parameter) { + if (parameter.getAlias() != null) { + return Stream.of(parameter.getName(), parameter.getAlias()); + } else { + return Stream.of(parameter.getName()); } } - private Set getUnknownParameters( MojoExecution mojoExecution, Set parameters ) - { - return stream( mojoExecution.getConfiguration().getChildren() ) - .map( x -> x.getName() ) - .filter( name -> !parameters.contains( name ) ) - .collect( Collectors.toSet() ); + private Set getUnknownParameters(MojoExecution mojoExecution, Set parameters) { + return stream(mojoExecution.getConfiguration().getChildren()) + .map(x -> x.getName()) + .filter(name -> !parameters.contains(name)) + .collect(Collectors.toSet()); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultProjectArtifactFactory.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultProjectArtifactFactory.java index b5868e7b92..1ce34fa786 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultProjectArtifactFactory.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultProjectArtifactFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,12 +16,11 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.project.MavenProject; @@ -33,25 +30,18 @@ import org.apache.maven.project.artifact.MavenMetadataSource; /** * Default component responsible for creation of MavenProject#dependencyArtifacts instances. */ -@SuppressWarnings( "deprecation" ) +@SuppressWarnings("deprecation") @Named -public class DefaultProjectArtifactFactory - implements ProjectArtifactFactory -{ +public class DefaultProjectArtifactFactory implements ProjectArtifactFactory { private final ArtifactFactory artifactFactory; @Inject - public DefaultProjectArtifactFactory( ArtifactFactory artifactFactory ) - { + public DefaultProjectArtifactFactory(ArtifactFactory artifactFactory) { this.artifactFactory = artifactFactory; } @Override - public Set createArtifacts( MavenProject project ) - throws InvalidDependencyVersionException - { - return MavenMetadataSource.createArtifacts( artifactFactory, - project.getDependencies(), null, null, project ); + public Set createArtifacts(MavenProject project) throws InvalidDependencyVersionException { + return MavenMetadataSource.createArtifacts(artifactFactory, project.getDependencies(), null, null, project); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DependencyContext.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DependencyContext.java index 5572f52f74..734f8a8cf3 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DependencyContext.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DependencyContext.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.project.MavenProject; +package org.apache.maven.lifecycle.internal; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.TreeSet; +import org.apache.maven.project.MavenProject; /** *

    @@ -37,8 +35,7 @@ import java.util.TreeSet; * @author Kristian Rosenvold (class extract only) */ // TODO From a concurrency perspective, this class is not good. The combination of mutable/immutable state is not nice -public class DependencyContext -{ +public class DependencyContext { private static final Collection UNRESOLVED = Arrays.asList(); @@ -56,58 +53,48 @@ public class DependencyContext private volatile int lastDependencyArtifactCount = -1; - public DependencyContext( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve ) - { + public DependencyContext( + MavenProject project, Collection scopesToCollect, Collection scopesToResolve) { this.project = project; scopesToCollectForCurrentProject = scopesToCollect; scopesToResolveForCurrentProject = scopesToResolve; - scopesToCollectForAggregatedProjects = Collections.synchronizedSet( new TreeSet<>() ); - scopesToResolveForAggregatedProjects = Collections.synchronizedSet( new TreeSet<>() ); + scopesToCollectForAggregatedProjects = Collections.synchronizedSet(new TreeSet<>()); + scopesToResolveForAggregatedProjects = Collections.synchronizedSet(new TreeSet<>()); } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public Collection getScopesToCollectForCurrentProject() - { + public Collection getScopesToCollectForCurrentProject() { return scopesToCollectForCurrentProject; } - public Collection getScopesToResolveForCurrentProject() - { + public Collection getScopesToResolveForCurrentProject() { return scopesToResolveForCurrentProject; } - public Collection getScopesToCollectForAggregatedProjects() - { + public Collection getScopesToCollectForAggregatedProjects() { return scopesToCollectForAggregatedProjects; } - public Collection getScopesToResolveForAggregatedProjects() - { + public Collection getScopesToResolveForAggregatedProjects() { return scopesToResolveForAggregatedProjects; } - public boolean isResolutionRequiredForCurrentProject() - { - return lastDependencyArtifacts != project.getDependencyArtifacts() || ( lastDependencyArtifacts != null - && lastDependencyArtifactCount != lastDependencyArtifacts.size() ); + public boolean isResolutionRequiredForCurrentProject() { + return lastDependencyArtifacts != project.getDependencyArtifacts() + || (lastDependencyArtifacts != null && lastDependencyArtifactCount != lastDependencyArtifacts.size()); } - public boolean isResolutionRequiredForAggregatedProjects( Collection scopesToCollect, - Collection scopesToResolve ) - { - return scopesToCollectForAggregatedProjects.addAll( scopesToCollect ) - || scopesToResolveForAggregatedProjects.addAll( scopesToResolve ); + public boolean isResolutionRequiredForAggregatedProjects( + Collection scopesToCollect, Collection scopesToResolve) { + return scopesToCollectForAggregatedProjects.addAll(scopesToCollect) + || scopesToResolveForAggregatedProjects.addAll(scopesToResolve); } - public void synchronizeWithProjectState() - { + public void synchronizeWithProjectState() { lastDependencyArtifacts = project.getDependencyArtifacts(); - lastDependencyArtifactCount = ( lastDependencyArtifacts != null ) ? lastDependencyArtifacts.size() : 0; + lastDependencyArtifactCount = (lastDependencyArtifacts != null) ? lastDependencyArtifacts.size() : 0; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionEventCatapult.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionEventCatapult.java index acff5661f8..109b31d8b6 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionEventCatapult.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionEventCatapult.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.execution.MavenSession; @@ -30,11 +29,9 @@ import org.apache.maven.plugin.MojoExecution; * * @author Benjamin Bentmann */ -public interface ExecutionEventCatapult -{ +public interface ExecutionEventCatapult { - void fire( ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution ); - - void fire( ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution, Exception exception ); + void fire(ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution); + void fire(ExecutionEvent.Type eventType, MavenSession session, MojoExecution mojoExecution, Exception exception); } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionPlanItem.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionPlanItem.java index a52eeb0b17..77816bbd99 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionPlanItem.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ExecutionPlanItem.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,16 +16,16 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; +import java.util.ArrayList; +import java.util.List; import org.apache.maven.lifecycle.internal.builder.BuilderCommon; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.project.MavenProject; -import java.util.ArrayList; -import java.util.List; - /** *

    * Wraps individual MojoExecutions, containing information about completion status and scheduling. @@ -37,49 +35,39 @@ import java.util.List; * @since 3.0 * @author Kristian Rosenvold */ -public class ExecutionPlanItem -{ +public class ExecutionPlanItem { private final MojoExecution mojoExecution; - public ExecutionPlanItem( MojoExecution mojoExecution ) - { + public ExecutionPlanItem(MojoExecution mojoExecution) { this.mojoExecution = mojoExecution; } - public static List createExecutionPlanItems( MavenProject mavenProject, - List executions ) - { - BuilderCommon.attachToThread( mavenProject ); + public static List createExecutionPlanItems( + MavenProject mavenProject, List executions) { + BuilderCommon.attachToThread(mavenProject); List result = new ArrayList<>(); - for ( MojoExecution mojoExecution : executions ) - { - result.add( new ExecutionPlanItem( mojoExecution ) ); + for (MojoExecution mojoExecution : executions) { + result.add(new ExecutionPlanItem(mojoExecution)); } return result; } - public MojoExecution getMojoExecution() - { + public MojoExecution getMojoExecution() { return mojoExecution; } - public String getLifecyclePhase() - { + public String getLifecyclePhase() { return mojoExecution.getLifecyclePhase(); } - public Plugin getPlugin() - { + public Plugin getPlugin() { final MojoDescriptor mojoDescriptor = getMojoExecution().getMojoDescriptor(); return mojoDescriptor.getPluginDescriptor().getPlugin(); } @Override - public String toString() - { - return "ExecutionPlanItem{" + ", mojoExecution=" + mojoExecution + '}' - + super.toString(); + public String toString() { + return "ExecutionPlanItem{" + ", mojoExecution=" + mojoExecution + '}' + super.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/GoalTask.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/GoalTask.java index abcdda596e..927e6e609d 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/GoalTask.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/GoalTask.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; /** *

    @@ -28,19 +27,16 @@ package org.apache.maven.lifecycle.internal; * @since 3.0 * @author Benjamin Bentmann */ -public final class GoalTask -{ +public final class GoalTask { final String pluginGoal; - public GoalTask( String pluginGoal ) - { + public GoalTask(String pluginGoal) { this.pluginGoal = pluginGoal; } @Override - public String toString() - { + public String toString() { return pluginGoal; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDebugLogger.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDebugLogger.java index a26b197b2a..eddf9c52fc 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDebugLogger.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDebugLogger.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.lifecycle.MavenExecutionPlan; import org.apache.maven.lifecycle.internal.builder.BuilderCommon; import org.apache.maven.plugin.MojoExecution; @@ -50,125 +47,105 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class LifecycleDebugLogger -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class LifecycleDebugLogger { + private final Logger logger = LoggerFactory.getLogger(getClass()); - public void debug( String s ) - { - logger.debug( s ); + public void debug(String s) { + logger.debug(s); } - public void info( String s ) - { - logger.info( s ); + public void info(String s) { + logger.info(s); } - public void debugReactorPlan( ProjectBuildList projectBuilds ) - { - if ( !logger.isDebugEnabled() ) - { + public void debugReactorPlan(ProjectBuildList projectBuilds) { + if (!logger.isDebugEnabled()) { return; } - logger.debug( "=== REACTOR BUILD PLAN ================================================" ); + logger.debug("=== REACTOR BUILD PLAN ================================================"); - for ( Iterator it = projectBuilds.iterator(); it.hasNext(); ) - { + for (Iterator it = projectBuilds.iterator(); it.hasNext(); ) { ProjectSegment projectBuild = it.next(); - logger.debug( "Project: " + projectBuild.getProject().getId() ); - logger.debug( "Tasks: " + projectBuild.getTaskSegment().getTasks() ); - logger.debug( "Style: " + ( projectBuild.getTaskSegment().isAggregating() ? "Aggregating" : "Regular" ) ); + logger.debug("Project: " + projectBuild.getProject().getId()); + logger.debug("Tasks: " + projectBuild.getTaskSegment().getTasks()); + logger.debug("Style: " + (projectBuild.getTaskSegment().isAggregating() ? "Aggregating" : "Regular")); - if ( it.hasNext() ) - { - logger.debug( "-----------------------------------------------------------------------" ); + if (it.hasNext()) { + logger.debug("-----------------------------------------------------------------------"); } } - logger.debug( "=======================================================================" ); + logger.debug("======================================================================="); } - - public void debugProjectPlan( MavenProject currentProject, MavenExecutionPlan executionPlan ) - { - if ( !logger.isDebugEnabled() ) - { + public void debugProjectPlan(MavenProject currentProject, MavenExecutionPlan executionPlan) { + if (!logger.isDebugEnabled()) { return; } - logger.debug( "=== PROJECT BUILD PLAN ================================================" ); - logger.debug( "Project: " + BuilderCommon.getKey( currentProject ) ); + logger.debug("=== PROJECT BUILD PLAN ================================================"); + logger.debug("Project: " + BuilderCommon.getKey(currentProject)); - debugDependencyRequirements( executionPlan.getMojoExecutions() ); + debugDependencyRequirements(executionPlan.getMojoExecutions()); - logger.debug( "Repositories (dependencies): " + currentProject.getRemoteProjectRepositories() ); - logger.debug( "Repositories (plugins) : " + currentProject.getRemotePluginRepositories() ); + logger.debug("Repositories (dependencies): " + currentProject.getRemoteProjectRepositories()); + logger.debug("Repositories (plugins) : " + currentProject.getRemotePluginRepositories()); - for ( ExecutionPlanItem mojoExecution : executionPlan ) - { - debugMojoExecution( mojoExecution.getMojoExecution() ); + for (ExecutionPlanItem mojoExecution : executionPlan) { + debugMojoExecution(mojoExecution.getMojoExecution()); } - logger.debug( "=======================================================================" ); + logger.debug("======================================================================="); } - private void debugMojoExecution( MojoExecution mojoExecution ) - { + private void debugMojoExecution(MojoExecution mojoExecution) { String mojoExecId = - mojoExecution.getGroupId() + ':' + mojoExecution.getArtifactId() + ':' + mojoExecution.getVersion() + ':' - + mojoExecution.getGoal() + " (" + mojoExecution.getExecutionId() + ')'; + mojoExecution.getGroupId() + ':' + mojoExecution.getArtifactId() + ':' + mojoExecution.getVersion() + + ':' + mojoExecution.getGoal() + " (" + mojoExecution.getExecutionId() + ')'; Map> forkedExecutions = mojoExecution.getForkedExecutions(); - if ( !forkedExecutions.isEmpty() ) - { - for ( Map.Entry> fork : forkedExecutions.entrySet() ) - { - logger.debug( "--- init fork of " + fork.getKey() + " for " + mojoExecId + " ---" ); + if (!forkedExecutions.isEmpty()) { + for (Map.Entry> fork : forkedExecutions.entrySet()) { + logger.debug("--- init fork of " + fork.getKey() + " for " + mojoExecId + " ---"); - debugDependencyRequirements( fork.getValue() ); + debugDependencyRequirements(fork.getValue()); - for ( MojoExecution forkedExecution : fork.getValue() ) - { - debugMojoExecution( forkedExecution ); + for (MojoExecution forkedExecution : fork.getValue()) { + debugMojoExecution(forkedExecution); } - logger.debug( "--- exit fork of " + fork.getKey() + " for " + mojoExecId + " ---" ); + logger.debug("--- exit fork of " + fork.getKey() + " for " + mojoExecId + " ---"); } } - logger.debug( "-----------------------------------------------------------------------" ); - logger.debug( "Goal: " + mojoExecId ); + logger.debug("-----------------------------------------------------------------------"); + logger.debug("Goal: " + mojoExecId); logger.debug( - "Style: " + ( mojoExecution.getMojoDescriptor().isAggregator() ? "Aggregating" : "Regular" ) ); - logger.debug( "Configuration: " + mojoExecution.getConfiguration() ); + "Style: " + (mojoExecution.getMojoDescriptor().isAggregator() ? "Aggregating" : "Regular")); + logger.debug("Configuration: " + mojoExecution.getConfiguration()); } - private void debugDependencyRequirements( List mojoExecutions ) - { + private void debugDependencyRequirements(List mojoExecutions) { Set scopesToCollect = new TreeSet<>(); Set scopesToResolve = new TreeSet<>(); - for ( MojoExecution mojoExecution : mojoExecutions ) - { + for (MojoExecution mojoExecution : mojoExecutions) { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); String scopeToCollect = mojoDescriptor.getDependencyCollectionRequired(); - if ( StringUtils.isNotEmpty( scopeToCollect ) ) - { - scopesToCollect.add( scopeToCollect ); + if (StringUtils.isNotEmpty(scopeToCollect)) { + scopesToCollect.add(scopeToCollect); } String scopeToResolve = mojoDescriptor.getDependencyResolutionRequired(); - if ( StringUtils.isNotEmpty( scopeToResolve ) ) - { - scopesToResolve.add( scopeToResolve ); + if (StringUtils.isNotEmpty(scopeToResolve)) { + scopesToResolve.add(scopeToResolve); } } - logger.debug( "Dependencies (collect): " + scopesToCollect ); - logger.debug( "Dependencies (resolve): " + scopesToResolve ); + logger.debug("Dependencies (collect): " + scopesToCollect); + logger.debug("Dependencies (resolve): " + scopesToResolve); } - -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java index b3b26210f0..5a5db6e7fc 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.io.File; - import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -29,10 +27,8 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; @@ -65,9 +61,8 @@ import org.slf4j.LoggerFactory; * @author Kristian Rosenvold (extracted class) */ @Named -public class LifecycleDependencyResolver -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class LifecycleDependencyResolver { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final ProjectDependenciesResolver dependenciesResolver; @@ -82,176 +77,157 @@ public class LifecycleDependencyResolver ProjectDependenciesResolver dependenciesResolver, ProjectArtifactFactory artifactFactory, EventSpyDispatcher eventSpyDispatcher, - ProjectArtifactsCache projectArtifactsCache ) - { + ProjectArtifactsCache projectArtifactsCache) { this.dependenciesResolver = dependenciesResolver; this.artifactFactory = artifactFactory; this.eventSpyDispatcher = eventSpyDispatcher; this.projectArtifactsCache = projectArtifactsCache; } - public static List getProjects( MavenProject project, MavenSession session, boolean aggregator ) - { - if ( aggregator ) - { + public static List getProjects(MavenProject project, MavenSession session, boolean aggregator) { + if (aggregator) { return session.getProjects(); - } - else - { - return Collections.singletonList( project ); + } else { + return Collections.singletonList(project); } } - public void resolveProjectDependencies( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, - boolean aggregating, Set projectArtifacts ) - throws LifecycleExecutionException - { + public void resolveProjectDependencies( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + boolean aggregating, + Set projectArtifacts) + throws LifecycleExecutionException { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - try - { + try { ClassLoader projectRealm = project.getClassRealm(); - if ( projectRealm != null && projectRealm != tccl ) - { - Thread.currentThread().setContextClassLoader( projectRealm ); + if (projectRealm != null && projectRealm != tccl) { + Thread.currentThread().setContextClassLoader(projectRealm); } - if ( project.getDependencyArtifacts() == null ) - { - try - { - project.setDependencyArtifacts( artifactFactory.createArtifacts( project ) ); - } - catch ( InvalidDependencyVersionException e ) - { - throw new LifecycleExecutionException( e ); + if (project.getDependencyArtifacts() == null) { + try { + project.setDependencyArtifacts(artifactFactory.createArtifacts(project)); + } catch (InvalidDependencyVersionException e) { + throw new LifecycleExecutionException(e); } } - Set resolvedArtifacts = resolveProjectArtifacts( project, scopesToCollect, scopesToResolve, - session, aggregating, projectArtifacts ); + Set resolvedArtifacts = resolveProjectArtifacts( + project, scopesToCollect, scopesToResolve, session, aggregating, projectArtifacts); - Map reactorProjects = new HashMap<>( session.getProjects().size() ); - for ( MavenProject reactorProject : session.getProjects() ) - { - reactorProjects.put( reactorProject.getArtifact(), reactorProject.getArtifact().getFile() ); + Map reactorProjects = + new HashMap<>(session.getProjects().size()); + for (MavenProject reactorProject : session.getProjects()) { + reactorProjects.put( + reactorProject.getArtifact(), + reactorProject.getArtifact().getFile()); } Map map = new HashMap<>(); - for ( Artifact artifact : resolvedArtifacts ) - { + for (Artifact artifact : resolvedArtifacts) { /** * MNG-6300: resolvedArtifacts can be cache result; this ensures reactor files are always up-to-date * During lifecycle the Artifact.getFile() can change from target/classes to the actual jar. * This clearly shows that target/classes should not be abused as artifactFile just for the classpath */ - File reactorProjectFile = reactorProjects.get( artifact ); - if ( reactorProjectFile != null ) - { - artifact.setFile( reactorProjectFile ); + File reactorProjectFile = reactorProjects.get(artifact); + if (reactorProjectFile != null) { + artifact.setFile(reactorProjectFile); } - map.put( artifact.getDependencyConflictId(), artifact ); + map.put(artifact.getDependencyConflictId(), artifact); } - project.setResolvedArtifacts( resolvedArtifacts ); + project.setResolvedArtifacts(resolvedArtifacts); - for ( Artifact artifact : project.getDependencyArtifacts() ) - { - if ( artifact.getFile() == null ) - { - Artifact resolved = map.get( artifact.getDependencyConflictId() ); - if ( resolved != null ) - { - artifact.setFile( resolved.getFile() ); - artifact.setDependencyTrail( resolved.getDependencyTrail() ); - artifact.setResolvedVersion( resolved.getVersion() ); - artifact.setResolved( true ); + for (Artifact artifact : project.getDependencyArtifacts()) { + if (artifact.getFile() == null) { + Artifact resolved = map.get(artifact.getDependencyConflictId()); + if (resolved != null) { + artifact.setFile(resolved.getFile()); + artifact.setDependencyTrail(resolved.getDependencyTrail()); + artifact.setResolvedVersion(resolved.getVersion()); + artifact.setResolved(true); } } } - } - finally - { - Thread.currentThread().setContextClassLoader( tccl ); + } finally { + Thread.currentThread().setContextClassLoader(tccl); } } - public Set resolveProjectArtifacts( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, - boolean aggregating, Set projectArtifacts ) - throws LifecycleExecutionException - { + public Set resolveProjectArtifacts( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + boolean aggregating, + Set projectArtifacts) + throws LifecycleExecutionException { Set resolvedArtifacts; - ProjectArtifactsCache.Key cacheKey = projectArtifactsCache.createKey( project, scopesToCollect, - scopesToResolve, aggregating, session.getRepositorySession() ); + ProjectArtifactsCache.Key cacheKey = projectArtifactsCache.createKey( + project, scopesToCollect, scopesToResolve, aggregating, session.getRepositorySession()); ProjectArtifactsCache.CacheRecord recordArtifacts; - recordArtifacts = projectArtifactsCache.get( cacheKey ); + recordArtifacts = projectArtifactsCache.get(cacheKey); - if ( recordArtifacts != null ) - { + if (recordArtifacts != null) { resolvedArtifacts = recordArtifacts.getArtifacts(); - } - else - { - try - { - resolvedArtifacts = getDependencies( project, scopesToCollect, scopesToResolve, session, - aggregating, projectArtifacts ); - recordArtifacts = projectArtifactsCache.put( cacheKey, resolvedArtifacts ); - } - catch ( LifecycleExecutionException e ) - { - projectArtifactsCache.put( cacheKey, e ); - projectArtifactsCache.register( project, cacheKey, recordArtifacts ); + } else { + try { + resolvedArtifacts = getDependencies( + project, scopesToCollect, scopesToResolve, session, aggregating, projectArtifacts); + recordArtifacts = projectArtifactsCache.put(cacheKey, resolvedArtifacts); + } catch (LifecycleExecutionException e) { + projectArtifactsCache.put(cacheKey, e); + projectArtifactsCache.register(project, cacheKey, recordArtifacts); throw e; } } - projectArtifactsCache.register( project, cacheKey, recordArtifacts ); + projectArtifactsCache.register(project, cacheKey, recordArtifacts); return resolvedArtifacts; } - private Set getDependencies( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, - boolean aggregating, Set projectArtifacts ) - throws LifecycleExecutionException - { - if ( scopesToCollect == null ) - { + private Set getDependencies( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + boolean aggregating, + Set projectArtifacts) + throws LifecycleExecutionException { + if (scopesToCollect == null) { scopesToCollect = Collections.emptySet(); } - if ( scopesToResolve == null ) - { + if (scopesToResolve == null) { scopesToResolve = Collections.emptySet(); } - if ( scopesToCollect.isEmpty() && scopesToResolve.isEmpty() ) - { + if (scopesToCollect.isEmpty() && scopesToResolve.isEmpty()) { return new LinkedHashSet<>(); } - scopesToCollect = new HashSet<>( scopesToCollect ); - scopesToCollect.addAll( scopesToResolve ); + scopesToCollect = new HashSet<>(scopesToCollect); + scopesToCollect.addAll(scopesToResolve); - DependencyFilter collectionFilter = new ScopeDependencyFilter( null, negate( scopesToCollect ) ); - DependencyFilter resolutionFilter = new ScopeDependencyFilter( null, negate( scopesToResolve ) ); - resolutionFilter = AndDependencyFilter.newInstance( collectionFilter, resolutionFilter ); + DependencyFilter collectionFilter = new ScopeDependencyFilter(null, negate(scopesToCollect)); + DependencyFilter resolutionFilter = new ScopeDependencyFilter(null, negate(scopesToResolve)); + resolutionFilter = AndDependencyFilter.newInstance(collectionFilter, resolutionFilter); resolutionFilter = - AndDependencyFilter.newInstance( resolutionFilter, new ReactorDependencyFilter( projectArtifacts ) ); + AndDependencyFilter.newInstance(resolutionFilter, new ReactorDependencyFilter(projectArtifacts)); DependencyResolutionResult result; - try - { + try { DefaultDependencyResolutionRequest request = - new DefaultDependencyResolutionRequest( project, session.getRepositorySession() ); - request.setResolutionFilter( resolutionFilter ); + new DefaultDependencyResolutionRequest(project, session.getRepositorySession()); + request.setResolutionFilter(resolutionFilter); - eventSpyDispatcher.onEvent( request ); + eventSpyDispatcher.onEvent(request); - result = dependenciesResolver.resolve( request ); - } - catch ( DependencyResolutionException e ) - { + result = dependenciesResolver.resolve(request); + } catch (DependencyResolutionException e) { result = e.getResult(); /* @@ -259,47 +235,42 @@ public class LifecycleDependencyResolver * plugins that require dependency resolution although they usually run in phases of the build where project * artifacts haven't been assembled yet. The prime example of this is "mvn release:prepare". */ - if ( aggregating && areAllDependenciesInReactor( session.getProjects(), - result.getUnresolvedDependencies() ) ) - { - logger.warn( "The following dependencies could not be resolved at this point of the build" - + " but seem to be part of the reactor:" ); + if (aggregating && areAllDependenciesInReactor(session.getProjects(), result.getUnresolvedDependencies())) { + logger.warn("The following dependencies could not be resolved at this point of the build" + + " but seem to be part of the reactor:"); - for ( Dependency dependency : result.getUnresolvedDependencies() ) - { - logger.warn( "o " + dependency ); + for (Dependency dependency : result.getUnresolvedDependencies()) { + logger.warn("o " + dependency); } - logger.warn( "Try running the build up to the lifecycle phase \"package\"" ); - } - else - { - throw new LifecycleExecutionException( null, project, e ); + logger.warn("Try running the build up to the lifecycle phase \"package\""); + } else { + throw new LifecycleExecutionException(null, project, e); } } - eventSpyDispatcher.onEvent( result ); + eventSpyDispatcher.onEvent(result); Set artifacts = new LinkedHashSet<>(); - if ( result.getDependencyGraph() != null && !result.getDependencyGraph().getChildren().isEmpty() ) - { - RepositoryUtils.toArtifacts( artifacts, result.getDependencyGraph().getChildren(), - Collections.singletonList( project.getArtifact().getId() ), collectionFilter ); + if (result.getDependencyGraph() != null + && !result.getDependencyGraph().getChildren().isEmpty()) { + RepositoryUtils.toArtifacts( + artifacts, + result.getDependencyGraph().getChildren(), + Collections.singletonList(project.getArtifact().getId()), + collectionFilter); } return artifacts; } - private boolean areAllDependenciesInReactor( Collection projects, - Collection dependencies ) - { - Set projectKeys = getReactorProjectKeys( projects ); + private boolean areAllDependenciesInReactor( + Collection projects, Collection dependencies) { + Set projectKeys = getReactorProjectKeys(projects); - for ( Dependency dependency : dependencies ) - { + for (Dependency dependency : dependencies) { org.eclipse.aether.artifact.Artifact a = dependency.getArtifact(); - String key = ArtifactUtils.key( a.getGroupId(), a.getArtifactId(), a.getVersion() ); - if ( !projectKeys.contains( key ) ) - { + String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getVersion()); + if (!projectKeys.contains(key)) { return false; } } @@ -307,50 +278,37 @@ public class LifecycleDependencyResolver return true; } - private Set getReactorProjectKeys( Collection projects ) - { - Set projectKeys = new HashSet<>( projects.size() * 2 ); - for ( MavenProject project : projects ) - { - String key = ArtifactUtils.key( project.getGroupId(), project.getArtifactId(), project.getVersion() ); - projectKeys.add( key ); + private Set getReactorProjectKeys(Collection projects) { + Set projectKeys = new HashSet<>(projects.size() * 2); + for (MavenProject project : projects) { + String key = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion()); + projectKeys.add(key); } return projectKeys; } - private Collection negate( Collection scopes ) - { + private Collection negate(Collection scopes) { Collection result = new HashSet<>(); - Collections.addAll( result, "system", "compile", "provided", "runtime", "test" ); + Collections.addAll(result, "system", "compile", "provided", "runtime", "test"); - for ( String scope : scopes ) - { - if ( "compile".equals( scope ) ) - { - result.remove( "compile" ); - result.remove( "system" ); - result.remove( "provided" ); - } - else if ( "runtime".equals( scope ) ) - { - result.remove( "compile" ); - result.remove( "runtime" ); - } - else if ( "compile+runtime".equals( scope ) ) - { - result.remove( "compile" ); - result.remove( "system" ); - result.remove( "provided" ); - result.remove( "runtime" ); - } - else if ( "runtime+system".equals( scope ) ) - { - result.remove( "compile" ); - result.remove( "system" ); - result.remove( "runtime" ); - } - else if ( "test".equals( scope ) ) - { + for (String scope : scopes) { + if ("compile".equals(scope)) { + result.remove("compile"); + result.remove("system"); + result.remove("provided"); + } else if ("runtime".equals(scope)) { + result.remove("compile"); + result.remove("runtime"); + } else if ("compile+runtime".equals(scope)) { + result.remove("compile"); + result.remove("system"); + result.remove("provided"); + result.remove("runtime"); + } else if ("runtime+system".equals(scope)) { + result.remove("compile"); + result.remove("system"); + result.remove("runtime"); + } else if ("test".equals(scope)) { result.clear(); } } @@ -358,33 +316,25 @@ public class LifecycleDependencyResolver return result; } - private static class ReactorDependencyFilter - implements DependencyFilter - { + private static class ReactorDependencyFilter implements DependencyFilter { private Set keys = new HashSet<>(); - ReactorDependencyFilter( Collection artifacts ) - { - for ( Artifact artifact : artifacts ) - { - String key = ArtifactUtils.key( artifact ); - keys.add( key ); + ReactorDependencyFilter(Collection artifacts) { + for (Artifact artifact : artifacts) { + String key = ArtifactUtils.key(artifact); + keys.add(key); } } - public boolean accept( DependencyNode node, List parents ) - { + public boolean accept(DependencyNode node, List parents) { Dependency dependency = node.getDependency(); - if ( dependency != null ) - { + if (dependency != null) { org.eclipse.aether.artifact.Artifact a = dependency.getArtifact(); - String key = ArtifactUtils.key( a.getGroupId(), a.getArtifactId(), a.getVersion() ); - return !keys.contains( key ); + String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getVersion()); + return !keys.contains(key); } return false; } - } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java index c5ed0f14ee..1a7f41d163 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,7 +16,10 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; +import java.util.List; +import java.util.Set; import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleNotFoundException; import org.apache.maven.lifecycle.LifecyclePhaseNotFoundException; @@ -34,36 +35,34 @@ import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; -import java.util.List; -import java.util.Set; - /** * @since 3.0 * @author Benjamin Bentmann * @author Kristian Rosenvold (extract interface only) */ -public interface LifecycleExecutionPlanCalculator -{ - MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List tasks ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; +public interface LifecycleExecutionPlanCalculator { + MavenExecutionPlan calculateExecutionPlan(MavenSession session, MavenProject project, List tasks) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; - MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List tasks, - boolean setup ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; + MavenExecutionPlan calculateExecutionPlan( + MavenSession session, MavenProject project, List tasks, boolean setup) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; - void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; - - void setupMojoExecution( MavenSession session, MavenProject project, MojoExecution mojoExecution, - Set alreadyPlannedExecutions ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; + void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; + void setupMojoExecution( + MavenSession session, + MavenProject project, + MojoExecution mojoExecution, + Set alreadyPlannedExecutions) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java index 17340fbe7e..8e930e0310 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.HashSet; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.BuildSuccess; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.execution.MavenSession; @@ -50,8 +47,7 @@ import org.apache.maven.session.scope.internal.SessionScope; */ @Named @Singleton -public class LifecycleModuleBuilder -{ +public class LifecycleModuleBuilder { private final MojoExecutor mojoExecutor; private final BuilderCommon builderCommon; @@ -65,84 +61,75 @@ public class LifecycleModuleBuilder BuilderCommon builderCommon, ExecutionEventCatapult eventCatapult, List listeners, - SessionScope sessionScope ) - { + SessionScope sessionScope) { this.mojoExecutor = mojoExecutor; this.builderCommon = builderCommon; this.eventCatapult = eventCatapult; - this.projectExecutionListener = new CompoundProjectExecutionListener( listeners ); + this.projectExecutionListener = new CompoundProjectExecutionListener(listeners); this.sessionScope = sessionScope; } - public void buildProject( MavenSession session, ReactorContext reactorContext, MavenProject currentProject, - TaskSegment taskSegment ) - { - buildProject( session, session, reactorContext, currentProject, taskSegment ); + public void buildProject( + MavenSession session, ReactorContext reactorContext, MavenProject currentProject, TaskSegment taskSegment) { + buildProject(session, session, reactorContext, currentProject, taskSegment); } - public void buildProject( MavenSession session, MavenSession rootSession, ReactorContext reactorContext, - MavenProject currentProject, TaskSegment taskSegment ) - { - session.setCurrentProject( currentProject ); + public void buildProject( + MavenSession session, + MavenSession rootSession, + ReactorContext reactorContext, + MavenProject currentProject, + TaskSegment taskSegment) { + session.setCurrentProject(currentProject); long buildStartTime = System.currentTimeMillis(); - try - { + try { - if ( reactorContext.getReactorBuildStatus().isHaltedOrBlacklisted( currentProject ) ) - { - eventCatapult.fire( ExecutionEvent.Type.ProjectSkipped, session, null ); + if (reactorContext.getReactorBuildStatus().isHaltedOrBlacklisted(currentProject)) { + eventCatapult.fire(ExecutionEvent.Type.ProjectSkipped, session, null); return; } - BuilderCommon.attachToThread( currentProject ); + BuilderCommon.attachToThread(currentProject); - projectExecutionListener.beforeProjectExecution( new ProjectExecutionEvent( session, currentProject ) ); + projectExecutionListener.beforeProjectExecution(new ProjectExecutionEvent(session, currentProject)); - eventCatapult.fire( ExecutionEvent.Type.ProjectStarted, session, null ); + eventCatapult.fire(ExecutionEvent.Type.ProjectStarted, session, null); MavenExecutionPlan executionPlan = - builderCommon.resolveBuildPlan( session, currentProject, taskSegment, new HashSet<>() ); + builderCommon.resolveBuildPlan(session, currentProject, taskSegment, new HashSet<>()); List mojoExecutions = executionPlan.getMojoExecutions(); - projectExecutionListener.beforeProjectLifecycleExecution( new ProjectExecutionEvent( session, - currentProject, - mojoExecutions ) ); - mojoExecutor.execute( session, mojoExecutions, reactorContext.getProjectIndex() ); + projectExecutionListener.beforeProjectLifecycleExecution( + new ProjectExecutionEvent(session, currentProject, mojoExecutions)); + mojoExecutor.execute(session, mojoExecutions, reactorContext.getProjectIndex()); long buildEndTime = System.currentTimeMillis(); - projectExecutionListener.afterProjectExecutionSuccess( new ProjectExecutionEvent( session, currentProject, - mojoExecutions ) ); + projectExecutionListener.afterProjectExecutionSuccess( + new ProjectExecutionEvent(session, currentProject, mojoExecutions)); - reactorContext.getResult().addBuildSummary( new BuildSuccess( currentProject, - buildEndTime - buildStartTime ) ); + reactorContext.getResult().addBuildSummary(new BuildSuccess(currentProject, buildEndTime - buildStartTime)); - eventCatapult.fire( ExecutionEvent.Type.ProjectSucceeded, session, null ); - } - catch ( Throwable t ) - { - builderCommon.handleBuildError( reactorContext, rootSession, session, currentProject, t, buildStartTime ); + eventCatapult.fire(ExecutionEvent.Type.ProjectSucceeded, session, null); + } catch (Throwable t) { + builderCommon.handleBuildError(reactorContext, rootSession, session, currentProject, t, buildStartTime); - projectExecutionListener.afterProjectExecutionFailure( new ProjectExecutionEvent( session, currentProject, - t ) ); + projectExecutionListener.afterProjectExecutionFailure( + new ProjectExecutionEvent(session, currentProject, t)); // rethrow original errors and runtime exceptions - if ( t instanceof RuntimeException ) - { + if (t instanceof RuntimeException) { throw (RuntimeException) t; } - if ( t instanceof Error ) - { + if (t instanceof Error) { throw (Error) t; } - } - finally - { - session.setCurrentProject( null ); + } finally { + session.setCurrentProject(null); - Thread.currentThread().setContextClassLoader( reactorContext.getOriginalContextClassLoader() ); + Thread.currentThread().setContextClassLoader(reactorContext.getOriginalContextClassLoader()); } } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecyclePluginResolver.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecyclePluginResolver.java index 1f6fab0a58..d06c0254a0 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecyclePluginResolver.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecyclePluginResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.HashMap; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginManagement; @@ -43,49 +40,39 @@ import org.apache.maven.project.MavenProject; */ @Named @Singleton -public class LifecyclePluginResolver -{ +public class LifecyclePluginResolver { private final PluginVersionResolver pluginVersionResolver; @Inject - public LifecyclePluginResolver( PluginVersionResolver pluginVersionResolver ) - { + public LifecyclePluginResolver(PluginVersionResolver pluginVersionResolver) { this.pluginVersionResolver = pluginVersionResolver; } - public void resolveMissingPluginVersions( MavenProject project, MavenSession session ) - throws PluginVersionResolutionException - { - Map versions = new HashMap<>( 64 ); + public void resolveMissingPluginVersions(MavenProject project, MavenSession session) + throws PluginVersionResolutionException { + Map versions = new HashMap<>(64); - for ( Plugin plugin : project.getBuildPlugins() ) - { - if ( plugin.getVersion() == null ) - { - PluginVersionRequest request = new DefaultPluginVersionRequest( plugin, session.getRepositorySession(), - project.getRemotePluginRepositories() ); - plugin.setVersion( pluginVersionResolver.resolve( request ).getVersion() ); + for (Plugin plugin : project.getBuildPlugins()) { + if (plugin.getVersion() == null) { + PluginVersionRequest request = new DefaultPluginVersionRequest( + plugin, session.getRepositorySession(), project.getRemotePluginRepositories()); + plugin.setVersion(pluginVersionResolver.resolve(request).getVersion()); } - versions.put( plugin.getKey(), plugin.getVersion() ); + versions.put(plugin.getKey(), plugin.getVersion()); } PluginManagement pluginManagement = project.getPluginManagement(); - if ( pluginManagement != null ) - { - for ( Plugin plugin : pluginManagement.getPlugins() ) - { - if ( plugin.getVersion() == null ) - { - plugin.setVersion( versions.get( plugin.getKey() ) ); - if ( plugin.getVersion() == null ) - { - PluginVersionRequest request = - new DefaultPluginVersionRequest( plugin, session.getRepositorySession(), - project.getRemotePluginRepositories() ); - plugin.setVersion( pluginVersionResolver.resolve( request ).getVersion() ); + if (pluginManagement != null) { + for (Plugin plugin : pluginManagement.getPlugins()) { + if (plugin.getVersion() == null) { + plugin.setVersion(versions.get(plugin.getKey())); + if (plugin.getVersion() == null) { + PluginVersionRequest request = new DefaultPluginVersionRequest( + plugin, session.getRepositorySession(), project.getRemotePluginRepositories()); + plugin.setVersion(pluginVersionResolver.resolve(request).getVersion()); } } } } } -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java index 9f2eb5e1a5..e16e0bada7 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.List; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.execution.MavenExecutionResult; import org.apache.maven.execution.MavenSession; @@ -47,9 +44,8 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class LifecycleStarter -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class LifecycleStarter { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final ExecutionEventCatapult eventCatapult; @@ -73,8 +69,7 @@ public class LifecycleStarter LifecycleDebugLogger lifecycleDebugLogger, LifecycleTaskSegmentCalculator lifecycleTaskSegmentCalculator, Map builders, - SessionScope sessionScope ) - { + SessionScope sessionScope) { this.eventCatapult = eventCatapult; this.defaultLifeCycles = defaultLifeCycles; this.buildListCalculator = buildListCalculator; @@ -84,80 +79,68 @@ public class LifecycleStarter this.sessionScope = sessionScope; } - public void execute( MavenSession session ) - { - eventCatapult.fire( ExecutionEvent.Type.SessionStarted, session, null ); + public void execute(MavenSession session) { + eventCatapult.fire(ExecutionEvent.Type.SessionStarted, session, null); ReactorContext reactorContext = null; ProjectBuildList projectBuilds = null; MavenExecutionResult result = session.getResult(); - try - { - if ( buildExecutionRequiresProject( session ) && projectIsNotPresent( session ) ) - { - throw new MissingProjectException( "The goal you specified requires a project to execute" - + " but there is no POM in this directory (" + session.getExecutionRootDirectory() + ")." - + " Please verify you invoked Maven from the correct directory." ); + try { + if (buildExecutionRequiresProject(session) && projectIsNotPresent(session)) { + throw new MissingProjectException("The goal you specified requires a project to execute" + + " but there is no POM in this directory (" + session.getExecutionRootDirectory() + ")." + + " Please verify you invoked Maven from the correct directory."); } - List taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments( session ); - projectBuilds = buildListCalculator.calculateProjectBuilds( session, taskSegments ); + List taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments(session); + projectBuilds = buildListCalculator.calculateProjectBuilds(session, taskSegments); - if ( projectBuilds.isEmpty() ) - { - throw new NoGoalSpecifiedException( "No goals have been specified for this build." - + " You must specify a valid lifecycle phase or a goal in the format : or" - + " :[:]:." - + " Available lifecycle phases are: " + defaultLifeCycles.getLifecyclePhaseList() + "." ); + if (projectBuilds.isEmpty()) { + throw new NoGoalSpecifiedException("No goals have been specified for this build." + + " You must specify a valid lifecycle phase or a goal in the format : or" + + " :[:]:." + + " Available lifecycle phases are: " + defaultLifeCycles.getLifecyclePhaseList() + "."); } - ProjectIndex projectIndex = new ProjectIndex( session.getProjects() ); + ProjectIndex projectIndex = new ProjectIndex(session.getProjects()); - if ( logger.isDebugEnabled() ) - { - lifecycleDebugLogger.debugReactorPlan( projectBuilds ); + if (logger.isDebugEnabled()) { + lifecycleDebugLogger.debugReactorPlan(projectBuilds); } ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); - ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus( session.getProjectDependencyGraph() ); - reactorContext = new ReactorContext( result, projectIndex, oldContextClassLoader, reactorBuildStatus ); + ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus(session.getProjectDependencyGraph()); + reactorContext = new ReactorContext(result, projectIndex, oldContextClassLoader, reactorBuildStatus); String builderId = session.getRequest().getBuilderId(); - Builder builder = builders.get( builderId ); - if ( builder == null ) - { - throw new BuilderNotFoundException( String.format( "The builder requested using id = %s cannot be" - + " found", builderId ) ); + Builder builder = builders.get(builderId); + if (builder == null) { + throw new BuilderNotFoundException( + String.format("The builder requested using id = %s cannot be" + " found", builderId)); } int degreeOfConcurrency = session.getRequest().getDegreeOfConcurrency(); - if ( degreeOfConcurrency > 1 ) - { - logger.info( "" ); - logger.info( String.format( "Using the %s implementation with a thread count of %d", - builder.getClass().getSimpleName(), degreeOfConcurrency ) ); + if (degreeOfConcurrency > 1) { + logger.info(""); + logger.info(String.format( + "Using the %s implementation with a thread count of %d", + builder.getClass().getSimpleName(), degreeOfConcurrency)); } - builder.build( session, reactorContext, projectBuilds, taskSegments, reactorBuildStatus ); + builder.build(session, reactorContext, projectBuilds, taskSegments, reactorBuildStatus); - } - catch ( Exception e ) - { - result.addException( e ); - } - finally - { - eventCatapult.fire( ExecutionEvent.Type.SessionEnded, session, null ); + } catch (Exception e) { + result.addException(e); + } finally { + eventCatapult.fire(ExecutionEvent.Type.SessionEnded, session, null); } } - private boolean buildExecutionRequiresProject( MavenSession session ) - { - return lifecycleTaskSegmentCalculator.requiresProject( session ); + private boolean buildExecutionRequiresProject(MavenSession session) { + return lifecycleTaskSegmentCalculator.requiresProject(session); } - private boolean projectIsNotPresent( MavenSession session ) - { + private boolean projectIsNotPresent(MavenSession session) { return !session.getRequest().isProjectPresent(); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTask.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTask.java index 56aafd5a18..0fa29f05b1 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTask.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTask.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; /** *

    @@ -28,24 +27,20 @@ package org.apache.maven.lifecycle.internal; * @since 3.0 * @author Benjamin Bentmann */ -public final class LifecycleTask -{ +public final class LifecycleTask { private final String lifecyclePhase; - public LifecycleTask( String lifecyclePhase ) - { + public LifecycleTask(String lifecyclePhase) { this.lifecyclePhase = lifecyclePhase; } @Override - public String toString() - { + public String toString() { return getLifecyclePhase(); } - public String getLifecyclePhase() - { + public String getLifecyclePhase() { return lifecyclePhase; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculator.java index 7dd84d8d1b..d3e3550970 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,7 +16,9 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; +import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleNotFoundException; import org.apache.maven.lifecycle.LifecyclePhaseNotFoundException; @@ -30,8 +30,6 @@ import org.apache.maven.plugin.PluginResolutionException; import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; -import java.util.List; - /** *

    * Calculates the task segments in the build @@ -44,18 +42,16 @@ import java.util.List; * @author jdcasey * @author Kristian Rosenvold (extracted interface) */ -public interface LifecycleTaskSegmentCalculator -{ - List calculateTaskSegments( MavenSession session ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException; +public interface LifecycleTaskSegmentCalculator { + List calculateTaskSegments(MavenSession session) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException; - List calculateTaskSegments( MavenSession session, List tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException; - - boolean requiresProject( MavenSession session ); + List calculateTaskSegments(MavenSession session, List tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException; + boolean requiresProject(MavenSession session); } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoDescriptorCreator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoDescriptorCreator.java index 65b1cb8b6f..3a0db94abe 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoDescriptorCreator.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoDescriptorCreator.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.xml.Dom; import org.apache.maven.execution.MavenSession; import org.apache.maven.internal.xml.Xpp3Dom; @@ -68,9 +65,8 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class MojoDescriptorCreator -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class MojoDescriptorCreator { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final PluginVersionResolver pluginVersionResolver; private final BuildPluginManager pluginManager; private final PluginPrefixResolver pluginPrefixResolver; @@ -81,20 +77,16 @@ public class MojoDescriptorCreator PluginVersionResolver pluginVersionResolver, BuildPluginManager pluginManager, PluginPrefixResolver pluginPrefixResolver, - LifecyclePluginResolver lifecyclePluginResolver ) - { + LifecyclePluginResolver lifecyclePluginResolver) { this.pluginVersionResolver = pluginVersionResolver; this.pluginManager = pluginManager; this.pluginPrefixResolver = pluginPrefixResolver; this.lifecyclePluginResolver = lifecyclePluginResolver; } - private Plugin findPlugin( String groupId, String artifactId, Collection plugins ) - { - for ( Plugin plugin : plugins ) - { - if ( artifactId.equals( plugin.getArtifactId() ) && groupId.equals( plugin.getGroupId() ) ) - { + private Plugin findPlugin(String groupId, String artifactId, Collection plugins) { + for (Plugin plugin : plugins) { + if (artifactId.equals(plugin.getArtifactId()) && groupId.equals(plugin.getGroupId())) { return plugin; } } @@ -102,49 +94,46 @@ public class MojoDescriptorCreator return null; } - public static org.codehaus.plexus.util.xml.Xpp3Dom convert( MojoDescriptor mojoDescriptor ) - { + public static org.codehaus.plexus.util.xml.Xpp3Dom convert(MojoDescriptor mojoDescriptor) { PlexusConfiguration c = mojoDescriptor.getMojoConfiguration(); List children = new ArrayList<>(); PlexusConfiguration[] ces = c.getChildren(); - if ( ces != null ) - { - for ( PlexusConfiguration ce : ces ) - { - String value = ce.getValue( null ); - String defaultValue = ce.getAttribute( "default-value", null ); - if ( value != null || defaultValue != null ) - { - Xpp3Dom e = new Xpp3Dom( ce.getName(), value, - defaultValue != null ? Collections.singletonMap( "default-value", defaultValue ) : null, - null, null ); - children.add( e ); + if (ces != null) { + for (PlexusConfiguration ce : ces) { + String value = ce.getValue(null); + String defaultValue = ce.getAttribute("default-value", null); + if (value != null || defaultValue != null) { + Xpp3Dom e = new Xpp3Dom( + ce.getName(), + value, + defaultValue != null ? Collections.singletonMap("default-value", defaultValue) : null, + null, + null); + children.add(e); } } } - Xpp3Dom dom = new Xpp3Dom( "configuration", null, null, children, null ); - return new org.codehaus.plexus.util.xml.Xpp3Dom( dom ); + Xpp3Dom dom = new Xpp3Dom("configuration", null, null, children, null); + return new org.codehaus.plexus.util.xml.Xpp3Dom(dom); } // org.apache.maven.plugins:maven-remote-resources-plugin:1.0:process@executionId - public MojoDescriptor getMojoDescriptor( String task, MavenSession session, MavenProject project ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException - { + public MojoDescriptor getMojoDescriptor(String task, MavenSession session, MavenProject project) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException { String goal = null; Plugin plugin = null; - StringTokenizer tok = new StringTokenizer( task, ":" ); + StringTokenizer tok = new StringTokenizer(task, ":"); int numTokens = tok.countTokens(); - if ( numTokens >= 4 ) - { + if (numTokens >= 4) { // We have everything that we need // // org.apache.maven.plugins:maven-remote-resources-plugin:1.0:process @@ -155,25 +144,21 @@ public class MojoDescriptorCreator // goal // plugin = new Plugin(); - plugin.setGroupId( tok.nextToken() ); - plugin.setArtifactId( tok.nextToken() ); - plugin.setVersion( tok.nextToken() ); + plugin.setGroupId(tok.nextToken()); + plugin.setArtifactId(tok.nextToken()); + plugin.setVersion(tok.nextToken()); goal = tok.nextToken(); // This won't be valid, but it constructs something easy to read in the error message - while ( tok.hasMoreTokens() ) - { + while (tok.hasMoreTokens()) { goal += ":" + tok.nextToken(); } - } - else if ( numTokens == 3 ) - { + } else if (numTokens == 3) { // groupId:artifactId:goal or pluginPrefix:version:goal (since Maven 3.9.0) String firstToken = tok.nextToken(); // groupId or pluginPrefix? heuristics: groupId contains dot (.) but not pluginPrefix - if ( firstToken.contains( "." ) ) - { + if (firstToken.contains(".")) { // We have everything that we need except the version // // org.apache.maven.plugins:maven-remote-resources-plugin:???:process @@ -184,31 +169,24 @@ public class MojoDescriptorCreator // goal // plugin = new Plugin(); - plugin.setGroupId( firstToken ); - plugin.setArtifactId( tok.nextToken() ); - } - else - { + plugin.setGroupId(firstToken); + plugin.setArtifactId(tok.nextToken()); + } else { // pluginPrefix:version:goal, like remote-resources:3.5.0:process - plugin = findPluginForPrefix( firstToken, session ); - plugin.setVersion( tok.nextToken() ); + plugin = findPluginForPrefix(firstToken, session); + plugin.setVersion(tok.nextToken()); } goal = tok.nextToken(); - } - else - { + } else { // We have a prefix and goal // // idea:idea // String prefix = tok.nextToken(); - if ( numTokens == 2 ) - { + if (numTokens == 2) { goal = tok.nextToken(); - } - else - { + } else { // goal was missing - pass through to MojoNotFoundException goal = ""; } @@ -222,93 +200,77 @@ public class MojoDescriptorCreator // Maven plugin deployment we will find the right PluginDescriptor from the remote // repository. - plugin = findPluginForPrefix( prefix, session ); + plugin = findPluginForPrefix(prefix, session); } - int executionIdx = goal.indexOf( '@' ); - if ( executionIdx > 0 ) - { - goal = goal.substring( 0, executionIdx ); + int executionIdx = goal.indexOf('@'); + if (executionIdx > 0) { + goal = goal.substring(0, executionIdx); } - injectPluginDeclarationFromProject( plugin, project ); + injectPluginDeclarationFromProject(plugin, project); // If there is no version to be found then we need to look in the repository metadata for // this plugin and see what's specified as the latest release. // - if ( plugin.getVersion() == null ) - { - resolvePluginVersion( plugin, session, project ); + if (plugin.getVersion() == null) { + resolvePluginVersion(plugin, session, project); } - return pluginManager.getMojoDescriptor( plugin, goal.toString(), project.getRemotePluginRepositories(), - session.getRepositorySession() ); + return pluginManager.getMojoDescriptor( + plugin, goal.toString(), project.getRemotePluginRepositories(), session.getRepositorySession()); } // TODO take repo mans into account as one may be aggregating prefixes of many // TODO collect at the root of the repository, read the one at the root, and fetch remote if something is missing // or the user forces the issue - public Plugin findPluginForPrefix( String prefix, MavenSession session ) - throws NoPluginFoundForPrefixException - { + public Plugin findPluginForPrefix(String prefix, MavenSession session) throws NoPluginFoundForPrefixException { // [prefix]:[goal] - if ( session.getCurrentProject() != null ) - { - try - { - lifecyclePluginResolver.resolveMissingPluginVersions( session.getCurrentProject(), session ); - } - catch ( PluginVersionResolutionException e ) - { + if (session.getCurrentProject() != null) { + try { + lifecyclePluginResolver.resolveMissingPluginVersions(session.getCurrentProject(), session); + } catch (PluginVersionResolutionException e) { // not critical here - logger.debug( e.getMessage(), e ); + logger.debug(e.getMessage(), e); } } - PluginPrefixRequest prefixRequest = new DefaultPluginPrefixRequest( prefix, session ); - PluginPrefixResult prefixResult = pluginPrefixResolver.resolve( prefixRequest ); + PluginPrefixRequest prefixRequest = new DefaultPluginPrefixRequest(prefix, session); + PluginPrefixResult prefixResult = pluginPrefixResolver.resolve(prefixRequest); Plugin plugin = new Plugin(); - plugin.setGroupId( prefixResult.getGroupId() ); - plugin.setArtifactId( prefixResult.getArtifactId() ); + plugin.setGroupId(prefixResult.getGroupId()); + plugin.setArtifactId(prefixResult.getArtifactId()); return plugin; } - private void resolvePluginVersion( Plugin plugin, MavenSession session, MavenProject project ) - throws PluginVersionResolutionException - { - PluginVersionRequest versionRequest = - new DefaultPluginVersionRequest( plugin, session.getRepositorySession(), - project.getRemotePluginRepositories() ); - plugin.setVersion( pluginVersionResolver.resolve( versionRequest ).getVersion() ); + private void resolvePluginVersion(Plugin plugin, MavenSession session, MavenProject project) + throws PluginVersionResolutionException { + PluginVersionRequest versionRequest = new DefaultPluginVersionRequest( + plugin, session.getRepositorySession(), project.getRemotePluginRepositories()); + plugin.setVersion(pluginVersionResolver.resolve(versionRequest).getVersion()); } - private void injectPluginDeclarationFromProject( Plugin plugin, MavenProject project ) - { - Plugin pluginInPom = findPlugin( plugin, project.getBuildPlugins() ); + private void injectPluginDeclarationFromProject(Plugin plugin, MavenProject project) { + Plugin pluginInPom = findPlugin(plugin, project.getBuildPlugins()); - if ( pluginInPom == null && project.getPluginManagement() != null ) - { - pluginInPom = findPlugin( plugin, project.getPluginManagement().getPlugins() ); + if (pluginInPom == null && project.getPluginManagement() != null) { + pluginInPom = findPlugin(plugin, project.getPluginManagement().getPlugins()); } - if ( pluginInPom != null ) - { - if ( plugin.getVersion() == null ) - { - plugin.setVersion( pluginInPom.getVersion() ); + if (pluginInPom != null) { + if (plugin.getVersion() == null) { + plugin.setVersion(pluginInPom.getVersion()); } - plugin.setDependencies( new ArrayList<>( pluginInPom.getDependencies() ) ); + plugin.setDependencies(new ArrayList<>(pluginInPom.getDependencies())); } } - private Plugin findPlugin( Plugin plugin, Collection plugins ) - { - return findPlugin( plugin.getGroupId(), plugin.getArtifactId(), plugins ); + private Plugin findPlugin(Plugin plugin, Collection plugins) { + return findPlugin(plugin.getGroupId(), plugin.getArtifactId(), plugins); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java index 9b9eb761a8..62c0f95a5f 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.Arrays; @@ -31,12 +30,10 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.CumulativeScopeArtifactFilter; @@ -50,8 +47,8 @@ import org.apache.maven.plugin.MavenPluginManager; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionRunner; -import org.apache.maven.plugin.MojosExecutionStrategy; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.MojosExecutionStrategy; import org.apache.maven.plugin.PluginConfigurationException; import org.apache.maven.plugin.PluginIncompatibleException; import org.apache.maven.plugin.PluginManagerException; @@ -75,10 +72,9 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class MojoExecutor -{ +public class MojoExecutor { - private static final Logger LOGGER = LoggerFactory.getLogger( MojoExecutor.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(MojoExecutor.class); private final BuildPluginManager pluginManager; private final MavenPluginManager mavenPluginManager; @@ -97,8 +93,7 @@ public class MojoExecutor MavenPluginManager mavenPluginManager, LifecycleDependencyResolver lifeCycleDependencyResolver, ExecutionEventCatapult eventCatapult, - Provider mojosExecutionStrategy ) - { + Provider mojosExecutionStrategy) { this.pluginManager = pluginManager; this.mavenPluginManager = mavenPluginManager; this.lifeCycleDependencyResolver = lifeCycleDependencyResolver; @@ -106,130 +101,113 @@ public class MojoExecutor this.mojosExecutionStrategy = mojosExecutionStrategy; } - public DependencyContext newDependencyContext( MavenSession session, List mojoExecutions ) - { + public DependencyContext newDependencyContext(MavenSession session, List mojoExecutions) { Set scopesToCollect = new TreeSet<>(); Set scopesToResolve = new TreeSet<>(); - collectDependencyRequirements( scopesToResolve, scopesToCollect, mojoExecutions ); + collectDependencyRequirements(scopesToResolve, scopesToCollect, mojoExecutions); - return new DependencyContext( session.getCurrentProject(), scopesToCollect, scopesToResolve ); + return new DependencyContext(session.getCurrentProject(), scopesToCollect, scopesToResolve); } - private void collectDependencyRequirements( Set scopesToResolve, Set scopesToCollect, - Collection mojoExecutions ) - { - for ( MojoExecution mojoExecution : mojoExecutions ) - { + private void collectDependencyRequirements( + Set scopesToResolve, Set scopesToCollect, Collection mojoExecutions) { + for (MojoExecution mojoExecution : mojoExecutions) { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); - scopesToResolve.addAll( toScopes( mojoDescriptor.getDependencyResolutionRequired() ) ); + scopesToResolve.addAll(toScopes(mojoDescriptor.getDependencyResolutionRequired())); - scopesToCollect.addAll( toScopes( mojoDescriptor.getDependencyCollectionRequired() ) ); + scopesToCollect.addAll(toScopes(mojoDescriptor.getDependencyCollectionRequired())); } } - private Collection toScopes( String classpath ) - { + private Collection toScopes(String classpath) { Collection scopes = Collections.emptyList(); - if ( StringUtils.isNotEmpty( classpath ) ) - { - if ( Artifact.SCOPE_COMPILE.equals( classpath ) ) - { - scopes = Arrays.asList( Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED ); - } - else if ( Artifact.SCOPE_RUNTIME.equals( classpath ) ) - { - scopes = Arrays.asList( Artifact.SCOPE_COMPILE, Artifact.SCOPE_RUNTIME ); - } - else if ( Artifact.SCOPE_COMPILE_PLUS_RUNTIME.equals( classpath ) ) - { - scopes = Arrays.asList( Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED, - Artifact.SCOPE_RUNTIME ); - } - else if ( Artifact.SCOPE_RUNTIME_PLUS_SYSTEM.equals( classpath ) ) - { - scopes = Arrays.asList( Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_RUNTIME ); - } - else if ( Artifact.SCOPE_TEST.equals( classpath ) ) - { - scopes = Arrays.asList( Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED, - Artifact.SCOPE_RUNTIME, Artifact.SCOPE_TEST ); + if (StringUtils.isNotEmpty(classpath)) { + if (Artifact.SCOPE_COMPILE.equals(classpath)) { + scopes = Arrays.asList(Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED); + } else if (Artifact.SCOPE_RUNTIME.equals(classpath)) { + scopes = Arrays.asList(Artifact.SCOPE_COMPILE, Artifact.SCOPE_RUNTIME); + } else if (Artifact.SCOPE_COMPILE_PLUS_RUNTIME.equals(classpath)) { + scopes = Arrays.asList( + Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME); + } else if (Artifact.SCOPE_RUNTIME_PLUS_SYSTEM.equals(classpath)) { + scopes = Arrays.asList(Artifact.SCOPE_COMPILE, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_RUNTIME); + } else if (Artifact.SCOPE_TEST.equals(classpath)) { + scopes = Arrays.asList( + Artifact.SCOPE_COMPILE, + Artifact.SCOPE_SYSTEM, + Artifact.SCOPE_PROVIDED, + Artifact.SCOPE_RUNTIME, + Artifact.SCOPE_TEST); } } - return Collections.unmodifiableCollection( scopes ); + return Collections.unmodifiableCollection(scopes); } - public void execute( final MavenSession session, - final List mojoExecutions, - final ProjectIndex projectIndex ) - throws LifecycleExecutionException + public void execute( + final MavenSession session, final List mojoExecutions, final ProjectIndex projectIndex) + throws LifecycleExecutionException { - { - final DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions ); + final DependencyContext dependencyContext = newDependencyContext(session, mojoExecutions); - final PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() ); + final PhaseRecorder phaseRecorder = new PhaseRecorder(session.getCurrentProject()); - mojosExecutionStrategy.get().execute( mojoExecutions, session, new MojoExecutionRunner() - { + mojosExecutionStrategy.get().execute(mojoExecutions, session, new MojoExecutionRunner() { @Override - public void run( MojoExecution mojoExecution ) throws LifecycleExecutionException - { - MojoExecutor.this.execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder ); + public void run(MojoExecution mojoExecution) throws LifecycleExecutionException { + MojoExecutor.this.execute(session, mojoExecution, projectIndex, dependencyContext, phaseRecorder); } - } ); + }); } - private void execute( MavenSession session, MojoExecution mojoExecution, ProjectIndex projectIndex, - DependencyContext dependencyContext, PhaseRecorder phaseRecorder ) - throws LifecycleExecutionException - { - execute( session, mojoExecution, projectIndex, dependencyContext ); - phaseRecorder.observeExecution( mojoExecution ); + private void execute( + MavenSession session, + MojoExecution mojoExecution, + ProjectIndex projectIndex, + DependencyContext dependencyContext, + PhaseRecorder phaseRecorder) + throws LifecycleExecutionException { + execute(session, mojoExecution, projectIndex, dependencyContext); + phaseRecorder.observeExecution(mojoExecution); } - private void execute( MavenSession session, MojoExecution mojoExecution, ProjectIndex projectIndex, - DependencyContext dependencyContext ) - throws LifecycleExecutionException - { + private void execute( + MavenSession session, + MojoExecution mojoExecution, + ProjectIndex projectIndex, + DependencyContext dependencyContext) + throws LifecycleExecutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); - try - { - mavenPluginManager.checkPrerequisites( mojoDescriptor.getPluginDescriptor() ); - } - catch ( PluginIncompatibleException e ) - { - throw new LifecycleExecutionException( mojoExecution, session.getCurrentProject(), e ); + try { + mavenPluginManager.checkPrerequisites(mojoDescriptor.getPluginDescriptor()); + } catch (PluginIncompatibleException e) { + throw new LifecycleExecutionException(mojoExecution, session.getCurrentProject(), e); } - if ( mojoDescriptor.isProjectRequired() && !session.getRequest().isProjectPresent() ) - { + if (mojoDescriptor.isProjectRequired() && !session.getRequest().isProjectPresent()) { Throwable cause = new MissingProjectException( - "Goal requires a project to execute" + " but there is no POM in this directory (" - + session.getExecutionRootDirectory() + ")." - + " Please verify you invoked Maven from the correct directory." ); - throw new LifecycleExecutionException( mojoExecution, null, cause ); + "Goal requires a project to execute" + " but there is no POM in this directory (" + + session.getExecutionRootDirectory() + ")." + + " Please verify you invoked Maven from the correct directory."); + throw new LifecycleExecutionException(mojoExecution, null, cause); } - if ( mojoDescriptor.isOnlineRequired() && session.isOffline() ) - { - if ( MojoExecution.Source.CLI.equals( mojoExecution.getSource() ) ) - { + if (mojoDescriptor.isOnlineRequired() && session.isOffline()) { + if (MojoExecution.Source.CLI.equals(mojoExecution.getSource())) { Throwable cause = new IllegalStateException( - "Goal requires online mode for execution" + " but Maven is currently offline." ); - throw new LifecycleExecutionException( mojoExecution, session.getCurrentProject(), cause ); - } - else - { - eventCatapult.fire( ExecutionEvent.Type.MojoSkipped, session, mojoExecution ); + "Goal requires online mode for execution" + " but Maven is currently offline."); + throw new LifecycleExecutionException(mojoExecution, session.getCurrentProject(), cause); + } else { + eventCatapult.fire(ExecutionEvent.Type.MojoSkipped, session, mojoExecution); return; } } - doExecute( session, mojoExecution, projectIndex, dependencyContext ); + doExecute(session, mojoExecution, projectIndex, dependencyContext); } /** @@ -240,304 +218,256 @@ public class MojoExecutor * TODO: ideally, the builder should take care of the ordering in a smarter way * TODO: and concurrency issues fixed with MNG-7157 */ - private class ProjectLock implements AutoCloseable - { + private class ProjectLock implements AutoCloseable { final Lock acquiredAggregatorLock; final OwnerReentrantLock acquiredProjectLock; - ProjectLock( MavenSession session, MojoDescriptor mojoDescriptor ) - { - mojos.put( Thread.currentThread(), mojoDescriptor ); - if ( session.getRequest().getDegreeOfConcurrency() > 1 ) - { + ProjectLock(MavenSession session, MojoDescriptor mojoDescriptor) { + mojos.put(Thread.currentThread(), mojoDescriptor); + if (session.getRequest().getDegreeOfConcurrency() > 1) { boolean aggregator = mojoDescriptor.isAggregator(); acquiredAggregatorLock = aggregator ? aggregatorLock.writeLock() : aggregatorLock.readLock(); - acquiredProjectLock = getProjectLock( session ); - if ( !acquiredAggregatorLock.tryLock() ) - { + acquiredProjectLock = getProjectLock(session); + if (!acquiredAggregatorLock.tryLock()) { Thread owner = aggregatorLock.getOwner(); - MojoDescriptor ownerMojo = owner != null ? mojos.get( owner ) : null; + MojoDescriptor ownerMojo = owner != null ? mojos.get(owner) : null; String str = ownerMojo != null ? " The " + ownerMojo.getId() : "An"; String msg = str + " aggregator mojo is already being executed " + "in this parallel build, those kind of mojos require exclusive access to " + "reactor to prevent race conditions. This mojo execution will be blocked " + "until the aggregator mojo is done."; - warn( msg ); + warn(msg); acquiredAggregatorLock.lock(); } - if ( !acquiredProjectLock.tryLock() ) - { + if (!acquiredProjectLock.tryLock()) { Thread owner = acquiredProjectLock.getOwner(); - MojoDescriptor ownerMojo = owner != null ? mojos.get( owner ) : null; + MojoDescriptor ownerMojo = owner != null ? mojos.get(owner) : null; String str = ownerMojo != null ? " The " + ownerMojo.getId() : "A"; String msg = str + " mojo is already being executed " + "on the project " + session.getCurrentProject().getGroupId() + ":" + session.getCurrentProject().getArtifactId() + ". " + "This mojo execution will be blocked " + "until the mojo is done."; - warn( msg ); + warn(msg); acquiredProjectLock.lock(); } - } - else - { + } else { acquiredAggregatorLock = null; acquiredProjectLock = null; } } @Override - public void close() - { + public void close() { // release the lock in the reverse order of the acquisition - if ( acquiredProjectLock != null ) - { + if (acquiredProjectLock != null) { acquiredProjectLock.unlock(); } - if ( acquiredAggregatorLock != null ) - { + if (acquiredAggregatorLock != null) { acquiredAggregatorLock.unlock(); } - mojos.remove( Thread.currentThread() ); + mojos.remove(Thread.currentThread()); } - @SuppressWarnings( { "unchecked", "rawtypes" } ) - private OwnerReentrantLock getProjectLock( MavenSession session ) - { + @SuppressWarnings({"unchecked", "rawtypes"}) + private OwnerReentrantLock getProjectLock(MavenSession session) { SessionData data = session.getRepositorySession().getData(); // TODO: when resolver 1.7.3 is released, the code below should be changed to // TODO: Map locks = ( Map ) ((Map) data).computeIfAbsent( // TODO: ProjectLock.class, l -> new ConcurrentHashMap<>() ); - Map locks = ( Map ) data.get( ProjectLock.class ); + Map locks = (Map) data.get(ProjectLock.class); // initialize the value if not already done (in case of a concurrent access) to the method - if ( locks == null ) - { + if (locks == null) { // the call to data.set(k, null, v) is effectively a call to data.putIfAbsent(k, v) - data.set( ProjectLock.class, null, new ConcurrentHashMap<>() ); - locks = ( Map ) data.get( ProjectLock.class ); + data.set(ProjectLock.class, null, new ConcurrentHashMap<>()); + locks = (Map) data.get(ProjectLock.class); } - return locks.computeIfAbsent( session.getCurrentProject(), p -> new OwnerReentrantLock() ); + return locks.computeIfAbsent(session.getCurrentProject(), p -> new OwnerReentrantLock()); } } - static class OwnerReentrantLock extends ReentrantLock - { + static class OwnerReentrantLock extends ReentrantLock { @Override - public Thread getOwner() - { + public Thread getOwner() { return super.getOwner(); } } - static class OwnerReentrantReadWriteLock extends ReentrantReadWriteLock - { + static class OwnerReentrantReadWriteLock extends ReentrantReadWriteLock { @Override - public Thread getOwner() - { + public Thread getOwner() { return super.getOwner(); } } - private static void warn( String msg ) - { - for ( String s : MultilineMessageHelper.format( msg ) ) - { - LOGGER.warn( s ); + private static void warn(String msg) { + for (String s : MultilineMessageHelper.format(msg)) { + LOGGER.warn(s); } } - private void doExecute( MavenSession session, MojoExecution mojoExecution, ProjectIndex projectIndex, - DependencyContext dependencyContext ) - throws LifecycleExecutionException - { + private void doExecute( + MavenSession session, + MojoExecution mojoExecution, + ProjectIndex projectIndex, + DependencyContext dependencyContext) + throws LifecycleExecutionException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); - List forkedProjects = executeForkedExecutions( mojoExecution, session, projectIndex ); + List forkedProjects = executeForkedExecutions(mojoExecution, session, projectIndex); - ensureDependenciesAreResolved( mojoDescriptor, session, dependencyContext ); + ensureDependenciesAreResolved(mojoDescriptor, session, dependencyContext); - try ( ProjectLock lock = new ProjectLock( session, mojoDescriptor ) ) - { - doExecute2( session, mojoExecution ); - } - finally - { - for ( MavenProject forkedProject : forkedProjects ) - { - forkedProject.setExecutionProject( null ); + try (ProjectLock lock = new ProjectLock(session, mojoDescriptor)) { + doExecute2(session, mojoExecution); + } finally { + for (MavenProject forkedProject : forkedProjects) { + forkedProject.setExecutionProject(null); } } } - private void doExecute2( MavenSession session, MojoExecution mojoExecution ) - throws LifecycleExecutionException - { - eventCatapult.fire( ExecutionEvent.Type.MojoStarted, session, mojoExecution ); - try - { - try - { - pluginManager.executeMojo( session, mojoExecution ); - } - catch ( MojoFailureException | PluginManagerException | PluginConfigurationException - | MojoExecutionException e ) - { - throw new LifecycleExecutionException( mojoExecution, session.getCurrentProject(), e ); + private void doExecute2(MavenSession session, MojoExecution mojoExecution) throws LifecycleExecutionException { + eventCatapult.fire(ExecutionEvent.Type.MojoStarted, session, mojoExecution); + try { + try { + pluginManager.executeMojo(session, mojoExecution); + } catch (MojoFailureException + | PluginManagerException + | PluginConfigurationException + | MojoExecutionException e) { + throw new LifecycleExecutionException(mojoExecution, session.getCurrentProject(), e); } - eventCatapult.fire( ExecutionEvent.Type.MojoSucceeded, session, mojoExecution ); - } - catch ( LifecycleExecutionException e ) - { - eventCatapult.fire( ExecutionEvent.Type.MojoFailed, session, mojoExecution, e ); + eventCatapult.fire(ExecutionEvent.Type.MojoSucceeded, session, mojoExecution); + } catch (LifecycleExecutionException e) { + eventCatapult.fire(ExecutionEvent.Type.MojoFailed, session, mojoExecution, e); throw e; } } - public void ensureDependenciesAreResolved( MojoDescriptor mojoDescriptor, MavenSession session, - DependencyContext dependencyContext ) - throws LifecycleExecutionException + public void ensureDependenciesAreResolved( + MojoDescriptor mojoDescriptor, MavenSession session, DependencyContext dependencyContext) + throws LifecycleExecutionException { - { MavenProject project = dependencyContext.getProject(); boolean aggregating = mojoDescriptor.isAggregator(); - if ( dependencyContext.isResolutionRequiredForCurrentProject() ) - { + if (dependencyContext.isResolutionRequiredForCurrentProject()) { Collection scopesToCollect = dependencyContext.getScopesToCollectForCurrentProject(); Collection scopesToResolve = dependencyContext.getScopesToResolveForCurrentProject(); - lifeCycleDependencyResolver.resolveProjectDependencies( project, scopesToCollect, scopesToResolve, session, - aggregating, Collections.emptySet() ); + lifeCycleDependencyResolver.resolveProjectDependencies( + project, scopesToCollect, scopesToResolve, session, aggregating, Collections.emptySet()); dependencyContext.synchronizeWithProjectState(); } - if ( aggregating ) - { - Collection scopesToCollect = toScopes( mojoDescriptor.getDependencyCollectionRequired() ); - Collection scopesToResolve = toScopes( mojoDescriptor.getDependencyResolutionRequired() ); + if (aggregating) { + Collection scopesToCollect = toScopes(mojoDescriptor.getDependencyCollectionRequired()); + Collection scopesToResolve = toScopes(mojoDescriptor.getDependencyResolutionRequired()); - if ( dependencyContext.isResolutionRequiredForAggregatedProjects( scopesToCollect, scopesToResolve ) ) - { - for ( MavenProject aggregatedProject : session.getProjects() ) - { - if ( aggregatedProject != project ) - { - lifeCycleDependencyResolver.resolveProjectDependencies( aggregatedProject, scopesToCollect, - scopesToResolve, session, aggregating, - Collections.emptySet() ); + if (dependencyContext.isResolutionRequiredForAggregatedProjects(scopesToCollect, scopesToResolve)) { + for (MavenProject aggregatedProject : session.getProjects()) { + if (aggregatedProject != project) { + lifeCycleDependencyResolver.resolveProjectDependencies( + aggregatedProject, + scopesToCollect, + scopesToResolve, + session, + aggregating, + Collections.emptySet()); } } } } - ArtifactFilter artifactFilter = getArtifactFilter( mojoDescriptor ); - List projectsToResolve = - LifecycleDependencyResolver.getProjects( session.getCurrentProject(), session, - mojoDescriptor.isAggregator() ); - for ( MavenProject projectToResolve : projectsToResolve ) - { - projectToResolve.setArtifactFilter( artifactFilter ); + ArtifactFilter artifactFilter = getArtifactFilter(mojoDescriptor); + List projectsToResolve = LifecycleDependencyResolver.getProjects( + session.getCurrentProject(), session, mojoDescriptor.isAggregator()); + for (MavenProject projectToResolve : projectsToResolve) { + projectToResolve.setArtifactFilter(artifactFilter); } } - private ArtifactFilter getArtifactFilter( MojoDescriptor mojoDescriptor ) - { + private ArtifactFilter getArtifactFilter(MojoDescriptor mojoDescriptor) { String scopeToResolve = mojoDescriptor.getDependencyResolutionRequired(); String scopeToCollect = mojoDescriptor.getDependencyCollectionRequired(); - List scopes = new ArrayList<>( 2 ); - if ( StringUtils.isNotEmpty( scopeToCollect ) ) - { - scopes.add( scopeToCollect ); + List scopes = new ArrayList<>(2); + if (StringUtils.isNotEmpty(scopeToCollect)) { + scopes.add(scopeToCollect); } - if ( StringUtils.isNotEmpty( scopeToResolve ) ) - { - scopes.add( scopeToResolve ); + if (StringUtils.isNotEmpty(scopeToResolve)) { + scopes.add(scopeToResolve); } - if ( scopes.isEmpty() ) - { + if (scopes.isEmpty()) { return null; - } - else - { - return new CumulativeScopeArtifactFilter( scopes ); + } else { + return new CumulativeScopeArtifactFilter(scopes); } } - public List executeForkedExecutions( MojoExecution mojoExecution, MavenSession session, - ProjectIndex projectIndex ) - throws LifecycleExecutionException - { + public List executeForkedExecutions( + MojoExecution mojoExecution, MavenSession session, ProjectIndex projectIndex) + throws LifecycleExecutionException { List forkedProjects = Collections.emptyList(); Map> forkedExecutions = mojoExecution.getForkedExecutions(); - if ( !forkedExecutions.isEmpty() ) - { - eventCatapult.fire( ExecutionEvent.Type.ForkStarted, session, mojoExecution ); + if (!forkedExecutions.isEmpty()) { + eventCatapult.fire(ExecutionEvent.Type.ForkStarted, session, mojoExecution); MavenProject project = session.getCurrentProject(); - forkedProjects = new ArrayList<>( forkedExecutions.size() ); + forkedProjects = new ArrayList<>(forkedExecutions.size()); - try - { - for ( Map.Entry> fork : forkedExecutions.entrySet() ) - { + try { + for (Map.Entry> fork : forkedExecutions.entrySet()) { String projectId = fork.getKey(); - int index = projectIndex.getIndices().get( projectId ); + int index = projectIndex.getIndices().get(projectId); - MavenProject forkedProject = projectIndex.getProjects().get( projectId ); + MavenProject forkedProject = projectIndex.getProjects().get(projectId); - forkedProjects.add( forkedProject ); + forkedProjects.add(forkedProject); MavenProject executedProject = forkedProject.clone(); - forkedProject.setExecutionProject( executedProject ); + forkedProject.setExecutionProject(executedProject); List mojoExecutions = fork.getValue(); - if ( mojoExecutions.isEmpty() ) - { + if (mojoExecutions.isEmpty()) { continue; } - try - { - session.setCurrentProject( executedProject ); - session.getProjects().set( index, executedProject ); - projectIndex.getProjects().put( projectId, executedProject ); + try { + session.setCurrentProject(executedProject); + session.getProjects().set(index, executedProject); + projectIndex.getProjects().put(projectId, executedProject); - eventCatapult.fire( ExecutionEvent.Type.ForkedProjectStarted, session, mojoExecution ); + eventCatapult.fire(ExecutionEvent.Type.ForkedProjectStarted, session, mojoExecution); - execute( session, mojoExecutions, projectIndex ); + execute(session, mojoExecutions, projectIndex); - eventCatapult.fire( ExecutionEvent.Type.ForkedProjectSucceeded, session, mojoExecution ); - } - catch ( LifecycleExecutionException e ) - { - eventCatapult.fire( ExecutionEvent.Type.ForkedProjectFailed, session, mojoExecution, e ); + eventCatapult.fire(ExecutionEvent.Type.ForkedProjectSucceeded, session, mojoExecution); + } catch (LifecycleExecutionException e) { + eventCatapult.fire(ExecutionEvent.Type.ForkedProjectFailed, session, mojoExecution, e); throw e; - } - finally - { - projectIndex.getProjects().put( projectId, forkedProject ); - session.getProjects().set( index, forkedProject ); - session.setCurrentProject( project ); + } finally { + projectIndex.getProjects().put(projectId, forkedProject); + session.getProjects().set(index, forkedProject); + session.setCurrentProject(project); } } - eventCatapult.fire( ExecutionEvent.Type.ForkSucceeded, session, mojoExecution ); - } - catch ( LifecycleExecutionException e ) - { - eventCatapult.fire( ExecutionEvent.Type.ForkFailed, session, mojoExecution, e ); + eventCatapult.fire(ExecutionEvent.Type.ForkSucceeded, session, mojoExecution); + } catch (LifecycleExecutionException e) { + eventCatapult.fire(ExecutionEvent.Type.ForkFailed, session, mojoExecution, e); throw e; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/PhaseRecorder.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/PhaseRecorder.java index 3316c50130..cbf5267aa7 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/PhaseRecorder.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/PhaseRecorder.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; @@ -28,50 +27,37 @@ import org.apache.maven.project.MavenProject; * @author Benjamin Bentmann * @author Kristian Rosenvold */ -public class PhaseRecorder -{ +public class PhaseRecorder { private String lastLifecyclePhase; private final MavenProject project; - public PhaseRecorder( MavenProject project ) - { + public PhaseRecorder(MavenProject project) { this.project = project; } - public void observeExecution( MojoExecution mojoExecution ) - { + public void observeExecution(MojoExecution mojoExecution) { String lifecyclePhase = mojoExecution.getLifecyclePhase(); - if ( lifecyclePhase != null ) - { - if ( lastLifecyclePhase == null ) - { + if (lifecyclePhase != null) { + if (lastLifecyclePhase == null) { lastLifecyclePhase = lifecyclePhase; - } - else if ( !lifecyclePhase.equals( lastLifecyclePhase ) ) - { - project.addLifecyclePhase( lastLifecyclePhase ); + } else if (!lifecyclePhase.equals(lastLifecyclePhase)) { + project.addLifecyclePhase(lastLifecyclePhase); lastLifecyclePhase = lifecyclePhase; } } - if ( lastLifecyclePhase != null ) - { - project.addLifecyclePhase( lastLifecyclePhase ); + if (lastLifecyclePhase != null) { + project.addLifecyclePhase(lastLifecyclePhase); } } - public boolean isDifferentPhase( MojoExecution nextMojoExecution ) - { + public boolean isDifferentPhase(MojoExecution nextMojoExecution) { String lifecyclePhase = nextMojoExecution.getLifecyclePhase(); - if ( lifecyclePhase == null ) - { + if (lifecyclePhase == null) { return lastLifecyclePhase != null; } - return !lifecyclePhase.equals( lastLifecyclePhase ); - + return !lifecyclePhase.equals(lastLifecyclePhase); } - - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectArtifactFactory.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectArtifactFactory.java index e698811f6d..d2ddd226b5 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectArtifactFactory.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectArtifactFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; import org.apache.maven.project.artifact.InvalidDependencyVersionException; @@ -33,8 +31,6 @@ import org.apache.maven.project.artifact.InvalidDependencyVersionException; * * @since 3.2.4 */ -public interface ProjectArtifactFactory -{ - Set createArtifacts( MavenProject project ) - throws InvalidDependencyVersionException; +public interface ProjectArtifactFactory { + Set createArtifacts(MavenProject project) throws InvalidDependencyVersionException; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectBuildList.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectBuildList.java index 6e54398fbc..92d18f2de4 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectBuildList.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectBuildList.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.Collections; @@ -27,7 +26,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; @@ -42,14 +40,11 @@ import org.apache.maven.project.MavenProject; * @since 3.0 * @author Kristian Rosenvold */ -public class ProjectBuildList - implements Iterable -{ +public class ProjectBuildList implements Iterable { private final List items; - public ProjectBuildList( List items ) - { - this.items = Collections.unmodifiableList( items ); + public ProjectBuildList(List items) { + this.items = Collections.unmodifiableList(items); } // TODO Optimize; or maybe just rewrite the whole way aggregating mojos are being run. @@ -58,27 +53,21 @@ public class ProjectBuildList * @param taskSegment the requested task segment * @return a project build list for the supplied task segment */ - public ProjectBuildList getByTaskSegment( TaskSegment taskSegment ) - { + public ProjectBuildList getByTaskSegment(TaskSegment taskSegment) { List currentSegment = new ArrayList<>(); - for ( ProjectSegment projectBuild : items ) - { - if ( taskSegment == projectBuild.getTaskSegment() ) - { // NOTE: There's no notion of taskSegment equality. - currentSegment.add( projectBuild ); + for (ProjectSegment projectBuild : items) { + if (taskSegment == projectBuild.getTaskSegment()) { // NOTE: There's no notion of taskSegment equality. + currentSegment.add(projectBuild); } } - return new ProjectBuildList( currentSegment ); + return new ProjectBuildList(currentSegment); } - public Map selectSegment( TaskSegment taskSegment ) - { + public Map selectSegment(TaskSegment taskSegment) { Map result = new HashMap<>(); - for ( ProjectSegment projectBuild : items ) - { - if ( taskSegment == projectBuild.getTaskSegment() ) - { // NOTE: There's no notion of taskSegment equality. - result.put( projectBuild.getProject(), projectBuild ); + for (ProjectSegment projectBuild : items) { + if (taskSegment == projectBuild.getTaskSegment()) { // NOTE: There's no notion of taskSegment equality. + result.put(projectBuild.getProject(), projectBuild); } } return result; @@ -89,70 +78,56 @@ public class ProjectBuildList * @param mavenProject the requested project * @return The projectSegment or null. */ - public ProjectSegment findByMavenProject( MavenProject mavenProject ) - { - for ( ProjectSegment projectBuild : items ) - { - if ( mavenProject.equals( projectBuild.getProject() ) ) - { + public ProjectSegment findByMavenProject(MavenProject mavenProject) { + for (ProjectSegment projectBuild : items) { + if (mavenProject.equals(projectBuild.getProject())) { return projectBuild; } } return null; } - public Iterator iterator() - { + public Iterator iterator() { return items.iterator(); } - public void closeAll() - { - for ( ProjectSegment item : items ) - { + public void closeAll() { + for (ProjectSegment item : items) { MavenSession sessionForThisModule = item.getSession(); - sessionForThisModule.setCurrentProject( null ); + sessionForThisModule.setCurrentProject(null); } } - public int size() - { + public int size() { return items.size(); } - public ProjectSegment get( int index ) - { - return items.get( index ); + public ProjectSegment get(int index) { + return items.get(index); } - public Set getReactorProjectKeys() - { - Set projectKeys = new HashSet<>( items.size() * 2 ); - for ( ProjectSegment projectBuild : items ) - { + public Set getReactorProjectKeys() { + Set projectKeys = new HashSet<>(items.size() * 2); + for (ProjectSegment projectBuild : items) { MavenProject project = projectBuild.getProject(); - String key = ArtifactUtils.key( project.getGroupId(), project.getArtifactId(), project.getVersion() ); - projectKeys.add( key ); + String key = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion()); + projectKeys.add(key); } return projectKeys; } - - public boolean isEmpty() - { + public boolean isEmpty() { return items.isEmpty(); } /** * @return a set of all the projects managed by the build */ - public Set getProjects() - { + public Set getProjects() { Set projects = new HashSet<>(); - for ( ProjectSegment s : items ) - { - projects.add( s.getProject() ); + for (ProjectSegment s : items) { + projects.add(s.getProject()); } return projects; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectIndex.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectIndex.java index 1c1cae4aa7..da00908e1e 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectIndex.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectIndex.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.lifecycle.internal.builder.BuilderCommon; -import org.apache.maven.project.MavenProject; +package org.apache.maven.lifecycle.internal; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.maven.lifecycle.internal.builder.BuilderCommon; +import org.apache.maven.project.MavenProject; /** *

    @@ -37,35 +35,30 @@ import java.util.Map; * @author Kristian Rosenvold (extracted class only) */ // TODO Kristian wonders if this class really is necessary and if it overlaps other concepts. -public final class ProjectIndex -{ +public final class ProjectIndex { private final Map projects; private final Map indices; - public ProjectIndex( List projects ) - { - this.projects = new HashMap<>( projects.size() * 2 ); - this.indices = new HashMap<>( projects.size() * 2 ); + public ProjectIndex(List projects) { + this.projects = new HashMap<>(projects.size() * 2); + this.indices = new HashMap<>(projects.size() * 2); - for ( int i = 0; i < projects.size(); i++ ) - { - MavenProject project = projects.get( i ); - String key = BuilderCommon.getKey( project ); + for (int i = 0; i < projects.size(); i++) { + MavenProject project = projects.get(i); + String key = BuilderCommon.getKey(project); - this.getProjects().put( key, project ); - this.getIndices().put( key, i ); + this.getProjects().put(key, project); + this.getIndices().put(key, i); } } - public Map getProjects() - { + public Map getProjects() { return projects; } - public Map getIndices() - { + public Map getIndices() { return indices; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectSegment.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectSegment.java index 6b736a1352..8b4d24460e 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectSegment.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectSegment.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; +import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.project.MavenProject; -import java.util.List; - /** * A build context that matches a Maven project to a given task segment, and the session to be used. *

    @@ -55,8 +53,7 @@ import java.util.List; * @author Benjamin Bentmann * @author Kristian Rosenvold */ -public final class ProjectSegment -{ +public final class ProjectSegment { private final MavenProject project; private final TaskSegment taskSegment; @@ -67,44 +64,37 @@ public final class ProjectSegment private final List transitiveUpstreamProjects; - public ProjectSegment( MavenProject project, TaskSegment taskSegment, MavenSession copiedSession ) - { + public ProjectSegment(MavenProject project, TaskSegment taskSegment, MavenSession copiedSession) { this.project = project; this.taskSegment = taskSegment; this.session = copiedSession; final ProjectDependencyGraph dependencyGraph = getSession().getProjectDependencyGraph(); - nonTransitiveUpstreamProjects = dependencyGraph.getUpstreamProjects( getProject(), false ); - transitiveUpstreamProjects = dependencyGraph.getUpstreamProjects( getProject(), true ); + nonTransitiveUpstreamProjects = dependencyGraph.getUpstreamProjects(getProject(), false); + transitiveUpstreamProjects = dependencyGraph.getUpstreamProjects(getProject(), true); } - public MavenSession getSession() - { + public MavenSession getSession() { return session; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public TaskSegment getTaskSegment() - { + public TaskSegment getTaskSegment() { return taskSegment; } - public List getImmediateUpstreamProjects() - { + public List getImmediateUpstreamProjects() { return nonTransitiveUpstreamProjects; } - public List getTransitiveUpstreamProjects() - { + public List getTransitiveUpstreamProjects() { return transitiveUpstreamProjects; } @Override - public String toString() - { + public String toString() { return getProject().getId() + " -> " + getTaskSegment(); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorBuildStatus.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorBuildStatus.java index 9bd8b868fd..5f9286ef98 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorBuildStatus.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorBuildStatus.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,14 +16,14 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.execution.ProjectDependencyGraph; -import org.apache.maven.lifecycle.internal.builder.BuilderCommon; -import org.apache.maven.project.MavenProject; +package org.apache.maven.lifecycle.internal; import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import org.apache.maven.execution.ProjectDependencyGraph; +import org.apache.maven.lifecycle.internal.builder.BuilderCommon; +import org.apache.maven.project.MavenProject; /** * Contains status information that is global to an entire reactor build. @@ -33,48 +31,38 @@ import java.util.HashSet; * @since 3.0 * @author Kristian Rosenvold */ -public class ReactorBuildStatus -{ +public class ReactorBuildStatus { private final ProjectDependencyGraph projectDependencyGraph; - private final Collection blackListedProjects = Collections.synchronizedSet( new HashSet<>() ); + private final Collection blackListedProjects = Collections.synchronizedSet(new HashSet<>()); private volatile boolean halted = false; - public ReactorBuildStatus( ProjectDependencyGraph projectDependencyGraph ) - { + public ReactorBuildStatus(ProjectDependencyGraph projectDependencyGraph) { this.projectDependencyGraph = projectDependencyGraph; } - public boolean isBlackListed( MavenProject project ) - { - return blackListedProjects.contains( BuilderCommon.getKey( project ) ); + public boolean isBlackListed(MavenProject project) { + return blackListedProjects.contains(BuilderCommon.getKey(project)); } - public void blackList( MavenProject project ) - { - if ( blackListedProjects.add( BuilderCommon.getKey( project ) ) && projectDependencyGraph != null ) - { - for ( MavenProject downstreamProject : projectDependencyGraph.getDownstreamProjects( project, true ) ) - { - blackListedProjects.add( BuilderCommon.getKey( downstreamProject ) ); + public void blackList(MavenProject project) { + if (blackListedProjects.add(BuilderCommon.getKey(project)) && projectDependencyGraph != null) { + for (MavenProject downstreamProject : projectDependencyGraph.getDownstreamProjects(project, true)) { + blackListedProjects.add(BuilderCommon.getKey(downstreamProject)); } } } - public void halt() - { + public void halt() { halted = true; } - public boolean isHalted() - { + public boolean isHalted() { return halted; } - public boolean isHaltedOrBlacklisted( MavenProject mavenProject ) - { - return isBlackListed( mavenProject ) || isHalted(); + public boolean isHaltedOrBlacklisted(MavenProject mavenProject) { + return isBlackListed(mavenProject) || isHalted(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java index 076c6229f8..4c750a7cc9 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import org.apache.maven.execution.MavenExecutionResult; @@ -29,8 +28,7 @@ import org.apache.maven.execution.MavenExecutionResult; * @author Kristian Rosenvold * NOTE: This class is not part of any public api and can be changed or deleted without prior notice. */ -public class ReactorContext -{ +public class ReactorContext { private final MavenExecutionResult result; private final ProjectIndex projectIndex; @@ -39,33 +37,30 @@ public class ReactorContext private final ReactorBuildStatus reactorBuildStatus; - public ReactorContext( MavenExecutionResult result, ProjectIndex projectIndex, - ClassLoader originalContextClassLoader, ReactorBuildStatus reactorBuildStatus ) - { + public ReactorContext( + MavenExecutionResult result, + ProjectIndex projectIndex, + ClassLoader originalContextClassLoader, + ReactorBuildStatus reactorBuildStatus) { this.result = result; this.projectIndex = projectIndex; this.originalContextClassLoader = originalContextClassLoader; this.reactorBuildStatus = reactorBuildStatus; } - public ReactorBuildStatus getReactorBuildStatus() - { + public ReactorBuildStatus getReactorBuildStatus() { return reactorBuildStatus; } - public MavenExecutionResult getResult() - { + public MavenExecutionResult getResult() { return result; } - public ProjectIndex getProjectIndex() - { + public ProjectIndex getProjectIndex() { return projectIndex; } - public ClassLoader getOriginalContextClassLoader() - { + public ClassLoader getOriginalContextClassLoader() { return originalContextClassLoader; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/TaskSegment.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/TaskSegment.java index 5b0165f7d5..354a52cee7 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/TaskSegment.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/TaskSegment.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; import java.util.ArrayList; import java.util.Arrays; @@ -32,8 +31,7 @@ import java.util.List; * @author Benjamin Bentmann * @author Kristian Rosenvold (extracted class only) */ -public final class TaskSegment -{ +public final class TaskSegment { // Can be both "LifeCycleTask" (clean/install) and "GoalTask" (org.mortbay.jetty:maven-jetty-plugin:6.1.19:run) @@ -41,31 +39,26 @@ public final class TaskSegment private final boolean aggregating; - public TaskSegment( boolean aggregating ) - { + public TaskSegment(boolean aggregating) { this.aggregating = aggregating; tasks = new ArrayList<>(); } - public TaskSegment( boolean aggregating, Object... tasks ) - { + public TaskSegment(boolean aggregating, Object... tasks) { this.aggregating = aggregating; - this.tasks = new ArrayList<>( Arrays.asList( tasks ) ); + this.tasks = new ArrayList<>(Arrays.asList(tasks)); } @Override - public String toString() - { + public String toString() { return getTasks().toString(); } - public List getTasks() - { + public List getTasks() { return tasks; } - public boolean isAggregating() - { + public boolean isAggregating() { return aggregating; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/Builder.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/Builder.java index 95e387de1e..a173aa2081 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/Builder.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/Builder.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.lifecycle.internal.builder; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.builder; import java.util.List; import java.util.concurrent.ExecutionException; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.ProjectBuildList; import org.apache.maven.lifecycle.internal.ReactorBuildStatus; @@ -36,13 +34,16 @@ import org.apache.maven.lifecycle.internal.TaskSegment; * Note: This interface is part of work in progress and can be changed or removed without notice. * @author jvanzyl */ -public interface Builder -{ +public interface Builder { // // Be nice to whittle this down to Session, maybe add task segments to the session. The session really is // the place to store reactor related information. // - void build( MavenSession session, ReactorContext reactorContext, ProjectBuildList projectBuilds, - List taskSegments, ReactorBuildStatus reactorBuildStatus ) - throws ExecutionException, InterruptedException; + void build( + MavenSession session, + ReactorContext reactorContext, + ProjectBuildList projectBuilds, + List taskSegments, + ReactorBuildStatus reactorBuildStatus) + throws ExecutionException, InterruptedException; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderCommon.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderCommon.java index 47e9a1edcd..5fbc2a1548 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderCommon.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderCommon.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.lifecycle.internal.builder; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.builder; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.BuildFailure; import org.apache.maven.execution.ExecutionEvent; @@ -71,8 +68,7 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class BuilderCommon -{ +public class BuilderCommon { private final Logger logger; private final LifecycleDebugLogger lifecycleDebugLogger; private final LifecycleExecutionPlanCalculator lifeCycleExecutionPlanCalculator; @@ -82,9 +78,8 @@ public class BuilderCommon public BuilderCommon( LifecycleDebugLogger lifecycleDebugLogger, LifecycleExecutionPlanCalculator lifeCycleExecutionPlanCalculator, - ExecutionEventCatapult eventCatapult ) - { - this.logger = LoggerFactory.getLogger( getClass() ); + ExecutionEventCatapult eventCatapult) { + this.logger = LoggerFactory.getLogger(getClass()); this.lifecycleDebugLogger = lifecycleDebugLogger; this.lifeCycleExecutionPlanCalculator = lifeCycleExecutionPlanCalculator; this.eventCatapult = eventCatapult; @@ -97,161 +92,139 @@ public class BuilderCommon LifecycleDebugLogger lifecycleDebugLogger, LifecycleExecutionPlanCalculator lifeCycleExecutionPlanCalculator, ExecutionEventCatapult eventCatapult, - Logger logger ) - { + Logger logger) { this.lifecycleDebugLogger = lifecycleDebugLogger; this.lifeCycleExecutionPlanCalculator = lifeCycleExecutionPlanCalculator; this.eventCatapult = eventCatapult; this.logger = logger; } - public MavenExecutionPlan resolveBuildPlan( MavenSession session, MavenProject project, TaskSegment taskSegment, - Set projectArtifacts ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException, - LifecycleExecutionException - { + public MavenExecutionPlan resolveBuildPlan( + MavenSession session, MavenProject project, TaskSegment taskSegment, Set projectArtifacts) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException, + LifecycleExecutionException { MavenExecutionPlan executionPlan = - lifeCycleExecutionPlanCalculator.calculateExecutionPlan( session, project, taskSegment.getTasks() ); + lifeCycleExecutionPlanCalculator.calculateExecutionPlan(session, project, taskSegment.getTasks()); - lifecycleDebugLogger.debugProjectPlan( project, executionPlan ); + lifecycleDebugLogger.debugProjectPlan(project, executionPlan); // With Maven 4's build/consumer the POM will always rewrite during distribution. // The maven-gpg-plugin uses the original POM, causing an invalid signature. // Fail as long as there's no solution available yet Properties userProperties = session.getUserProperties(); - if ( Features.buildConsumer( userProperties ).isActive() ) - { + if (Features.buildConsumer(userProperties).isActive()) { Optional gpgMojo = executionPlan.getMojoExecutions().stream() - .filter( m -> "maven-gpg-plugin".equals( m.getArtifactId() ) - && "org.apache.maven.plugins".equals( m.getGroupId() ) ) - .findAny(); + .filter(m -> "maven-gpg-plugin".equals(m.getArtifactId()) + && "org.apache.maven.plugins".equals(m.getGroupId())) + .findAny(); - if ( gpgMojo.isPresent() ) - { - throw new LifecycleExecutionException( "The maven-gpg-plugin is not supported by Maven 4." - + " Verify if there is a compatible signing solution," - + " add -D" + Features.buildConsumer( userProperties ).propertyName() + "=false" - + " or use Maven 3." ); + if (gpgMojo.isPresent()) { + throw new LifecycleExecutionException("The maven-gpg-plugin is not supported by Maven 4." + + " Verify if there is a compatible signing solution," + + " add -D" + Features.buildConsumer(userProperties).propertyName() + "=false" + + " or use Maven 3."); } } - if ( session.getRequest().getDegreeOfConcurrency() > 1 && session.getProjects().size() > 1 ) - { + if (session.getRequest().getDegreeOfConcurrency() > 1 + && session.getProjects().size() > 1) { final Set unsafePlugins = executionPlan.getNonThreadSafePlugins(); - if ( !unsafePlugins.isEmpty() ) - { - for ( String s : MultilineMessageHelper.format( + if (!unsafePlugins.isEmpty()) { + for (String s : MultilineMessageHelper.format( "Your build is requesting parallel execution, but this project contains the following " + "plugin(s) that have goals not marked as thread-safe to support parallel execution.", "While this /may/ work fine, please look for plugin updates and/or " + "request plugins be made thread-safe.", - "If reporting an issue, report it against the plugin in question, not against Apache Maven." ) ) - { - logger.warn( s ); + "If reporting an issue, report it against the plugin in question, not against Apache Maven.")) { + logger.warn(s); } - if ( logger.isDebugEnabled() ) - { + if (logger.isDebugEnabled()) { final Set unsafeGoals = executionPlan.getNonThreadSafeMojos(); - logger.warn( "The following goals are not marked as thread-safe in " + project.getName() + ":" ); - for ( MojoDescriptor unsafeGoal : unsafeGoals ) - { - logger.warn( " " + unsafeGoal.getId() ); + logger.warn("The following goals are not marked as thread-safe in " + project.getName() + ":"); + for (MojoDescriptor unsafeGoal : unsafeGoals) { + logger.warn(" " + unsafeGoal.getId()); } - } - else - { - logger.warn( "The following plugins are not marked as thread-safe in " + project.getName() + ":" ); - for ( Plugin unsafePlugin : unsafePlugins ) - { - logger.warn( " " + unsafePlugin.getId() ); + } else { + logger.warn("The following plugins are not marked as thread-safe in " + project.getName() + ":"); + for (Plugin unsafePlugin : unsafePlugins) { + logger.warn(" " + unsafePlugin.getId()); } - logger.warn( "" ); - logger.warn( "Enable verbose output (-X) to see precisely which goals are not marked as" - + " thread-safe." ); + logger.warn(""); + logger.warn("Enable verbose output (-X) to see precisely which goals are not marked as" + + " thread-safe."); } - logger.warn( MultilineMessageHelper.separatorLine() ); + logger.warn(MultilineMessageHelper.separatorLine()); } } final String defaulModelId = DefaultLifecyclePluginAnalyzer.DEFAULTLIFECYCLEBINDINGS_MODELID; List unversionedPlugins = executionPlan.getMojoExecutions().stream() - .map( MojoExecution::getPlugin ) - .filter( p -> p.getLocation( "version" ) != null - && p.getLocation( "version" ).getSource() != null - && defaulModelId.equals( p.getLocation( "version" ).getSource().getModelId() ) ) - .distinct() - .map( Plugin::getArtifactId ) // managed by us, groupId is always o.a.m.plugins - .collect( Collectors.toList() ); + .map(MojoExecution::getPlugin) + .filter(p -> p.getLocation("version") != null + && p.getLocation("version").getSource() != null + && defaulModelId.equals( + p.getLocation("version").getSource().getModelId())) + .distinct() + .map(Plugin::getArtifactId) // managed by us, groupId is always o.a.m.plugins + .collect(Collectors.toList()); - if ( !unversionedPlugins.isEmpty() ) - { - logger.warn( "Version not locked for default bindings plugins " + unversionedPlugins - + ", you should define versions in pluginManagement section of your " + "pom.xml or parent" ); + if (!unversionedPlugins.isEmpty()) { + logger.warn("Version not locked for default bindings plugins " + unversionedPlugins + + ", you should define versions in pluginManagement section of your " + "pom.xml or parent"); } return executionPlan; } - public void handleBuildError( final ReactorContext buildContext, final MavenSession rootSession, - final MavenSession currentSession, final MavenProject mavenProject, Throwable t, - final long buildStartTime ) - { + public void handleBuildError( + final ReactorContext buildContext, + final MavenSession rootSession, + final MavenSession currentSession, + final MavenProject mavenProject, + Throwable t, + final long buildStartTime) { // record the error and mark the project as failed long buildEndTime = System.currentTimeMillis(); - buildContext.getResult().addException( t ); - buildContext.getResult().addBuildSummary( new BuildFailure( mavenProject, buildEndTime - buildStartTime, t ) ); + buildContext.getResult().addException(t); + buildContext.getResult().addBuildSummary(new BuildFailure(mavenProject, buildEndTime - buildStartTime, t)); // notify listeners about "soft" project build failures only - if ( t instanceof Exception && !( t instanceof RuntimeException ) ) - { - eventCatapult.fire( ExecutionEvent.Type.ProjectFailed, currentSession, null, (Exception) t ); + if (t instanceof Exception && !(t instanceof RuntimeException)) { + eventCatapult.fire(ExecutionEvent.Type.ProjectFailed, currentSession, null, (Exception) t); } // reactor failure modes - if ( t instanceof RuntimeException || !( t instanceof Exception ) ) - { + if (t instanceof RuntimeException || !(t instanceof Exception)) { // fail fast on RuntimeExceptions, Errors and "other" Throwables // assume these are system errors and further build is meaningless buildContext.getReactorBuildStatus().halt(); - } - else if ( MavenExecutionRequest.REACTOR_FAIL_NEVER.equals( rootSession.getReactorFailureBehavior() ) ) - { + } else if (MavenExecutionRequest.REACTOR_FAIL_NEVER.equals(rootSession.getReactorFailureBehavior())) { // continue the build - } - else if ( MavenExecutionRequest.REACTOR_FAIL_AT_END.equals( rootSession.getReactorFailureBehavior() ) ) - { + } else if (MavenExecutionRequest.REACTOR_FAIL_AT_END.equals(rootSession.getReactorFailureBehavior())) { // continue the build but ban all projects that depend on the failed one - buildContext.getReactorBuildStatus().blackList( mavenProject ); - } - else if ( MavenExecutionRequest.REACTOR_FAIL_FAST.equals( rootSession.getReactorFailureBehavior() ) ) - { + buildContext.getReactorBuildStatus().blackList(mavenProject); + } else if (MavenExecutionRequest.REACTOR_FAIL_FAST.equals(rootSession.getReactorFailureBehavior())) { buildContext.getReactorBuildStatus().halt(); - } - else - { - logger.error( "invalid reactor failure behavior " + rootSession.getReactorFailureBehavior() ); + } else { + logger.error("invalid reactor failure behavior " + rootSession.getReactorFailureBehavior()); buildContext.getReactorBuildStatus().halt(); } } - public static void attachToThread( MavenProject currentProject ) - { + public static void attachToThread(MavenProject currentProject) { ClassRealm projectRealm = currentProject.getClassRealm(); - if ( projectRealm != null ) - { - Thread.currentThread().setContextClassLoader( projectRealm ); + if (projectRealm != null) { + Thread.currentThread().setContextClassLoader(projectRealm); } } // TODO I'm really wondering where this method belongs; smells like it should be on MavenProject, but for some // reason it isn't ? This localization is kind-of a code smell. - public static String getKey( MavenProject project ) - { + public static String getKey(MavenProject project) { return project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderNotFoundException.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderNotFoundException.java index 250d65de02..bcb7c90b8d 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderNotFoundException.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/BuilderNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder; * "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 + * 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 @@ -18,15 +16,13 @@ package org.apache.maven.lifecycle.internal.builder; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.builder; /** * BuilderNotFoundException */ -public class BuilderNotFoundException - extends Exception -{ - public BuilderNotFoundException( String message ) - { - super( message ); +public class BuilderNotFoundException extends Exception { + public BuilderNotFoundException(String message) { + super(message); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraph.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraph.java index efa8c28288..c8a3d0975d 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraph.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraph.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder.multithreaded; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder.multithreaded; * "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 + * 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 @@ -18,17 +16,17 @@ package org.apache.maven.lifecycle.internal.builder.multithreaded; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.execution.ProjectDependencyGraph; -import org.apache.maven.lifecycle.internal.ProjectBuildList; -import org.apache.maven.lifecycle.internal.ProjectSegment; -import org.apache.maven.project.MavenProject; +package org.apache.maven.lifecycle.internal.builder.multithreaded; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import org.apache.maven.execution.ProjectDependencyGraph; +import org.apache.maven.lifecycle.internal.ProjectBuildList; +import org.apache.maven.lifecycle.internal.ProjectSegment; +import org.apache.maven.project.MavenProject; /** *

    @@ -39,8 +37,7 @@ import java.util.Set; * @since 3.0 * @author Kristian Rosenvold */ -public class ConcurrencyDependencyGraph -{ +public class ConcurrencyDependencyGraph { private final ProjectBuildList projectBuilds; @@ -48,14 +45,12 @@ public class ConcurrencyDependencyGraph private final Set finishedProjects = new HashSet<>(); - public ConcurrencyDependencyGraph( ProjectBuildList projectBuilds, ProjectDependencyGraph projectDependencyGraph ) - { + public ConcurrencyDependencyGraph(ProjectBuildList projectBuilds, ProjectDependencyGraph projectDependencyGraph) { this.projectDependencyGraph = projectDependencyGraph; this.projectBuilds = projectBuilds; } - public int getNumberOfBuilds() - { + public int getNumberOfBuilds() { return projectBuilds.size(); } @@ -64,18 +59,16 @@ public class ConcurrencyDependencyGraph * * @return A set of all the initial builds */ - - public List getRootSchedulableBuilds() - { + public List getRootSchedulableBuilds() { Set result = new LinkedHashSet<>(); - for ( ProjectSegment projectBuild : projectBuilds ) - { - if ( projectDependencyGraph.getUpstreamProjects( projectBuild.getProject(), false ).isEmpty() ) - { - result.add( projectBuild.getProject() ); + for (ProjectSegment projectBuild : projectBuilds) { + if (projectDependencyGraph + .getUpstreamProjects(projectBuild.getProject(), false) + .isEmpty()) { + result.add(projectBuild.getProject()); } } - return new ArrayList<>( result ); + return new ArrayList<>(result); } /** @@ -84,23 +77,19 @@ public class ConcurrencyDependencyGraph * @param mavenProject The project * @return The list of builds that are eligible for starting now that the provided project is done */ - public List markAsFinished( MavenProject mavenProject ) - { - finishedProjects.add( mavenProject ); - return getSchedulableNewProcesses( mavenProject ); + public List markAsFinished(MavenProject mavenProject) { + finishedProjects.add(mavenProject); + return getSchedulableNewProcesses(mavenProject); } - private List getSchedulableNewProcesses( MavenProject finishedProject ) - { + private List getSchedulableNewProcesses(MavenProject finishedProject) { List result = new ArrayList<>(); // schedule dependent projects, if all of their requirements are met - for ( MavenProject dependentProject : projectDependencyGraph.getDownstreamProjects( finishedProject, false ) ) - { + for (MavenProject dependentProject : projectDependencyGraph.getDownstreamProjects(finishedProject, false)) { final List upstreamProjects = - projectDependencyGraph.getUpstreamProjects( dependentProject, false ); - if ( finishedProjects.containsAll( upstreamProjects ) ) - { - result.add( dependentProject ); + projectDependencyGraph.getUpstreamProjects(dependentProject, false); + if (finishedProjects.containsAll(upstreamProjects)) { + result.add(dependentProject); } } return result; @@ -109,23 +98,20 @@ public class ConcurrencyDependencyGraph /** * @return set of projects that have yet to be processed successfully by the build. */ - public Set getUnfinishedProjects() - { - Set unfinished = new HashSet<>( projectBuilds.getProjects() ); - unfinished.removeAll( finishedProjects ); + public Set getUnfinishedProjects() { + Set unfinished = new HashSet<>(projectBuilds.getProjects()); + unfinished.removeAll(finishedProjects); return unfinished; } /** * @return set of projects that have been successfully processed by the build. */ - protected Set getFinishedProjects() - { + protected Set getFinishedProjects() { return finishedProjects; } - protected ProjectBuildList getProjectBuilds() - { + protected ProjectBuildList getProjectBuilds() { return projectBuilds; } @@ -135,9 +121,8 @@ public class ConcurrencyDependencyGraph * @param p * @return List of prerequisite projects */ - protected List getDependencies( MavenProject p ) - { - return projectDependencyGraph.getUpstreamProjects( p, false ); + protected List getDependencies(MavenProject p) { + return projectDependencyGraph.getUpstreamProjects(p, false); } /** @@ -146,10 +131,9 @@ public class ConcurrencyDependencyGraph * @param p * @return List of uncompleted prerequisite projects */ - public List getActiveDependencies( MavenProject p ) - { - List activeDependencies = projectDependencyGraph.getUpstreamProjects( p, false ); - activeDependencies.removeAll( finishedProjects ); + public List getActiveDependencies(MavenProject p) { + List activeDependencies = projectDependencyGraph.getUpstreamProjects(p, false); + activeDependencies.removeAll(finishedProjects); return activeDependencies; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder.java index 7c5ca00768..b7038a5b5e 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder.multithreaded; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder.multithreaded; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal.builder.multithreaded; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.builder.multithreaded; import java.util.List; import java.util.Map; @@ -31,11 +30,9 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.BuildThreadFactory; import org.apache.maven.lifecycle.internal.LifecycleModuleBuilder; @@ -63,166 +60,151 @@ import org.slf4j.LoggerFactory; * Builds one or more lifecycles for a full module * NOTE: This class is not part of any public api and can be changed or deleted without prior notice. */ -@Named( "multithreaded" ) +@Named("multithreaded") @Singleton -public class MultiThreadedBuilder - implements Builder -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class MultiThreadedBuilder implements Builder { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final LifecycleModuleBuilder lifecycleModuleBuilder; @Inject - public MultiThreadedBuilder( LifecycleModuleBuilder lifecycleModuleBuilder ) - { + public MultiThreadedBuilder(LifecycleModuleBuilder lifecycleModuleBuilder) { this.lifecycleModuleBuilder = lifecycleModuleBuilder; } @Override - public void build( MavenSession session, ReactorContext reactorContext, ProjectBuildList projectBuilds, - List taskSegments, ReactorBuildStatus reactorBuildStatus ) - throws ExecutionException, InterruptedException - { - int nThreads = Math.min( session.getRequest().getDegreeOfConcurrency(), session.getProjects().size() ); + public void build( + MavenSession session, + ReactorContext reactorContext, + ProjectBuildList projectBuilds, + List taskSegments, + ReactorBuildStatus reactorBuildStatus) + throws ExecutionException, InterruptedException { + int nThreads = Math.min( + session.getRequest().getDegreeOfConcurrency(), + session.getProjects().size()); boolean parallel = nThreads > 1; // Propagate the parallel flag to the root session and all of the cloned sessions in each project segment - session.setParallel( parallel ); - for ( ProjectSegment segment : projectBuilds ) - { - segment.getSession().setParallel( parallel ); + session.setParallel(parallel); + for (ProjectSegment segment : projectBuilds) { + segment.getSession().setParallel(parallel); } - ExecutorService executor = Executors.newFixedThreadPool( nThreads, new BuildThreadFactory() ); - CompletionService service = new ExecutorCompletionService<>( executor ); + ExecutorService executor = Executors.newFixedThreadPool(nThreads, new BuildThreadFactory()); + CompletionService service = new ExecutorCompletionService<>(executor); // Currently disabled ThreadOutputMuxer muxer = null; // new ThreadOutputMuxer( analyzer.getProjectBuilds(), System.out ); - for ( TaskSegment taskSegment : taskSegments ) - { - ProjectBuildList segmentProjectBuilds = projectBuilds.getByTaskSegment( taskSegment ); - Map projectBuildMap = projectBuilds.selectSegment( taskSegment ); - try - { + for (TaskSegment taskSegment : taskSegments) { + ProjectBuildList segmentProjectBuilds = projectBuilds.getByTaskSegment(taskSegment); + Map projectBuildMap = projectBuilds.selectSegment(taskSegment); + try { ConcurrencyDependencyGraph analyzer = - new ConcurrencyDependencyGraph( segmentProjectBuilds, - session.getProjectDependencyGraph() ); - multiThreadedProjectTaskSegmentBuild( analyzer, reactorContext, session, service, taskSegment, - projectBuildMap, muxer ); - if ( reactorContext.getReactorBuildStatus().isHalted() ) - { + new ConcurrencyDependencyGraph(segmentProjectBuilds, session.getProjectDependencyGraph()); + multiThreadedProjectTaskSegmentBuild( + analyzer, reactorContext, session, service, taskSegment, projectBuildMap, muxer); + if (reactorContext.getReactorBuildStatus().isHalted()) { break; } - } - catch ( Exception e ) - { - session.getResult().addException( e ); + } catch (Exception e) { + session.getResult().addException(e); break; } - } executor.shutdown(); - executor.awaitTermination( Long.MAX_VALUE, TimeUnit.MILLISECONDS ); + executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } - private void multiThreadedProjectTaskSegmentBuild( ConcurrencyDependencyGraph analyzer, - ReactorContext reactorContext, MavenSession rootSession, - CompletionService service, - TaskSegment taskSegment, - Map projectBuildList, - ThreadOutputMuxer muxer ) - { + private void multiThreadedProjectTaskSegmentBuild( + ConcurrencyDependencyGraph analyzer, + ReactorContext reactorContext, + MavenSession rootSession, + CompletionService service, + TaskSegment taskSegment, + Map projectBuildList, + ThreadOutputMuxer muxer) { // gather artifactIds which are not unique so that the respective thread names can be extended with the groupId Set duplicateArtifactIds = projectBuildList.keySet().stream() - .map( MavenProject::getArtifactId ) - .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) ) - .entrySet().stream() - .filter( p -> p.getValue() > 1 ) - .map( Map.Entry::getKey ) - .collect( Collectors.toSet() ); + .map(MavenProject::getArtifactId) + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) + .entrySet() + .stream() + .filter(p -> p.getValue() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); // schedule independent projects - for ( MavenProject mavenProject : analyzer.getRootSchedulableBuilds() ) - { - ProjectSegment projectSegment = projectBuildList.get( mavenProject ); - logger.debug( "Scheduling: " + projectSegment.getProject() ); - Callable cb = - createBuildCallable( rootSession, projectSegment, reactorContext, taskSegment, muxer, - duplicateArtifactIds ); - service.submit( cb ); + for (MavenProject mavenProject : analyzer.getRootSchedulableBuilds()) { + ProjectSegment projectSegment = projectBuildList.get(mavenProject); + logger.debug("Scheduling: " + projectSegment.getProject()); + Callable cb = createBuildCallable( + rootSession, projectSegment, reactorContext, taskSegment, muxer, duplicateArtifactIds); + service.submit(cb); } // for each finished project - for ( int i = 0; i < analyzer.getNumberOfBuilds(); i++ ) - { - try - { + for (int i = 0; i < analyzer.getNumberOfBuilds(); i++) { + try { ProjectSegment projectBuild = service.take().get(); - if ( reactorContext.getReactorBuildStatus().isHalted() ) - { + if (reactorContext.getReactorBuildStatus().isHalted()) { break; } // MNG-6170: Only schedule other modules from reactor if we have more modules to build than one. - if ( analyzer.getNumberOfBuilds() > 1 ) - { + if (analyzer.getNumberOfBuilds() > 1) { final List newItemsThatCanBeBuilt = - analyzer.markAsFinished( projectBuild.getProject() ); - for ( MavenProject mavenProject : newItemsThatCanBeBuilt ) - { - ProjectSegment scheduledDependent = projectBuildList.get( mavenProject ); - logger.debug( "Scheduling: " + scheduledDependent ); - Callable cb = - createBuildCallable( rootSession, scheduledDependent, reactorContext, taskSegment, muxer, - duplicateArtifactIds ); - service.submit( cb ); + analyzer.markAsFinished(projectBuild.getProject()); + for (MavenProject mavenProject : newItemsThatCanBeBuilt) { + ProjectSegment scheduledDependent = projectBuildList.get(mavenProject); + logger.debug("Scheduling: " + scheduledDependent); + Callable cb = createBuildCallable( + rootSession, + scheduledDependent, + reactorContext, + taskSegment, + muxer, + duplicateArtifactIds); + service.submit(cb); } } - } - catch ( InterruptedException e ) - { - rootSession.getResult().addException( e ); + } catch (InterruptedException e) { + rootSession.getResult().addException(e); break; - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { // TODO MNG-5766 changes likely made this redundant - rootSession.getResult().addException( e ); + rootSession.getResult().addException(e); break; } } } - private Callable createBuildCallable( final MavenSession rootSession, - final ProjectSegment projectBuild, - final ReactorContext reactorContext, - final TaskSegment taskSegment, - final ThreadOutputMuxer muxer, - final Set duplicateArtifactIds ) - { - return () -> - { + private Callable createBuildCallable( + final MavenSession rootSession, + final ProjectSegment projectBuild, + final ReactorContext reactorContext, + final TaskSegment taskSegment, + final ThreadOutputMuxer muxer, + final Set duplicateArtifactIds) { + return () -> { final Thread currentThread = Thread.currentThread(); final String originalThreadName = currentThread.getName(); final MavenProject project = projectBuild.getProject(); - final String threadNameSuffix = duplicateArtifactIds.contains( project.getArtifactId() ) + final String threadNameSuffix = duplicateArtifactIds.contains(project.getArtifactId()) ? project.getGroupId() + ":" + project.getArtifactId() : project.getArtifactId(); - currentThread.setName( "mvn-builder-" + threadNameSuffix ); + currentThread.setName("mvn-builder-" + threadNameSuffix); - try - { + try { // muxer.associateThreadWithProjectSegment( projectBuild ); - lifecycleModuleBuilder.buildProject( projectBuild.getSession(), rootSession, reactorContext, project, - taskSegment ); + lifecycleModuleBuilder.buildProject( + projectBuild.getSession(), rootSession, reactorContext, project, taskSegment); // muxer.setThisModuleComplete( projectBuild ); return projectBuild; - } - finally - { - currentThread.setName( originalThreadName ); + } finally { + currentThread.setName(originalThreadName); } }; } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxer.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxer.java index 273570b68e..2898a5ca23 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxer.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxer.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder.multithreaded; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder.multithreaded; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.internal.builder.multithreaded; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.builder.multithreaded; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -28,7 +27,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; - import org.apache.maven.lifecycle.internal.ProjectBuildList; import org.apache.maven.lifecycle.internal.ProjectSegment; @@ -40,23 +38,21 @@ import org.apache.maven.lifecycle.internal.ProjectSegment; * @since 3.0 * @author Kristian Rosenvold */ -@SuppressWarnings( { "SynchronizationOnLocalVariableOrMethodParameter" } ) -public class ThreadOutputMuxer -{ +@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) +public class ThreadOutputMuxer { private final Iterator projects; private final ThreadLocal projectBuildThreadLocal = new ThreadLocal<>(); - private final Map streams = - new HashMap<>(); + private final Map streams = new HashMap<>(); private final Map printStreams = new HashMap<>(); private final ByteArrayOutputStream defaultOutputStreamForUnknownData = new ByteArrayOutputStream(); - private final PrintStream defaultPrintStream = new PrintStream( defaultOutputStreamForUnknownData ); + private final PrintStream defaultPrintStream = new PrintStream(defaultOutputStreamForUnknownData); - private final Set completedBuilds = Collections.synchronizedSet( new HashSet<>() ); + private final Set completedBuilds = Collections.synchronizedSet(new HashSet<>()); private volatile ProjectSegment currentBuild; @@ -67,52 +63,37 @@ public class ThreadOutputMuxer /** * A simple but safe solution for printing to the console. */ - - class ConsolePrinter - implements Runnable - { + class ConsolePrinter implements Runnable { private volatile boolean running; private final ProjectBuildList projectBuildList; - ConsolePrinter( ProjectBuildList projectBuildList ) - { + ConsolePrinter(ProjectBuildList projectBuildList) { this.projectBuildList = projectBuildList; } - public void run() - { + public void run() { running = true; - for ( ProjectSegment projectBuild : projectBuildList ) - { - final PrintStream projectStream = printStreams.get( projectBuild ); - ByteArrayOutputStream projectOs = streams.get( projectBuild ); + for (ProjectSegment projectBuild : projectBuildList) { + final PrintStream projectStream = printStreams.get(projectBuild); + ByteArrayOutputStream projectOs = streams.get(projectBuild); - do - { - synchronized ( projectStream ) - { - try - { - projectStream.wait( 100 ); + do { + synchronized (projectStream) { + try { + projectStream.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); } - catch ( InterruptedException e ) - { - throw new RuntimeException( e ); - } - try - { - projectOs.writeTo( originalSystemOUtStream ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + try { + projectOs.writeTo(originalSystemOUtStream); + } catch (IOException e) { + throw new RuntimeException(e); } projectOs.reset(); } - } - while ( !completedBuilds.contains( projectBuild ) ); + } while (!completedBuilds.contains(projectBuild)); } running = false; } @@ -121,355 +102,287 @@ public class ThreadOutputMuxer Wait until we are sure the print-stream thread is running. */ - public void waitUntilRunning( boolean expect ) - { - while ( !running == expect ) - { - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException e ) - { - throw new RuntimeException( e ); + public void waitUntilRunning(boolean expect) { + while (!running == expect) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + throw new RuntimeException(e); } } } } - public ThreadOutputMuxer( ProjectBuildList segmentChunks, PrintStream originalSystemOut ) - { + public ThreadOutputMuxer(ProjectBuildList segmentChunks, PrintStream originalSystemOut) { projects = segmentChunks.iterator(); - for ( ProjectSegment segmentChunk : segmentChunks ) - { + for (ProjectSegment segmentChunk : segmentChunks) { final ByteArrayOutputStream value = new ByteArrayOutputStream(); - streams.put( segmentChunk, value ); - printStreams.put( segmentChunk, new PrintStream( value ) ); + streams.put(segmentChunk, value); + printStreams.put(segmentChunk, new PrintStream(value)); } setNext(); this.originalSystemOUtStream = originalSystemOut; - System.setOut( new ThreadBoundPrintStream( this.originalSystemOUtStream ) ); - printer = new ConsolePrinter( segmentChunks ); - new Thread( printer ).start(); - printer.waitUntilRunning( true ); + System.setOut(new ThreadBoundPrintStream(this.originalSystemOUtStream)); + printer = new ConsolePrinter(segmentChunks); + new Thread(printer).start(); + printer.waitUntilRunning(true); } - public void close() - { - printer.waitUntilRunning( false ); - System.setOut( this.originalSystemOUtStream ); + public void close() { + printer.waitUntilRunning(false); + System.setOut(this.originalSystemOUtStream); } - private void setNext() - { + private void setNext() { currentBuild = projects.hasNext() ? projects.next() : null; } - private boolean ownsRealOutputStream( ProjectSegment projectBuild ) - { - return projectBuild.equals( currentBuild ); + private boolean ownsRealOutputStream(ProjectSegment projectBuild) { + return projectBuild.equals(currentBuild); } - private PrintStream getThreadBoundPrintStream() - { + private PrintStream getThreadBoundPrintStream() { ProjectSegment threadProject = projectBuildThreadLocal.get(); - if ( threadProject == null ) - { + if (threadProject == null) { return defaultPrintStream; } - if ( ownsRealOutputStream( threadProject ) ) - { + if (ownsRealOutputStream(threadProject)) { return originalSystemOUtStream; } - return printStreams.get( threadProject ); + return printStreams.get(threadProject); } - public void associateThreadWithProjectSegment( ProjectSegment projectBuild ) - { - projectBuildThreadLocal.set( projectBuild ); + public void associateThreadWithProjectSegment(ProjectSegment projectBuild) { + projectBuildThreadLocal.set(projectBuild); } - public void setThisModuleComplete( ProjectSegment projectBuild ) - { - completedBuilds.add( projectBuild ); - PrintStream stream = printStreams.get( projectBuild ); - synchronized ( stream ) - { + public void setThisModuleComplete(ProjectSegment projectBuild) { + completedBuilds.add(projectBuild); + PrintStream stream = printStreams.get(projectBuild); + synchronized (stream) { stream.notifyAll(); } disconnectThreadFromProject(); } - private void disconnectThreadFromProject() - { + private void disconnectThreadFromProject() { projectBuildThreadLocal.remove(); } - private class ThreadBoundPrintStream - extends PrintStream - { + private class ThreadBoundPrintStream extends PrintStream { - ThreadBoundPrintStream( PrintStream systemOutStream ) - { - super( systemOutStream ); + ThreadBoundPrintStream(PrintStream systemOutStream) { + super(systemOutStream); } - private PrintStream getOutputStreamForCurrentThread() - { + private PrintStream getOutputStreamForCurrentThread() { return getThreadBoundPrintStream(); } @Override - public void println() - { + public void println() { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { + synchronized (currentStream) { currentStream.println(); currentStream.notifyAll(); } } @Override - public void print( char c ) - { + public void print(char c) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( c ); + synchronized (currentStream) { + currentStream.print(c); currentStream.notifyAll(); } } @Override - public void println( char x ) - { + public void println(char x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.println( x ); + synchronized (currentStream) { + currentStream.println(x); currentStream.notifyAll(); } } @Override - public void print( double d ) - { + public void print(double d) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( d ); + synchronized (currentStream) { + currentStream.print(d); currentStream.notifyAll(); } } @Override - public void println( double x ) - { + public void println(double x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.println( x ); + synchronized (currentStream) { + currentStream.println(x); currentStream.notifyAll(); } } @Override - public void print( float f ) - { + public void print(float f) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( f ); + synchronized (currentStream) { + currentStream.print(f); currentStream.notifyAll(); } } @Override - public void println( float x ) - { + public void println(float x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.println( x ); + synchronized (currentStream) { + currentStream.println(x); currentStream.notifyAll(); } } @Override - public void print( int i ) - { + public void print(int i) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( i ); + synchronized (currentStream) { + currentStream.print(i); currentStream.notifyAll(); } } @Override - public void println( int x ) - { + public void println(int x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.println( x ); + synchronized (currentStream) { + currentStream.println(x); currentStream.notifyAll(); } } @Override - public void print( long l ) - { + public void print(long l) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( l ); + synchronized (currentStream) { + currentStream.print(l); currentStream.notifyAll(); } } @Override - public void println( long x ) - { + public void println(long x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( x ); + synchronized (currentStream) { + currentStream.print(x); currentStream.notifyAll(); } } @Override - public void print( boolean b ) - { + public void print(boolean b) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( b ); + synchronized (currentStream) { + currentStream.print(b); currentStream.notifyAll(); } } @Override - public void println( boolean x ) - { + public void println(boolean x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( x ); + synchronized (currentStream) { + currentStream.print(x); currentStream.notifyAll(); } } @Override - public void print( char s[] ) - { + public void print(char s[]) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( s ); + synchronized (currentStream) { + currentStream.print(s); currentStream.notifyAll(); } } @Override - public void println( char x[] ) - { + public void println(char x[]) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( x ); + synchronized (currentStream) { + currentStream.print(x); currentStream.notifyAll(); } } @Override - public void print( Object obj ) - { + public void print(Object obj) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( obj ); + synchronized (currentStream) { + currentStream.print(obj); currentStream.notifyAll(); } } @Override - public void println( Object x ) - { + public void println(Object x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.println( x ); + synchronized (currentStream) { + currentStream.println(x); currentStream.notifyAll(); } } @Override - public void print( String s ) - { + public void print(String s) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.print( s ); + synchronized (currentStream) { + currentStream.print(s); currentStream.notifyAll(); } } @Override - public void println( String x ) - { + public void println(String x) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.println( x ); + synchronized (currentStream) { + currentStream.println(x); currentStream.notifyAll(); } } @Override - public void write( byte b[], int off, int len ) - { + public void write(byte b[], int off, int len) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.write( b, off, len ); + synchronized (currentStream) { + currentStream.write(b, off, len); currentStream.notifyAll(); } } @Override - public void close() - { + public void close() { getOutputStreamForCurrentThread().close(); } @Override - public void flush() - { + public void flush() { getOutputStreamForCurrentThread().flush(); } @Override - public void write( int b ) - { + public void write(int b) { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.write( b ); + synchronized (currentStream) { + currentStream.write(b); currentStream.notifyAll(); } } @Override - public void write( byte b[] ) - throws IOException - { + public void write(byte b[]) throws IOException { final PrintStream currentStream = getOutputStreamForCurrentThread(); - synchronized ( currentStream ) - { - currentStream.write( b ); + synchronized (currentStream) { + currentStream.write(b); currentStream.notifyAll(); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/singlethreaded/SingleThreadedBuilder.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/singlethreaded/SingleThreadedBuilder.java index fee39d52b9..d4da91e58e 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/singlethreaded/SingleThreadedBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/singlethreaded/SingleThreadedBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.builder.singlethreaded; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal.builder.singlethreaded; * "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 + * 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 @@ -18,13 +16,12 @@ package org.apache.maven.lifecycle.internal.builder.singlethreaded; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.builder.singlethreaded; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.LifecycleModuleBuilder; import org.apache.maven.lifecycle.internal.ProjectBuildList; @@ -39,37 +36,31 @@ import org.apache.maven.lifecycle.internal.builder.Builder; * A {@link Builder} encapsulates a strategy for building a set of Maven projects. The default strategy in Maven builds * the the projects serially, but a {@link Builder} can employ any type of concurrency model to build the projects. */ -@Named( "singlethreaded" ) +@Named("singlethreaded") @Singleton -public class SingleThreadedBuilder - implements Builder -{ +public class SingleThreadedBuilder implements Builder { private final LifecycleModuleBuilder lifecycleModuleBuilder; @Inject - public SingleThreadedBuilder( LifecycleModuleBuilder lifecycleModuleBuilder ) - { + public SingleThreadedBuilder(LifecycleModuleBuilder lifecycleModuleBuilder) { this.lifecycleModuleBuilder = lifecycleModuleBuilder; } - public void build( MavenSession session, ReactorContext reactorContext, ProjectBuildList projectBuilds, - List taskSegments, ReactorBuildStatus reactorBuildStatus ) - { - for ( TaskSegment taskSegment : taskSegments ) - { - for ( ProjectSegment projectBuild : projectBuilds.getByTaskSegment( taskSegment ) ) - { - try - { - lifecycleModuleBuilder.buildProject( session, reactorContext, projectBuild.getProject(), - taskSegment ); - if ( reactorBuildStatus.isHalted() ) - { + public void build( + MavenSession session, + ReactorContext reactorContext, + ProjectBuildList projectBuilds, + List taskSegments, + ReactorBuildStatus reactorBuildStatus) { + for (TaskSegment taskSegment : taskSegments) { + for (ProjectSegment projectBuild : projectBuilds.getByTaskSegment(taskSegment)) { + try { + lifecycleModuleBuilder.buildProject( + session, reactorContext, projectBuild.getProject(), taskSegment); + if (reactorBuildStatus.isHalted()) { break; } - } - catch ( Exception e ) - { + } catch (Exception e) { break; // Why are we just ignoring this exception? Are exceptions are being used for flow control } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping.java b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping.java index 4001a97fa0..4ae3426e35 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.mapping; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.mapping; * "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 + * 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 @@ -18,21 +16,20 @@ package org.apache.maven.lifecycle.mapping; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.mapping; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toMap; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.toMap; - /** * DefaultLifecycleMapping */ -public class DefaultLifecycleMapping - implements LifecycleMapping -{ +public class DefaultLifecycleMapping implements LifecycleMapping { private List lifecycles; @@ -48,56 +45,44 @@ public class DefaultLifecycleMapping * @deprecated Should not be used in Java code. */ @Deprecated - public DefaultLifecycleMapping() - { - } + public DefaultLifecycleMapping() {} /** * Ctor to be used in Java code/providers. */ - public DefaultLifecycleMapping( final List lifecycles ) - { - this.lifecycleMap = Collections.unmodifiableMap( - lifecycles.stream().collect( toMap( Lifecycle::getId, identity() ) ) - ); + public DefaultLifecycleMapping(final List lifecycles) { + this.lifecycleMap = + Collections.unmodifiableMap(lifecycles.stream().collect(toMap(Lifecycle::getId, identity()))); } /** * Plexus: Populates the lifecycle map from the injected list of lifecycle mappings (if not already done). */ - private void initLifecycleMap() - { - if ( lifecycleMap == null ) - { + private void initLifecycleMap() { + if (lifecycleMap == null) { lifecycleMap = new HashMap<>(); - if ( lifecycles != null ) - { - for ( Lifecycle lifecycle : lifecycles ) - { - lifecycleMap.put( lifecycle.getId(), lifecycle ); + if (lifecycles != null) { + for (Lifecycle lifecycle : lifecycles) { + lifecycleMap.put(lifecycle.getId(), lifecycle); } - } - else - { + } else { /* * NOTE: This is to provide a migration path for implementors of the legacy API which did not know about * getLifecycles(). */ - String[] lifecycleIds = { "default", "clean", "site" }; + String[] lifecycleIds = {"default", "clean", "site"}; - for ( String lifecycleId : lifecycleIds ) - { - Map phases = getLifecyclePhases( lifecycleId ); - if ( phases != null ) - { + for (String lifecycleId : lifecycleIds) { + Map phases = getLifecyclePhases(lifecycleId); + if (phases != null) { Lifecycle lifecycle = new Lifecycle(); - lifecycle.setId( lifecycleId ); - lifecycle.setLifecyclePhases( phases ); + lifecycle.setId(lifecycleId); + lifecycle.setLifecyclePhases(phases); - lifecycleMap.put( lifecycleId, lifecycle ); + lifecycleMap.put(lifecycleId, lifecycle); } } } @@ -105,8 +90,7 @@ public class DefaultLifecycleMapping } @Override - public Map getLifecycles() - { + public Map getLifecycles() { initLifecycleMap(); return lifecycleMap; @@ -114,35 +98,27 @@ public class DefaultLifecycleMapping @Deprecated @Override - public List getOptionalMojos( String lifecycle ) - { + public List getOptionalMojos(String lifecycle) { return null; } - private Map getLifecyclePhases( String lifecycle ) - { + private Map getLifecyclePhases(String lifecycle) { initLifecycleMap(); - Lifecycle lifecycleMapping = lifecycleMap.get( lifecycle ); + Lifecycle lifecycleMapping = lifecycleMap.get(lifecycle); - if ( lifecycleMapping != null ) - { + if (lifecycleMapping != null) { return lifecycleMapping.getLifecyclePhases(); - } - else if ( "default".equals( lifecycle ) ) - { + } else if ("default".equals(lifecycle)) { return phases; - } - else - { + } else { return null; } } @Deprecated @Override - public Map getPhases( String lifecycle ) - { - return LifecyclePhase.toLegacyMap( getLifecyclePhases( lifecycle ) ); + public Map getPhases(String lifecycle) { + return LifecyclePhase.toLegacyMap(getLifecyclePhases(lifecycle)); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/Lifecycle.java b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/Lifecycle.java index 8afffd9758..8b6387f4f6 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/Lifecycle.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/Lifecycle.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.mapping; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.mapping; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.mapping; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.mapping; import java.util.Collections; import java.util.LinkedHashMap; @@ -26,8 +25,7 @@ import java.util.Map; /** * Lifecycle definition for a packaging (multiple packagings share the same lifecycle id = usually "default"). */ -public class Lifecycle -{ +public class Lifecycle { /** * Field id */ @@ -41,16 +39,14 @@ public class Lifecycle /** * Method getId */ - public String getId() - { + public String getId() { return this.id; } /** * Method getLifecyclePhases */ - public Map getLifecyclePhases() - { + public Map getLifecyclePhases() { return this.lifecyclePhases; } @@ -59,8 +55,7 @@ public class Lifecycle * * @param id */ - public void setId( String id ) - { + public void setId(String id) { this.id = id; } @@ -69,41 +64,34 @@ public class Lifecycle * * @param lifecyclePhases */ - public void setLifecyclePhases( Map lifecyclePhases ) - { + public void setLifecyclePhases(Map lifecyclePhases) { this.lifecyclePhases = lifecyclePhases; } @Deprecated - public Map getPhases() - { + public Map getPhases() { Map lphases = getLifecyclePhases(); - if ( lphases == null ) - { + if (lphases == null) { return null; } - if ( lphases.isEmpty() ) - { + if (lphases.isEmpty()) { return Collections.emptyMap(); } Map phases = new LinkedHashMap<>(); - for ( Map.Entry e: lphases.entrySet() ) - { - phases.put( e.getKey(), e.getValue().toString() ); + for (Map.Entry e : lphases.entrySet()) { + phases.put(e.getKey(), e.getValue().toString()); } return phases; } @Deprecated - public void setPhases( Map phases ) - { + public void setPhases(Map phases) { Map lphases = new LinkedHashMap<>(); - for ( Map.Entry e: phases.entrySet() ) - { - lphases.put( e.getKey(), new LifecyclePhase( e.getValue() ) ); + for (Map.Entry e : phases.entrySet()) { + lphases.put(e.getKey(), new LifecyclePhase(e.getValue())); } - setLifecyclePhases( lphases ); + setLifecyclePhases(lphases); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMapping.java b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMapping.java index 55d5544d45..a33ec32c03 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMapping.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMapping.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.mapping; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.mapping; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.mapping; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.mapping; import java.util.List; import java.util.Map; @@ -25,8 +24,7 @@ import java.util.Map; /** * LifecycleMapping */ -public interface LifecycleMapping -{ +public interface LifecycleMapping { @Deprecated String ROLE = LifecycleMapping.class.getName(); @@ -34,9 +32,8 @@ public interface LifecycleMapping Map getLifecycles(); @Deprecated - List getOptionalMojos( String lifecycle ); + List getOptionalMojos(String lifecycle); @Deprecated - Map getPhases( String lifecycle ); - + Map getPhases(String lifecycle); } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMojo.java b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMojo.java index f928c5095e..a4761c29db 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMojo.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecycleMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.mapping; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.mapping; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.lifecycle.mapping; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.mapping; import java.util.List; - import org.apache.maven.api.xml.Dom; import org.apache.maven.model.Dependency; @@ -29,40 +27,33 @@ import org.apache.maven.model.Dependency; * * @see LifecyclePhase */ -public class LifecycleMojo -{ +public class LifecycleMojo { private String goal; private Dom configuration; private List dependencies; - public String getGoal() - { + public String getGoal() { return goal; } - public Dom getConfiguration() - { + public Dom getConfiguration() { return configuration; } - public List getDependencies() - { + public List getDependencies() { return dependencies; } - public void setGoal( String goal ) - { + public void setGoal(String goal) { this.goal = goal; } - public void setConfiguration( Dom configuration ) - { + public void setConfiguration(Dom configuration) { this.configuration = configuration; } - public void setDependencies( List dependencies ) - { + public void setDependencies(List dependencies) { this.dependencies = dependencies; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecyclePhase.java b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecyclePhase.java index 4f8b6038e7..6ab545d43e 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecyclePhase.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/mapping/LifecyclePhase.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.mapping; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.mapping; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.lifecycle.mapping; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.mapping; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import org.codehaus.plexus.util.StringUtils; /** @@ -32,90 +30,70 @@ import org.codehaus.plexus.util.StringUtils; * * @see LifecycleMojo */ -public class LifecyclePhase -{ +public class LifecyclePhase { private List mojos; - public LifecyclePhase() - { + public LifecyclePhase() {} + + public LifecyclePhase(String goals) { + set(goals); } - public LifecyclePhase( String goals ) - { - set( goals ); - } - - public List getMojos() - { + public List getMojos() { return mojos; } - public void setMojos( List mojos ) - { + public void setMojos(List mojos) { this.mojos = mojos; } - public void set( String goals ) - { + public void set(String goals) { mojos = new ArrayList<>(); - if ( StringUtils.isNotEmpty( goals ) ) - { - String[] mojoGoals = StringUtils.split( goals, "," ); + if (StringUtils.isNotEmpty(goals)) { + String[] mojoGoals = StringUtils.split(goals, ","); - for ( String mojoGoal: mojoGoals ) - { + for (String mojoGoal : mojoGoals) { LifecycleMojo lifecycleMojo = new LifecycleMojo(); - lifecycleMojo.setGoal( mojoGoal.trim() ); - mojos.add( lifecycleMojo ); + lifecycleMojo.setGoal(mojoGoal.trim()); + mojos.add(lifecycleMojo); } } } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; List mojos = getMojos(); - if ( mojos != null ) - { - for ( LifecycleMojo mojo: mojos ) - { - if ( first ) - { + if (mojos != null) { + for (LifecycleMojo mojo : mojos) { + if (first) { first = false; + } else { + sb.append(','); } - else - { - sb.append( ',' ); - } - sb.append( mojo.getGoal() ); + sb.append(mojo.getGoal()); } } return sb.toString(); } @Deprecated - public static Map toLegacyMap( Map lifecyclePhases ) - { - if ( lifecyclePhases == null ) - { + public static Map toLegacyMap(Map lifecyclePhases) { + if (lifecyclePhases == null) { return null; } - if ( lifecyclePhases.isEmpty() ) - { + if (lifecyclePhases.isEmpty()) { return Collections.emptyMap(); } Map phases = new LinkedHashMap<>(); - for ( Map.Entry e: lifecyclePhases.entrySet() ) - { - phases.put( e.getKey(), e.getValue().toString() ); + for (Map.Entry e : lifecyclePhases.entrySet()) { + phases.put(e.getKey(), e.getValue().toString()); } return phases; } - } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/AbstractLifecycleProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/AbstractLifecycleProvider.java index 27ea758c7d..acdbe37257 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/AbstractLifecycleProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/AbstractLifecycleProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers; * "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 + * 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 @@ -18,55 +16,46 @@ package org.apache.maven.lifecycle.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; - import javax.inject.Provider; - import org.apache.maven.lifecycle.Lifecycle; import org.apache.maven.lifecycle.mapping.LifecyclePhase; /** * Base lifecycle provider. */ -public abstract class AbstractLifecycleProvider - implements Provider -{ +public abstract class AbstractLifecycleProvider implements Provider { private final Lifecycle lifecycle; - protected AbstractLifecycleProvider( String id, String[] phases, String[] pluginBindings ) - { + protected AbstractLifecycleProvider(String id, String[] phases, String[] pluginBindings) { HashMap defaultBindings = null; - if ( pluginBindings != null ) - { + if (pluginBindings != null) { final int len = pluginBindings.length; - if ( len < 2 || len % 2 != 0 ) - { - throw new IllegalArgumentException( "Plugin bindings must have more than 0, even count of elements" ); + if (len < 2 || len % 2 != 0) { + throw new IllegalArgumentException("Plugin bindings must have more than 0, even count of elements"); } - defaultBindings = new LinkedHashMap<>( len / 2 ); + defaultBindings = new LinkedHashMap<>(len / 2); - for ( int i = 0; i < len; i += 2 ) - { - defaultBindings.put( pluginBindings[i], new LifecyclePhase( pluginBindings[i + 1] ) ); + for (int i = 0; i < len; i += 2) { + defaultBindings.put(pluginBindings[i], new LifecyclePhase(pluginBindings[i + 1])); } } this.lifecycle = new Lifecycle( - id, - Collections.unmodifiableList( Arrays.asList( phases ) ), - defaultBindings == null ? null : Collections.unmodifiableMap( defaultBindings ) - ); + id, + Collections.unmodifiableList(Arrays.asList(phases)), + defaultBindings == null ? null : Collections.unmodifiableMap(defaultBindings)); } @Override - public Lifecycle get() - { + public Lifecycle get() { return lifecycle; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/CleanLifecycleProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/CleanLifecycleProvider.java index 4ffbdbbb43..e9c5fd711e 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/CleanLifecycleProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/CleanLifecycleProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers; import javax.inject.Inject; import javax.inject.Named; @@ -26,19 +25,13 @@ import javax.inject.Singleton; /** * {@code clean} lifecycle provider. */ -@Named( CleanLifecycleProvider.LIFECYCLE_ID ) +@Named(CleanLifecycleProvider.LIFECYCLE_ID) @Singleton -public final class CleanLifecycleProvider - extends AbstractLifecycleProvider -{ +public final class CleanLifecycleProvider extends AbstractLifecycleProvider { protected static final String LIFECYCLE_ID = "clean"; // START SNIPPET: clean - private static final String[] PHASES = { - "pre-clean", - "clean", - "post-clean" - }; + private static final String[] PHASES = {"pre-clean", "clean", "post-clean"}; private static final String MAVEN_CLEAN_PLUGIN_VERSION = "3.1.0"; @@ -48,8 +41,7 @@ public final class CleanLifecycleProvider // END SNIPPET: clean @Inject - public CleanLifecycleProvider() - { - super( LIFECYCLE_ID, PHASES, BINDINGS ); + public CleanLifecycleProvider() { + super(LIFECYCLE_ID, PHASES, BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/DefaultLifecycleProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/DefaultLifecycleProvider.java index 7eb2247e24..b55a3a76aa 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/DefaultLifecycleProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/DefaultLifecycleProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers; import javax.inject.Inject; import javax.inject.Named; @@ -26,11 +25,9 @@ import javax.inject.Singleton; /** * {@code default} lifecycle provider. */ -@Named( DefaultLifecycleProvider.LIFECYCLE_ID ) +@Named(DefaultLifecycleProvider.LIFECYCLE_ID) @Singleton -public final class DefaultLifecycleProvider - extends AbstractLifecycleProvider -{ +public final class DefaultLifecycleProvider extends AbstractLifecycleProvider { protected static final String LIFECYCLE_ID = "default"; // START SNIPPET: default @@ -62,10 +59,12 @@ public final class DefaultLifecycleProvider // END SNIPPET: default @Inject - public DefaultLifecycleProvider() - { - super( LIFECYCLE_ID, PHASES, - null // no global plugin bindings for default lifecycle: they are defined per-packaging in separate providers - ); + public DefaultLifecycleProvider() { + super( + LIFECYCLE_ID, + PHASES, + null // no global plugin bindings for default lifecycle: they are defined per-packaging in separate + // providers + ); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/SiteLifecycleProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/SiteLifecycleProvider.java index 4c6a59d946..6d06e641fc 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/SiteLifecycleProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/SiteLifecycleProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers; import javax.inject.Inject; import javax.inject.Named; @@ -26,30 +25,22 @@ import javax.inject.Singleton; /** * {@code site} lifecycle provider. */ -@Named( SiteLifecycleProvider.LIFECYCLE_ID ) +@Named(SiteLifecycleProvider.LIFECYCLE_ID) @Singleton -public final class SiteLifecycleProvider - extends AbstractLifecycleProvider -{ +public final class SiteLifecycleProvider extends AbstractLifecycleProvider { protected static final String LIFECYCLE_ID = "site"; // START SNIPPET: site - private static final String[] PHASES = { - "pre-site", - "site", - "post-site", - "site-deploy" - }; + private static final String[] PHASES = {"pre-site", "site", "post-site", "site-deploy"}; private static final String[] BINDINGS = { - "site", "org.apache.maven.plugins:maven-site-plugin:3.9.1:site", + "site", "org.apache.maven.plugins:maven-site-plugin:3.9.1:site", "site-deploy", "org.apache.maven.plugins:maven-site-plugin:3.9.1:deploy" }; // END SNIPPET: site @Inject - public SiteLifecycleProvider() - { - super( LIFECYCLE_ID, PHASES, BINDINGS ); + public SiteLifecycleProvider() { + super(LIFECYCLE_ID, PHASES, BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/WrapperLifecycleProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/WrapperLifecycleProvider.java index b4a196623c..35fa80c799 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/WrapperLifecycleProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/WrapperLifecycleProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers; import javax.inject.Inject; import javax.inject.Named; @@ -26,27 +25,19 @@ import javax.inject.Singleton; /** * {@code wrapper} lifecycle provider. */ -@Named( WrapperLifecycleProvider.LIFECYCLE_ID ) +@Named(WrapperLifecycleProvider.LIFECYCLE_ID) @Singleton -public final class WrapperLifecycleProvider - extends AbstractLifecycleProvider -{ +public final class WrapperLifecycleProvider extends AbstractLifecycleProvider { protected static final String LIFECYCLE_ID = "wrapper"; // START SNIPPET: wrapper - private static final String[] PHASES = - { - "wrapper" - }; + private static final String[] PHASES = {"wrapper"}; - private static final String[] BINDINGS = { - "wrapper", "org.apache.maven.plugins:maven-wrapper-plugin:3.1.0:wrapper" - }; + private static final String[] BINDINGS = {"wrapper", "org.apache.maven.plugins:maven-wrapper-plugin:3.1.0:wrapper"}; // END SNIPPET: wrapper @Inject - public WrapperLifecycleProvider() - { - super( LIFECYCLE_ID, PHASES, BINDINGS ); + public WrapperLifecycleProvider() { + super(LIFECYCLE_ID, PHASES, BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/AbstractLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/AbstractLifecycleMappingProvider.java index 9faae05c29..6492934fca 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/AbstractLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/AbstractLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,25 +16,22 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; + +import static java.util.Objects.requireNonNull; import java.util.Collections; import java.util.HashMap; - import javax.inject.Provider; - import org.apache.maven.lifecycle.mapping.DefaultLifecycleMapping; import org.apache.maven.lifecycle.mapping.Lifecycle; import org.apache.maven.lifecycle.mapping.LifecycleMapping; import org.apache.maven.lifecycle.mapping.LifecyclePhase; -import static java.util.Objects.requireNonNull; - /** * Base lifecycle mapping provider, ie per-packaging plugin bindings for {@code default} lifecycle. */ -public abstract class AbstractLifecycleMappingProvider - implements Provider -{ +public abstract class AbstractLifecycleMappingProvider implements Provider { protected static final String RESOURCES_PLUGIN_VERSION = "3.2.0"; protected static final String COMPILER_PLUGIN_VERSION = "3.8.1"; @@ -63,31 +58,27 @@ public abstract class AbstractLifecycleMappingProvider private final LifecycleMapping lifecycleMapping; - protected AbstractLifecycleMappingProvider( String[] pluginBindings ) - { - requireNonNull( pluginBindings ); + protected AbstractLifecycleMappingProvider(String[] pluginBindings) { + requireNonNull(pluginBindings); final int len = pluginBindings.length; - if ( len < 2 || len % 2 != 0 ) - { - throw new IllegalArgumentException( "Plugin bindings must have more than 0, even count of elements" ); + if (len < 2 || len % 2 != 0) { + throw new IllegalArgumentException("Plugin bindings must have more than 0, even count of elements"); } - HashMap lifecyclePhaseBindings = new HashMap<>( len / 2 ); - for ( int i = 0; i < len; i = i + 2 ) - { - lifecyclePhaseBindings.put( pluginBindings[i], new LifecyclePhase( pluginBindings[i + 1] ) ); + HashMap lifecyclePhaseBindings = new HashMap<>(len / 2); + for (int i = 0; i < len; i = i + 2) { + lifecyclePhaseBindings.put(pluginBindings[i], new LifecyclePhase(pluginBindings[i + 1])); } Lifecycle lifecycle = new Lifecycle(); - lifecycle.setId( "default" ); - lifecycle.setLifecyclePhases( Collections.unmodifiableMap( lifecyclePhaseBindings ) ); + lifecycle.setId("default"); + lifecycle.setLifecyclePhases(Collections.unmodifiableMap(lifecyclePhaseBindings)); - this.lifecycleMapping = new DefaultLifecycleMapping( Collections.singletonList( lifecycle ) ); + this.lifecycleMapping = new DefaultLifecycleMapping(Collections.singletonList(lifecycle)); } @Override - public LifecycleMapping get() - { + public LifecycleMapping get() { return lifecycleMapping; } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EarLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EarLifecycleMappingProvider.java index 4c6eec7dae..feef89aac4 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EarLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EarLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,26 +25,24 @@ import javax.inject.Singleton; /** * {@code ear} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "ear" ) +@Named("ear") @Singleton -public final class EarLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class EarLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: ear - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { - "generate-resources", "org.apache.maven.plugins:maven-ear-plugin:" + EAR_PLUGIN_VERSION + ":generate-application-xml", - "process-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", - "package", "org.apache.maven.plugins:maven-ear-plugin:" + EAR_PLUGIN_VERSION + ":ear", - "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { + "generate-resources", + "org.apache.maven.plugins:maven-ear-plugin:" + EAR_PLUGIN_VERSION + ":generate-application-xml", + "process-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", + "package", "org.apache.maven.plugins:maven-ear-plugin:" + EAR_PLUGIN_VERSION + ":ear", + "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: ear @Inject - public EarLifecycleMappingProvider() - { - super( BINDINGS ); + public EarLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EjbLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EjbLifecycleMappingProvider.java index ce90d69bbc..272d2ad086 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EjbLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/EjbLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,29 +25,27 @@ import javax.inject.Singleton; /** * {@code ejb} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "ejb" ) +@Named("ejb") @Singleton -public final class EjbLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class EjbLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: ejb - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { - "process-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", - "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", - "process-test-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", - "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", - "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", - "package", "org.apache.maven.plugins:maven-ejb-plugin:" + EJB_PLUGIN_VERSION + ":ejb", - "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { + "process-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", + "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", + "process-test-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", + "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", + "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", + "package", "org.apache.maven.plugins:maven-ejb-plugin:" + EJB_PLUGIN_VERSION + ":ejb", + "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: ejb - + @Inject - public EjbLifecycleMappingProvider() - { - super( BINDINGS ); + public EjbLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/JarLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/JarLifecycleMappingProvider.java index 05bfe98f99..455d9b77f8 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/JarLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/JarLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,29 +25,27 @@ import javax.inject.Singleton; /** * {@code jar} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "jar" ) +@Named("jar") @Singleton -public final class JarLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class JarLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: jar - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { - "process-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", - "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", - "process-test-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", - "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", - "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", - "package", "org.apache.maven.plugins:maven-jar-plugin:" + JAR_PLUGIN_VERSION + ":jar", - "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { + "process-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", + "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", + "process-test-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", + "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", + "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", + "package", "org.apache.maven.plugins:maven-jar-plugin:" + JAR_PLUGIN_VERSION + ":jar", + "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: jar - + @Inject - public JarLifecycleMappingProvider() - { - super( BINDINGS ); + public JarLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/MavenPluginLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/MavenPluginLifecycleMappingProvider.java index 82e1a40579..cacbefd182 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/MavenPluginLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/MavenPluginLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,31 +25,31 @@ import javax.inject.Singleton; /** * {@code maven-plugin} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "maven-plugin" ) +@Named("maven-plugin") @Singleton -public final class MavenPluginLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class MavenPluginLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: maven-plugin - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { - "process-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", - "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", - "process-classes", "org.apache.maven.plugins:maven-plugin-plugin:" + PLUGIN_PLUGIN_VERSION + ":descriptor", - "process-test-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", - "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", - "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", - "package", "org.apache.maven.plugins:maven-jar-plugin:" + JAR_PLUGIN_VERSION + ":jar," - + "org.apache.maven.plugins:maven-plugin-plugin:" + PLUGIN_PLUGIN_VERSION + ":addPluginArtifactMetadata", - "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { + "process-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", + "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", + "process-classes", "org.apache.maven.plugins:maven-plugin-plugin:" + PLUGIN_PLUGIN_VERSION + ":descriptor", + "process-test-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", + "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", + "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", + "package", + "org.apache.maven.plugins:maven-jar-plugin:" + JAR_PLUGIN_VERSION + ":jar," + + "org.apache.maven.plugins:maven-plugin-plugin:" + PLUGIN_PLUGIN_VERSION + + ":addPluginArtifactMetadata", + "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: maven-plugin - + @Inject - public MavenPluginLifecycleMappingProvider() - { - super( BINDINGS ); + public MavenPluginLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/PomLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/PomLifecycleMappingProvider.java index 3237e3c76e..1f05e9dd21 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/PomLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/PomLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,23 +25,19 @@ import javax.inject.Singleton; /** * {@code pom} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "pom" ) +@Named("pom") @Singleton -public final class PomLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class PomLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: pom - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: pom - + @Inject - public PomLifecycleMappingProvider() - { - super( BINDINGS ); + public PomLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/RarLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/RarLifecycleMappingProvider.java index 0d85e96340..1bcffdebdd 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/RarLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/RarLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,29 +25,27 @@ import javax.inject.Singleton; /** * {@code rar} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "rar" ) +@Named("rar") @Singleton -public final class RarLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class RarLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: rar - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { - "process-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", - "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", - "process-test-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", - "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", - "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", - "package", "org.apache.maven.plugins:maven-rar-plugin:" + RAR_PLUGIN_VERSION + ":rar", - "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { + "process-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", + "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", + "process-test-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", + "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", + "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", + "package", "org.apache.maven.plugins:maven-rar-plugin:" + RAR_PLUGIN_VERSION + ":rar", + "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: rar - + @Inject - public RarLifecycleMappingProvider() - { - super( BINDINGS ); + public RarLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/WarLifecycleMappingProvider.java b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/WarLifecycleMappingProvider.java index 33f2290b50..976570154b 100644 --- a/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/WarLifecycleMappingProvider.java +++ b/maven-core/src/main/java/org/apache/maven/lifecycle/providers/packaging/WarLifecycleMappingProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.providers.packaging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.providers.packaging; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.lifecycle.providers.packaging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.providers.packaging; import javax.inject.Inject; import javax.inject.Named; @@ -26,29 +25,27 @@ import javax.inject.Singleton; /** * {@code war} packaging plugins bindings provider for {@code default} lifecycle. */ -@Named( "war" ) +@Named("war") @Singleton -public final class WarLifecycleMappingProvider - extends AbstractLifecycleMappingProvider -{ +public final class WarLifecycleMappingProvider extends AbstractLifecycleMappingProvider { // START SNIPPET: war - @SuppressWarnings( "checkstyle:linelength" ) - private static final String[] BINDINGS = - { - "process-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", - "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", - "process-test-resources", "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", - "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", - "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", - "package", "org.apache.maven.plugins:maven-war-plugin:" + WAR_PLUGIN_VERSION + ":war", - "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", - "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" + @SuppressWarnings("checkstyle:linelength") + private static final String[] BINDINGS = { + "process-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":resources", + "compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":compile", + "process-test-resources", + "org.apache.maven.plugins:maven-resources-plugin:" + RESOURCES_PLUGIN_VERSION + ":testResources", + "test-compile", "org.apache.maven.plugins:maven-compiler-plugin:" + COMPILER_PLUGIN_VERSION + ":testCompile", + "test", "org.apache.maven.plugins:maven-surefire-plugin:" + SUREFIRE_PLUGIN_VERSION + ":test", + "package", "org.apache.maven.plugins:maven-war-plugin:" + WAR_PLUGIN_VERSION + ":war", + "install", "org.apache.maven.plugins:maven-install-plugin:" + INSTALL_PLUGIN_VERSION + ":install", + "deploy", "org.apache.maven.plugins:maven-deploy-plugin:" + DEPLOY_PLUGIN_VERSION + ":deploy" }; // END SNIPPET: war - + @Inject - public WarLifecycleMappingProvider() - { - super( BINDINGS ); + public WarLifecycleMappingProvider() { + super(BINDINGS); } } diff --git a/maven-core/src/main/java/org/apache/maven/model/plugin/DefaultLifecycleBindingsInjector.java b/maven-core/src/main/java/org/apache/maven/model/plugin/DefaultLifecycleBindingsInjector.java index 688b609089..d548c2378f 100644 --- a/maven-core/src/main/java/org/apache/maven/model/plugin/DefaultLifecycleBindingsInjector.java +++ b/maven-core/src/main/java/org/apache/maven/model/plugin/DefaultLifecycleBindingsInjector.java @@ -1,5 +1,3 @@ -package org.apache.maven.model.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.model.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.model.plugin; import java.util.ArrayList; import java.util.Collection; @@ -26,22 +25,20 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - -import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer; import org.apache.maven.api.model.Build; import org.apache.maven.api.model.Model; import org.apache.maven.api.model.Plugin; import org.apache.maven.api.model.PluginContainer; import org.apache.maven.api.model.PluginExecution; import org.apache.maven.api.model.PluginManagement; +import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer; import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.model.building.ModelProblemCollector; import org.apache.maven.model.building.ModelProblem.Severity; import org.apache.maven.model.building.ModelProblem.Version; +import org.apache.maven.model.building.ModelProblemCollector; import org.apache.maven.model.building.ModelProblemCollectorRequest; import org.apache.maven.model.merge.MavenModelMerger; @@ -52,146 +49,127 @@ import org.apache.maven.model.merge.MavenModelMerger; */ @Named @Singleton -public class DefaultLifecycleBindingsInjector - implements LifecycleBindingsInjector -{ +public class DefaultLifecycleBindingsInjector implements LifecycleBindingsInjector { private final LifecycleBindingsMerger merger = new LifecycleBindingsMerger(); private final LifeCyclePluginAnalyzer lifecycle; @Inject - public DefaultLifecycleBindingsInjector( LifeCyclePluginAnalyzer lifecycle ) - { + public DefaultLifecycleBindingsInjector(LifeCyclePluginAnalyzer lifecycle) { this.lifecycle = lifecycle; } - public void injectLifecycleBindings( org.apache.maven.model.Model model, ModelBuildingRequest request, - ModelProblemCollector problems ) - { + public void injectLifecycleBindings( + org.apache.maven.model.Model model, ModelBuildingRequest request, ModelProblemCollector problems) { String packaging = model.getPackaging(); Collection defaultPlugins = - lifecycle.getPluginsBoundByDefaultToAllLifecycles( packaging ); + lifecycle.getPluginsBoundByDefaultToAllLifecycles(packaging); - if ( defaultPlugins == null ) - { - problems.add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( "Unknown packaging: " + packaging ) - .setLocation( model.getLocation( "packaging" ) ) ); - } - else if ( !defaultPlugins.isEmpty() ) - { + if (defaultPlugins == null) { + problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage("Unknown packaging: " + packaging) + .setLocation(model.getLocation("packaging"))); + } else if (!defaultPlugins.isEmpty()) { List plugins = defaultPlugins.stream() - .map( org.apache.maven.model.Plugin::getDelegate ) - .collect( Collectors.toList() ); + .map(org.apache.maven.model.Plugin::getDelegate) + .collect(Collectors.toList()); Model lifecycleModel = Model.newBuilder() - .build( Build.newBuilder().plugins( plugins ).build() ) - .build(); - model.update( merger.merge( model.getDelegate(), lifecycleModel ) ); + .build(Build.newBuilder().plugins(plugins).build()) + .build(); + model.update(merger.merge(model.getDelegate(), lifecycleModel)); } } /** * The domain-specific model merger for lifecycle bindings */ - protected static class LifecycleBindingsMerger - extends MavenModelMerger - { + protected static class LifecycleBindingsMerger extends MavenModelMerger { private static final String PLUGIN_MANAGEMENT = "plugin-management"; - public Model merge( Model target, Model source ) - { + public Model merge(Model target, Model source) { Build targetBuild = target.getBuild(); - if ( targetBuild == null ) - { + if (targetBuild == null) { targetBuild = Build.newInstance(); } - Map context = - Collections.singletonMap( PLUGIN_MANAGEMENT, target.getBuild().getPluginManagement() ); + Map context = Collections.singletonMap( + PLUGIN_MANAGEMENT, target.getBuild().getPluginManagement()); - Build.Builder builder = Build.newBuilder( target.getBuild() ); - mergePluginContainer_Plugins( builder, targetBuild, source.getBuild(), false, context ); + Build.Builder builder = Build.newBuilder(target.getBuild()); + mergePluginContainer_Plugins(builder, targetBuild, source.getBuild(), false, context); - return target.withBuild( builder.build() ); + return target.withBuild(builder.build()); } - @SuppressWarnings( { "checkstyle:methodname" } ) + @SuppressWarnings({"checkstyle:methodname"}) @Override - protected void mergePluginContainer_Plugins( PluginContainer.Builder builder, - PluginContainer target, PluginContainer source, - boolean sourceDominant, Map context ) - { + protected void mergePluginContainer_Plugins( + PluginContainer.Builder builder, + PluginContainer target, + PluginContainer source, + boolean sourceDominant, + Map context) { List src = source.getPlugins(); - if ( !src.isEmpty() ) - { + if (!src.isEmpty()) { List tgt = target.getPlugins(); - Map merged = new LinkedHashMap<>( ( src.size() + tgt.size() ) * 2 ); + Map merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2); - for ( Plugin element : tgt ) - { - Object key = getPluginKey().apply( element ); - merged.put( key, element ); + for (Plugin element : tgt) { + Object key = getPluginKey().apply(element); + merged.put(key, element); } Map added = new LinkedHashMap<>(); - for ( Plugin element : src ) - { - Object key = getPluginKey().apply( element ); - Plugin existing = merged.get( key ); - if ( existing != null ) - { - element = mergePlugin( existing, element, sourceDominant, context ); + for (Plugin element : src) { + Object key = getPluginKey().apply(element); + Plugin existing = merged.get(key); + if (existing != null) { + element = mergePlugin(existing, element, sourceDominant, context); + } else { + added.put(key, element); } - else - { - added.put( key, element ); - } - merged.put( key, element ); + merged.put(key, element); } - if ( !added.isEmpty() ) - { - PluginManagement pluginMgmt = (PluginManagement) context.get( PLUGIN_MANAGEMENT ); - if ( pluginMgmt != null ) - { - for ( Plugin managedPlugin : pluginMgmt.getPlugins() ) - { - Object key = getPluginKey().apply( managedPlugin ); - Plugin addedPlugin = added.get( key ); - if ( addedPlugin != null ) - { - Plugin plugin = mergePlugin( managedPlugin, addedPlugin, - sourceDominant, Collections.emptyMap() ); - merged.put( key, plugin ); + if (!added.isEmpty()) { + PluginManagement pluginMgmt = (PluginManagement) context.get(PLUGIN_MANAGEMENT); + if (pluginMgmt != null) { + for (Plugin managedPlugin : pluginMgmt.getPlugins()) { + Object key = getPluginKey().apply(managedPlugin); + Plugin addedPlugin = added.get(key); + if (addedPlugin != null) { + Plugin plugin = + mergePlugin(managedPlugin, addedPlugin, sourceDominant, Collections.emptyMap()); + merged.put(key, plugin); } } } } - List result = new ArrayList<>( merged.values() ); + List result = new ArrayList<>(merged.values()); - builder.plugins( result ); + builder.plugins(result); } } @Override - protected void mergePluginExecution_Priority( PluginExecution.Builder builder, PluginExecution target, - PluginExecution source, boolean sourceDominant, - Map context ) - { - if ( target.getPriority() > source.getPriority() ) - { - builder.priority( source.getPriority() ); - builder.location( "priority", source.getLocation( "priority" ) ); + protected void mergePluginExecution_Priority( + PluginExecution.Builder builder, + PluginExecution target, + PluginExecution source, + boolean sourceDominant, + Map context) { + if (target.getPriority() > source.getPriority()) { + builder.priority(source.getPriority()); + builder.location("priority", source.getLocation("priority")); } } - //mergePluginExecution_Priority( builder, target, source, sourceDominant, context ); + // mergePluginExecution_Priority( builder, target, source, sourceDominant, context ); } - } diff --git a/maven-core/src/main/java/org/apache/maven/monitor/event/EventDispatcher.java b/maven-core/src/main/java/org/apache/maven/monitor/event/EventDispatcher.java index 492a2980ce..d75cb251d1 100644 --- a/maven-core/src/main/java/org/apache/maven/monitor/event/EventDispatcher.java +++ b/maven-core/src/main/java/org/apache/maven/monitor/event/EventDispatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.monitor.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.monitor.event; * "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 + * 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 @@ -18,20 +16,19 @@ package org.apache.maven.monitor.event; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.monitor.event; /** * @author jdcasey */ @Deprecated -public interface EventDispatcher -{ +public interface EventDispatcher { - void addEventMonitor( EventMonitor monitor ); + void addEventMonitor(EventMonitor monitor); - void dispatchStart( String event, String target ); + void dispatchStart(String event, String target); - void dispatchEnd( String event, String target ); + void dispatchEnd(String event, String target); - void dispatchError( String event, String target, Throwable cause ); - -} \ No newline at end of file + void dispatchError(String event, String target, Throwable cause); +} diff --git a/maven-core/src/main/java/org/apache/maven/monitor/event/EventMonitor.java b/maven-core/src/main/java/org/apache/maven/monitor/event/EventMonitor.java index 3e726746ad..12562ec378 100644 --- a/maven-core/src/main/java/org/apache/maven/monitor/event/EventMonitor.java +++ b/maven-core/src/main/java/org/apache/maven/monitor/event/EventMonitor.java @@ -1,5 +1,3 @@ -package org.apache.maven.monitor.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.monitor.event; * "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 + * 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 @@ -18,18 +16,17 @@ package org.apache.maven.monitor.event; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.monitor.event; /** * @author jdcasey */ @Deprecated -public interface EventMonitor -{ +public interface EventMonitor { - void startEvent( String eventName, String target, long timestamp ); + void startEvent(String eventName, String target, long timestamp); - void endEvent( String eventName, String target, long timestamp ); + void endEvent(String eventName, String target, long timestamp); - void errorEvent( String eventName, String target, long timestamp, Throwable cause ); - -} \ No newline at end of file + void errorEvent(String eventName, String target, long timestamp, Throwable cause); +} diff --git a/maven-core/src/main/java/org/apache/maven/plugin/BuildPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/BuildPluginManager.java index 6c1b9cbf4d..9889234bda 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/BuildPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/BuildPluginManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.MojoDescriptor; @@ -32,23 +30,21 @@ import org.eclipse.aether.repository.RemoteRepository; /** * @author Jason van Zyl */ -public interface BuildPluginManager -{ +public interface BuildPluginManager { // igorf: Way too many declared exceptions! - PluginDescriptor loadPlugin( Plugin plugin, List repositories, RepositorySystemSession session ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - InvalidPluginDescriptorException; + PluginDescriptor loadPlugin(Plugin plugin, List repositories, RepositorySystemSession session) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + InvalidPluginDescriptorException; // igorf: Way too many declared exceptions! - MojoDescriptor getMojoDescriptor( Plugin plugin, String goal, List repositories, - RepositorySystemSession session ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException; + MojoDescriptor getMojoDescriptor( + Plugin plugin, String goal, List repositories, RepositorySystemSession session) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException; - ClassRealm getPluginRealm( MavenSession session, PluginDescriptor pluginDescriptor ) - throws PluginResolutionException, PluginManagerException; - - void executeMojo( MavenSession session, MojoExecution execution ) - throws MojoFailureException, MojoExecutionException, PluginConfigurationException, PluginManagerException; + ClassRealm getPluginRealm(MavenSession session, PluginDescriptor pluginDescriptor) + throws PluginResolutionException, PluginManagerException; + void executeMojo(MavenSession session, MojoExecution execution) + throws MojoFailureException, MojoExecutionException, PluginConfigurationException, PluginManagerException; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/CacheUtils.java b/maven-core/src/main/java/org/apache/maven/plugin/CacheUtils.java index 118db83119..54a9907f0d 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/CacheUtils.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/CacheUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.Iterator; import java.util.List; import java.util.Objects; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Exclusion; import org.apache.maven.model.Plugin; @@ -30,91 +28,80 @@ import org.apache.maven.model.Plugin; /** * @author Benjamin Bentmann */ -class CacheUtils -{ +class CacheUtils { /** * @deprecated Use {@link Objects#equals(Object)} */ @Deprecated - public static boolean eq( T s1, T s2 ) - { - return Objects.equals( s1, s2 ); + public static boolean eq(T s1, T s2) { + return Objects.equals(s1, s2); } /** * @deprecated Use {@link Objects#hashCode(Object)} */ @Deprecated - public static int hash( Object obj ) - { + public static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - public static int pluginHashCode( Plugin plugin ) - { + public static int pluginHashCode(Plugin plugin) { int hash = 17; - hash = hash * 31 + Objects.hashCode( plugin.getGroupId() ); - hash = hash * 31 + Objects.hashCode( plugin.getArtifactId() ); - hash = hash * 31 + Objects.hashCode( plugin.getVersion() ); + hash = hash * 31 + Objects.hashCode(plugin.getGroupId()); + hash = hash * 31 + Objects.hashCode(plugin.getArtifactId()); + hash = hash * 31 + Objects.hashCode(plugin.getVersion()); - hash = hash * 31 + ( plugin.isExtensions() ? 1 : 0 ); + hash = hash * 31 + (plugin.isExtensions() ? 1 : 0); - for ( Dependency dependency : plugin.getDependencies() ) - { - hash = hash * 31 + Objects.hashCode( dependency.getGroupId() ); - hash = hash * 31 + Objects.hashCode( dependency.getArtifactId() ); - hash = hash * 31 + Objects.hashCode( dependency.getVersion() ); - hash = hash * 31 + Objects.hashCode( dependency.getType() ); - hash = hash * 31 + Objects.hashCode( dependency.getClassifier() ); - hash = hash * 31 + Objects.hashCode( dependency.getScope() ); + for (Dependency dependency : plugin.getDependencies()) { + hash = hash * 31 + Objects.hashCode(dependency.getGroupId()); + hash = hash * 31 + Objects.hashCode(dependency.getArtifactId()); + hash = hash * 31 + Objects.hashCode(dependency.getVersion()); + hash = hash * 31 + Objects.hashCode(dependency.getType()); + hash = hash * 31 + Objects.hashCode(dependency.getClassifier()); + hash = hash * 31 + Objects.hashCode(dependency.getScope()); - for ( Exclusion exclusion : dependency.getExclusions() ) - { - hash = hash * 31 + Objects.hashCode( exclusion.getGroupId() ); - hash = hash * 31 + Objects.hashCode( exclusion.getArtifactId() ); + for (Exclusion exclusion : dependency.getExclusions()) { + hash = hash * 31 + Objects.hashCode(exclusion.getGroupId()); + hash = hash * 31 + Objects.hashCode(exclusion.getArtifactId()); } } return hash; } - public static boolean pluginEquals( Plugin a, Plugin b ) - { - return Objects.equals( a.getArtifactId(), b.getArtifactId() ) // - && Objects.equals( a.getGroupId(), b.getGroupId() ) // - && Objects.equals( a.getVersion(), b.getVersion() ) // - && a.isExtensions() == b.isExtensions() // - && dependenciesEquals( a.getDependencies(), b.getDependencies() ); + public static boolean pluginEquals(Plugin a, Plugin b) { + return Objects.equals(a.getArtifactId(), b.getArtifactId()) // + && Objects.equals(a.getGroupId(), b.getGroupId()) // + && Objects.equals(a.getVersion(), b.getVersion()) // + && a.isExtensions() == b.isExtensions() // + && dependenciesEquals(a.getDependencies(), b.getDependencies()); } - private static boolean dependenciesEquals( List a, List b ) - { - if ( a.size() != b.size() ) - { + private static boolean dependenciesEquals(List a, List b) { + if (a.size() != b.size()) { return false; } Iterator aI = a.iterator(); Iterator bI = b.iterator(); - while ( aI.hasNext() ) - { + while (aI.hasNext()) { Dependency aD = aI.next(); Dependency bD = bI.next(); - boolean r = Objects.equals( aD.getGroupId(), bD.getGroupId() ) // - && Objects.equals( aD.getArtifactId(), bD.getArtifactId() ) // - && Objects.equals( aD.getVersion(), bD.getVersion() ) // - && Objects.equals( aD.getType(), bD.getType() ) // - && Objects.equals( aD.getClassifier(), bD.getClassifier() ) // - && Objects.equals( aD.getScope(), bD.getScope() ); + boolean r = Objects.equals(aD.getGroupId(), bD.getGroupId()) // + && Objects.equals(aD.getArtifactId(), bD.getArtifactId()) // + && Objects.equals(aD.getVersion(), bD.getVersion()) // + && Objects.equals(aD.getType(), bD.getType()) // + && Objects.equals(aD.getClassifier(), bD.getClassifier()) // + && Objects.equals(aD.getScope(), bD.getScope()); - r &= exclusionsEquals( aD.getExclusions(), bD.getExclusions() ); + r &= exclusionsEquals(aD.getExclusions(), bD.getExclusions()); - if ( !r ) - { + if (!r) { return false; } } @@ -122,31 +109,26 @@ class CacheUtils return true; } - private static boolean exclusionsEquals( List a, List b ) - { - if ( a.size() != b.size() ) - { + private static boolean exclusionsEquals(List a, List b) { + if (a.size() != b.size()) { return false; } Iterator aI = a.iterator(); Iterator bI = b.iterator(); - while ( aI.hasNext() ) - { + while (aI.hasNext()) { Exclusion aD = aI.next(); Exclusion bD = bI.next(); - boolean r = Objects.equals( aD.getGroupId(), bD.getGroupId() ) // - && Objects.equals( aD.getArtifactId(), bD.getArtifactId() ); + boolean r = Objects.equals(aD.getGroupId(), bD.getGroupId()) // + && Objects.equals(aD.getArtifactId(), bD.getArtifactId()); - if ( !r ) - { + if (!r) { return false; } } return true; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/CompoundMojoExecutionListener.java b/maven-core/src/main/java/org/apache/maven/plugin/CompoundMojoExecutionListener.java index e61ffbd06b..691dd68800 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/CompoundMojoExecutionListener.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/CompoundMojoExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,47 +16,35 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.Collection; - import org.apache.maven.execution.MojoExecutionEvent; import org.apache.maven.execution.MojoExecutionListener; -class CompoundMojoExecutionListener - implements MojoExecutionListener -{ +class CompoundMojoExecutionListener implements MojoExecutionListener { private final Collection listeners; - CompoundMojoExecutionListener( Collection listeners ) - { + CompoundMojoExecutionListener(Collection listeners) { this.listeners = listeners; // NB this is live injected collection } - public void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException - { - for ( MojoExecutionListener listener : listeners ) - { - listener.beforeMojoExecution( event ); + public void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException { + for (MojoExecutionListener listener : listeners) { + listener.beforeMojoExecution(event); } } - public void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException - { - for ( MojoExecutionListener listener : listeners ) - { - listener.afterMojoExecutionSuccess( event ); + public void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException { + for (MojoExecutionListener listener : listeners) { + listener.afterMojoExecutionSuccess(event); } } - public void afterExecutionFailure( MojoExecutionEvent event ) - { - for ( MojoExecutionListener listener : listeners ) - { - listener.afterExecutionFailure( event ); + public void afterExecutionFailure(MojoExecutionEvent event) { + for (MojoExecutionListener listener : listeners) { + listener.afterExecutionFailure(event); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/CycleDetectedInPluginGraphException.java b/maven-core/src/main/java/org/apache/maven/plugin/CycleDetectedInPluginGraphException.java index d7f6e8ad7f..a2fe3c4fa4 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/CycleDetectedInPluginGraphException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/CycleDetectedInPluginGraphException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.api.model.Plugin; import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; @@ -27,20 +26,16 @@ import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphEx * * @author Brett Porter */ -public class CycleDetectedInPluginGraphException - extends Exception -{ +public class CycleDetectedInPluginGraphException extends Exception { private final Plugin plugin; - public CycleDetectedInPluginGraphException( Plugin plugin, CycleDetectedInComponentGraphException e ) - { - super( "A cycle was detected in the component graph of the plugin: " + plugin.getArtifactId() ); + public CycleDetectedInPluginGraphException(Plugin plugin, CycleDetectedInComponentGraphException e) { + super("A cycle was detected in the component graph of the plugin: " + plugin.getArtifactId()); this.plugin = plugin; } - public Plugin getPlugin() - { + public Plugin getPlugin() { return plugin; } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DebugConfigurationListener.java b/maven-core/src/main/java/org/apache/maven/plugin/DebugConfigurationListener.java index 2ad629fc58..80bfdff9d1 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DebugConfigurationListener.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DebugConfigurationListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.lang.reflect.Array; - import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.slf4j.Logger; @@ -30,29 +28,22 @@ import org.slf4j.Logger; * @author Brett Porter */ @Deprecated -public class DebugConfigurationListener - implements ConfigurationListener -{ +public class DebugConfigurationListener implements ConfigurationListener { private final Logger logger; - public DebugConfigurationListener( Logger logger ) - { + public DebugConfigurationListener(Logger logger) { this.logger = logger; } - public void notifyFieldChangeUsingSetter( String fieldName, Object value, Object target ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( " (s) " + fieldName + " = " + toString( value ) ); + public void notifyFieldChangeUsingSetter(String fieldName, Object value, Object target) { + if (logger.isDebugEnabled()) { + logger.debug(" (s) " + fieldName + " = " + toString(value)); } } - public void notifyFieldChangeUsingReflection( String fieldName, Object value, Object target ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( " (f) " + fieldName + " = " + toString( value ) ); + public void notifyFieldChangeUsingReflection(String fieldName, Object value, Object target) { + if (logger.isDebugEnabled()) { + logger.debug(" (f) " + fieldName + " = " + toString(value)); } } @@ -62,30 +53,23 @@ public class DebugConfigurationListener * @param obj The object to create a string representation for, may be null. * @return The string representation, never null. */ - private String toString( Object obj ) - { + private String toString(Object obj) { String str; - if ( obj != null && obj.getClass().isArray() ) - { - int n = Array.getLength( obj ); - StringBuilder buf = new StringBuilder( 256 ); - buf.append( '[' ); - for ( int i = 0; i < n; i++ ) - { - if ( i > 0 ) - { - buf.append( ", " ); + if (obj != null && obj.getClass().isArray()) { + int n = Array.getLength(obj); + StringBuilder buf = new StringBuilder(256); + buf.append('['); + for (int i = 0; i < n; i++) { + if (i > 0) { + buf.append(", "); } - buf.append( String.valueOf( Array.get( obj, i ) ) ); + buf.append(String.valueOf(Array.get(obj, i))); } - buf.append( ']' ); + buf.append(']'); str = buf.toString(); - } - else - { - str = String.valueOf( obj ); + } else { + str = String.valueOf(obj); } return str; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java index a5c284458a..4f7823fe59 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,15 +16,14 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.api.Project; import org.apache.maven.api.plugin.MojoException; import org.apache.maven.execution.MavenSession; @@ -54,9 +51,7 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultBuildPluginManager - implements BuildPluginManager -{ +public class DefaultBuildPluginManager implements BuildPluginManager { private final MavenPluginManager mavenPluginManager; private final LegacySupport legacySupport; @@ -68,12 +63,11 @@ public class DefaultBuildPluginManager MavenPluginManager mavenPluginManager, LegacySupport legacySupport, MojoExecutionScope scope, - List mojoExecutionListeners ) - { + List mojoExecutionListeners) { this.mavenPluginManager = mavenPluginManager; this.legacySupport = legacySupport; this.scope = scope; - this.mojoExecutionListener = new CompoundMojoExecutionListener( mojoExecutionListeners ); + this.mojoExecutionListener = new CompoundMojoExecutionListener(mojoExecutionListeners); } /** @@ -85,21 +79,19 @@ public class DefaultBuildPluginManager * @throws PluginResolutionException The plugin could be found but could not be resolved. * @throws InvalidPluginDescriptorException */ - public PluginDescriptor loadPlugin( Plugin plugin, List repositories, - RepositorySystemSession session ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - InvalidPluginDescriptorException - { - return mavenPluginManager.getPluginDescriptor( plugin, repositories, session ); + public PluginDescriptor loadPlugin( + Plugin plugin, List repositories, RepositorySystemSession session) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + InvalidPluginDescriptorException { + return mavenPluginManager.getPluginDescriptor(plugin, repositories, session); } // ---------------------------------------------------------------------- // Mojo execution // ---------------------------------------------------------------------- - public void executeMojo( MavenSession session, MojoExecution mojoExecution ) - throws MojoFailureException, MojoExecutionException, PluginConfigurationException, PluginManagerException - { + public void executeMojo(MavenSession session, MojoExecution mojoExecution) + throws MojoFailureException, MojoExecutionException, PluginConfigurationException, PluginManagerException { MavenProject project = session.getCurrentProject(); MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); @@ -107,117 +99,95 @@ public class DefaultBuildPluginManager Mojo mojo = null; ClassRealm pluginRealm; - try - { - pluginRealm = getPluginRealm( session, mojoDescriptor.getPluginDescriptor() ); - } - catch ( PluginResolutionException e ) - { - throw new PluginExecutionException( mojoExecution, project, e ); + try { + pluginRealm = getPluginRealm(session, mojoDescriptor.getPluginDescriptor()); + } catch (PluginResolutionException e) { + throw new PluginExecutionException(mojoExecution, project, e); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( pluginRealm ); + Thread.currentThread().setContextClassLoader(pluginRealm); MavenSession oldSession = legacySupport.getSession(); scope.enter(); - try - { - scope.seed( MavenProject.class, project ); - scope.seed( MojoExecution.class, mojoExecution ); - scope.seed( org.apache.maven.api.plugin.Log.class, new DefaultLog( - LoggerFactory.getLogger( mojoExecution.getMojoDescriptor().getFullGoalName() ) ) ); - scope.seed( Project.class, ( ( DefaultSession) session.getSession() ).getProject( project ) ); - scope.seed( org.apache.maven.api.MojoExecution.class, new DefaultMojoExecution( mojoExecution ) ); + try { + scope.seed(MavenProject.class, project); + scope.seed(MojoExecution.class, mojoExecution); + scope.seed( + org.apache.maven.api.plugin.Log.class, + new DefaultLog(LoggerFactory.getLogger( + mojoExecution.getMojoDescriptor().getFullGoalName()))); + scope.seed(Project.class, ((DefaultSession) session.getSession()).getProject(project)); + scope.seed(org.apache.maven.api.MojoExecution.class, new DefaultMojoExecution(mojoExecution)); - if ( mojoDescriptor.isV4Api() ) - { + if (mojoDescriptor.isV4Api()) { org.apache.maven.api.plugin.Mojo mojoV4 = mavenPluginManager.getConfiguredMojo( - org.apache.maven.api.plugin.Mojo.class, session, mojoExecution ); - mojo = new MojoWrapper( mojoV4 ); - } - else - { - mojo = mavenPluginManager.getConfiguredMojo( Mojo.class, session, mojoExecution ); + org.apache.maven.api.plugin.Mojo.class, session, mojoExecution); + mojo = new MojoWrapper(mojoV4); + } else { + mojo = mavenPluginManager.getConfiguredMojo(Mojo.class, session, mojoExecution); } - legacySupport.setSession( session ); + legacySupport.setSession(session); // NOTE: DuplicateArtifactAttachmentException is currently unchecked, so be careful removing this try/catch! // This is necessary to avoid creating compatibility problems for existing plugins that use // MavenProjectHelper.attachArtifact(..). - try - { - MojoExecutionEvent mojoExecutionEvent = new MojoExecutionEvent( session, project, mojoExecution, mojo ); - mojoExecutionListener.beforeMojoExecution( mojoExecutionEvent ); + try { + MojoExecutionEvent mojoExecutionEvent = new MojoExecutionEvent(session, project, mojoExecution, mojo); + mojoExecutionListener.beforeMojoExecution(mojoExecutionEvent); mojo.execute(); - mojoExecutionListener.afterMojoExecutionSuccess( mojoExecutionEvent ); - } - catch ( ClassCastException e ) - { + mojoExecutionListener.afterMojoExecutionSuccess(mojoExecutionEvent); + } catch (ClassCastException e) { // to be processed in the outer catch block throw e; + } catch (RuntimeException e) { + throw new PluginExecutionException(mojoExecution, project, e); } - catch ( RuntimeException e ) - { - throw new PluginExecutionException( mojoExecution, project, e ); - } - } - catch ( PluginContainerException e ) - { + } catch (PluginContainerException e) { mojoExecutionListener.afterExecutionFailure( - new MojoExecutionEvent( session, project, mojoExecution, mojo, e ) ); - throw new PluginExecutionException( mojoExecution, project, e ); - } - catch ( NoClassDefFoundError e ) - { + new MojoExecutionEvent(session, project, mojoExecution, mojo, e)); + throw new PluginExecutionException(mojoExecution, project, e); + } catch (NoClassDefFoundError e) { mojoExecutionListener.afterExecutionFailure( - new MojoExecutionEvent( session, project, mojoExecution, mojo, e ) ); - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( "A required class was missing while executing " + mojoDescriptor.getId() + ": " - + e.getMessage() ); - pluginRealm.display( ps ); - Exception wrapper = new PluginContainerException( mojoDescriptor, pluginRealm, os.toString(), e ); - throw new PluginExecutionException( mojoExecution, project, wrapper ); - } - catch ( LinkageError e ) - { + new MojoExecutionEvent(session, project, mojoExecution, mojo, e)); + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println( + "A required class was missing while executing " + mojoDescriptor.getId() + ": " + e.getMessage()); + pluginRealm.display(ps); + Exception wrapper = new PluginContainerException(mojoDescriptor, pluginRealm, os.toString(), e); + throw new PluginExecutionException(mojoExecution, project, wrapper); + } catch (LinkageError e) { mojoExecutionListener.afterExecutionFailure( - new MojoExecutionEvent( session, project, mojoExecution, mojo, e ) ); - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( "An API incompatibility was encountered while executing " + mojoDescriptor.getId() + ": " - + e.getClass().getName() + ": " + e.getMessage() ); - pluginRealm.display( ps ); - Exception wrapper = new PluginContainerException( mojoDescriptor, pluginRealm, os.toString(), e ); - throw new PluginExecutionException( mojoExecution, project, wrapper ); - } - catch ( ClassCastException e ) - { + new MojoExecutionEvent(session, project, mojoExecution, mojo, e)); + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println("An API incompatibility was encountered while executing " + mojoDescriptor.getId() + ": " + + e.getClass().getName() + ": " + e.getMessage()); + pluginRealm.display(ps); + Exception wrapper = new PluginContainerException(mojoDescriptor, pluginRealm, os.toString(), e); + throw new PluginExecutionException(mojoExecution, project, wrapper); + } catch (ClassCastException e) { mojoExecutionListener.afterExecutionFailure( - new MojoExecutionEvent( session, project, mojoExecution, mojo, e ) ); - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( "A type incompatibility occurred while executing " + mojoDescriptor.getId() + ": " - + e.getMessage() ); - pluginRealm.display( ps ); - throw new PluginExecutionException( mojoExecution, project, os.toString(), e ); - } - catch ( RuntimeException e ) - { + new MojoExecutionEvent(session, project, mojoExecution, mojo, e)); + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println("A type incompatibility occurred while executing " + mojoDescriptor.getId() + ": " + + e.getMessage()); + pluginRealm.display(ps); + throw new PluginExecutionException(mojoExecution, project, os.toString(), e); + } catch (RuntimeException e) { mojoExecutionListener.afterExecutionFailure( - new MojoExecutionEvent( session, project, mojoExecution, mojo, e ) ); + new MojoExecutionEvent(session, project, mojoExecution, mojo, e)); throw e; - } - finally - { - mavenPluginManager.releaseMojo( mojo, mojoExecution ); + } finally { + mavenPluginManager.releaseMojo(mojo, mojoExecution); scope.exit(); - Thread.currentThread().setContextClassLoader( oldClassLoader ); - legacySupport.setSession( oldSession ); + Thread.currentThread().setContextClassLoader(oldClassLoader); + legacySupport.setSession(oldSession); } } @@ -226,58 +196,46 @@ public class DefaultBuildPluginManager * call, which is not nice. * @throws PluginResolutionException */ - public ClassRealm getPluginRealm( MavenSession session, PluginDescriptor pluginDescriptor ) - throws PluginResolutionException, PluginManagerException - { + public ClassRealm getPluginRealm(MavenSession session, PluginDescriptor pluginDescriptor) + throws PluginResolutionException, PluginManagerException { ClassRealm pluginRealm = pluginDescriptor.getClassRealm(); - if ( pluginRealm != null ) - { + if (pluginRealm != null) { return pluginRealm; } - mavenPluginManager.setupPluginRealm( pluginDescriptor, session, null, null, null ); + mavenPluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null); return pluginDescriptor.getClassRealm(); } - public MojoDescriptor getMojoDescriptor( Plugin plugin, String goal, List repositories, - RepositorySystemSession session ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException - { - return mavenPluginManager.getMojoDescriptor( plugin, goal, repositories, session ); + public MojoDescriptor getMojoDescriptor( + Plugin plugin, String goal, List repositories, RepositorySystemSession session) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException { + return mavenPluginManager.getMojoDescriptor(plugin, goal, repositories, session); } - private static class MojoWrapper implements Mojo - { + private static class MojoWrapper implements Mojo { private final org.apache.maven.api.plugin.Mojo mojoV4; - MojoWrapper( org.apache.maven.api.plugin.Mojo mojoV4 ) - { + MojoWrapper(org.apache.maven.api.plugin.Mojo mojoV4) { this.mojoV4 = mojoV4; } @Override - public void execute() throws MojoExecutionException, MojoFailureException - { - try - { + public void execute() throws MojoExecutionException, MojoFailureException { + try { mojoV4.execute(); - } - catch ( MojoException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (MojoException e) { + throw new MojoExecutionException(e.getMessage(), e); } } @Override - public void setLog( Log log ) - { - } + public void setLog(Log log) {} @Override - public Log getLog() - { + public Log getLog() { return null; } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultExtensionRealmCache.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultExtensionRealmCache.java index dd48a4f13c..8385d95984 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultExtensionRealmCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultExtensionRealmCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.io.File; import java.util.ArrayList; @@ -25,10 +24,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.project.ExtensionDescriptor; import org.apache.maven.project.MavenProject; @@ -41,15 +38,11 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable; */ @Named @Singleton -public class DefaultExtensionRealmCache - implements ExtensionRealmCache, Disposable -{ +public class DefaultExtensionRealmCache implements ExtensionRealmCache, Disposable { /** * CacheKey */ - protected static class CacheKey - implements Key - { + protected static class CacheKey implements Key { private final List files; @@ -61,54 +54,49 @@ public class DefaultExtensionRealmCache private final int hashCode; - public CacheKey( List extensionArtifacts ) - { - this.files = new ArrayList<>( extensionArtifacts.size() ); - this.timestamps = new ArrayList<>( extensionArtifacts.size() ); - this.sizes = new ArrayList<>( extensionArtifacts.size() ); - this.ids = new ArrayList<>( extensionArtifacts.size() ); + public CacheKey(List extensionArtifacts) { + this.files = new ArrayList<>(extensionArtifacts.size()); + this.timestamps = new ArrayList<>(extensionArtifacts.size()); + this.sizes = new ArrayList<>(extensionArtifacts.size()); + this.ids = new ArrayList<>(extensionArtifacts.size()); - for ( Artifact artifact : extensionArtifacts ) - { + for (Artifact artifact : extensionArtifacts) { File file = artifact.getFile(); - files.add( file ); - timestamps.add( ( file != null ) ? Long.valueOf( file.lastModified() ) : Long.valueOf( 0 ) ); - sizes.add( ( file != null ) ? Long.valueOf( file.length() ) : Long.valueOf( 0 ) ); - ids.add( artifact.getVersion() ); + files.add(file); + timestamps.add((file != null) ? Long.valueOf(file.lastModified()) : Long.valueOf(0)); + sizes.add((file != null) ? Long.valueOf(file.length()) : Long.valueOf(0)); + ids.add(artifact.getVersion()); } this.hashCode = - 31 * files.hashCode() + 31 * ids.hashCode() + 31 * timestamps.hashCode() + 31 * sizes.hashCode(); + 31 * files.hashCode() + 31 * ids.hashCode() + 31 * timestamps.hashCode() + 31 * sizes.hashCode(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof CacheKey ) ) - { + if (!(o instanceof CacheKey)) { return false; } CacheKey other = (CacheKey) o; - return ids.equals( other.ids ) && files.equals( other.files ) && timestamps.equals( other.timestamps ) - && sizes.equals( other.sizes ); + return ids.equals(other.ids) + && files.equals(other.files) + && timestamps.equals(other.timestamps) + && sizes.equals(other.sizes); } @Override - public String toString() - { + public String toString() { return files.toString(); } } @@ -116,58 +104,46 @@ public class DefaultExtensionRealmCache protected final Map cache = new ConcurrentHashMap<>(); @Override - public Key createKey( List extensionArtifacts ) - { - return new CacheKey( extensionArtifacts ); + public Key createKey(List extensionArtifacts) { + return new CacheKey(extensionArtifacts); } - public CacheRecord get( Key key ) - { - return cache.get( key ); + public CacheRecord get(Key key) { + return cache.get(key); } - public CacheRecord put( Key key, ClassRealm extensionRealm, ExtensionDescriptor extensionDescriptor, - List artifacts ) - { - Objects.requireNonNull( extensionRealm, "extensionRealm cannot be null" ); + public CacheRecord put( + Key key, ClassRealm extensionRealm, ExtensionDescriptor extensionDescriptor, List artifacts) { + Objects.requireNonNull(extensionRealm, "extensionRealm cannot be null"); - if ( cache.containsKey( key ) ) - { - throw new IllegalStateException( "Duplicate extension realm for extension " + key ); + if (cache.containsKey(key)) { + throw new IllegalStateException("Duplicate extension realm for extension " + key); } - CacheRecord record = new CacheRecord( extensionRealm, extensionDescriptor, artifacts ); + CacheRecord record = new CacheRecord(extensionRealm, extensionDescriptor, artifacts); - cache.put( key, record ); + cache.put(key, record); return record; } - public void flush() - { - for ( CacheRecord record : cache.values() ) - { + public void flush() { + for (CacheRecord record : cache.values()) { ClassRealm realm = record.getRealm(); - try - { - realm.getWorld().disposeRealm( realm.getId() ); - } - catch ( NoSuchRealmException e ) - { + try { + realm.getWorld().disposeRealm(realm.getId()); + } catch (NoSuchRealmException e) { // ignore } } cache.clear(); } - public void register( MavenProject project, Key key, CacheRecord record ) - { + public void register(MavenProject project, Key key, CacheRecord record) { // default cache does not track extension usage } - public void dispose() - { + public void dispose() { flush(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultMojosExecutionStrategy.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultMojosExecutionStrategy.java index 9507c7ad17..0156d66f78 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultMojosExecutionStrategy.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultMojosExecutionStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,29 +16,25 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.lifecycle.LifecycleExecutionException; - +import java.util.List; import javax.inject.Named; import javax.inject.Singleton; -import java.util.List; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.LifecycleExecutionException; /** * Default mojo execution strategy. It just iterates over mojo executions and runs one by one */ @Named @Singleton -public class DefaultMojosExecutionStrategy implements MojosExecutionStrategy -{ +public class DefaultMojosExecutionStrategy implements MojosExecutionStrategy { @Override - public void execute( List mojos, MavenSession session, MojoExecutionRunner mojoRunner ) - throws LifecycleExecutionException - { - for ( MojoExecution mojoExecution : mojos ) - { - mojoRunner.run( mojoExecution ); + public void execute(List mojos, MavenSession session, MojoExecutionRunner mojoRunner) + throws LifecycleExecutionException { + for (MojoExecution mojoExecution : mojos) { + mojoRunner.run(mojoExecution); } - } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginArtifactsCache.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginArtifactsCache.java index 7f8ff14064..ae445936bd 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginArtifactsCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginArtifactsCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.ArrayList; import java.util.Collections; @@ -25,10 +24,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Plugin; @@ -45,15 +42,11 @@ import org.eclipse.aether.repository.WorkspaceRepository; */ @Named @Singleton -public class DefaultPluginArtifactsCache - implements PluginArtifactsCache -{ +public class DefaultPluginArtifactsCache implements PluginArtifactsCache { /** * CacheKey */ - protected static class CacheKey - implements Key - { + protected static class CacheKey implements Key { private final Plugin plugin; private final WorkspaceRepository workspace; @@ -66,144 +59,126 @@ public class DefaultPluginArtifactsCache private final int hashCode; - public CacheKey( Plugin plugin, DependencyFilter extensionFilter, List repositories, - RepositorySystemSession session ) - { + public CacheKey( + Plugin plugin, + DependencyFilter extensionFilter, + List repositories, + RepositorySystemSession session) { this.plugin = plugin.clone(); - workspace = RepositoryUtils.getWorkspace( session ); + workspace = RepositoryUtils.getWorkspace(session); this.localRepo = session.getLocalRepository(); - this.repositories = new ArrayList<>( repositories.size() ); - for ( RemoteRepository repository : repositories ) - { - if ( repository.isRepositoryManager() ) - { - this.repositories.addAll( repository.getMirroredRepositories() ); - } - else - { - this.repositories.add( repository ); + this.repositories = new ArrayList<>(repositories.size()); + for (RemoteRepository repository : repositories) { + if (repository.isRepositoryManager()) { + this.repositories.addAll(repository.getMirroredRepositories()); + } else { + this.repositories.add(repository); } } this.filter = extensionFilter; int hash = 17; - hash = hash * 31 + CacheUtils.pluginHashCode( plugin ); - hash = hash * 31 + Objects.hashCode( workspace ); - hash = hash * 31 + Objects.hashCode( localRepo ); - hash = hash * 31 + RepositoryUtils.repositoriesHashCode( repositories ); - hash = hash * 31 + Objects.hashCode( extensionFilter ); + hash = hash * 31 + CacheUtils.pluginHashCode(plugin); + hash = hash * 31 + Objects.hashCode(workspace); + hash = hash * 31 + Objects.hashCode(localRepo); + hash = hash * 31 + RepositoryUtils.repositoriesHashCode(repositories); + hash = hash * 31 + Objects.hashCode(extensionFilter); this.hashCode = hash; } @Override - public String toString() - { + public String toString() { return plugin.getId(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof CacheKey ) ) - { + if (!(o instanceof CacheKey)) { return false; } CacheKey that = (CacheKey) o; - return CacheUtils.pluginEquals( plugin, that.plugin ) - && Objects.equals( workspace, that.workspace ) - && Objects.equals( localRepo, that.localRepo ) - && RepositoryUtils.repositoriesEquals( repositories, that.repositories ) - && Objects.equals( filter, that.filter ); + return CacheUtils.pluginEquals(plugin, that.plugin) + && Objects.equals(workspace, that.workspace) + && Objects.equals(localRepo, that.localRepo) + && RepositoryUtils.repositoriesEquals(repositories, that.repositories) + && Objects.equals(filter, that.filter); } } protected final Map cache = new ConcurrentHashMap<>(); - public Key createKey( Plugin plugin, DependencyFilter extensionFilter, List repositories, - RepositorySystemSession session ) - { - return new CacheKey( plugin, extensionFilter, repositories, session ); + public Key createKey( + Plugin plugin, + DependencyFilter extensionFilter, + List repositories, + RepositorySystemSession session) { + return new CacheKey(plugin, extensionFilter, repositories, session); } - public CacheRecord get( Key key ) - throws PluginResolutionException - { - CacheRecord cacheRecord = cache.get( key ); + public CacheRecord get(Key key) throws PluginResolutionException { + CacheRecord cacheRecord = cache.get(key); - if ( cacheRecord != null && cacheRecord.getException() != null ) - { + if (cacheRecord != null && cacheRecord.getException() != null) { throw cacheRecord.getException(); } return cacheRecord; } - public CacheRecord put( Key key, List pluginArtifacts ) - { - Objects.requireNonNull( pluginArtifacts, "pluginArtifacts cannot be null" ); + public CacheRecord put(Key key, List pluginArtifacts) { + Objects.requireNonNull(pluginArtifacts, "pluginArtifacts cannot be null"); - assertUniqueKey( key ); + assertUniqueKey(key); - CacheRecord record = - new CacheRecord( Collections.unmodifiableList( new ArrayList<>( pluginArtifacts ) ) ); + CacheRecord record = new CacheRecord(Collections.unmodifiableList(new ArrayList<>(pluginArtifacts))); - cache.put( key, record ); + cache.put(key, record); return record; } - protected void assertUniqueKey( Key key ) - { - if ( cache.containsKey( key ) ) - { - throw new IllegalStateException( "Duplicate artifact resolution result for plugin " + key ); + protected void assertUniqueKey(Key key) { + if (cache.containsKey(key)) { + throw new IllegalStateException("Duplicate artifact resolution result for plugin " + key); } } - public CacheRecord put( Key key, PluginResolutionException exception ) - { - Objects.requireNonNull( exception, "exception cannot be null" ); + public CacheRecord put(Key key, PluginResolutionException exception) { + Objects.requireNonNull(exception, "exception cannot be null"); - assertUniqueKey( key ); + assertUniqueKey(key); - CacheRecord record = new CacheRecord( exception ); + CacheRecord record = new CacheRecord(exception); - cache.put( key, record ); + cache.put(key, record); return record; } - public void flush() - { + public void flush() { cache.clear(); } - protected static int pluginHashCode( Plugin plugin ) - { - return CacheUtils.pluginHashCode( plugin ); + protected static int pluginHashCode(Plugin plugin) { + return CacheUtils.pluginHashCode(plugin); } - protected static boolean pluginEquals( Plugin a, Plugin b ) - { - return CacheUtils.pluginEquals( a, b ); + protected static boolean pluginEquals(Plugin a, Plugin b) { + return CacheUtils.pluginEquals(a, b); } - public void register( MavenProject project, Key cacheKey, CacheRecord record ) - { + public void register(MavenProject project, Key cacheKey, CacheRecord record) { // default cache does not track record usage } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java index 9e78b3c9b6..021ac4f2a5 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,16 +16,15 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.model.Plugin; @@ -51,123 +48,100 @@ import org.eclipse.aether.repository.WorkspaceRepository; */ @Named @Singleton -public class DefaultPluginDescriptorCache - implements PluginDescriptorCache -{ +public class DefaultPluginDescriptorCache implements PluginDescriptorCache { - private Map descriptors = new ConcurrentHashMap<>( 128 ); + private Map descriptors = new ConcurrentHashMap<>(128); - public void flush() - { + public void flush() { descriptors.clear(); } - public Key createKey( Plugin plugin, List repositories, RepositorySystemSession session ) - { - return new CacheKey( plugin, repositories, session ); + public Key createKey(Plugin plugin, List repositories, RepositorySystemSession session) { + return new CacheKey(plugin, repositories, session); } - public PluginDescriptor get( Key cacheKey ) - { - return clone( descriptors.get( cacheKey ) ); + public PluginDescriptor get(Key cacheKey) { + return clone(descriptors.get(cacheKey)); } @Override - public PluginDescriptor get( Key key, PluginDescriptorSupplier supplier ) - throws PluginDescriptorParsingException, PluginResolutionException, InvalidPluginDescriptorException - { - try - { - return clone( descriptors.computeIfAbsent( key, k -> - { - try - { - return clone( supplier.load() ); + public PluginDescriptor get(Key key, PluginDescriptorSupplier supplier) + throws PluginDescriptorParsingException, PluginResolutionException, InvalidPluginDescriptorException { + try { + return clone(descriptors.computeIfAbsent(key, k -> { + try { + return clone(supplier.load()); + } catch (PluginDescriptorParsingException + | PluginResolutionException + | InvalidPluginDescriptorException e) { + throw new RuntimeException(e); } - catch ( PluginDescriptorParsingException | PluginResolutionException - | InvalidPluginDescriptorException e ) - { - throw new RuntimeException( e ); - } - } ) ); - } - catch ( RuntimeException e ) - { - if ( e.getCause() instanceof PluginDescriptorParsingException ) - { + })); + } catch (RuntimeException e) { + if (e.getCause() instanceof PluginDescriptorParsingException) { throw (PluginDescriptorParsingException) e.getCause(); } - if ( e.getCause() instanceof PluginResolutionException ) - { + if (e.getCause() instanceof PluginResolutionException) { throw (PluginResolutionException) e.getCause(); } - if ( e.getCause() instanceof InvalidPluginDescriptorException ) - { + if (e.getCause() instanceof InvalidPluginDescriptorException) { throw (InvalidPluginDescriptorException) e.getCause(); } throw e; } } - public void put( Key cacheKey, PluginDescriptor pluginDescriptor ) - { - descriptors.put( cacheKey, clone( pluginDescriptor ) ); + public void put(Key cacheKey, PluginDescriptor pluginDescriptor) { + descriptors.put(cacheKey, clone(pluginDescriptor)); } - protected static PluginDescriptor clone( PluginDescriptor original ) - { + protected static PluginDescriptor clone(PluginDescriptor original) { PluginDescriptor clone = null; - if ( original != null ) - { + if (original != null) { clone = new PluginDescriptor(); - clone.setGroupId( original.getGroupId() ); - clone.setArtifactId( original.getArtifactId() ); - clone.setVersion( original.getVersion() ); - clone.setGoalPrefix( original.getGoalPrefix() ); - clone.setInheritedByDefault( original.isInheritedByDefault() ); + clone.setGroupId(original.getGroupId()); + clone.setArtifactId(original.getArtifactId()); + clone.setVersion(original.getVersion()); + clone.setGoalPrefix(original.getGoalPrefix()); + clone.setInheritedByDefault(original.isInheritedByDefault()); - clone.setName( original.getName() ); - clone.setDescription( original.getDescription() ); - clone.setRequiredMavenVersion( original.getRequiredMavenVersion() ); - clone.setRequiredJavaVersion( original.getRequiredJavaVersion() ); + clone.setName(original.getName()); + clone.setDescription(original.getDescription()); + clone.setRequiredMavenVersion(original.getRequiredMavenVersion()); + clone.setRequiredJavaVersion(original.getRequiredJavaVersion()); - clone.setPluginArtifact( ArtifactUtils.copyArtifactSafe( original.getPluginArtifact() ) ); + clone.setPluginArtifact(ArtifactUtils.copyArtifactSafe(original.getPluginArtifact())); - clone.setComponents( clone( original.getMojos(), clone ) ); - clone.setId( original.getId() ); - clone.setIsolatedRealm( original.isIsolatedRealm() ); - clone.setSource( original.getSource() ); + clone.setComponents(clone(original.getMojos(), clone)); + clone.setId(original.getId()); + clone.setIsolatedRealm(original.isIsolatedRealm()); + clone.setSource(original.getSource()); - clone.setDependencies( original.getDependencies() ); + clone.setDependencies(original.getDependencies()); } return clone; } - private static List> clone( List mojos, PluginDescriptor pluginDescriptor ) - { + private static List> clone(List mojos, PluginDescriptor pluginDescriptor) { List> clones = null; - if ( mojos != null ) - { - clones = new ArrayList<>( mojos.size() ); + if (mojos != null) { + clones = new ArrayList<>(mojos.size()); - for ( MojoDescriptor mojo : mojos ) - { + for (MojoDescriptor mojo : mojos) { MojoDescriptor clone = mojo.clone(); - clone.setPluginDescriptor( pluginDescriptor ); - clones.add( clone ); + clone.setPluginDescriptor(pluginDescriptor); + clones.add(clone); } } return clones; } - private static final class CacheKey - implements Key - { + private static final class CacheKey implements Key { private final String groupId; @@ -183,24 +157,19 @@ public class DefaultPluginDescriptorCache private final int hashCode; - CacheKey( Plugin plugin, List repositories, RepositorySystemSession session ) - { + CacheKey(Plugin plugin, List repositories, RepositorySystemSession session) { groupId = plugin.getGroupId(); artifactId = plugin.getArtifactId(); version = plugin.getVersion(); - workspace = RepositoryUtils.getWorkspace( session ); + workspace = RepositoryUtils.getWorkspace(session); localRepo = session.getLocalRepository(); - this.repositories = new ArrayList<>( repositories.size() ); - for ( RemoteRepository repository : repositories ) - { - if ( repository.isRepositoryManager() ) - { - this.repositories.addAll( repository.getMirroredRepositories() ); - } - else - { - this.repositories.add( repository ); + this.repositories = new ArrayList<>(repositories.size()); + for (RemoteRepository repository : repositories) { + if (repository.isRepositoryManager()) { + this.repositories.addAll(repository.getMirroredRepositories()); + } else { + this.repositories.add(repository); } } @@ -208,52 +177,44 @@ public class DefaultPluginDescriptorCache hash = hash * 31 + groupId.hashCode(); hash = hash * 31 + artifactId.hashCode(); hash = hash * 31 + version.hashCode(); - hash = hash * 31 + hash( workspace ); + hash = hash * 31 + hash(workspace); hash = hash * 31 + localRepo.hashCode(); - hash = hash * 31 + RepositoryUtils.repositoriesHashCode( repositories ); + hash = hash * 31 + RepositoryUtils.repositoriesHashCode(repositories); this.hashCode = hash; } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( !( obj instanceof CacheKey ) ) - { + if (!(obj instanceof CacheKey)) { return false; } CacheKey that = (CacheKey) obj; - return Objects.equals( this.artifactId, that.artifactId ) - && Objects.equals( this.groupId, that.groupId ) - && Objects.equals( this.version, that.version ) - && Objects.equals( this.localRepo, that.localRepo ) - && Objects.equals( this.workspace, that.workspace ) - && RepositoryUtils.repositoriesEquals( this.repositories, that.repositories ); + return Objects.equals(this.artifactId, that.artifactId) + && Objects.equals(this.groupId, that.groupId) + && Objects.equals(this.version, that.version) + && Objects.equals(this.localRepo, that.localRepo) + && Objects.equals(this.workspace, that.workspace) + && RepositoryUtils.repositoriesEquals(this.repositories, that.repositories); } @Override - public String toString() - { + public String toString() { return groupId + ':' + artifactId + ':' + version; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginRealmCache.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginRealmCache.java index 687cb93579..2e443ccfbb 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginRealmCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginRealmCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.ArrayList; import java.util.Collections; @@ -25,10 +24,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Plugin; @@ -47,15 +44,11 @@ import org.eclipse.aether.repository.WorkspaceRepository; */ @Named @Singleton -public class DefaultPluginRealmCache - implements PluginRealmCache, Disposable -{ +public class DefaultPluginRealmCache implements PluginRealmCache, Disposable { /** * CacheKey */ - protected static class CacheKey - implements Key - { + protected static class CacheKey implements Key { private final Plugin plugin; @@ -73,176 +66,149 @@ public class DefaultPluginRealmCache private final int hashCode; - public CacheKey( Plugin plugin, ClassLoader parentRealm, Map foreignImports, - DependencyFilter dependencyFilter, List repositories, - RepositorySystemSession session ) - { + public CacheKey( + Plugin plugin, + ClassLoader parentRealm, + Map foreignImports, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session) { this.plugin = plugin.clone(); - this.workspace = RepositoryUtils.getWorkspace( session ); + this.workspace = RepositoryUtils.getWorkspace(session); this.localRepo = session.getLocalRepository(); - this.repositories = new ArrayList<>( repositories.size() ); - for ( RemoteRepository repository : repositories ) - { - if ( repository.isRepositoryManager() ) - { - this.repositories.addAll( repository.getMirroredRepositories() ); - } - else - { - this.repositories.add( repository ); + this.repositories = new ArrayList<>(repositories.size()); + for (RemoteRepository repository : repositories) { + if (repository.isRepositoryManager()) { + this.repositories.addAll(repository.getMirroredRepositories()); + } else { + this.repositories.add(repository); } } this.parentRealm = parentRealm; - this.foreignImports = - ( foreignImports != null ) ? foreignImports : Collections.emptyMap(); + this.foreignImports = (foreignImports != null) ? foreignImports : Collections.emptyMap(); this.filter = dependencyFilter; int hash = 17; - hash = hash * 31 + CacheUtils.pluginHashCode( plugin ); - hash = hash * 31 + Objects.hashCode( workspace ); - hash = hash * 31 + Objects.hashCode( localRepo ); - hash = hash * 31 + RepositoryUtils.repositoriesHashCode( repositories ); - hash = hash * 31 + Objects.hashCode( parentRealm ); + hash = hash * 31 + CacheUtils.pluginHashCode(plugin); + hash = hash * 31 + Objects.hashCode(workspace); + hash = hash * 31 + Objects.hashCode(localRepo); + hash = hash * 31 + RepositoryUtils.repositoriesHashCode(repositories); + hash = hash * 31 + Objects.hashCode(parentRealm); hash = hash * 31 + this.foreignImports.hashCode(); - hash = hash * 31 + Objects.hashCode( dependencyFilter ); + hash = hash * 31 + Objects.hashCode(dependencyFilter); this.hashCode = hash; } @Override - public String toString() - { + public String toString() { return plugin.getId(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof CacheKey ) ) - { + if (!(o instanceof CacheKey)) { return false; } CacheKey that = (CacheKey) o; return parentRealm == that.parentRealm - && CacheUtils.pluginEquals( plugin, that.plugin ) - && Objects.equals( workspace, that.workspace ) - && Objects.equals( localRepo, that.localRepo ) - && RepositoryUtils.repositoriesEquals( this.repositories, that.repositories ) - && Objects.equals( filter, that.filter ) - && Objects.equals( foreignImports, that.foreignImports ); + && CacheUtils.pluginEquals(plugin, that.plugin) + && Objects.equals(workspace, that.workspace) + && Objects.equals(localRepo, that.localRepo) + && RepositoryUtils.repositoriesEquals(this.repositories, that.repositories) + && Objects.equals(filter, that.filter) + && Objects.equals(foreignImports, that.foreignImports); } } protected final Map cache = new ConcurrentHashMap<>(); - public Key createKey( Plugin plugin, ClassLoader parentRealm, Map foreignImports, - DependencyFilter dependencyFilter, List repositories, - RepositorySystemSession session ) - { - return new CacheKey( plugin, parentRealm, foreignImports, dependencyFilter, repositories, session ); + public Key createKey( + Plugin plugin, + ClassLoader parentRealm, + Map foreignImports, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session) { + return new CacheKey(plugin, parentRealm, foreignImports, dependencyFilter, repositories, session); } - public CacheRecord get( Key key ) - { - return cache.get( key ); + public CacheRecord get(Key key) { + return cache.get(key); } @Override - public CacheRecord get( Key key, PluginRealmSupplier supplier ) - throws PluginResolutionException, PluginContainerException - { - try - { - return cache.computeIfAbsent( key, k -> - { - try - { + public CacheRecord get(Key key, PluginRealmSupplier supplier) + throws PluginResolutionException, PluginContainerException { + try { + return cache.computeIfAbsent(key, k -> { + try { return supplier.load(); + } catch (PluginResolutionException | PluginContainerException e) { + throw new RuntimeException(e); } - catch ( PluginResolutionException | PluginContainerException e ) - { - throw new RuntimeException( e ); - } - } ); - } - catch ( RuntimeException e ) - { - if ( e.getCause() instanceof PluginResolutionException ) - { + }); + } catch (RuntimeException e) { + if (e.getCause() instanceof PluginResolutionException) { throw (PluginResolutionException) e.getCause(); } - if ( e.getCause() instanceof PluginContainerException ) - { + if (e.getCause() instanceof PluginContainerException) { throw (PluginContainerException) e.getCause(); } throw e; } } - public CacheRecord put( Key key, ClassRealm pluginRealm, List pluginArtifacts ) - { - Objects.requireNonNull( pluginRealm, "pluginRealm cannot be null" ); - Objects.requireNonNull( pluginArtifacts, "pluginArtifacts cannot be null" ); + public CacheRecord put(Key key, ClassRealm pluginRealm, List pluginArtifacts) { + Objects.requireNonNull(pluginRealm, "pluginRealm cannot be null"); + Objects.requireNonNull(pluginArtifacts, "pluginArtifacts cannot be null"); - if ( cache.containsKey( key ) ) - { - throw new IllegalStateException( "Duplicate plugin realm for plugin " + key ); + if (cache.containsKey(key)) { + throw new IllegalStateException("Duplicate plugin realm for plugin " + key); } - CacheRecord record = new CacheRecord( pluginRealm, pluginArtifacts ); + CacheRecord record = new CacheRecord(pluginRealm, pluginArtifacts); - cache.put( key, record ); + cache.put(key, record); return record; } - public void flush() - { - for ( CacheRecord record : cache.values() ) - { + public void flush() { + for (CacheRecord record : cache.values()) { ClassRealm realm = record.getRealm(); - try - { - realm.getWorld().disposeRealm( realm.getId() ); - } - catch ( NoSuchRealmException e ) - { + try { + realm.getWorld().disposeRealm(realm.getId()); + } catch (NoSuchRealmException e) { // ignore } } cache.clear(); } - protected static int pluginHashCode( Plugin plugin ) - { - return CacheUtils.pluginHashCode( plugin ); + protected static int pluginHashCode(Plugin plugin) { + return CacheUtils.pluginHashCode(plugin); } - protected static boolean pluginEquals( Plugin a, Plugin b ) - { - return CacheUtils.pluginEquals( a, b ); + protected static boolean pluginEquals(Plugin a, Plugin b) { + return CacheUtils.pluginEquals(a, b); } - public void register( MavenProject project, Key key, CacheRecord record ) - { + public void register(MavenProject project, Key key, CacheRecord record) { // default cache does not track plugin usage } - public void dispose() - { + public void dispose() { flush(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/ExtensionRealmCache.java b/maven-core/src/main/java/org/apache/maven/plugin/ExtensionRealmCache.java index 4d01aca4f5..44adc590db 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/ExtensionRealmCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/ExtensionRealmCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.project.ExtensionDescriptor; import org.apache.maven.project.MavenProject; @@ -34,21 +32,18 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; * @author Igor Fedorenko * @author Benjamin Bentmann */ -public interface ExtensionRealmCache -{ +public interface ExtensionRealmCache { /** * A cache key. */ - interface Key - { + interface Key { // marker interface for cache keys } /** * CacheRecord */ - class CacheRecord - { + class CacheRecord { private final ClassRealm realm; @@ -56,35 +51,31 @@ public interface ExtensionRealmCache private final List artifacts; - CacheRecord( ClassRealm realm, ExtensionDescriptor descriptor, List artifacts ) - { + CacheRecord(ClassRealm realm, ExtensionDescriptor descriptor, List artifacts) { this.realm = realm; this.descriptor = descriptor; this.artifacts = artifacts; } - public ClassRealm getRealm() - { + public ClassRealm getRealm() { return realm; } - public ExtensionDescriptor getDescriptor() - { + public ExtensionDescriptor getDescriptor() { return descriptor; } - public List getArtifacts() - { + public List getArtifacts() { return artifacts; } } - Key createKey( List extensionArtifacts ); + Key createKey(List extensionArtifacts); - CacheRecord get( Key key ); + CacheRecord get(Key key); - CacheRecord put( Key key, ClassRealm extensionRealm, ExtensionDescriptor extensionDescriptor, - List artifacts ); + CacheRecord put( + Key key, ClassRealm extensionRealm, ExtensionDescriptor extensionDescriptor, List artifacts); void flush(); @@ -96,6 +87,5 @@ public interface ExtensionRealmCache * @param project The project that employs the plugin realm, must not be {@code null}. * @param record The cache record being used for the project, must not be {@code null}. */ - void register( MavenProject project, Key key, CacheRecord record ); - + void register(MavenProject project, Key key, CacheRecord record); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginDescriptorException.java b/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginDescriptorException.java index 3a2e476965..c93c6a3dcd 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginDescriptorException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginDescriptorException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,30 +16,25 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; /** * InvalidPluginDescriptorException */ -public class InvalidPluginDescriptorException - extends Exception -{ +public class InvalidPluginDescriptorException extends Exception { - public InvalidPluginDescriptorException( String message, List errors ) - { - super( toMessage( message, errors ) ); + public InvalidPluginDescriptorException(String message, List errors) { + super(toMessage(message, errors)); } - private static String toMessage( String message, List errors ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( message ); - for ( String error : errors ) - { - buffer.append( ", " ).append( error ); + private static String toMessage(String message, List errors) { + StringBuilder buffer = new StringBuilder(256); + buffer.append(message); + for (String error : errors) { + buffer.append(", ").append(error); } return buffer.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginException.java b/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginException.java index b89fc8697d..20110fdd7d 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.artifact.InvalidDependencyVersionException; @@ -27,22 +26,16 @@ import org.apache.maven.project.artifact.InvalidDependencyVersionException; * * @author Brett Porter */ -public class InvalidPluginException - extends Exception -{ - public InvalidPluginException( String message, ProjectBuildingException e ) - { - super( message, e ); +public class InvalidPluginException extends Exception { + public InvalidPluginException(String message, ProjectBuildingException e) { + super(message, e); } - public InvalidPluginException( String message, InvalidDependencyVersionException e ) - { - super( message, e ); + public InvalidPluginException(String message, InvalidDependencyVersionException e) { + super(message, e); } - public InvalidPluginException( String message ) - { - super( message ); + public InvalidPluginException(String message) { + super(message); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/LegacySupport.java b/maven-core/src/main/java/org/apache/maven/plugin/LegacySupport.java index b246ed1877..97503e6343 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/LegacySupport.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/LegacySupport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.execution.MavenSession; import org.eclipse.aether.RepositorySystemSession; @@ -30,8 +29,7 @@ import org.eclipse.aether.RepositorySystemSession; * @since 3.0 * @author Benjamin Bentmann */ -public interface LegacySupport -{ +public interface LegacySupport { /** * Sets the currently active session. Some legacy components are basically stateful and their API is missing @@ -40,7 +38,7 @@ public interface LegacySupport * * @param session The currently active session, may be {@code null}. */ - void setSession( MavenSession session ); + void setSession(MavenSession session); /** * Gets the currently active session. @@ -55,5 +53,4 @@ public interface LegacySupport * @return The currently active repository session or {@code null} if none. */ RepositorySystemSession getRepositorySession(); - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java index d548f54510..88bed8e4fb 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.MojoDescriptor; @@ -38,8 +36,7 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface MavenPluginManager -{ +public interface MavenPluginManager { /** * Retrieves the descriptor for the specified plugin from its main artifact. @@ -50,9 +47,9 @@ public interface MavenPluginManager * @param session The repository session to use for resolving the plugin's main artifact, must not be {@code null}. * @return The plugin descriptor, never {@code null}. */ - PluginDescriptor getPluginDescriptor( Plugin plugin, List repositories, - RepositorySystemSession session ) - throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException; + PluginDescriptor getPluginDescriptor( + Plugin plugin, List repositories, RepositorySystemSession session) + throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException; /** * Retrieves the descriptor for the specified plugin goal from the plugin's main artifact. @@ -64,18 +61,17 @@ public interface MavenPluginManager * @param session The repository session to use for resolving the plugin's main artifact, must not be {@code null}. * @return The mojo descriptor, never {@code null}. */ - MojoDescriptor getMojoDescriptor( Plugin plugin, String goal, List repositories, - RepositorySystemSession session ) - throws MojoNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - InvalidPluginDescriptorException; + MojoDescriptor getMojoDescriptor( + Plugin plugin, String goal, List repositories, RepositorySystemSession session) + throws MojoNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + InvalidPluginDescriptorException; /** * Verifies that the specified plugin's prerequisites are met. * * @param pluginDescriptor The descriptor of the plugin to check, must not be {@code null}. */ - void checkPrerequisites( PluginDescriptor pluginDescriptor ) - throws PluginIncompatibleException; + void checkPrerequisites(PluginDescriptor pluginDescriptor) throws PluginIncompatibleException; /** * Sets up the class realm for the specified plugin. Both the class realm and the plugin artifacts that constitute @@ -89,18 +85,21 @@ public interface MavenPluginManager * @param imports The packages/types to import from the parent realm, may be {@code null}. * @param filter The filter used to exclude certain plugin dependencies, may be {@code null}. */ - void setupPluginRealm( PluginDescriptor pluginDescriptor, MavenSession session, ClassLoader parent, - List imports, DependencyFilter filter ) - throws PluginResolutionException, PluginContainerException; + void setupPluginRealm( + PluginDescriptor pluginDescriptor, + MavenSession session, + ClassLoader parent, + List imports, + DependencyFilter filter) + throws PluginResolutionException, PluginContainerException; /** * Sets up class realm for the specified build extensions plugin. * * @since 3.3.0 */ - ExtensionRealmCache.CacheRecord setupExtensionsRealm( MavenProject project, Plugin plugin, - RepositorySystemSession session ) - throws PluginManagerException; + ExtensionRealmCache.CacheRecord setupExtensionsRealm( + MavenProject project, Plugin plugin, RepositorySystemSession session) throws PluginManagerException; /** * Looks up the mojo for the specified mojo execution and populates its parameters from the configuration given by @@ -114,8 +113,8 @@ public interface MavenPluginManager * @param mojoExecution The mojo execution to retrieve the mojo for, must not be {@code null}. * @return The ready-to-execute mojo, never {@code null}. */ - T getConfiguredMojo( Class mojoInterface, MavenSession session, MojoExecution mojoExecution ) - throws PluginConfigurationException, PluginContainerException; + T getConfiguredMojo(Class mojoInterface, MavenSession session, MojoExecution mojoExecution) + throws PluginConfigurationException, PluginContainerException; /** * Releases the specified mojo back to the container. @@ -123,6 +122,5 @@ public interface MavenPluginManager * @param mojo The mojo to release, may be {@code null}. * @param mojoExecution The mojo execution the mojo was originally retrieved for, must not be {@code null}. */ - void releaseMojo( Object mojo, MojoExecution mojoExecution ); - + void releaseMojo(Object mojo, MojoExecution mojoExecution); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginPrerequisitesChecker.java b/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginPrerequisitesChecker.java index 715a16b2ab..0387fb6dfe 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginPrerequisitesChecker.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginPrerequisitesChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,21 +16,20 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.function.Consumer; - import org.apache.maven.plugin.descriptor.PluginDescriptor; /** * Service responsible for checking if plugin's prerequisites are met. */ @FunctionalInterface -public interface MavenPluginPrerequisitesChecker extends Consumer -{ +public interface MavenPluginPrerequisitesChecker extends Consumer { /** - * + * * @param pluginDescriptor * @throws IllegalStateException in case the checked prerequisites are not met */ - void accept( PluginDescriptor pluginDescriptor ); + void accept(PluginDescriptor pluginDescriptor); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/MojoExecution.java b/maven-core/src/main/java/org/apache/maven/plugin/MojoExecution.java index 095778b199..b4beb7e53c 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/MojoExecution.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/MojoExecution.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import org.apache.maven.api.xml.Dom; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.MojoDescriptor; @@ -30,8 +28,7 @@ import org.apache.maven.plugin.descriptor.MojoDescriptor; /** * MojoExecution */ -public class MojoExecution -{ +public class MojoExecution { private Plugin plugin; @@ -46,8 +43,7 @@ public class MojoExecution /** * Describes the source of an execution. */ - public enum Source - { + public enum Source { /** * An execution that originates from the direct invocation of a goal from the CLI. @@ -74,46 +70,40 @@ public class MojoExecution */ private Map> forkedExecutions = new LinkedHashMap<>(); - public MojoExecution( Plugin plugin, String goal, String executionId ) - { + public MojoExecution(Plugin plugin, String goal, String executionId) { this.plugin = plugin; this.goal = goal; this.executionId = executionId; } - public MojoExecution( MojoDescriptor mojoDescriptor ) - { + public MojoExecution(MojoDescriptor mojoDescriptor) { this.mojoDescriptor = mojoDescriptor; this.executionId = null; this.configuration = null; } - public MojoExecution( MojoDescriptor mojoDescriptor, String executionId, Source source ) - { + public MojoExecution(MojoDescriptor mojoDescriptor, String executionId, Source source) { this.mojoDescriptor = mojoDescriptor; this.executionId = executionId; this.configuration = null; this.source = source; } - public MojoExecution( MojoDescriptor mojoDescriptor, String executionId ) - { + public MojoExecution(MojoDescriptor mojoDescriptor, String executionId) { this.mojoDescriptor = mojoDescriptor; this.executionId = executionId; this.configuration = null; } - public MojoExecution( MojoDescriptor mojoDescriptor, org.codehaus.plexus.util.xml.Xpp3Dom configuration ) - { + public MojoExecution(MojoDescriptor mojoDescriptor, org.codehaus.plexus.util.xml.Xpp3Dom configuration) { this.mojoDescriptor = mojoDescriptor; this.configuration = configuration; this.executionId = null; } - public MojoExecution( MojoDescriptor mojoDescriptor, Dom configuration ) - { + public MojoExecution(MojoDescriptor mojoDescriptor, Dom configuration) { this.mojoDescriptor = mojoDescriptor; - this.configuration = new org.codehaus.plexus.util.xml.Xpp3Dom( configuration ); + this.configuration = new org.codehaus.plexus.util.xml.Xpp3Dom(configuration); this.executionId = null; } @@ -122,131 +112,106 @@ public class MojoExecution * * @return The source of this execution or {@code null} if unknown. */ - public Source getSource() - { + public Source getSource() { return source; } - public String getExecutionId() - { + public String getExecutionId() { return executionId; } - public Plugin getPlugin() - { - if ( mojoDescriptor != null ) - { + public Plugin getPlugin() { + if (mojoDescriptor != null) { return mojoDescriptor.getPluginDescriptor().getPlugin(); } return plugin; } - public MojoDescriptor getMojoDescriptor() - { + public MojoDescriptor getMojoDescriptor() { return mojoDescriptor; } - public org.codehaus.plexus.util.xml.Xpp3Dom getConfiguration() - { + public org.codehaus.plexus.util.xml.Xpp3Dom getConfiguration() { return configuration; } - public void setConfiguration( org.codehaus.plexus.util.xml.Xpp3Dom configuration ) - { + public void setConfiguration(org.codehaus.plexus.util.xml.Xpp3Dom configuration) { this.configuration = configuration; } - public void setConfiguration( Dom configuration ) - { - this.configuration = configuration != null ? new org.codehaus.plexus.util.xml.Xpp3Dom( configuration ) : null; + public void setConfiguration(Dom configuration) { + this.configuration = configuration != null ? new org.codehaus.plexus.util.xml.Xpp3Dom(configuration) : null; } - public String identify() - { - StringBuilder sb = new StringBuilder( 256 ); + public String identify() { + StringBuilder sb = new StringBuilder(256); - sb.append( executionId ); - sb.append( configuration.toString() ); + sb.append(executionId); + sb.append(configuration.toString()); return sb.toString(); } - public String getLifecyclePhase() - { + public String getLifecyclePhase() { return lifecyclePhase; } - public void setLifecyclePhase( String lifecyclePhase ) - { + public void setLifecyclePhase(String lifecyclePhase) { this.lifecyclePhase = lifecyclePhase; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 128 ); - if ( mojoDescriptor != null ) - { - buffer.append( mojoDescriptor.getId() ); + public String toString() { + StringBuilder buffer = new StringBuilder(128); + if (mojoDescriptor != null) { + buffer.append(mojoDescriptor.getId()); } - buffer.append( " {execution: " ).append( executionId ).append( '}' ); + buffer.append(" {execution: ").append(executionId).append('}'); return buffer.toString(); } - public String getGroupId() - { - if ( mojoDescriptor != null ) - { + public String getGroupId() { + if (mojoDescriptor != null) { return mojoDescriptor.getPluginDescriptor().getGroupId(); } return plugin.getGroupId(); } - public String getArtifactId() - { - if ( mojoDescriptor != null ) - { + public String getArtifactId() { + if (mojoDescriptor != null) { return mojoDescriptor.getPluginDescriptor().getArtifactId(); } return plugin.getArtifactId(); } - public String getVersion() - { - if ( mojoDescriptor != null ) - { + public String getVersion() { + if (mojoDescriptor != null) { return mojoDescriptor.getPluginDescriptor().getVersion(); } return plugin.getVersion(); } - public String getGoal() - { - if ( mojoDescriptor != null ) - { + public String getGoal() { + if (mojoDescriptor != null) { return mojoDescriptor.getGoal(); } return goal; } - public void setMojoDescriptor( MojoDescriptor mojoDescriptor ) - { + public void setMojoDescriptor(MojoDescriptor mojoDescriptor) { this.mojoDescriptor = mojoDescriptor; } - public Map> getForkedExecutions() - { + public Map> getForkedExecutions() { return forkedExecutions; } - public void setForkedExecutions( String projectKey, List forkedExecutions ) - { - this.forkedExecutions.put( projectKey, forkedExecutions ); + public void setForkedExecutions(String projectKey, List forkedExecutions) { + this.forkedExecutions.put(projectKey, forkedExecutions); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/MojoExecutionRunner.java b/maven-core/src/main/java/org/apache/maven/plugin/MojoExecutionRunner.java index eab55859be..f48a469aae 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/MojoExecutionRunner.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/MojoExecutionRunner.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,19 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.lifecycle.LifecycleExecutionException; /** * Provides context for mojo execution. Invocation of {@link #run(MojoExecution)} will result in actual execution */ -public interface MojoExecutionRunner -{ +public interface MojoExecutionRunner { /** * Runs mojo execution * * @param execution mojo execution * @throws LifecycleExecutionException */ - void run( MojoExecution execution ) throws LifecycleExecutionException; + void run(MojoExecution execution) throws LifecycleExecutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/MojosExecutionStrategy.java b/maven-core/src/main/java/org/apache/maven/plugin/MojosExecutionStrategy.java index e4babf68d7..025a6ee872 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/MojosExecutionStrategy.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/MojosExecutionStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,18 +16,17 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.lifecycle.LifecycleExecutionException; +package org.apache.maven.plugin; import java.util.List; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.LifecycleExecutionException; /** * Interface allows overriding default mojo execution strategy For example it is possible wrap some mojo execution to * decorate default functionality or skip some executions */ -public interface MojosExecutionStrategy -{ +public interface MojosExecutionStrategy { /** * Entry point to the execution strategy @@ -39,7 +36,6 @@ public interface MojosExecutionStrategy * @param mojoExecutionRunner mojo execution task which must be invoked by a strategy to actually run it * @throws LifecycleExecutionException */ - void execute( List mojos, MavenSession session, MojoExecutionRunner mojoExecutionRunner ) + void execute(List mojos, MavenSession session, MojoExecutionRunner mojoExecutionRunner) throws LifecycleExecutionException; - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginArtifactsCache.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginArtifactsCache.java index 11f5d701fc..35382471ee 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginArtifactsCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginArtifactsCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; @@ -36,58 +34,54 @@ import org.eclipse.aether.repository.RemoteRepository; * @author Igor Fedorenko * @author Benjamin Bentmann */ -public interface PluginArtifactsCache -{ +public interface PluginArtifactsCache { /** * A cache key. */ - interface Key - { + interface Key { // marker interface for cache keys } /** * CacheRecord */ - class CacheRecord - { + class CacheRecord { private final List artifacts; - public List getArtifacts() - { + public List getArtifacts() { return artifacts; } - public PluginResolutionException getException() - { + public PluginResolutionException getException() { return exception; } private final PluginResolutionException exception; - public CacheRecord( List artifacts ) - { + public CacheRecord(List artifacts) { this.artifacts = artifacts; this.exception = null; } - public CacheRecord( PluginResolutionException exception ) - { + public CacheRecord(PluginResolutionException exception) { this.artifacts = null; this.exception = exception; } } - Key createKey( Plugin plugin, DependencyFilter extensionFilter, List repositories, - RepositorySystemSession session ); + Key createKey( + Plugin plugin, + DependencyFilter extensionFilter, + List repositories, + RepositorySystemSession session); - CacheRecord get( Key key ) throws PluginResolutionException; + CacheRecord get(Key key) throws PluginResolutionException; - CacheRecord put( Key key, List pluginArtifacts ); + CacheRecord put(Key key, List pluginArtifacts); - CacheRecord put( Key key, PluginResolutionException e ); + CacheRecord put(Key key, PluginResolutionException e); void flush(); @@ -99,6 +93,5 @@ public interface PluginArtifactsCache * @param project The project that employs the plugin realm, must not be {@code null}. * @param record The cache record being used for the project, must not be {@code null}. */ - void register( MavenProject project, Key cacheKey, CacheRecord record ); - + void register(MavenProject project, Key cacheKey, CacheRecord record); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginConfigurationException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginConfigurationException.java index f4dcffcd30..802a6d3538 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginConfigurationException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginConfigurationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; @@ -27,47 +26,40 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti /** * @author Jason van Zyl */ -public class PluginConfigurationException - extends Exception -{ +public class PluginConfigurationException extends Exception { private PluginDescriptor pluginDescriptor; private String originalMessage; - public PluginConfigurationException( PluginDescriptor pluginDescriptor, String originalMessage ) - { - super( originalMessage ); + public PluginConfigurationException(PluginDescriptor pluginDescriptor, String originalMessage) { + super(originalMessage); this.pluginDescriptor = pluginDescriptor; this.originalMessage = originalMessage; } - public PluginConfigurationException( PluginDescriptor pluginDescriptor, String originalMessage, Throwable cause ) - { - super( originalMessage, cause ); + public PluginConfigurationException(PluginDescriptor pluginDescriptor, String originalMessage, Throwable cause) { + super(originalMessage, cause); this.pluginDescriptor = pluginDescriptor; this.originalMessage = originalMessage; } - public PluginConfigurationException( PluginDescriptor pluginDescriptor, String originalMessage, - ExpressionEvaluationException cause ) - { - super( originalMessage, cause ); + public PluginConfigurationException( + PluginDescriptor pluginDescriptor, String originalMessage, ExpressionEvaluationException cause) { + super(originalMessage, cause); this.pluginDescriptor = pluginDescriptor; this.originalMessage = originalMessage; } - public PluginConfigurationException( PluginDescriptor pluginDescriptor, String originalMessage, - ComponentConfigurationException cause ) - { - super( originalMessage, cause ); + public PluginConfigurationException( + PluginDescriptor pluginDescriptor, String originalMessage, ComponentConfigurationException cause) { + super(originalMessage, cause); this.pluginDescriptor = pluginDescriptor; this.originalMessage = originalMessage; } - public PluginConfigurationException( PluginDescriptor pluginDescriptor, String originalMessage, - ComponentLookupException cause ) - { - super( originalMessage, cause ); + public PluginConfigurationException( + PluginDescriptor pluginDescriptor, String originalMessage, ComponentLookupException cause) { + super(originalMessage, cause); this.pluginDescriptor = pluginDescriptor; this.originalMessage = originalMessage; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginContainerException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginContainerException.java index 91c49f20fc..2c49eb58b0 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginContainerException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginContainerException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.MojoDescriptor; @@ -36,53 +35,45 @@ import org.codehaus.plexus.configuration.PlexusConfigurationException; * @author jdcasey * */ -public class PluginContainerException - extends PluginManagerException -{ +public class PluginContainerException extends PluginManagerException { private ClassRealm pluginRealm; - public PluginContainerException( MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, - Throwable e ) - { - super( mojoDescriptor, message, e ); + public PluginContainerException( + MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, Throwable e) { + super(mojoDescriptor, message, e); this.pluginRealm = pluginRealm; } - public PluginContainerException( MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, - ComponentLookupException e ) - { - super( mojoDescriptor, message, e ); + public PluginContainerException( + MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, ComponentLookupException e) { + super(mojoDescriptor, message, e); this.pluginRealm = pluginRealm; } - public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, Throwable e ) - { - super( plugin, message, e ); + public PluginContainerException(Plugin plugin, ClassRealm pluginRealm, String message, Throwable e) { + super(plugin, message, e); this.pluginRealm = pluginRealm; } - public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, - PlexusConfigurationException e ) - { - super( plugin, message, e ); + public PluginContainerException( + Plugin plugin, ClassRealm pluginRealm, String message, PlexusConfigurationException e) { + super(plugin, message, e); this.pluginRealm = pluginRealm; } - public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, - ComponentRepositoryException e ) - { - super( plugin, message, e ); + public PluginContainerException( + Plugin plugin, ClassRealm pluginRealm, String message, ComponentRepositoryException e) { + super(plugin, message, e); this.pluginRealm = pluginRealm; } - public ClassRealm getPluginRealm() - { + public ClassRealm getPluginRealm() { return pluginRealm; } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorCache.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorCache.java index 646b506d22..ed52a0143e 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; - import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.eclipse.aether.RepositorySystemSession; @@ -36,33 +34,29 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginDescriptorCache -{ +public interface PluginDescriptorCache { /** * A cache key. */ - interface Key - { + interface Key { // marker interface for cache keys } @FunctionalInterface - interface PluginDescriptorSupplier - { + interface PluginDescriptorSupplier { PluginDescriptor load() throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException; } - Key createKey( Plugin plugin, List repositories, RepositorySystemSession session ); + Key createKey(Plugin plugin, List repositories, RepositorySystemSession session); - void put( Key key, PluginDescriptor pluginDescriptor ); + void put(Key key, PluginDescriptor pluginDescriptor); - PluginDescriptor get( Key key ); + PluginDescriptor get(Key key); - PluginDescriptor get( Key key, PluginDescriptorSupplier supplier ) + PluginDescriptor get(Key key, PluginDescriptorSupplier supplier) throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException; void flush(); - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorParsingException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorParsingException.java index 7d57b36346..8f724de7d2 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorParsingException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorParsingException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,41 +16,34 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.model.Plugin; /** * @author Jason van Zyl */ -public class PluginDescriptorParsingException - extends Exception -{ +public class PluginDescriptorParsingException extends Exception { - public PluginDescriptorParsingException( Plugin plugin, String descriptorLocation, Throwable e ) - { - super( createMessage( plugin, descriptorLocation, e ), e ); + public PluginDescriptorParsingException(Plugin plugin, String descriptorLocation, Throwable e) { + super(createMessage(plugin, descriptorLocation, e), e); } - private static String createMessage( Plugin plugin, String descriptorLocation, Throwable e ) - { + private static String createMessage(Plugin plugin, String descriptorLocation, Throwable e) { String message = "Failed to parse plugin descriptor"; - if ( plugin != null ) - { + if (plugin != null) { message += " for " + plugin.getId(); } - if ( descriptorLocation != null ) - { + if (descriptorLocation != null) { message += " (" + descriptorLocation + ")"; } - if ( e != null ) - { + if (e != null) { message += ": " + e.getMessage(); } return message; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginExecutionException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginExecutionException.java index a99fbbc196..66a3767d59 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginExecutionException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginExecutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.project.DuplicateArtifactAttachmentException; import org.apache.maven.project.MavenProject; @@ -26,68 +25,52 @@ import org.codehaus.plexus.util.StringUtils; /** * Exception in the plugin manager. */ -public class PluginExecutionException - extends PluginManagerException -{ +public class PluginExecutionException extends PluginManagerException { private final MojoExecution mojoExecution; - public PluginExecutionException( MojoExecution mojoExecution, MavenProject project, String message ) - { - super( mojoExecution.getMojoDescriptor(), project, message ); + public PluginExecutionException(MojoExecution mojoExecution, MavenProject project, String message) { + super(mojoExecution.getMojoDescriptor(), project, message); this.mojoExecution = mojoExecution; } - public PluginExecutionException( MojoExecution mojoExecution, MavenProject project, String message, - Throwable cause ) - { - super( mojoExecution.getMojoDescriptor(), project, message, cause ); + public PluginExecutionException( + MojoExecution mojoExecution, MavenProject project, String message, Throwable cause) { + super(mojoExecution.getMojoDescriptor(), project, message, cause); this.mojoExecution = mojoExecution; } - public PluginExecutionException( MojoExecution mojoExecution, MavenProject project, Exception cause ) - { - super( mojoExecution.getMojoDescriptor(), project, constructMessage( mojoExecution, cause ), cause ); + public PluginExecutionException(MojoExecution mojoExecution, MavenProject project, Exception cause) { + super(mojoExecution.getMojoDescriptor(), project, constructMessage(mojoExecution, cause), cause); this.mojoExecution = mojoExecution; } - public PluginExecutionException( MojoExecution mojoExecution, MavenProject project, - DuplicateArtifactAttachmentException cause ) - { - super( mojoExecution.getMojoDescriptor(), project, constructMessage( mojoExecution, cause ), cause ); + public PluginExecutionException( + MojoExecution mojoExecution, MavenProject project, DuplicateArtifactAttachmentException cause) { + super(mojoExecution.getMojoDescriptor(), project, constructMessage(mojoExecution, cause), cause); this.mojoExecution = mojoExecution; } - public MojoExecution getMojoExecution() - { + public MojoExecution getMojoExecution() { return mojoExecution; } - private static String constructMessage( MojoExecution mojoExecution, Throwable cause ) - { + private static String constructMessage(MojoExecution mojoExecution, Throwable cause) { String message; - if ( mojoExecution != null ) - { - message = - "Execution " + mojoExecution.getExecutionId() + " of goal " + mojoExecution.getMojoDescriptor().getId() - + " failed"; - } - else - { + if (mojoExecution != null) { + message = "Execution " + mojoExecution.getExecutionId() + " of goal " + + mojoExecution.getMojoDescriptor().getId() + " failed"; + } else { message = "Mojo execution failed"; } - if ( cause != null && StringUtils.isNotEmpty( cause.getMessage() ) ) - { + if (cause != null && StringUtils.isNotEmpty(cause.getMessage())) { message += ": " + cause.getMessage(); - } - else - { + } else { message += "."; } return message; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginIncompatibleException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginIncompatibleException.java index 808bd6dafd..d3c5edbf95 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginIncompatibleException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginIncompatibleException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,23 +16,20 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.model.Plugin; /** * Signals a plugin which is not compatible with the current Maven runtime. */ -public class PluginIncompatibleException - extends PluginManagerException -{ +public class PluginIncompatibleException extends PluginManagerException { - public PluginIncompatibleException( Plugin plugin, String message ) - { - this( plugin, message, null ); + public PluginIncompatibleException(Plugin plugin, String message) { + this(plugin, message, null); } - public PluginIncompatibleException( Plugin plugin, String message, Throwable cause ) - { - super( plugin, message, cause ); + public PluginIncompatibleException(Plugin plugin, String message, Throwable cause) { + super(plugin, message, cause); } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginLoaderException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginLoaderException.java index 161e1c4e7c..d2a01de662 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginLoaderException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginLoaderException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; @@ -34,91 +33,74 @@ import org.apache.maven.plugin.version.PluginVersionResolutionException; * @author jdcasey * */ -public class PluginLoaderException - extends Exception -{ +public class PluginLoaderException extends Exception { private String pluginKey; - public PluginLoaderException( Plugin plugin, String message, ArtifactResolutionException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, ArtifactResolutionException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, ArtifactNotFoundException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, ArtifactNotFoundException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, PluginNotFoundException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, PluginNotFoundException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, PluginVersionResolutionException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, PluginVersionResolutionException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, InvalidVersionSpecificationException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, InvalidVersionSpecificationException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, InvalidPluginException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, InvalidPluginException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, PluginManagerException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, PluginManagerException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message, PluginVersionNotFoundException cause ) - { - super( message, cause ); + public PluginLoaderException(Plugin plugin, String message, PluginVersionNotFoundException cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( Plugin plugin, String message ) - { - super( message ); + public PluginLoaderException(Plugin plugin, String message) { + super(message); pluginKey = plugin.getKey(); } - public PluginLoaderException( String message ) - { - super( message ); + public PluginLoaderException(String message) { + super(message); } - public PluginLoaderException( String message, Throwable cause ) - { - super( message, cause ); + public PluginLoaderException(String message, Throwable cause) { + super(message, cause); } - public PluginLoaderException( ReportPlugin plugin, String message, Throwable cause ) - { - super( message, cause ); + public PluginLoaderException(ReportPlugin plugin, String message, Throwable cause) { + super(message, cause); pluginKey = plugin.getKey(); } - public PluginLoaderException( ReportPlugin plugin, String message ) - { - super( message ); + public PluginLoaderException(ReportPlugin plugin, String message) { + super(message); pluginKey = plugin.getKey(); } - public String getPluginKey() - { + public String getPluginKey() { return pluginKey; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginManager.java index 48b8e5ef83..6b1cd17e20 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,7 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; +import java.util.Map; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; @@ -33,50 +33,46 @@ import org.apache.maven.project.artifact.InvalidDependencyVersionException; import org.apache.maven.settings.Settings; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.Map; - /** * @author Jason van Zyl */ @Deprecated -public interface PluginManager -{ +public interface PluginManager { String ROLE = PluginManager.class.getName(); - void executeMojo( MavenProject project, MojoExecution execution, MavenSession session ) - throws MojoExecutionException, ArtifactResolutionException, MojoFailureException, ArtifactNotFoundException, - InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException; + void executeMojo(MavenProject project, MojoExecution execution, MavenSession session) + throws MojoExecutionException, ArtifactResolutionException, MojoFailureException, ArtifactNotFoundException, + InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException; - PluginDescriptor getPluginDescriptorForPrefix( String prefix ); + PluginDescriptor getPluginDescriptorForPrefix(String prefix); - Plugin getPluginDefinitionForPrefix( String prefix, MavenSession session, MavenProject project ); + Plugin getPluginDefinitionForPrefix(String prefix, MavenSession session, MavenProject project); - PluginDescriptor verifyPlugin( Plugin plugin, MavenProject project, Settings settings, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, - InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, - PluginVersionNotFoundException; + PluginDescriptor verifyPlugin( + Plugin plugin, MavenProject project, Settings settings, ArtifactRepository localRepository) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, + PluginNotFoundException, PluginVersionNotFoundException; - Object getPluginComponent( Plugin plugin, String role, String roleHint ) - throws PluginManagerException, ComponentLookupException; + Object getPluginComponent(Plugin plugin, String role, String roleHint) + throws PluginManagerException, ComponentLookupException; - Map getPluginComponents( Plugin plugin, String role ) - throws ComponentLookupException, PluginManagerException; + Map getPluginComponents(Plugin plugin, String role) + throws ComponentLookupException, PluginManagerException; /** * @since 2.2.1 */ - PluginDescriptor loadPluginDescriptor( Plugin plugin, MavenProject project, MavenSession session ) - throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, - InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, - PluginVersionNotFoundException; + PluginDescriptor loadPluginDescriptor(Plugin plugin, MavenProject project, MavenSession session) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, + PluginNotFoundException, PluginVersionNotFoundException; /** * @since 2.2.1 */ - PluginDescriptor loadPluginFully( Plugin plugin, MavenProject project, MavenSession session ) - throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, - InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, - PluginVersionNotFoundException; - + PluginDescriptor loadPluginFully(Plugin plugin, MavenProject project, MavenSession session) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, + PluginNotFoundException, PluginVersionNotFoundException; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginManagerException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginManagerException.java index dc8f9a201e..a990172842 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginManagerException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginManagerException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.model.Plugin; @@ -34,9 +33,7 @@ import org.codehaus.plexus.configuration.PlexusConfigurationException; * * @author Brett Porter */ -public class PluginManagerException - extends Exception -{ +public class PluginManagerException extends Exception { private final String pluginGroupId; @@ -48,9 +45,8 @@ public class PluginManagerException private MavenProject project; - protected PluginManagerException( Plugin plugin, String message, MavenProject project, Throwable cause ) - { - super( message, cause ); + protected PluginManagerException(Plugin plugin, String message, MavenProject project, Throwable cause) { + super(message, cause); this.project = project; pluginGroupId = plugin.getGroupId(); @@ -58,27 +54,24 @@ public class PluginManagerException pluginVersion = plugin.getVersion(); } - public PluginManagerException( Plugin plugin, String message, Throwable cause ) - { - super( message, cause ); + public PluginManagerException(Plugin plugin, String message, Throwable cause) { + super(message, cause); pluginGroupId = plugin.getGroupId(); pluginArtifactId = plugin.getArtifactId(); pluginVersion = plugin.getVersion(); } - protected PluginManagerException( MojoDescriptor mojoDescriptor, String message, Throwable cause ) - { - super( message, cause ); + protected PluginManagerException(MojoDescriptor mojoDescriptor, String message, Throwable cause) { + super(message, cause); pluginGroupId = mojoDescriptor.getPluginDescriptor().getGroupId(); pluginArtifactId = mojoDescriptor.getPluginDescriptor().getArtifactId(); pluginVersion = mojoDescriptor.getPluginDescriptor().getVersion(); goal = mojoDescriptor.getGoal(); } - protected PluginManagerException( MojoDescriptor mojoDescriptor, MavenProject project, String message ) - { - super( message ); + protected PluginManagerException(MojoDescriptor mojoDescriptor, MavenProject project, String message) { + super(message); this.project = project; pluginGroupId = mojoDescriptor.getPluginDescriptor().getGroupId(); pluginArtifactId = mojoDescriptor.getPluginDescriptor().getArtifactId(); @@ -86,10 +79,9 @@ public class PluginManagerException goal = mojoDescriptor.getGoal(); } - protected PluginManagerException( MojoDescriptor mojoDescriptor, MavenProject project, String message, - Throwable cause ) - { - super( message, cause ); + protected PluginManagerException( + MojoDescriptor mojoDescriptor, MavenProject project, String message, Throwable cause) { + super(message, cause); this.project = project; pluginGroupId = mojoDescriptor.getPluginDescriptor().getGroupId(); pluginArtifactId = mojoDescriptor.getPluginDescriptor().getArtifactId(); @@ -97,37 +89,33 @@ public class PluginManagerException goal = mojoDescriptor.getGoal(); } - public PluginManagerException( Plugin plugin, InvalidVersionSpecificationException cause ) - { - super( cause ); + public PluginManagerException(Plugin plugin, InvalidVersionSpecificationException cause) { + super(cause); pluginGroupId = plugin.getGroupId(); pluginArtifactId = plugin.getArtifactId(); pluginVersion = plugin.getVersion(); } - public PluginManagerException( Plugin plugin, String message, PlexusConfigurationException cause ) - { - super( message, cause ); + public PluginManagerException(Plugin plugin, String message, PlexusConfigurationException cause) { + super(message, cause); pluginGroupId = plugin.getGroupId(); pluginArtifactId = plugin.getArtifactId(); pluginVersion = plugin.getVersion(); } - public PluginManagerException( Plugin plugin, String message, ComponentRepositoryException cause ) - { - super( message, cause ); + public PluginManagerException(Plugin plugin, String message, ComponentRepositoryException cause) { + super(message, cause); pluginGroupId = plugin.getGroupId(); pluginArtifactId = plugin.getArtifactId(); pluginVersion = plugin.getVersion(); } - public PluginManagerException( MojoDescriptor mojoDescriptor, MavenProject project, String message, - NoSuchRealmException cause ) - { - super( message, cause ); + public PluginManagerException( + MojoDescriptor mojoDescriptor, MavenProject project, String message, NoSuchRealmException cause) { + super(message, cause); this.project = project; pluginGroupId = mojoDescriptor.getPluginDescriptor().getGroupId(); @@ -136,10 +124,9 @@ public class PluginManagerException goal = mojoDescriptor.getGoal(); } - public PluginManagerException( MojoDescriptor mojoDescriptor, String message, MavenProject project, - PlexusContainerException cause ) - { - super( message, cause ); + public PluginManagerException( + MojoDescriptor mojoDescriptor, String message, MavenProject project, PlexusContainerException cause) { + super(message, cause); this.project = project; @@ -151,18 +138,16 @@ public class PluginManagerException goal = mojoDescriptor.getGoal(); } - public PluginManagerException( Plugin plugin, String message, PlexusContainerException cause ) - { - super( message, cause ); + public PluginManagerException(Plugin plugin, String message, PlexusContainerException cause) { + super(message, cause); pluginGroupId = plugin.getGroupId(); pluginArtifactId = plugin.getArtifactId(); pluginVersion = plugin.getVersion(); } - public PluginManagerException( Plugin plugin, String message, MavenProject project ) - { - super( message ); + public PluginManagerException(Plugin plugin, String message, MavenProject project) { + super(message); pluginGroupId = plugin.getGroupId(); pluginArtifactId = plugin.getArtifactId(); @@ -170,28 +155,23 @@ public class PluginManagerException this.project = project; } - public String getPluginGroupId() - { + public String getPluginGroupId() { return pluginGroupId; } - public String getPluginArtifactId() - { + public String getPluginArtifactId() { return pluginArtifactId; } - public String getPluginVersion() - { + public String getPluginVersion() { return pluginVersion; } - public String getGoal() - { + public String getGoal() { return goal; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginNotFoundException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginNotFoundException.java index ef54e2d723..14f1b0d2b7 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginNotFoundException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; @@ -31,28 +29,38 @@ import org.apache.maven.model.Plugin; * * @author Brett Porter */ -public class PluginNotFoundException - extends AbstractArtifactResolutionException -{ +public class PluginNotFoundException extends AbstractArtifactResolutionException { private Plugin plugin; - public PluginNotFoundException( Plugin plugin, ArtifactNotFoundException e ) - { - super( "Plugin could not be found - check that the goal name is correct: " + e.getMessage(), e.getGroupId(), - e.getArtifactId(), e.getVersion(), "maven-plugin", null, e.getRemoteRepositories(), null, e.getCause() ); + public PluginNotFoundException(Plugin plugin, ArtifactNotFoundException e) { + super( + "Plugin could not be found - check that the goal name is correct: " + e.getMessage(), + e.getGroupId(), + e.getArtifactId(), + e.getVersion(), + "maven-plugin", + null, + e.getRemoteRepositories(), + null, + e.getCause()); this.plugin = plugin; } - public PluginNotFoundException( Plugin plugin, List remoteRepositories ) - { - super( "Plugin could not be found, please check its coordinates for typos and ensure the required" - + " plugin repositories are defined in the POM", plugin.getGroupId(), plugin.getArtifactId(), - plugin.getVersion(), "maven-plugin", null, remoteRepositories, null ); + public PluginNotFoundException(Plugin plugin, List remoteRepositories) { + super( + "Plugin could not be found, please check its coordinates for typos and ensure the required" + + " plugin repositories are defined in the POM", + plugin.getGroupId(), + plugin.getArtifactId(), + plugin.getVersion(), + "maven-plugin", + null, + remoteRepositories, + null); this.plugin = plugin; } - public Plugin getPlugin() - { + public Plugin getPlugin() { return plugin; } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java index d1fa98d0ed..f4bfc88fb1 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; - import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; import org.codehaus.plexus.util.StringUtils; @@ -32,9 +30,7 @@ import org.codehaus.plexus.util.StringUtils; /** * PluginParameterException */ -public class PluginParameterException - extends PluginConfigurationException -{ +public class PluginParameterException extends PluginConfigurationException { private static final String LS = System.lineSeparator(); @@ -42,157 +38,143 @@ public class PluginParameterException private final MojoDescriptor mojo; - public PluginParameterException( MojoDescriptor mojo, List parameters ) - { - super( mojo.getPluginDescriptor(), "The parameters " + format( parameters ) + " for goal " - + mojo.getRoleHint() + " are missing or invalid" ); + public PluginParameterException(MojoDescriptor mojo, List parameters) { + super( + mojo.getPluginDescriptor(), + "The parameters " + format(parameters) + " for goal " + mojo.getRoleHint() + " are missing or invalid"); this.mojo = mojo; this.parameters = parameters; } - private static String format( List parameters ) - { - StringBuilder buffer = new StringBuilder( 128 ); - if ( parameters != null ) - { - for ( Parameter parameter : parameters ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + private static String format(List parameters) { + StringBuilder buffer = new StringBuilder(128); + if (parameters != null) { + for (Parameter parameter : parameters) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( '\'' ).append( parameter.getName() ).append( '\'' ); + buffer.append('\'').append(parameter.getName()).append('\''); } } return buffer.toString(); } - public MojoDescriptor getMojoDescriptor() - { + public MojoDescriptor getMojoDescriptor() { return mojo; } - public List getParameters() - { + public List getParameters() { return parameters; } - private static void decomposeParameterIntoUserInstructions( MojoDescriptor mojo, Parameter param, - StringBuilder messageBuffer ) - { + private static void decomposeParameterIntoUserInstructions( + MojoDescriptor mojo, Parameter param, StringBuilder messageBuffer) { String expression = param.getExpression(); - if ( param.isEditable() ) - { - boolean isArray = param.getType().endsWith( "[]" ); + if (param.isEditable()) { + boolean isArray = param.getType().endsWith("[]"); boolean isCollection = false; boolean isMap = false; boolean isProperties = false; - if ( !isArray ) - { - try - { - //assuming Type is available in current ClassLoader - isCollection = Collection.class.isAssignableFrom( Class.forName( param.getType() ) ); - isMap = Map.class.isAssignableFrom( Class.forName( param.getType() ) ); - isProperties = Properties.class.isAssignableFrom( Class.forName( param.getType() ) ); - } - catch ( ClassNotFoundException e ) - { + if (!isArray) { + try { + // assuming Type is available in current ClassLoader + isCollection = Collection.class.isAssignableFrom(Class.forName(param.getType())); + isMap = Map.class.isAssignableFrom(Class.forName(param.getType())); + isProperties = Properties.class.isAssignableFrom(Class.forName(param.getType())); + } catch (ClassNotFoundException e) { // assume it is not assignable from Collection or Map } } - messageBuffer.append( "Inside the definition for plugin '" ); - messageBuffer.append( mojo.getPluginDescriptor().getArtifactId() ); - messageBuffer.append( "', specify the following:" ).append( LS ).append( LS ); - messageBuffer.append( "" ).append( LS ).append( " ..." ).append( LS ); - messageBuffer.append( " <" ).append( param.getName() ).append( '>' ); - if ( isArray || isCollection ) - { - messageBuffer.append( LS ); - messageBuffer.append( " " ); + messageBuffer.append("Inside the definition for plugin '"); + messageBuffer.append(mojo.getPluginDescriptor().getArtifactId()); + messageBuffer.append("', specify the following:").append(LS).append(LS); + messageBuffer.append("").append(LS).append(" ...").append(LS); + messageBuffer.append(" <").append(param.getName()).append('>'); + if (isArray || isCollection) { + messageBuffer.append(LS); + messageBuffer.append(" "); + } else if (isProperties) { + messageBuffer.append(LS); + messageBuffer.append(" ").append(LS); + messageBuffer.append(" KEY").append(LS); + messageBuffer.append(" "); + } else if (isMap) { + messageBuffer.append(LS); + messageBuffer.append(" "); } - else if ( isProperties ) - { - messageBuffer.append( LS ); - messageBuffer.append( " " ).append( LS ); - messageBuffer.append( " KEY" ).append( LS ); - messageBuffer.append( " " ); + messageBuffer.append("VALUE"); + if (isArray || isCollection) { + messageBuffer.append("").append(LS); + messageBuffer.append(" "); + } else if (isProperties) { + messageBuffer.append("").append(LS); + messageBuffer.append(" ").append(LS); + messageBuffer.append(" "); + } else if (isMap) { + messageBuffer.append("").append(LS); + messageBuffer.append(" "); } - else if ( isMap ) - { - messageBuffer.append( LS ); - messageBuffer.append( " " ); - } - messageBuffer.append( "VALUE" ); - if ( isArray || isCollection ) - { - messageBuffer.append( "" ).append( LS ); - messageBuffer.append( " " ); - } - else if ( isProperties ) - { - messageBuffer.append( "" ).append( LS ); - messageBuffer.append( " " ).append( LS ); - messageBuffer.append( " " ); - } - else if ( isMap ) - { - messageBuffer.append( "" ).append( LS ); - messageBuffer.append( " " ); - } - messageBuffer.append( "" ).append( LS ); - messageBuffer.append( "" ); + messageBuffer.append("").append(LS); + messageBuffer.append(""); String alias = param.getAlias(); - if ( StringUtils.isNotEmpty( alias ) && !alias.equals( param.getName() ) ) - { - messageBuffer.append( LS ).append( LS ).append( "-OR-" ).append( LS ).append( LS ); - messageBuffer.append( "" ).append( LS ).append( " ..." ).append( LS ); - messageBuffer.append( " <" ).append( alias ).append( - ">VALUE" ).append( LS ).append( "" ).append( LS ); + if (StringUtils.isNotEmpty(alias) && !alias.equals(param.getName())) { + messageBuffer.append(LS).append(LS).append("-OR-").append(LS).append(LS); + messageBuffer + .append("") + .append(LS) + .append(" ...") + .append(LS); + messageBuffer + .append(" <") + .append(alias) + .append(">VALUE") + .append(LS) + .append("") + .append(LS); } } - if ( StringUtils.isEmpty( expression ) ) - { - messageBuffer.append( '.' ); - } - else - { - if ( param.isEditable() ) - { - messageBuffer.append( LS ).append( LS ).append( "-OR-" ).append( LS ).append( LS ); + if (StringUtils.isEmpty(expression)) { + messageBuffer.append('.'); + } else { + if (param.isEditable()) { + messageBuffer.append(LS).append(LS).append("-OR-").append(LS).append(LS); } - //addParameterUsageInfo( expression, messageBuffer ); + // addParameterUsageInfo( expression, messageBuffer ); } } - public String buildDiagnosticMessage() - { - StringBuilder messageBuffer = new StringBuilder( 256 ); + public String buildDiagnosticMessage() { + StringBuilder messageBuffer = new StringBuilder(256); List params = getParameters(); MojoDescriptor mojo = getMojoDescriptor(); - messageBuffer.append( "One or more required plugin parameters are invalid/missing for '" ) - .append( mojo.getPluginDescriptor().getGoalPrefix() ).append( ':' ).append( mojo.getGoal() ) - .append( "'" ).append( LS ); + messageBuffer + .append("One or more required plugin parameters are invalid/missing for '") + .append(mojo.getPluginDescriptor().getGoalPrefix()) + .append(':') + .append(mojo.getGoal()) + .append("'") + .append(LS); int idx = 0; - for ( Iterator it = params.iterator(); it.hasNext(); idx++ ) - { + for (Iterator it = params.iterator(); it.hasNext(); idx++) { Parameter param = it.next(); - messageBuffer.append( LS ).append( "[" ).append( idx ).append( "] " ); + messageBuffer.append(LS).append("[").append(idx).append("] "); - decomposeParameterIntoUserInstructions( mojo, param, messageBuffer ); + decomposeParameterIntoUserInstructions(mojo, param, messageBuffer); - messageBuffer.append( LS ); + messageBuffer.append(LS); } return messageBuffer.toString(); diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluator.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluator.java index 160e2dcae3..4cc7fba86d 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.io.File; import java.util.Properties; - import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; @@ -71,9 +69,7 @@ import org.codehaus.plexus.util.introspection.ReflectionValueExtractor; * @see MavenSession * @see MojoExecution */ -public class PluginParameterExpressionEvaluator - implements TypeAwareExpressionEvaluator -{ +public class PluginParameterExpressionEvaluator implements TypeAwareExpressionEvaluator { private MavenSession session; private MojoExecution mojoExecution; @@ -84,13 +80,11 @@ public class PluginParameterExpressionEvaluator private Properties properties; - public PluginParameterExpressionEvaluator( MavenSession session ) - { - this( session, null ); + public PluginParameterExpressionEvaluator(MavenSession session) { + this(session, null); } - public PluginParameterExpressionEvaluator( MavenSession session, MojoExecution mojoExecution ) - { + public PluginParameterExpressionEvaluator(MavenSession session, MojoExecution mojoExecution) { this.session = session; this.mojoExecution = mojoExecution; this.properties = new Properties(); @@ -100,269 +94,186 @@ public class PluginParameterExpressionEvaluator // Maven4: We may want to evaluate how this is used but we add these separate as the // getExecutionProperties is deprecated in MavenSession. // - this.properties.putAll( session.getUserProperties() ); - this.properties.putAll( session.getSystemProperties() ); + this.properties.putAll(session.getUserProperties()); + this.properties.putAll(session.getSystemProperties()); String basedir = null; - if ( project != null ) - { + if (project != null) { File projectFile = project.getBasedir(); // this should always be the case for non-super POM instances... - if ( projectFile != null ) - { + if (projectFile != null) { basedir = projectFile.getAbsolutePath(); } } - if ( basedir == null ) - { + if (basedir == null) { basedir = session.getExecutionRootDirectory(); } - if ( basedir == null ) - { - basedir = System.getProperty( "user.dir" ); + if (basedir == null) { + basedir = System.getProperty("user.dir"); } this.basedir = basedir; } @Override - public Object evaluate( String expr ) - throws ExpressionEvaluationException - { - return evaluate( expr, null ); + public Object evaluate(String expr) throws ExpressionEvaluationException { + return evaluate(expr, null); } @Override - @SuppressWarnings( "checkstyle:methodlength" ) - public Object evaluate( String expr, Class type ) - throws ExpressionEvaluationException - { + @SuppressWarnings("checkstyle:methodlength") + public Object evaluate(String expr, Class type) throws ExpressionEvaluationException { Object value = null; - if ( expr == null ) - { + 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 ); + 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 - { - Object subResult = evaluate( expr.substring( index, lastIndex + 1 ) ); + if ((index > 0) && (expr.charAt(index - 1) == '$')) { + retVal += expr.substring(index + 1, lastIndex + 1); + } else { + Object subResult = evaluate(expr.substring(index, lastIndex + 1)); - if ( subResult != null ) - { + if (subResult != null) { retVal += subResult; - } - else - { - retVal += "$" + expr.substring( index + 1, lastIndex + 1 ); + } else { + retVal += "$" + expr.substring(index + 1, lastIndex + 1); } } - retVal += evaluate( expr.substring( lastIndex + 1 ) ); + retVal += evaluate(expr.substring(lastIndex + 1)); return retVal; } } // Was not an expression - if ( expression.contains( "$$" ) ) - { - return expression.replaceAll( "\\$\\$", "\\$" ); - } - else - { + if (expression.contains("$$")) { + return expression.replaceAll("\\$\\$", "\\$"); + } else { return expression; } } MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); - if ( "localRepository".equals( expression ) ) - { + if ("localRepository".equals(expression)) { value = session.getLocalRepository(); - } - else if ( "session".equals( expression ) ) - { + } else if ("session".equals(expression)) { value = session; - } - else if ( expression.startsWith( "session" ) ) - { - try - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("session")) { + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, session ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, session); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), session); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( "reactorProjects".equals( expression ) ) - { + } else if ("reactorProjects".equals(expression)) { value = session.getProjects(); - } - else if ( "project".equals( expression ) ) - { + } else if ("project".equals(expression)) { value = project; - } - else if ( "executedProject".equals( expression ) ) - { + } else if ("executedProject".equals(expression)) { value = project.getExecutionProject(); - } - else if ( expression.startsWith( "project" ) || expression.startsWith( "pom" ) ) - { - try - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("project") || expression.startsWith("pom")) { + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 0, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, project ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(0, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, project); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), project); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), project ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( expression.equals( "repositorySystemSession" ) ) - { + } else if (expression.equals("repositorySystemSession")) { value = session.getRepositorySession(); - } - else if ( expression.equals( "mojo" ) || expression.equals( "mojoExecution" ) ) - { + } else if (expression.equals("mojo") || expression.equals("mojoExecution")) { value = mojoExecution; - } - else if ( expression.startsWith( "mojo" ) ) - { - try - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("mojo")) { + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, mojoExecution ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, mojoExecution); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), mojoExecution); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), mojoExecution ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( expression.equals( "plugin" ) ) - { + } else if (expression.equals("plugin")) { value = mojoDescriptor.getPluginDescriptor(); - } - else if ( expression.startsWith( "plugin" ) ) - { - try - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("plugin")) { + try { + int pathSeparator = expression.indexOf('/'); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, pluginDescriptor ); - value = value + expression.substring( pathSeparator ); - } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), pluginDescriptor ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, pluginDescriptor); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), pluginDescriptor); } + } catch (Exception e) { + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - catch ( Exception e ) - { - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); - } - } - else if ( "settings".equals( expression ) ) - { + } else if ("settings".equals(expression)) { value = session.getSettings(); - } - else if ( expression.startsWith( "settings" ) ) - { - try - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("settings")) { + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, session.getSettings() ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, session.getSettings()); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), session.getSettings()); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session.getSettings() ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( "basedir".equals( expression ) ) - { + } else if ("basedir".equals(expression)) { value = basedir; - } - else if ( expression.startsWith( "basedir" ) ) - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("basedir")) { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - value = basedir + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + value = basedir + expression.substring(pathSeparator); } } @@ -374,49 +285,39 @@ public class PluginParameterExpressionEvaluator * could still be converted by the configurator so we leave those alone). If so, back off to evaluating the * expression from properties only. */ - if ( value != null && type != null && !( value instanceof String ) && !isTypeCompatible( type, value ) ) - { + if (value != null && type != null && !(value instanceof String) && !isTypeCompatible(type, value)) { value = null; } - if ( value == null ) - { + if (value == null) { // The CLI should win for defining properties - if ( properties != null ) - { + if (properties != null) { // We will attempt to get nab a property as a way to specify a parameter // to a plugin. My particular case here is allowing the surefire plugin // to run a single test so I want to specify that class on the cli as // a parameter. - value = properties.getProperty( expression ); + value = properties.getProperty(expression); } - if ( ( value == null ) && ( ( project != null ) && ( project.getProperties() != null ) ) ) - { - value = project.getProperties().getProperty( expression ); + if ((value == null) && ((project != null) && (project.getProperties() != null))) { + value = project.getProperties().getProperty(expression); } - } - if ( value instanceof String ) - { + if (value instanceof String) { // TODO without #, this could just be an evaluate call... String val = (String) value; - int exprStartDelimiter = val.indexOf( "${" ); + int exprStartDelimiter = val.indexOf("${"); - if ( exprStartDelimiter >= 0 ) - { - if ( exprStartDelimiter > 0 ) - { - value = val.substring( 0, exprStartDelimiter ) + evaluate( val.substring( exprStartDelimiter ) ); - } - else - { - value = evaluate( val.substring( exprStartDelimiter ) ); + if (exprStartDelimiter >= 0) { + if (exprStartDelimiter > 0) { + value = val.substring(0, exprStartDelimiter) + evaluate(val.substring(exprStartDelimiter)); + } else { + value = evaluate(val.substring(exprStartDelimiter)); } } } @@ -424,49 +325,37 @@ public class PluginParameterExpressionEvaluator return value; } - private static boolean isTypeCompatible( Class type, Object value ) - { - if ( type.isInstance( value ) ) - { + private static boolean isTypeCompatible(Class type, Object value) { + if (type.isInstance(value)) { return true; } // likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid - return ( ( type.isPrimitive() || type.getName().startsWith( "java.lang." ) ) - && value.getClass().getName().startsWith( "java.lang." ) ); + return ((type.isPrimitive() || type.getName().startsWith("java.lang.")) + && value.getClass().getName().startsWith("java.lang.")); } - private String stripTokens( String expr ) - { - if ( expr.startsWith( "${" ) && ( expr.indexOf( '}' ) == expr.length() - 1 ) ) - { - expr = expr.substring( 2, expr.length() - 1 ); + private String stripTokens(String expr) { + if (expr.startsWith("${") && (expr.indexOf('}') == expr.length() - 1)) { + expr = expr.substring(2, expr.length() - 1); } return expr; } @Override - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { // TODO Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a // similar component for re-usage - if ( file != null ) - { - if ( file.isAbsolute() ) - { + if (file != null) { + if (file.isAbsolute()) { // path was already absolute, just normalize file separator and we're done - } - else if ( file.getPath().startsWith( File.separator ) ) - { + } else if (file.getPath().startsWith(File.separator)) { // drive-relative Windows path, don't align with project directory but with drive root file = file.getAbsoluteFile(); - } - else - { + } else { // an ordinary relative path, align with project directory - file = new File( new File( basedir, file.getPath() ).toURI().normalize() ).getAbsoluteFile(); + file = new File(new File(basedir, file.getPath()).toURI().normalize()).getAbsoluteFile(); } } return file; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorV4.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorV4.java index bab7cd4ae6..9e48efbee4 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorV4.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorV4.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; - import org.apache.maven.api.Project; import org.apache.maven.api.Session; import org.apache.maven.internal.impl.DefaultMojoExecution; @@ -74,9 +72,7 @@ import org.codehaus.plexus.util.introspection.ReflectionValueExtractor; * @see Session * @see MojoExecution */ -public class PluginParameterExpressionEvaluatorV4 - implements TypeAwareExpressionEvaluator -{ +public class PluginParameterExpressionEvaluatorV4 implements TypeAwareExpressionEvaluator { private Session session; private MojoExecution mojoExecution; @@ -87,13 +83,11 @@ public class PluginParameterExpressionEvaluatorV4 private Properties properties; - public PluginParameterExpressionEvaluatorV4( Session session, Project project ) - { - this( session, project, null ); + public PluginParameterExpressionEvaluatorV4(Session session, Project project) { + this(session, project, null); } - public PluginParameterExpressionEvaluatorV4( Session session, Project project, MojoExecution mojoExecution ) - { + public PluginParameterExpressionEvaluatorV4(Session session, Project project, MojoExecution mojoExecution) { this.session = session; this.mojoExecution = mojoExecution; this.properties = new Properties(); @@ -103,274 +97,195 @@ public class PluginParameterExpressionEvaluatorV4 // Maven4: We may want to evaluate how this is used but we add these separate as the // getExecutionProperties is deprecated in MavenSession. // - this.properties.putAll( session.getUserProperties() ); - this.properties.putAll( session.getSystemProperties() ); + this.properties.putAll(session.getUserProperties()); + this.properties.putAll(session.getSystemProperties()); Path basedir = null; - if ( project != null ) - { + if (project != null) { Optional projectFile = project.getBasedir(); // this should always be the case for non-super POM instances... - if ( projectFile.isPresent() ) - { + if (projectFile.isPresent()) { basedir = projectFile.get().toAbsolutePath(); } } - if ( basedir == null ) - { + if (basedir == null) { basedir = session.getExecutionRootDirectory(); } - if ( basedir == null ) - { - basedir = Paths.get( System.getProperty( "user.dir" ) ); + if (basedir == null) { + basedir = Paths.get(System.getProperty("user.dir")); } this.basedir = basedir; } @Override - public Object evaluate( String expr ) - throws ExpressionEvaluationException - { - return evaluate( expr, null ); + public Object evaluate(String expr) throws ExpressionEvaluationException { + return evaluate(expr, null); } @Override - @SuppressWarnings( "checkstyle:methodlength" ) - public Object evaluate( String expr, Class type ) - throws ExpressionEvaluationException - { + @SuppressWarnings("checkstyle:methodlength") + public Object evaluate(String expr, Class type) throws ExpressionEvaluationException { Object value = null; - if ( expr == null ) - { + 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 ); + 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 - { - Object subResult = evaluate( expr.substring( index, lastIndex + 1 ) ); + if ((index > 0) && (expr.charAt(index - 1) == '$')) { + retVal += expr.substring(index + 1, lastIndex + 1); + } else { + Object subResult = evaluate(expr.substring(index, lastIndex + 1)); - if ( subResult != null ) - { + if (subResult != null) { retVal += subResult; - } - else - { - retVal += "$" + expr.substring( index + 1, lastIndex + 1 ); + } else { + retVal += "$" + expr.substring(index + 1, lastIndex + 1); } } - retVal += evaluate( expr.substring( lastIndex + 1 ) ); + retVal += evaluate(expr.substring(lastIndex + 1)); return retVal; } } // Was not an expression - if ( expression.contains( "$$" ) ) - { - return expression.replaceAll( "\\$\\$", "\\$" ); - } - else - { + if (expression.contains("$$")) { + return expression.replaceAll("\\$\\$", "\\$"); + } else { return expression; } } - if ( "localRepository".equals( expression ) ) - { + if ("localRepository".equals(expression)) { // TODO: v4 value = session.getLocalRepository(); - } - else if ( "session".equals( expression ) ) - { + } else if ("session".equals(expression)) { value = session; - } - else if ( expression.startsWith( "session" ) ) - { + } else if (expression.startsWith("session")) { // TODO: v4 - try - { - int pathSeparator = expression.indexOf( '/' ); + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, session ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, session); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), session); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( "reactorProjects".equals( expression ) ) - { + } else if ("reactorProjects".equals(expression)) { value = session.getProjects(); - } - else if ( "project".equals( expression ) ) - { + } else if ("project".equals(expression)) { value = project; - } - else if ( "executedProject".equals( expression ) ) - { - value = ( (DefaultSession) session ).getProject( - ( (DefaultSession) session ).getMavenSession().getCurrentProject().getExecutionProject() ); - } - else if ( expression.startsWith( "project" ) || expression.startsWith( "pom" ) ) - { + } else if ("executedProject".equals(expression)) { + value = ((DefaultSession) session) + .getProject(((DefaultSession) session) + .getMavenSession() + .getCurrentProject() + .getExecutionProject()); + } else if (expression.startsWith("project") || expression.startsWith("pom")) { // TODO: v4 - try - { - int pathSeparator = expression.indexOf( '/' ); + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 0, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, project ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(0, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, project); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), project); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), project ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( expression.equals( "repositorySystemSession" ) ) - { + } else if (expression.equals("repositorySystemSession")) { // TODO: v4 - } - else if ( expression.equals( "mojo" ) || expression.equals( "mojoExecution" ) ) - { - value = new DefaultMojoExecution( mojoExecution ); - } - else if ( expression.startsWith( "mojo" ) ) - { + } else if (expression.equals("mojo") || expression.equals("mojoExecution")) { + value = new DefaultMojoExecution(mojoExecution); + } else if (expression.startsWith("mojo")) { // TODO: v4 - try - { - int pathSeparator = expression.indexOf( '/' ); + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, mojoExecution ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, mojoExecution); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), mojoExecution); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), mojoExecution ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( expression.equals( "plugin" ) ) - { + } else if (expression.equals("plugin")) { // TODO: v4 value = mojoExecution.getMojoDescriptor().getPluginDescriptor(); - } - else if ( expression.startsWith( "plugin" ) ) - { + } else if (expression.startsWith("plugin")) { // TODO: v4 - try - { - int pathSeparator = expression.indexOf( '/' ); + try { + int pathSeparator = expression.indexOf('/'); - PluginDescriptor pluginDescriptor = mojoExecution.getMojoDescriptor().getPluginDescriptor(); + PluginDescriptor pluginDescriptor = + mojoExecution.getMojoDescriptor().getPluginDescriptor(); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, pluginDescriptor ); - value = value + expression.substring( pathSeparator ); - } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), pluginDescriptor ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, pluginDescriptor); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), pluginDescriptor); } + } catch (Exception e) { + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - catch ( Exception e ) - { - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); - } - } - else if ( "settings".equals( expression ) ) - { + } else if ("settings".equals(expression)) { value = session.getSettings(); - } - else if ( expression.startsWith( "settings" ) ) - { - try - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("settings")) { + try { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - String pathExpression = expression.substring( 1, pathSeparator ); - value = ReflectionValueExtractor.evaluate( pathExpression, session.getSettings() ); - value = value + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + String pathExpression = expression.substring(1, pathSeparator); + value = ReflectionValueExtractor.evaluate(pathExpression, session.getSettings()); + value = value + expression.substring(pathSeparator); + } else { + value = ReflectionValueExtractor.evaluate(expression.substring(1), session.getSettings()); } - else - { - value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session.getSettings() ); - } - } - catch ( Exception e ) - { + } catch (Exception e) { // TODO don't catch exception - throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression, - e ); + throw new ExpressionEvaluationException( + "Error evaluating plugin parameter expression: " + expression, e); } - } - else if ( "basedir".equals( expression ) ) - { + } else if ("basedir".equals(expression)) { value = basedir.toString(); - } - else if ( expression.startsWith( "basedir" ) ) - { - int pathSeparator = expression.indexOf( '/' ); + } else if (expression.startsWith("basedir")) { + int pathSeparator = expression.indexOf('/'); - if ( pathSeparator > 0 ) - { - value = basedir.toString() + expression.substring( pathSeparator ); + if (pathSeparator > 0) { + value = basedir.toString() + expression.substring(pathSeparator); } } @@ -382,49 +297,39 @@ public class PluginParameterExpressionEvaluatorV4 * could still be converted by the configurator so we leave those alone). If so, back off to evaluating the * expression from properties only. */ - if ( value != null && type != null && !( value instanceof String ) && !isTypeCompatible( type, value ) ) - { + if (value != null && type != null && !(value instanceof String) && !isTypeCompatible(type, value)) { value = null; } - if ( value == null ) - { + if (value == null) { // The CLI should win for defining properties - if ( properties != null ) - { + if (properties != null) { // We will attempt to get nab a property as a way to specify a parameter // to a plugin. My particular case here is allowing the surefire plugin // to run a single test so I want to specify that class on the cli as // a parameter. - value = properties.getProperty( expression ); + value = properties.getProperty(expression); } - if ( ( value == null ) && ( ( project != null ) && ( project.getModel().getProperties() != null ) ) ) - { - value = project.getModel().getProperties().get( expression ); + if ((value == null) && ((project != null) && (project.getModel().getProperties() != null))) { + value = project.getModel().getProperties().get(expression); } - } - if ( value instanceof String ) - { + if (value instanceof String) { // TODO without #, this could just be an evaluate call... String val = (String) value; - int exprStartDelimiter = val.indexOf( "${" ); + int exprStartDelimiter = val.indexOf("${"); - if ( exprStartDelimiter >= 0 ) - { - if ( exprStartDelimiter > 0 ) - { - value = val.substring( 0, exprStartDelimiter ) + evaluate( val.substring( exprStartDelimiter ) ); - } - else - { - value = evaluate( val.substring( exprStartDelimiter ) ); + if (exprStartDelimiter >= 0) { + if (exprStartDelimiter > 0) { + value = val.substring(0, exprStartDelimiter) + evaluate(val.substring(exprStartDelimiter)); + } else { + value = evaluate(val.substring(exprStartDelimiter)); } } } @@ -432,49 +337,40 @@ public class PluginParameterExpressionEvaluatorV4 return value; } - private static boolean isTypeCompatible( Class type, Object value ) - { - if ( type.isInstance( value ) ) - { + private static boolean isTypeCompatible(Class type, Object value) { + if (type.isInstance(value)) { return true; } // likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid - return ( ( type.isPrimitive() || type.getName().startsWith( "java.lang." ) ) - && value.getClass().getName().startsWith( "java.lang." ) ); + return ((type.isPrimitive() || type.getName().startsWith("java.lang.")) + && value.getClass().getName().startsWith("java.lang.")); } - private String stripTokens( String expr ) - { - if ( expr.startsWith( "${" ) && ( expr.indexOf( '}' ) == expr.length() - 1 ) ) - { - expr = expr.substring( 2, expr.length() - 1 ); + private String stripTokens(String expr) { + if (expr.startsWith("${") && (expr.indexOf('}') == expr.length() - 1)) { + expr = expr.substring(2, expr.length() - 1); } return expr; } @Override - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { // TODO Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a // similar component for re-usage - if ( file != null ) - { - if ( file.isAbsolute() ) - { + if (file != null) { + if (file.isAbsolute()) { // path was already absolute, just normalize file separator and we're done - } - else if ( file.getPath().startsWith( File.separator ) ) - { + } else if (file.getPath().startsWith(File.separator)) { // drive-relative Windows path, don't align with project directory but with drive root file = file.getAbsoluteFile(); - } - else - { + } else { // an ordinary relative path, align with project directory - file = basedir.resolve( file.getPath() ).normalize().toAbsolutePath().toFile(); + file = basedir.resolve(file.getPath()) + .normalize() + .toAbsolutePath() + .toFile(); } } return file; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginRealmCache.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginRealmCache.java index fecfaccfbc..3066f6dffc 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginRealmCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginRealmCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import java.util.List; import java.util.Map; - import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; @@ -38,20 +36,16 @@ import org.eclipse.aether.repository.RemoteRepository; * @author Igor Fedorenko * @author Benjamin Bentmann */ -public interface PluginRealmCache -{ +public interface PluginRealmCache { /** * CacheRecord */ - class CacheRecord - { - public ClassRealm getRealm() - { + class CacheRecord { + public ClassRealm getRealm() { return realm; } - public List getArtifacts() - { + public List getArtifacts() { return artifacts; } @@ -59,8 +53,7 @@ public interface PluginRealmCache private final List artifacts; - public CacheRecord( ClassRealm realm, List artifacts ) - { + public CacheRecord(ClassRealm realm, List artifacts) { this.realm = realm; this.artifacts = artifacts; } @@ -69,27 +62,28 @@ public interface PluginRealmCache /** * A cache key. */ - interface Key - { + interface Key { // marker interface for cache keys } @FunctionalInterface - interface PluginRealmSupplier - { + interface PluginRealmSupplier { CacheRecord load() throws PluginResolutionException, PluginContainerException; } - Key createKey( Plugin plugin, ClassLoader parentRealm, Map foreignImports, - DependencyFilter dependencyFilter, List repositories, - RepositorySystemSession session ); + Key createKey( + Plugin plugin, + ClassLoader parentRealm, + Map foreignImports, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session); - CacheRecord get( Key key ); + CacheRecord get(Key key); - CacheRecord get( Key key, PluginRealmSupplier supplier ) - throws PluginResolutionException, PluginContainerException; + CacheRecord get(Key key, PluginRealmSupplier supplier) throws PluginResolutionException, PluginContainerException; - CacheRecord put( Key key, ClassRealm pluginRealm, List pluginArtifacts ); + CacheRecord put(Key key, ClassRealm pluginRealm, List pluginArtifacts); void flush(); @@ -101,6 +95,5 @@ public interface PluginRealmCache * @param project The project that employs the plugin realm, must not be {@code null}. * @param record The cache record being used for the project, must not be {@code null}. */ - void register( MavenProject project, Key key, CacheRecord record ); - + void register(MavenProject project, Key key, CacheRecord record); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginResolutionException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginResolutionException.java index ab2806436f..8c0f69c8bc 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginResolutionException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; import org.apache.maven.model.Plugin; @@ -26,22 +25,18 @@ import org.apache.maven.model.Plugin; * * @author Brett Porter */ -public class PluginResolutionException - extends Exception -{ +public class PluginResolutionException extends Exception { private final Plugin plugin; - public PluginResolutionException( Plugin plugin, Throwable cause ) - { - super( "Plugin " + plugin.getId() + " or one of its dependencies could not be resolved: " + cause.getMessage(), - cause ); + public PluginResolutionException(Plugin plugin, Throwable cause) { + super( + "Plugin " + plugin.getId() + " or one of its dependencies could not be resolved: " + cause.getMessage(), + cause); this.plugin = plugin; } - public Plugin getPlugin() - { + public Plugin getPlugin() { return plugin; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginParametersValidator.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginParametersValidator.java index d0fb15db06..60edaba7a1 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginParametersValidator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginParametersValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.Arrays; import java.util.List; - import org.apache.maven.plugin.descriptor.Parameter; import org.apache.maven.shared.utils.logging.MessageBuilder; import org.apache.maven.shared.utils.logging.MessageUtils; @@ -35,71 +33,55 @@ import org.slf4j.Logger; * * @author Slawomir Jaranowski */ -abstract class AbstractMavenPluginParametersValidator implements MavenPluginConfigurationValidator -{ +abstract class AbstractMavenPluginParametersValidator implements MavenPluginConfigurationValidator { // plugin author can provide @Parameter( property = "session" ) in this case property will always evaluate // so, we need ignore those // source org.apache.maven.plugin.PluginParameterExpressionEvaluator private static final List IGNORED_PROPERTY_VALUES = Arrays.asList( - "basedir", - "executedProject", - "localRepository", - "mojo", - "mojoExecution", - "plugin", - "project", - "reactorProjects", - "session", - "settings" - ); + "basedir", + "executedProject", + "localRepository", + "mojo", + "mojoExecution", + "plugin", + "project", + "reactorProjects", + "session", + "settings"); - private static final List IGNORED_PROPERTY_PREFIX = Arrays.asList( - "mojo.", - "plugin.", - "project.", - "session.", - "settings." - ); + private static final List IGNORED_PROPERTY_PREFIX = + Arrays.asList("mojo.", "plugin.", "project.", "session.", "settings."); protected abstract Logger getLogger(); - protected static boolean isValueSet( PlexusConfiguration config, - ExpressionEvaluator expressionEvaluator ) - { - if ( config == null ) - { + protected static boolean isValueSet(PlexusConfiguration config, ExpressionEvaluator expressionEvaluator) { + if (config == null) { return false; } // there are sub items ... so configuration is declared - if ( config.getChildCount() > 0 ) - { + if (config.getChildCount() > 0) { return true; } String strValue = config.getValue(); - if ( strValue == null || strValue.isEmpty() ) - { + if (strValue == null || strValue.isEmpty()) { return false; } - if ( isIgnoredProperty( strValue ) ) - { + if (isIgnoredProperty(strValue)) { return false; } // for declaration like @Parameter( property = "config.property" ) // the value will contain ${config.property} - try - { - return expressionEvaluator.evaluate( strValue ) != null; - } - catch ( ExpressionEvaluationException e ) - { + try { + return expressionEvaluator.evaluate(strValue) != null; + } catch (ExpressionEvaluationException e) { // not important // will be reported during Mojo fields populate } @@ -108,45 +90,35 @@ abstract class AbstractMavenPluginParametersValidator implements MavenPluginConf return false; } - private static boolean isIgnoredProperty( String strValue ) - { - if ( !strValue.startsWith( "${" ) ) - { + private static boolean isIgnoredProperty(String strValue) { + if (!strValue.startsWith("${")) { return false; } - String propertyName = strValue.replace( "${", "" ).replace( "}", "" ); + String propertyName = strValue.replace("${", "").replace("}", ""); - if ( IGNORED_PROPERTY_VALUES.contains( propertyName ) ) - { + if (IGNORED_PROPERTY_VALUES.contains(propertyName)) { return true; } - return IGNORED_PROPERTY_PREFIX.stream().anyMatch( propertyName::startsWith ); + return IGNORED_PROPERTY_PREFIX.stream().anyMatch(propertyName::startsWith); } - protected abstract String getParameterLogReason( Parameter parameter ); + protected abstract String getParameterLogReason(Parameter parameter); - protected void logParameter( Parameter parameter ) - { + protected void logParameter(Parameter parameter) { MessageBuilder messageBuilder = MessageUtils.buffer() - .warning( "Parameter '" ) - .warning( parameter.getName() ) - .warning( '\'' ); + .warning("Parameter '") + .warning(parameter.getName()) + .warning('\''); - if ( parameter.getExpression() != null ) - { - String userProperty = parameter.getExpression().replace( "${", "'" ).replace( '}', '\'' ); - messageBuilder - .warning( " (user property " ) - .warning( userProperty ) - .warning( ")" ); + if (parameter.getExpression() != null) { + String userProperty = parameter.getExpression().replace("${", "'").replace('}', '\''); + messageBuilder.warning(" (user property ").warning(userProperty).warning(")"); } - messageBuilder - .warning( " " ) - .warning( getParameterLogReason( parameter ) ); + messageBuilder.warning(" ").warning(getParameterLogReason(parameter)); - getLogger().warn( messageBuilder.toString() ); + getLogger().warn(messageBuilder.toString()); } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java index bc02e1f7e9..c1525eb12e 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,11 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.concurrent.atomic.AtomicReference; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.LegacySupport; import org.eclipse.aether.RepositorySystemSession; @@ -38,41 +35,30 @@ import org.eclipse.aether.RepositorySystemSession; */ @Named @Singleton -public class DefaultLegacySupport - implements LegacySupport -{ +public class DefaultLegacySupport implements LegacySupport { - private static final ThreadLocal> SESSION = - new InheritableThreadLocal<>(); + private static final ThreadLocal> SESSION = new InheritableThreadLocal<>(); - public void setSession( MavenSession session ) - { + public void setSession(MavenSession session) { AtomicReference reference = DefaultLegacySupport.SESSION.get(); - if ( reference != null ) - { - reference.set( null ); + if (reference != null) { + reference.set(null); } - if ( session == null && reference != null ) - { + if (session == null && reference != null) { DefaultLegacySupport.SESSION.remove(); - } - else - { - DefaultLegacySupport.SESSION.set( new AtomicReference<>( session ) ); + } else { + DefaultLegacySupport.SESSION.set(new AtomicReference<>(session)); } } - public MavenSession getSession() - { + public MavenSession getSession() { AtomicReference currentSession = DefaultLegacySupport.SESSION.get(); return currentSession != null ? currentSession.get() : null; } - public RepositorySystemSession getRepositorySession() - { + public RepositorySystemSession getRepositorySession() { MavenSession session = getSession(); - return ( session != null ) ? session.getRepositorySession() : null; + return (session != null) ? session.getRepositorySession() : null; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java index 8fdfb3e9ad..7a92acfb8a 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,29 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.jar.JarFile; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.RepositoryUtils; import org.apache.maven.api.xml.Dom; import org.apache.maven.artifact.Artifact; @@ -26,6 +46,7 @@ import org.apache.maven.classrealm.ClassRealmManager; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.scope.internal.MojoExecutionScopeModule; import org.apache.maven.internal.impl.DefaultSession; +import org.apache.maven.internal.xml.XmlPlexusConfiguration; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.ContextEnabled; import org.apache.maven.plugin.DebugConfigurationListener; @@ -61,7 +82,6 @@ import org.apache.maven.project.ExtensionDescriptorBuilder; import org.apache.maven.project.MavenProject; import org.apache.maven.rtinfo.RuntimeInformation; import org.apache.maven.session.scope.internal.SessionScopeModule; -import org.apache.maven.internal.xml.XmlPlexusConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; @@ -88,29 +108,6 @@ import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.jar.JarFile; -import java.util.stream.Collectors; -import java.util.zip.ZipEntry; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - /** * Provides basic services to manage Maven plugins and their mojos. This component is kept general in its design such * that the plugins/mojos can be used in arbitrary contexts. In particular, the mojos can be used for ordinary build @@ -121,9 +118,7 @@ import javax.inject.Singleton; */ @Named @Singleton -public class DefaultMavenPluginManager - implements MavenPluginManager -{ +public class DefaultMavenPluginManager implements MavenPluginManager { /** *

    @@ -136,7 +131,7 @@ public class DefaultMavenPluginManager */ public static final String KEY_EXTENSIONS_REALMS = DefaultMavenPluginManager.class.getName() + "/extensionsRealms"; - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private PlexusContainer container; private ClassRealmManager classRealmManager; @@ -155,7 +150,7 @@ public class DefaultMavenPluginManager private final PluginDescriptorBuilder builder = new PluginDescriptorBuilder(); @Inject - @SuppressWarnings( "checkstyle:ParameterNumber" ) + @SuppressWarnings("checkstyle:ParameterNumber") public DefaultMavenPluginManager( PlexusContainer container, ClassRealmManager classRealmManager, @@ -168,8 +163,7 @@ public class DefaultMavenPluginManager PluginArtifactsCache pluginArtifactsCache, MavenPluginValidator pluginValidator, List configurationValidators, - List prerequisitesCheckers ) - { + List prerequisitesCheckers) { this.container = container; this.classRealmManager = classRealmManager; this.pluginDescriptorCache = pluginDescriptorCache; @@ -184,234 +178,203 @@ public class DefaultMavenPluginManager this.prerequisitesCheckers = prerequisitesCheckers; } - public PluginDescriptor getPluginDescriptor( Plugin plugin, List repositories, - RepositorySystemSession session ) - throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException - { - PluginDescriptorCache.Key cacheKey = pluginDescriptorCache.createKey( plugin, repositories, session ); + public PluginDescriptor getPluginDescriptor( + Plugin plugin, List repositories, RepositorySystemSession session) + throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException { + PluginDescriptorCache.Key cacheKey = pluginDescriptorCache.createKey(plugin, repositories, session); - PluginDescriptor pluginDescriptor = pluginDescriptorCache.get( cacheKey, () -> - { + PluginDescriptor pluginDescriptor = pluginDescriptorCache.get(cacheKey, () -> { org.eclipse.aether.artifact.Artifact artifact = - pluginDependenciesResolver.resolve( plugin, repositories, session ); + pluginDependenciesResolver.resolve(plugin, repositories, session); - Artifact pluginArtifact = RepositoryUtils.toArtifact( artifact ); + Artifact pluginArtifact = RepositoryUtils.toArtifact(artifact); - PluginDescriptor descriptor = extractPluginDescriptor( pluginArtifact, plugin ); + PluginDescriptor descriptor = extractPluginDescriptor(pluginArtifact, plugin); - if ( StringUtils.isBlank( descriptor.getRequiredMavenVersion() ) ) - { + if (StringUtils.isBlank(descriptor.getRequiredMavenVersion())) { // only take value from underlying POM if plugin descriptor has no explicit Maven requirement - descriptor.setRequiredMavenVersion( artifact.getProperty( "requiredMavenVersion", null ) ); + descriptor.setRequiredMavenVersion(artifact.getProperty("requiredMavenVersion", null)); } return descriptor; - } ); + }); - pluginDescriptor.setPlugin( plugin ); + pluginDescriptor.setPlugin(plugin); return pluginDescriptor; } - private PluginDescriptor extractPluginDescriptor( Artifact pluginArtifact, Plugin plugin ) - throws PluginDescriptorParsingException, InvalidPluginDescriptorException - { + private PluginDescriptor extractPluginDescriptor(Artifact pluginArtifact, Plugin plugin) + throws PluginDescriptorParsingException, InvalidPluginDescriptorException { PluginDescriptor pluginDescriptor = null; File pluginFile = pluginArtifact.getFile(); - try - { - if ( pluginFile.isFile() ) - { - try ( JarFile pluginJar = new JarFile( pluginFile, false ) ) - { - ZipEntry pluginDescriptorEntry = pluginJar.getEntry( getPluginDescriptorLocation() ); + try { + if (pluginFile.isFile()) { + try (JarFile pluginJar = new JarFile(pluginFile, false)) { + ZipEntry pluginDescriptorEntry = pluginJar.getEntry(getPluginDescriptorLocation()); - if ( pluginDescriptorEntry != null ) - { - InputStream is = pluginJar.getInputStream( pluginDescriptorEntry ); + if (pluginDescriptorEntry != null) { + InputStream is = pluginJar.getInputStream(pluginDescriptorEntry); - pluginDescriptor = parsePluginDescriptor( is, plugin, pluginFile.getAbsolutePath() ); + pluginDescriptor = parsePluginDescriptor(is, plugin, pluginFile.getAbsolutePath()); } } - } - else - { - File pluginXml = new File( pluginFile, getPluginDescriptorLocation() ); + } else { + File pluginXml = new File(pluginFile, getPluginDescriptorLocation()); - if ( pluginXml.isFile() ) - { - try ( InputStream is = new BufferedInputStream( new FileInputStream( pluginXml ) ) ) - { - pluginDescriptor = parsePluginDescriptor( is, plugin, pluginXml.getAbsolutePath() ); + if (pluginXml.isFile()) { + try (InputStream is = new BufferedInputStream(new FileInputStream(pluginXml))) { + pluginDescriptor = parsePluginDescriptor(is, plugin, pluginXml.getAbsolutePath()); } } } - if ( pluginDescriptor == null ) - { - throw new IOException( "No plugin descriptor found at " + getPluginDescriptorLocation() ); + if (pluginDescriptor == null) { + throw new IOException("No plugin descriptor found at " + getPluginDescriptorLocation()); } - } - catch ( IOException e ) - { - throw new PluginDescriptorParsingException( plugin, pluginFile.getAbsolutePath(), e ); + } catch (IOException e) { + throw new PluginDescriptorParsingException(plugin, pluginFile.getAbsolutePath(), e); } List errors = new ArrayList<>(); - pluginValidator.validate( pluginArtifact, pluginDescriptor, errors ); + pluginValidator.validate(pluginArtifact, pluginDescriptor, errors); - if ( !errors.isEmpty() ) - { + if (!errors.isEmpty()) { throw new InvalidPluginDescriptorException( - "Invalid plugin descriptor for " + plugin.getId() + " (" + pluginFile + ")", errors ); + "Invalid plugin descriptor for " + plugin.getId() + " (" + pluginFile + ")", errors); } - pluginDescriptor.setPluginArtifact( pluginArtifact ); + pluginDescriptor.setPluginArtifact(pluginArtifact); return pluginDescriptor; } - private String getPluginDescriptorLocation() - { + private String getPluginDescriptorLocation() { return "META-INF/maven/plugin.xml"; } - private PluginDescriptor parsePluginDescriptor( InputStream is, Plugin plugin, String descriptorLocation ) - throws PluginDescriptorParsingException - { - try - { - Reader reader = ReaderFactory.newXmlReader( is ); + private PluginDescriptor parsePluginDescriptor(InputStream is, Plugin plugin, String descriptorLocation) + throws PluginDescriptorParsingException { + try { + Reader reader = ReaderFactory.newXmlReader(is); - return builder.build( reader, descriptorLocation ); - } - catch ( IOException | PlexusConfigurationException e ) - { - throw new PluginDescriptorParsingException( plugin, descriptorLocation, e ); + return builder.build(reader, descriptorLocation); + } catch (IOException | PlexusConfigurationException e) { + throw new PluginDescriptorParsingException(plugin, descriptorLocation, e); } } - public MojoDescriptor getMojoDescriptor( Plugin plugin, String goal, List repositories, - RepositorySystemSession session ) - throws MojoNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - InvalidPluginDescriptorException - { - PluginDescriptor pluginDescriptor = getPluginDescriptor( plugin, repositories, session ); + public MojoDescriptor getMojoDescriptor( + Plugin plugin, String goal, List repositories, RepositorySystemSession session) + throws MojoNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + InvalidPluginDescriptorException { + PluginDescriptor pluginDescriptor = getPluginDescriptor(plugin, repositories, session); - MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo( goal ); + MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal); - if ( mojoDescriptor == null ) - { - throw new MojoNotFoundException( goal, pluginDescriptor ); + if (mojoDescriptor == null) { + throw new MojoNotFoundException(goal, pluginDescriptor); } return mojoDescriptor; } - @Override - public void checkPrerequisites( PluginDescriptor pluginDescriptor ) - throws PluginIncompatibleException - { + public void checkPrerequisites(PluginDescriptor pluginDescriptor) throws PluginIncompatibleException { List prerequisiteExceptions = new ArrayList<>(); - prerequisitesCheckers.forEach( c -> - { - try - { - c.accept( pluginDescriptor ); - } - catch ( IllegalStateException e ) - { - prerequisiteExceptions.add( e ); + prerequisitesCheckers.forEach(c -> { + try { + c.accept(pluginDescriptor); + } catch (IllegalStateException e) { + prerequisiteExceptions.add(e); } - } ); + }); // aggregate all exceptions - if ( !prerequisiteExceptions.isEmpty() ) - { + if (!prerequisiteExceptions.isEmpty()) { String messages = prerequisiteExceptions.stream() - .map( IllegalStateException::getMessage ) - .collect( Collectors.joining( ", " ) ); - PluginIncompatibleException pie = new PluginIncompatibleException( pluginDescriptor.getPlugin(), - "The plugin " + pluginDescriptor.getId() - + " has unmet prerequisites: " - + messages, prerequisiteExceptions.get( 0 ) ); + .map(IllegalStateException::getMessage) + .collect(Collectors.joining(", ")); + PluginIncompatibleException pie = new PluginIncompatibleException( + pluginDescriptor.getPlugin(), + "The plugin " + pluginDescriptor.getId() + " has unmet prerequisites: " + messages, + prerequisiteExceptions.get(0)); // the first exception is added as cause, all other ones as suppressed exceptions - prerequisiteExceptions.stream().skip( 1 ).forEach( pie::addSuppressed ); + prerequisiteExceptions.stream().skip(1).forEach(pie::addSuppressed); throw pie; } } - public void setupPluginRealm( PluginDescriptor pluginDescriptor, MavenSession session, - ClassLoader parent, List imports, DependencyFilter filter ) - throws PluginResolutionException, PluginContainerException - { + public void setupPluginRealm( + PluginDescriptor pluginDescriptor, + MavenSession session, + ClassLoader parent, + List imports, + DependencyFilter filter) + throws PluginResolutionException, PluginContainerException { Plugin plugin = pluginDescriptor.getPlugin(); MavenProject project = session.getCurrentProject(); - if ( plugin.isExtensions() ) - { + if (plugin.isExtensions()) { ExtensionRealmCache.CacheRecord extensionRecord; - try - { + try { RepositorySystemSession repositorySession = session.getRepositorySession(); - extensionRecord = setupExtensionsRealm( project, plugin, repositorySession ); - } - catch ( PluginManagerException e ) - { + extensionRecord = setupExtensionsRealm(project, plugin, repositorySession); + } catch (PluginManagerException e) { // extensions realm is expected to be fully setup at this point // any exception means a problem in maven code, not a user error - throw new IllegalStateException( e ); + throw new IllegalStateException(e); } ClassRealm pluginRealm = extensionRecord.getRealm(); List pluginArtifacts = extensionRecord.getArtifacts(); - for ( ComponentDescriptor componentDescriptor : pluginDescriptor.getComponents() ) - { - componentDescriptor.setRealm( pluginRealm ); + for (ComponentDescriptor componentDescriptor : pluginDescriptor.getComponents()) { + componentDescriptor.setRealm(pluginRealm); } - pluginDescriptor.setClassRealm( pluginRealm ); - pluginDescriptor.setArtifacts( pluginArtifacts ); - } - else - { - Map foreignImports = calcImports( project, parent, imports ); + pluginDescriptor.setClassRealm(pluginRealm); + pluginDescriptor.setArtifacts(pluginArtifacts); + } else { + Map foreignImports = calcImports(project, parent, imports); - PluginRealmCache.Key cacheKey = pluginRealmCache.createKey( plugin, parent, foreignImports, filter, - project.getRemotePluginRepositories(), - session.getRepositorySession() ); + PluginRealmCache.Key cacheKey = pluginRealmCache.createKey( + plugin, + parent, + foreignImports, + filter, + project.getRemotePluginRepositories(), + session.getRepositorySession()); - PluginRealmCache.CacheRecord cacheRecord = pluginRealmCache.get( cacheKey, () -> - { - createPluginRealm( pluginDescriptor, session, parent, foreignImports, filter ); + PluginRealmCache.CacheRecord cacheRecord = pluginRealmCache.get(cacheKey, () -> { + createPluginRealm(pluginDescriptor, session, parent, foreignImports, filter); return new PluginRealmCache.CacheRecord( - pluginDescriptor.getClassRealm(), pluginDescriptor.getArtifacts() ); - } ); + pluginDescriptor.getClassRealm(), pluginDescriptor.getArtifacts()); + }); - pluginDescriptor.setClassRealm( cacheRecord.getRealm() ); - pluginDescriptor.setArtifacts( new ArrayList<>( cacheRecord.getArtifacts() ) ); - for ( ComponentDescriptor componentDescriptor : pluginDescriptor.getComponents() ) - { - componentDescriptor.setRealm( cacheRecord.getRealm() ); + pluginDescriptor.setClassRealm(cacheRecord.getRealm()); + pluginDescriptor.setArtifacts(new ArrayList<>(cacheRecord.getArtifacts())); + for (ComponentDescriptor componentDescriptor : pluginDescriptor.getComponents()) { + componentDescriptor.setRealm(cacheRecord.getRealm()); } - pluginRealmCache.register( project, cacheKey, cacheRecord ); + pluginRealmCache.register(project, cacheKey, cacheRecord); } } - private void createPluginRealm( PluginDescriptor pluginDescriptor, MavenSession session, ClassLoader parent, - Map foreignImports, DependencyFilter filter ) - throws PluginResolutionException, PluginContainerException - { - Plugin plugin = - Objects.requireNonNull( pluginDescriptor.getPlugin(), "pluginDescriptor.plugin cannot be null" ); + private void createPluginRealm( + PluginDescriptor pluginDescriptor, + MavenSession session, + ClassLoader parent, + Map foreignImports, + DependencyFilter filter) + throws PluginResolutionException, PluginContainerException { + Plugin plugin = Objects.requireNonNull(pluginDescriptor.getPlugin(), "pluginDescriptor.plugin cannot be null"); - Artifact pluginArtifact = Objects.requireNonNull( pluginDescriptor.getPluginArtifact(), - "pluginDescriptor.pluginArtifact cannot be null" ); + Artifact pluginArtifact = Objects.requireNonNull( + pluginDescriptor.getPluginArtifact(), "pluginDescriptor.pluginArtifact cannot be null"); MavenProject project = session.getCurrentProject(); @@ -420,451 +383,386 @@ public class DefaultMavenPluginManager RepositorySystemSession repositorySession = session.getRepositorySession(); DependencyFilter dependencyFilter = project.getExtensionDependencyFilter(); - dependencyFilter = AndDependencyFilter.newInstance( dependencyFilter, filter ); + dependencyFilter = AndDependencyFilter.newInstance(dependencyFilter, filter); - DependencyNode root = - pluginDependenciesResolver.resolve( plugin, RepositoryUtils.toArtifact( pluginArtifact ), dependencyFilter, - project.getRemotePluginRepositories(), repositorySession ); + DependencyNode root = pluginDependenciesResolver.resolve( + plugin, + RepositoryUtils.toArtifact(pluginArtifact), + dependencyFilter, + project.getRemotePluginRepositories(), + repositorySession); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); - root.accept( nlg ); + root.accept(nlg); - pluginArtifacts = toMavenArtifacts( root, nlg ); + pluginArtifacts = toMavenArtifacts(root, nlg); - pluginRealm = classRealmManager.createPluginRealm( plugin, parent, null, foreignImports, - toAetherArtifacts( pluginArtifacts ) ); + pluginRealm = classRealmManager.createPluginRealm( + plugin, parent, null, foreignImports, toAetherArtifacts(pluginArtifacts)); - discoverPluginComponents( pluginRealm, plugin, pluginDescriptor ); + discoverPluginComponents(pluginRealm, plugin, pluginDescriptor); - pluginDescriptor.setClassRealm( pluginRealm ); - pluginDescriptor.setArtifacts( pluginArtifacts ); + pluginDescriptor.setClassRealm(pluginRealm); + pluginDescriptor.setArtifacts(pluginArtifacts); } - private void discoverPluginComponents( final ClassRealm pluginRealm, Plugin plugin, - PluginDescriptor pluginDescriptor ) - throws PluginContainerException - { - try - { - if ( pluginDescriptor != null ) - { - for ( ComponentDescriptor componentDescriptor : pluginDescriptor.getComponents() ) - { - componentDescriptor.setRealm( pluginRealm ); - container.addComponentDescriptor( componentDescriptor ); + private void discoverPluginComponents( + final ClassRealm pluginRealm, Plugin plugin, PluginDescriptor pluginDescriptor) + throws PluginContainerException { + try { + if (pluginDescriptor != null) { + for (ComponentDescriptor componentDescriptor : pluginDescriptor.getComponents()) { + componentDescriptor.setRealm(pluginRealm); + container.addComponentDescriptor(componentDescriptor); } } - ( (DefaultPlexusContainer) container ).discoverComponents( pluginRealm, new SessionScopeModule( container ), - new MojoExecutionScopeModule( container ) ); - } - catch ( ComponentLookupException | CycleDetectedInComponentGraphException e ) - { - throw new PluginContainerException( plugin, pluginRealm, - "Error in component graph of plugin " + plugin.getId() + ": " - + e.getMessage(), e ); + ((DefaultPlexusContainer) container) + .discoverComponents( + pluginRealm, new SessionScopeModule(container), new MojoExecutionScopeModule(container)); + } catch (ComponentLookupException | CycleDetectedInComponentGraphException e) { + throw new PluginContainerException( + plugin, + pluginRealm, + "Error in component graph of plugin " + plugin.getId() + ": " + e.getMessage(), + e); } } - private List toAetherArtifacts( final List pluginArtifacts ) - { - return new ArrayList<>( RepositoryUtils.toArtifacts( pluginArtifacts ) ); + private List toAetherArtifacts(final List pluginArtifacts) { + return new ArrayList<>(RepositoryUtils.toArtifacts(pluginArtifacts)); } - private List toMavenArtifacts( DependencyNode root, PreorderNodeListGenerator nlg ) - { - List artifacts = new ArrayList<>( nlg.getNodes().size() ); - RepositoryUtils.toArtifacts( artifacts, Collections.singleton( root ), Collections.emptyList(), null ); - artifacts.removeIf( artifact -> artifact.getFile() == null ); - return Collections.unmodifiableList( artifacts ); + private List toMavenArtifacts(DependencyNode root, PreorderNodeListGenerator nlg) { + List artifacts = new ArrayList<>(nlg.getNodes().size()); + RepositoryUtils.toArtifacts(artifacts, Collections.singleton(root), Collections.emptyList(), null); + artifacts.removeIf(artifact -> artifact.getFile() == null); + return Collections.unmodifiableList(artifacts); } - private Map calcImports( MavenProject project, ClassLoader parent, List imports ) - { + private Map calcImports(MavenProject project, ClassLoader parent, List imports) { Map foreignImports = new HashMap<>(); ClassLoader projectRealm = project.getClassRealm(); - if ( projectRealm != null ) - { - foreignImports.put( "", projectRealm ); - } - else - { - foreignImports.put( "", classRealmManager.getMavenApiRealm() ); + if (projectRealm != null) { + foreignImports.put("", projectRealm); + } else { + foreignImports.put("", classRealmManager.getMavenApiRealm()); } - if ( parent != null && imports != null ) - { - for ( String parentImport : imports ) - { - foreignImports.put( parentImport, parent ); + if (parent != null && imports != null) { + for (String parentImport : imports) { + foreignImports.put(parentImport, parent); } } return foreignImports; } - public T getConfiguredMojo( Class mojoInterface, MavenSession session, MojoExecution mojoExecution ) - throws PluginConfigurationException, PluginContainerException - { + public T getConfiguredMojo(Class mojoInterface, MavenSession session, MojoExecution mojoExecution) + throws PluginConfigurationException, PluginContainerException { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); ClassRealm pluginRealm = pluginDescriptor.getClassRealm(); - if ( pluginRealm == null ) - { - try - { - setupPluginRealm( pluginDescriptor, session, null, null, null ); - } - catch ( PluginResolutionException e ) - { + if (pluginRealm == null) { + try { + setupPluginRealm(pluginDescriptor, session, null, null, null); + } catch (PluginResolutionException e) { String msg = "Cannot setup plugin realm [mojoDescriptor=" + mojoDescriptor.getId() + ", pluginDescriptor=" + pluginDescriptor.getId() + "]"; - throw new PluginConfigurationException( pluginDescriptor, msg, e ); + throw new PluginConfigurationException(pluginDescriptor, msg, e); } pluginRealm = pluginDescriptor.getClassRealm(); } - if ( logger.isDebugEnabled() ) - { - logger.debug( "Loading mojo " + mojoDescriptor.getId() + " from plugin realm " + pluginRealm ); + if (logger.isDebugEnabled()) { + logger.debug("Loading mojo " + mojoDescriptor.getId() + " from plugin realm " + pluginRealm); } // We are forcing the use of the plugin realm for all lookups that might occur during // the lifecycle that is part of the lookup. Here we are specifically trying to keep // lookups that occur in contextualize calls in line with the right realm. - ClassRealm oldLookupRealm = container.setLookupRealm( pluginRealm ); + ClassRealm oldLookupRealm = container.setLookupRealm(pluginRealm); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( pluginRealm ); + Thread.currentThread().setContextClassLoader(pluginRealm); - try - { + try { T mojo; - try - { - mojo = container.lookup( mojoInterface, mojoDescriptor.getRoleHint() ); - } - catch ( ComponentLookupException e ) - { + try { + mojo = container.lookup(mojoInterface, mojoDescriptor.getRoleHint()); + } catch (ComponentLookupException e) { Throwable cause = e.getCause(); - while ( cause != null && !( cause instanceof LinkageError ) - && !( cause instanceof ClassNotFoundException ) ) - { + while (cause != null + && !(cause instanceof LinkageError) + && !(cause instanceof ClassNotFoundException)) { cause = cause.getCause(); } - if ( ( cause instanceof NoClassDefFoundError ) || ( cause instanceof ClassNotFoundException ) ) - { - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( "Unable to load the mojo '" + mojoDescriptor.getGoal() + "' in the plugin '" - + pluginDescriptor.getId() + "'. A required class is missing: " - + cause.getMessage() ); - pluginRealm.display( ps ); + if ((cause instanceof NoClassDefFoundError) || (cause instanceof ClassNotFoundException)) { + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println("Unable to load the mojo '" + mojoDescriptor.getGoal() + "' in the plugin '" + + pluginDescriptor.getId() + "'. A required class is missing: " + + cause.getMessage()); + pluginRealm.display(ps); - throw new PluginContainerException( mojoDescriptor, pluginRealm, os.toString(), cause ); - } - else if ( cause instanceof LinkageError ) - { - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( "Unable to load the mojo '" + mojoDescriptor.getGoal() + "' in the plugin '" - + pluginDescriptor.getId() + "' due to an API incompatibility: " - + e.getClass().getName() + ": " + cause.getMessage() ); - pluginRealm.display( ps ); + throw new PluginContainerException(mojoDescriptor, pluginRealm, os.toString(), cause); + } else if (cause instanceof LinkageError) { + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println("Unable to load the mojo '" + mojoDescriptor.getGoal() + "' in the plugin '" + + pluginDescriptor.getId() + "' due to an API incompatibility: " + + e.getClass().getName() + ": " + cause.getMessage()); + pluginRealm.display(ps); - throw new PluginContainerException( mojoDescriptor, pluginRealm, os.toString(), cause ); + throw new PluginContainerException(mojoDescriptor, pluginRealm, os.toString(), cause); } - throw new PluginContainerException( mojoDescriptor, pluginRealm, - "Unable to load the mojo '" + mojoDescriptor.getGoal() - + "' (or one of its required components) from the plugin '" - + pluginDescriptor.getId() + "'", e ); + throw new PluginContainerException( + mojoDescriptor, + pluginRealm, + "Unable to load the mojo '" + mojoDescriptor.getGoal() + + "' (or one of its required components) from the plugin '" + + pluginDescriptor.getId() + "'", + e); } - if ( mojo instanceof ContextEnabled ) - { + if (mojo instanceof ContextEnabled) { MavenProject project = session.getCurrentProject(); - Map pluginContext = session.getPluginContext( pluginDescriptor, project ); + Map pluginContext = session.getPluginContext(pluginDescriptor, project); - if ( pluginContext != null ) - { - pluginContext.put( "project", project ); + if (pluginContext != null) { + pluginContext.put("project", project); - pluginContext.put( "pluginDescriptor", pluginDescriptor ); + pluginContext.put("pluginDescriptor", pluginDescriptor); - ( (ContextEnabled) mojo ).setPluginContext( pluginContext ); + ((ContextEnabled) mojo).setPluginContext(pluginContext); } } - if ( mojo instanceof Mojo ) - { - Logger mojoLogger = LoggerFactory.getLogger( mojoDescriptor.getImplementation() ); - ( (Mojo) mojo ).setLog( new MojoLogWrapper( mojoLogger ) ); + if (mojo instanceof Mojo) { + Logger mojoLogger = LoggerFactory.getLogger(mojoDescriptor.getImplementation()); + ((Mojo) mojo).setLog(new MojoLogWrapper(mojoLogger)); } Dom dom = mojoExecution.getConfiguration() != null - ? mojoExecution.getConfiguration().getDom() : null; + ? mojoExecution.getConfiguration().getDom() + : null; PlexusConfiguration pomConfiguration; - if ( dom == null ) - { - pomConfiguration = new DefaultPlexusConfiguration( "configuration" ); - } - else - { - pomConfiguration = XmlPlexusConfiguration.toPlexusConfiguration( dom ); + if (dom == null) { + pomConfiguration = new DefaultPlexusConfiguration("configuration"); + } else { + pomConfiguration = XmlPlexusConfiguration.toPlexusConfiguration(dom); } ExpressionEvaluator expressionEvaluator; - if ( mojoDescriptor.isV4Api() ) - { + if (mojoDescriptor.isV4Api()) { expressionEvaluator = new PluginParameterExpressionEvaluatorV4( session.getSession(), - ( ( DefaultSession ) session.getSession() ).getProject( session.getCurrentProject() ), - mojoExecution ); - } - else - { - expressionEvaluator = new PluginParameterExpressionEvaluator( session, mojoExecution ); + ((DefaultSession) session.getSession()).getProject(session.getCurrentProject()), + mojoExecution); + } else { + expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution); } - for ( MavenPluginConfigurationValidator validator: configurationValidators ) - { - validator.validate( mojoDescriptor, pomConfiguration, expressionEvaluator ); + for (MavenPluginConfigurationValidator validator : configurationValidators) { + validator.validate(mojoDescriptor, pomConfiguration, expressionEvaluator); } - populateMojoExecutionFields( mojo, mojoExecution.getExecutionId(), mojoDescriptor, pluginRealm, - pomConfiguration, expressionEvaluator ); + populateMojoExecutionFields( + mojo, + mojoExecution.getExecutionId(), + mojoDescriptor, + pluginRealm, + pomConfiguration, + expressionEvaluator); return mojo; - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); - container.setLookupRealm( oldLookupRealm ); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); + container.setLookupRealm(oldLookupRealm); } } - private void populateMojoExecutionFields( Object mojo, String executionId, MojoDescriptor mojoDescriptor, - ClassRealm pluginRealm, PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator ) - throws PluginConfigurationException - { + private void populateMojoExecutionFields( + Object mojo, + String executionId, + MojoDescriptor mojoDescriptor, + ClassRealm pluginRealm, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator) + throws PluginConfigurationException { ComponentConfigurator configurator = null; String configuratorId = mojoDescriptor.getComponentConfigurator(); - if ( StringUtils.isEmpty( configuratorId ) ) - { + if (StringUtils.isEmpty(configuratorId)) { configuratorId = mojoDescriptor.isV4Api() ? "enhanced" : "basic"; } - try - { + try { // TODO could the configuration be passed to lookup and the configurator known to plexus via the descriptor // so that this method could entirely be handled by a plexus lookup? - configurator = container.lookup( ComponentConfigurator.class, configuratorId ); + configurator = container.lookup(ComponentConfigurator.class, configuratorId); - ConfigurationListener listener = new DebugConfigurationListener( logger ); + ConfigurationListener listener = new DebugConfigurationListener(logger); ValidatingConfigurationListener validator = - new ValidatingConfigurationListener( mojo, mojoDescriptor, listener ); + new ValidatingConfigurationListener(mojo, mojoDescriptor, listener); - logger.debug( "Configuring mojo execution '" + mojoDescriptor.getId() + ':' + executionId + "' with " - + configuratorId + " configurator -->" ); + logger.debug("Configuring mojo execution '" + mojoDescriptor.getId() + ':' + executionId + "' with " + + configuratorId + " configurator -->"); - configurator.configureComponent( mojo, configuration, expressionEvaluator, pluginRealm, validator ); + configurator.configureComponent(mojo, configuration, expressionEvaluator, pluginRealm, validator); - logger.debug( "-- end configuration --" ); + logger.debug("-- end configuration --"); Collection missingParameters = validator.getMissingParameters(); - if ( !missingParameters.isEmpty() ) - { - if ( "basic".equals( configuratorId ) ) - { - throw new PluginParameterException( mojoDescriptor, new ArrayList<>( missingParameters ) ); - } - else - { + if (!missingParameters.isEmpty()) { + if ("basic".equals(configuratorId)) { + throw new PluginParameterException(mojoDescriptor, new ArrayList<>(missingParameters)); + } else { /* * NOTE: Other configurators like the map-oriented one don't call into the listener, so do it the * hard way. */ - validateParameters( mojoDescriptor, configuration, expressionEvaluator ); + validateParameters(mojoDescriptor, configuration, expressionEvaluator); } } - } - catch ( ComponentConfigurationException e ) - { + } catch (ComponentConfigurationException e) { String message = "Unable to parse configuration of mojo " + mojoDescriptor.getId(); - if ( e.getFailedConfiguration() != null ) - { + if (e.getFailedConfiguration() != null) { message += " for parameter " + e.getFailedConfiguration().getName(); } message += ": " + e.getMessage(); - throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), message, e ); - } - catch ( ComponentLookupException e ) - { - throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), - "Unable to retrieve component configurator " + configuratorId - + " for configuration of mojo " + mojoDescriptor.getId(), e ); - } - catch ( NoClassDefFoundError e ) - { - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( "A required class was missing during configuration of mojo " + mojoDescriptor.getId() + ": " - + e.getMessage() ); - pluginRealm.display( ps ); + throw new PluginConfigurationException(mojoDescriptor.getPluginDescriptor(), message, e); + } catch (ComponentLookupException e) { + throw new PluginConfigurationException( + mojoDescriptor.getPluginDescriptor(), + "Unable to retrieve component configurator " + configuratorId + " for configuration of mojo " + + mojoDescriptor.getId(), + e); + } catch (NoClassDefFoundError e) { + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println("A required class was missing during configuration of mojo " + mojoDescriptor.getId() + ": " + + e.getMessage()); + pluginRealm.display(ps); - throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), os.toString(), e ); - } - catch ( LinkageError e ) - { - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - ps.println( - "An API incompatibility was encountered during configuration of mojo " + mojoDescriptor.getId() + ": " - + e.getClass().getName() + ": " + e.getMessage() ); - pluginRealm.display( ps ); + throw new PluginConfigurationException(mojoDescriptor.getPluginDescriptor(), os.toString(), e); + } catch (LinkageError e) { + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + ps.println("An API incompatibility was encountered during configuration of mojo " + mojoDescriptor.getId() + + ": " + e.getClass().getName() + ": " + e.getMessage()); + pluginRealm.display(ps); - throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), os.toString(), e ); - } - finally - { - if ( configurator != null ) - { - try - { - container.release( configurator ); - } - catch ( ComponentLifecycleException e ) - { - logger.debug( "Failed to release mojo configurator - ignoring." ); + throw new PluginConfigurationException(mojoDescriptor.getPluginDescriptor(), os.toString(), e); + } finally { + if (configurator != null) { + try { + container.release(configurator); + } catch (ComponentLifecycleException e) { + logger.debug("Failed to release mojo configurator - ignoring."); } } } } - private void validateParameters( MojoDescriptor mojoDescriptor, PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator ) - throws ComponentConfigurationException, PluginParameterException - { - if ( mojoDescriptor.getParameters() == null ) - { + private void validateParameters( + MojoDescriptor mojoDescriptor, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator) + throws ComponentConfigurationException, PluginParameterException { + if (mojoDescriptor.getParameters() == null) { return; } List invalidParameters = new ArrayList<>(); - for ( Parameter parameter : mojoDescriptor.getParameters() ) - { - if ( !parameter.isRequired() ) - { + for (Parameter parameter : mojoDescriptor.getParameters()) { + if (!parameter.isRequired()) { continue; } Object value = null; - PlexusConfiguration config = configuration.getChild( parameter.getName(), false ); - if ( config != null ) - { - String expression = config.getValue( null ); + PlexusConfiguration config = configuration.getChild(parameter.getName(), false); + if (config != null) { + String expression = config.getValue(null); - try - { - value = expressionEvaluator.evaluate( expression ); + try { + value = expressionEvaluator.evaluate(expression); - if ( value == null ) - { - value = config.getAttribute( "default-value", null ); + if (value == null) { + value = config.getAttribute("default-value", null); } - } - catch ( ExpressionEvaluationException e ) - { + } catch (ExpressionEvaluationException e) { String msg = "Error evaluating the expression '" + expression + "' for configuration value '" - + configuration.getName() + "'"; - throw new ComponentConfigurationException( configuration, msg, e ); + + configuration.getName() + "'"; + throw new ComponentConfigurationException(configuration, msg, e); } } - if ( value == null && ( config == null || config.getChildCount() <= 0 ) ) - { - invalidParameters.add( parameter ); + if (value == null && (config == null || config.getChildCount() <= 0)) { + invalidParameters.add(parameter); } } - if ( !invalidParameters.isEmpty() ) - { - throw new PluginParameterException( mojoDescriptor, invalidParameters ); + if (!invalidParameters.isEmpty()) { + throw new PluginParameterException(mojoDescriptor, invalidParameters); } } - public void releaseMojo( Object mojo, MojoExecution mojoExecution ) - { - if ( mojo != null ) - { - try - { - container.release( mojo ); - } - catch ( ComponentLifecycleException e ) - { + public void releaseMojo(Object mojo, MojoExecution mojoExecution) { + if (mojo != null) { + try { + container.release(mojo); + } catch (ComponentLifecycleException e) { String goalExecId = mojoExecution.getGoal(); - if ( mojoExecution.getExecutionId() != null ) - { + if (mojoExecution.getExecutionId() != null) { goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}"; } - logger.debug( "Error releasing mojo for " + goalExecId, e ); + logger.debug("Error releasing mojo for " + goalExecId, e); } } } - public ExtensionRealmCache.CacheRecord setupExtensionsRealm( MavenProject project, Plugin plugin, - RepositorySystemSession session ) - throws PluginManagerException - { - @SuppressWarnings( "unchecked" ) Map pluginRealms = - (Map) project.getContextValue( KEY_EXTENSIONS_REALMS ); - if ( pluginRealms == null ) - { + public ExtensionRealmCache.CacheRecord setupExtensionsRealm( + MavenProject project, Plugin plugin, RepositorySystemSession session) throws PluginManagerException { + @SuppressWarnings("unchecked") + Map pluginRealms = + (Map) project.getContextValue(KEY_EXTENSIONS_REALMS); + if (pluginRealms == null) { pluginRealms = new HashMap<>(); - project.setContextValue( KEY_EXTENSIONS_REALMS, pluginRealms ); + project.setContextValue(KEY_EXTENSIONS_REALMS, pluginRealms); } final String pluginKey = plugin.getId(); - ExtensionRealmCache.CacheRecord extensionRecord = pluginRealms.get( pluginKey ); - if ( extensionRecord != null ) - { + ExtensionRealmCache.CacheRecord extensionRecord = pluginRealms.get(pluginKey); + if (extensionRecord != null) { return extensionRecord; } final List repositories = project.getRemotePluginRepositories(); // resolve plugin version as necessary - if ( plugin.getVersion() == null ) - { - PluginVersionRequest versionRequest = new DefaultPluginVersionRequest( plugin, session, repositories ); - try - { - plugin.setVersion( pluginVersionResolver.resolve( versionRequest ).getVersion() ); - } - catch ( PluginVersionResolutionException e ) - { - throw new PluginManagerException( plugin, e.getMessage(), e ); + if (plugin.getVersion() == null) { + PluginVersionRequest versionRequest = new DefaultPluginVersionRequest(plugin, session, repositories); + try { + plugin.setVersion(pluginVersionResolver.resolve(versionRequest).getVersion()); + } catch (PluginVersionResolutionException e) { + throw new PluginManagerException(plugin, e.getMessage(), e); } } @@ -872,97 +770,74 @@ public class DefaultMavenPluginManager // resolve plugin artifacts List artifacts; - PluginArtifactsCache.Key cacheKey = pluginArtifactsCache.createKey( plugin, null, repositories, session ); + PluginArtifactsCache.Key cacheKey = pluginArtifactsCache.createKey(plugin, null, repositories, session); PluginArtifactsCache.CacheRecord recordArtifacts; - try - { - recordArtifacts = pluginArtifactsCache.get( cacheKey ); + try { + recordArtifacts = pluginArtifactsCache.get(cacheKey); + } catch (PluginResolutionException e) { + throw new PluginManagerException(plugin, e.getMessage(), e); } - catch ( PluginResolutionException e ) - { - throw new PluginManagerException( plugin, e.getMessage(), e ); - } - if ( recordArtifacts != null ) - { + if (recordArtifacts != null) { artifacts = recordArtifacts.getArtifacts(); - } - else - { - try - { - artifacts = resolveExtensionArtifacts( plugin, repositories, session ); - recordArtifacts = pluginArtifactsCache.put( cacheKey, artifacts ); - } - catch ( PluginResolutionException e ) - { - pluginArtifactsCache.put( cacheKey, e ); - pluginArtifactsCache.register( project, cacheKey, recordArtifacts ); - throw new PluginManagerException( plugin, e.getMessage(), e ); + } else { + try { + artifacts = resolveExtensionArtifacts(plugin, repositories, session); + recordArtifacts = pluginArtifactsCache.put(cacheKey, artifacts); + } catch (PluginResolutionException e) { + pluginArtifactsCache.put(cacheKey, e); + pluginArtifactsCache.register(project, cacheKey, recordArtifacts); + throw new PluginManagerException(plugin, e.getMessage(), e); } } - pluginArtifactsCache.register( project, cacheKey, recordArtifacts ); + pluginArtifactsCache.register(project, cacheKey, recordArtifacts); // create and cache extensions realms - final ExtensionRealmCache.Key extensionKey = extensionRealmCache.createKey( artifacts ); - extensionRecord = extensionRealmCache.get( extensionKey ); - if ( extensionRecord == null ) - { - ClassRealm extensionRealm = - classRealmManager.createExtensionRealm( plugin, toAetherArtifacts( artifacts ) ); + final ExtensionRealmCache.Key extensionKey = extensionRealmCache.createKey(artifacts); + extensionRecord = extensionRealmCache.get(extensionKey); + if (extensionRecord == null) { + ClassRealm extensionRealm = classRealmManager.createExtensionRealm(plugin, toAetherArtifacts(artifacts)); // TODO figure out how to use the same PluginDescriptor when running mojos PluginDescriptor pluginDescriptor = null; - if ( plugin.isExtensions() && !artifacts.isEmpty() ) - { + if (plugin.isExtensions() && !artifacts.isEmpty()) { // ignore plugin descriptor parsing errors at this point // these errors will reported during calculation of project build execution plan - try - { - pluginDescriptor = extractPluginDescriptor( artifacts.get( 0 ), plugin ); - } - catch ( PluginDescriptorParsingException | InvalidPluginDescriptorException e ) - { + try { + pluginDescriptor = extractPluginDescriptor(artifacts.get(0), plugin); + } catch (PluginDescriptorParsingException | InvalidPluginDescriptorException e) { // ignore, see above } } - discoverPluginComponents( extensionRealm, plugin, pluginDescriptor ); + discoverPluginComponents(extensionRealm, plugin, pluginDescriptor); ExtensionDescriptor extensionDescriptor = null; - Artifact extensionArtifact = artifacts.get( 0 ); - try - { - extensionDescriptor = extensionDescriptorBuilder.build( extensionArtifact.getFile() ); - } - catch ( IOException e ) - { + Artifact extensionArtifact = artifacts.get(0); + try { + extensionDescriptor = extensionDescriptorBuilder.build(extensionArtifact.getFile()); + } catch (IOException e) { String message = "Invalid extension descriptor for " + plugin.getId() + ": " + e.getMessage(); - if ( logger.isDebugEnabled() ) - { - logger.error( message, e ); - } - else - { - logger.error( message ); + if (logger.isDebugEnabled()) { + logger.error(message, e); + } else { + logger.error(message); } } - extensionRecord = extensionRealmCache.put( extensionKey, extensionRealm, extensionDescriptor, artifacts ); + extensionRecord = extensionRealmCache.put(extensionKey, extensionRealm, extensionDescriptor, artifacts); } - extensionRealmCache.register( project, extensionKey, extensionRecord ); - pluginRealms.put( pluginKey, extensionRecord ); + extensionRealmCache.register(project, extensionKey, extensionRecord); + pluginRealms.put(pluginKey, extensionRecord); return extensionRecord; } - private List resolveExtensionArtifacts( Plugin extensionPlugin, List repositories, - RepositorySystemSession session ) - throws PluginResolutionException - { - DependencyNode root = pluginDependenciesResolver.resolve( extensionPlugin, null, null, repositories, session ); + private List resolveExtensionArtifacts( + Plugin extensionPlugin, List repositories, RepositorySystemSession session) + throws PluginResolutionException { + DependencyNode root = pluginDependenciesResolver.resolve(extensionPlugin, null, null, repositories, session); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); - root.accept( nlg ); - return toMavenArtifacts( root, nlg ); + root.accept(nlg); + return toMavenArtifacts(root, nlg); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginValidator.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginValidator.java index da7c4b66fd..66bf83c7fd 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginValidator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,40 +16,33 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.descriptor.PluginDescriptor; - import javax.inject.Named; import javax.inject.Singleton; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.descriptor.PluginDescriptor; /** * DefaultMavenPluginValidator */ @Named @Singleton -class DefaultMavenPluginValidator - implements MavenPluginValidator -{ +class DefaultMavenPluginValidator implements MavenPluginValidator { @Override - public void validate( Artifact pluginArtifact, PluginDescriptor pluginDescriptor, List errors ) - { - if ( !pluginArtifact.getGroupId().equals( pluginDescriptor.getGroupId() ) ) - { - errors.add( "Plugin's descriptor contains the wrong group ID: " + pluginDescriptor.getGroupId() ); + public void validate(Artifact pluginArtifact, PluginDescriptor pluginDescriptor, List errors) { + if (!pluginArtifact.getGroupId().equals(pluginDescriptor.getGroupId())) { + errors.add("Plugin's descriptor contains the wrong group ID: " + pluginDescriptor.getGroupId()); } - if ( !pluginArtifact.getArtifactId().equals( pluginDescriptor.getArtifactId() ) ) - { - errors.add( "Plugin's descriptor contains the wrong artifact ID: " + pluginDescriptor.getArtifactId() ); + if (!pluginArtifact.getArtifactId().equals(pluginDescriptor.getArtifactId())) { + errors.add("Plugin's descriptor contains the wrong artifact ID: " + pluginDescriptor.getArtifactId()); } - if ( !pluginArtifact.getBaseVersion().equals( pluginDescriptor.getVersion() ) ) - { - errors.add( "Plugin's descriptor contains the wrong version: " + pluginDescriptor.getVersion() ); + if (!pluginArtifact.getBaseVersion().equals(pluginDescriptor.getVersion())) { + errors.add("Plugin's descriptor contains the wrong version: " + pluginDescriptor.getVersion()); } } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java index a31ca6201c..f3e7b142fd 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,16 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; @@ -71,80 +68,71 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultPluginDependenciesResolver - implements PluginDependenciesResolver -{ +public class DefaultPluginDependenciesResolver implements PluginDependenciesResolver { private static final String REPOSITORY_CONTEXT = "plugin"; - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final RepositorySystem repoSystem; @Inject - public DefaultPluginDependenciesResolver( RepositorySystem repoSystem ) - { + public DefaultPluginDependenciesResolver(RepositorySystem repoSystem) { this.repoSystem = repoSystem; } - private Artifact toArtifact( Plugin plugin, RepositorySystemSession session ) - { - return new DefaultArtifact( plugin.getGroupId(), plugin.getArtifactId(), null, "jar", plugin.getVersion(), - session.getArtifactTypeRegistry().get( "maven-plugin" ) ); + private Artifact toArtifact(Plugin plugin, RepositorySystemSession session) { + return new DefaultArtifact( + plugin.getGroupId(), + plugin.getArtifactId(), + null, + "jar", + plugin.getVersion(), + session.getArtifactTypeRegistry().get("maven-plugin")); } - public Artifact resolve( Plugin plugin, List repositories, RepositorySystemSession session ) - throws PluginResolutionException - { - RequestTrace trace = RequestTrace.newChild( null, plugin ); + public Artifact resolve(Plugin plugin, List repositories, RepositorySystemSession session) + throws PluginResolutionException { + RequestTrace trace = RequestTrace.newChild(null, plugin); - Artifact pluginArtifact = toArtifact( plugin, session ); + Artifact pluginArtifact = toArtifact(plugin, session); - try - { - DefaultRepositorySystemSession pluginSession = new DefaultRepositorySystemSession( session ); - pluginSession.setArtifactDescriptorPolicy( new SimpleArtifactDescriptorPolicy( true, false ) ); + try { + DefaultRepositorySystemSession pluginSession = new DefaultRepositorySystemSession(session); + pluginSession.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(true, false)); ArtifactDescriptorRequest request = - new ArtifactDescriptorRequest( pluginArtifact, repositories, REPOSITORY_CONTEXT ); - request.setTrace( trace ); - ArtifactDescriptorResult result = repoSystem.readArtifactDescriptor( pluginSession, request ); + new ArtifactDescriptorRequest(pluginArtifact, repositories, REPOSITORY_CONTEXT); + request.setTrace(trace); + ArtifactDescriptorResult result = repoSystem.readArtifactDescriptor(pluginSession, request); pluginArtifact = result.getArtifact(); - if ( logger.isWarnEnabled() ) - { - if ( !result.getRelocations().isEmpty() ) - { + if (logger.isWarnEnabled()) { + if (!result.getRelocations().isEmpty()) { String message = pluginArtifact instanceof org.apache.maven.repository.internal.RelocatedArtifact - ? ( ( org.apache.maven.repository.internal.RelocatedArtifact ) pluginArtifact ).getMessage() + ? ((org.apache.maven.repository.internal.RelocatedArtifact) pluginArtifact).getMessage() : null; - logger.warn( "The artifact " + result.getRelocations().get( 0 ) + " has been relocated to " - + pluginArtifact + ( message != null ? ": " + message : "" ) ); + logger.warn("The artifact " + result.getRelocations().get(0) + " has been relocated to " + + pluginArtifact + (message != null ? ": " + message : "")); } } - String requiredMavenVersion = (String) result.getProperties().get( "prerequisites.maven" ); - if ( requiredMavenVersion != null ) - { - Map props = new LinkedHashMap<>( pluginArtifact.getProperties() ); - props.put( "requiredMavenVersion", requiredMavenVersion ); - pluginArtifact = pluginArtifact.setProperties( props ); + String requiredMavenVersion = (String) result.getProperties().get("prerequisites.maven"); + if (requiredMavenVersion != null) { + Map props = new LinkedHashMap<>(pluginArtifact.getProperties()); + props.put("requiredMavenVersion", requiredMavenVersion); + pluginArtifact = pluginArtifact.setProperties(props); } - } - catch ( ArtifactDescriptorException e ) - { - throw new PluginResolutionException( plugin, e ); + } catch (ArtifactDescriptorException e) { + throw new PluginResolutionException(plugin, e); } - try - { - ArtifactRequest request = new ArtifactRequest( pluginArtifact, repositories, REPOSITORY_CONTEXT ); - request.setTrace( trace ); - pluginArtifact = repoSystem.resolveArtifact( session, request ).getArtifact(); - } - catch ( ArtifactResolutionException e ) - { - throw new PluginResolutionException( plugin, e ); + try { + ArtifactRequest request = new ArtifactRequest(pluginArtifact, repositories, REPOSITORY_CONTEXT); + request.setTrace(trace); + pluginArtifact = repoSystem.resolveArtifact(session, request).getArtifact(); + } catch (ArtifactResolutionException e) { + throw new PluginResolutionException(plugin, e); } return pluginArtifact; @@ -153,174 +141,155 @@ public class DefaultPluginDependenciesResolver /** * @since 3.3.0 */ - public DependencyNode resolveCoreExtension( Plugin plugin, DependencyFilter dependencyFilter, - List repositories, RepositorySystemSession session ) - throws PluginResolutionException - { - return resolveInternal( plugin, null /* pluginArtifact */, dependencyFilter, - repositories, session ); + public DependencyNode resolveCoreExtension( + Plugin plugin, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session) + throws PluginResolutionException { + return resolveInternal(plugin, null /* pluginArtifact */, dependencyFilter, repositories, session); } - public DependencyNode resolve( Plugin plugin, Artifact pluginArtifact, DependencyFilter dependencyFilter, - List repositories, RepositorySystemSession session ) - throws PluginResolutionException - { - return resolveInternal( plugin, pluginArtifact, dependencyFilter, repositories, - session ); + public DependencyNode resolve( + Plugin plugin, + Artifact pluginArtifact, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session) + throws PluginResolutionException { + return resolveInternal(plugin, pluginArtifact, dependencyFilter, repositories, session); } - private DependencyNode resolveInternal( Plugin plugin, Artifact pluginArtifact, DependencyFilter dependencyFilter, - List repositories, RepositorySystemSession session ) - throws PluginResolutionException - { - RequestTrace trace = RequestTrace.newChild( null, plugin ); + private DependencyNode resolveInternal( + Plugin plugin, + Artifact pluginArtifact, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session) + throws PluginResolutionException { + RequestTrace trace = RequestTrace.newChild(null, plugin); - if ( pluginArtifact == null ) - { - pluginArtifact = toArtifact( plugin, session ); + if (pluginArtifact == null) { + pluginArtifact = toArtifact(plugin, session); } - DependencyFilter collectionFilter = new ScopeDependencyFilter( "provided", "test" ); - DependencyFilter resolutionFilter = AndDependencyFilter.newInstance( collectionFilter, dependencyFilter ); + DependencyFilter collectionFilter = new ScopeDependencyFilter("provided", "test"); + DependencyFilter resolutionFilter = AndDependencyFilter.newInstance(collectionFilter, dependencyFilter); DependencyNode node; - try - { - DefaultRepositorySystemSession pluginSession = new DefaultRepositorySystemSession( session ); - pluginSession.setDependencySelector( session.getDependencySelector() ); - pluginSession.setDependencyGraphTransformer( session.getDependencyGraphTransformer() ); + try { + DefaultRepositorySystemSession pluginSession = new DefaultRepositorySystemSession(session); + pluginSession.setDependencySelector(session.getDependencySelector()); + pluginSession.setDependencyGraphTransformer(session.getDependencyGraphTransformer()); CollectRequest request = new CollectRequest(); - request.setRequestContext( REPOSITORY_CONTEXT ); - request.setRepositories( repositories ); - request.setRoot( new org.eclipse.aether.graph.Dependency( pluginArtifact, null ) ); - for ( Dependency dependency : plugin.getDependencies() ) - { + request.setRequestContext(REPOSITORY_CONTEXT); + request.setRepositories(repositories); + request.setRoot(new org.eclipse.aether.graph.Dependency(pluginArtifact, null)); + for (Dependency dependency : plugin.getDependencies()) { org.eclipse.aether.graph.Dependency pluginDep = - RepositoryUtils.toDependency( dependency, session.getArtifactTypeRegistry() ); - if ( !JavaScopes.SYSTEM.equals( pluginDep.getScope() ) ) - { - pluginDep = pluginDep.setScope( JavaScopes.RUNTIME ); + RepositoryUtils.toDependency(dependency, session.getArtifactTypeRegistry()); + if (!JavaScopes.SYSTEM.equals(pluginDep.getScope())) { + pluginDep = pluginDep.setScope(JavaScopes.RUNTIME); } - request.addDependency( pluginDep ); + request.addDependency(pluginDep); } - DependencyRequest depRequest = new DependencyRequest( request, resolutionFilter ); - depRequest.setTrace( trace ); + DependencyRequest depRequest = new DependencyRequest(request, resolutionFilter); + depRequest.setTrace(trace); - request.setTrace( RequestTrace.newChild( trace, depRequest ) ); + request.setTrace(RequestTrace.newChild(trace, depRequest)); - node = repoSystem.collectDependencies( pluginSession, request ).getRoot(); + node = repoSystem.collectDependencies(pluginSession, request).getRoot(); - if ( logger.isDebugEnabled() ) - { - node.accept( new GraphLogger() ); + if (logger.isDebugEnabled()) { + node.accept(new GraphLogger()); } - depRequest.setRoot( node ); - repoSystem.resolveDependencies( session, depRequest ); - } - catch ( DependencyCollectionException e ) - { - throw new PluginResolutionException( plugin, e ); - } - catch ( DependencyResolutionException e ) - { - throw new PluginResolutionException( plugin, e.getCause() ); + depRequest.setRoot(node); + repoSystem.resolveDependencies(session, depRequest); + } catch (DependencyCollectionException e) { + throw new PluginResolutionException(plugin, e); + } catch (DependencyResolutionException e) { + throw new PluginResolutionException(plugin, e.getCause()); } return node; } // Keep this class in sync with org.apache.maven.project.DefaultProjectDependenciesResolver.GraphLogger - class GraphLogger - implements DependencyVisitor - { + class GraphLogger implements DependencyVisitor { private String indent = ""; - public boolean visitEnter( DependencyNode node ) - { - StringBuilder buffer = new StringBuilder( 128 ); - buffer.append( indent ); + public boolean visitEnter(DependencyNode node) { + StringBuilder buffer = new StringBuilder(128); + buffer.append(indent); org.eclipse.aether.graph.Dependency dep = node.getDependency(); - if ( dep != null ) - { + if (dep != null) { org.eclipse.aether.artifact.Artifact art = dep.getArtifact(); - buffer.append( art ); - if ( StringUtils.isNotEmpty( dep.getScope() ) ) - { - buffer.append( ':' ).append( dep.getScope() ); + buffer.append(art); + if (StringUtils.isNotEmpty(dep.getScope())) { + buffer.append(':').append(dep.getScope()); } - if ( dep.isOptional() ) - { - buffer.append( " (optional)" ); + if (dep.isOptional()) { + buffer.append(" (optional)"); } // TODO We currently cannot tell which section contained the management // information. When the resolver provides this information, these log messages should be updated // to contain it. - if ( ( node.getManagedBits() & DependencyNode.MANAGED_SCOPE ) == DependencyNode.MANAGED_SCOPE ) - { - final String premanagedScope = DependencyManagerUtils.getPremanagedScope( node ); - buffer.append( " (scope managed from " ); - buffer.append( Objects.toString( premanagedScope, "default" ) ); - buffer.append( ')' ); + if ((node.getManagedBits() & DependencyNode.MANAGED_SCOPE) == DependencyNode.MANAGED_SCOPE) { + final String premanagedScope = DependencyManagerUtils.getPremanagedScope(node); + buffer.append(" (scope managed from "); + buffer.append(Objects.toString(premanagedScope, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_VERSION ) == DependencyNode.MANAGED_VERSION ) - { - final String premanagedVersion = DependencyManagerUtils.getPremanagedVersion( node ); - buffer.append( " (version managed from " ); - buffer.append( Objects.toString( premanagedVersion, "default" ) ); - buffer.append( ')' ); + if ((node.getManagedBits() & DependencyNode.MANAGED_VERSION) == DependencyNode.MANAGED_VERSION) { + final String premanagedVersion = DependencyManagerUtils.getPremanagedVersion(node); + buffer.append(" (version managed from "); + buffer.append(Objects.toString(premanagedVersion, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL ) == DependencyNode.MANAGED_OPTIONAL ) - { - final Boolean premanagedOptional = DependencyManagerUtils.getPremanagedOptional( node ); - buffer.append( " (optionality managed from " ); - buffer.append( Objects.toString( premanagedOptional, "default" ) ); - buffer.append( ')' ); + if ((node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL) == DependencyNode.MANAGED_OPTIONAL) { + final Boolean premanagedOptional = DependencyManagerUtils.getPremanagedOptional(node); + buffer.append(" (optionality managed from "); + buffer.append(Objects.toString(premanagedOptional, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_EXCLUSIONS ) - == DependencyNode.MANAGED_EXCLUSIONS ) - { + if ((node.getManagedBits() & DependencyNode.MANAGED_EXCLUSIONS) == DependencyNode.MANAGED_EXCLUSIONS) { final Collection premanagedExclusions = - DependencyManagerUtils.getPremanagedExclusions( node ); + DependencyManagerUtils.getPremanagedExclusions(node); - buffer.append( " (exclusions managed from " ); - buffer.append( Objects.toString( premanagedExclusions, "default" ) ); - buffer.append( ')' ); + buffer.append(" (exclusions managed from "); + buffer.append(Objects.toString(premanagedExclusions, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_PROPERTIES ) - == DependencyNode.MANAGED_PROPERTIES ) - { + if ((node.getManagedBits() & DependencyNode.MANAGED_PROPERTIES) == DependencyNode.MANAGED_PROPERTIES) { final Map premanagedProperties = - DependencyManagerUtils.getPremanagedProperties( node ); + DependencyManagerUtils.getPremanagedProperties(node); - buffer.append( " (properties managed from " ); - buffer.append( Objects.toString( premanagedProperties, "default" ) ); - buffer.append( ')' ); + buffer.append(" (properties managed from "); + buffer.append(Objects.toString(premanagedProperties, "default")); + buffer.append(')'); } } - logger.debug( buffer.toString() ); + logger.debug(buffer.toString()); indent += " "; return true; } - public boolean visitLeave( DependencyNode node ) - { - indent = indent.substring( 0, indent.length() - 3 ); + public boolean visitLeave(DependencyNode node) { + indent = indent.substring(0, indent.length() - 3); return true; } - } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginManager.java index 24f71353ae..b98908b2be 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,12 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; @@ -66,9 +63,7 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupExcepti */ @Named @Singleton -public class DefaultPluginManager - implements PluginManager -{ +public class DefaultPluginManager implements PluginManager { private final PlexusContainer container; private final MavenPluginManager pluginManager; @@ -82,8 +77,7 @@ public class DefaultPluginManager MavenPluginManager pluginManager, PluginVersionResolver pluginVersionResolver, PluginPrefixResolver pluginPrefixResolver, - LegacySupport legacySupport ) - { + LegacySupport legacySupport) { this.container = container; this.pluginManager = pluginManager; this.pluginVersionResolver = pluginVersionResolver; @@ -91,176 +85,137 @@ public class DefaultPluginManager this.legacySupport = legacySupport; } - public void executeMojo( MavenProject project, MojoExecution execution, MavenSession session ) - throws MojoExecutionException, ArtifactResolutionException, MojoFailureException, ArtifactNotFoundException, - InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException - { + public void executeMojo(MavenProject project, MojoExecution execution, MavenSession session) + throws MojoExecutionException, ArtifactResolutionException, MojoFailureException, ArtifactNotFoundException, + InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException { throw new UnsupportedOperationException(); } - public Object getPluginComponent( Plugin plugin, String role, String roleHint ) - throws PluginManagerException, ComponentLookupException - { + public Object getPluginComponent(Plugin plugin, String role, String roleHint) + throws PluginManagerException, ComponentLookupException { MavenSession session = legacySupport.getSession(); PluginDescriptor pluginDescriptor; - try - { - pluginDescriptor = - pluginManager.getPluginDescriptor( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); + try { + pluginDescriptor = pluginManager.getPluginDescriptor( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); - pluginManager.setupPluginRealm( pluginDescriptor, session, null, null, null ); - } - catch ( Exception e ) - { - throw new PluginManagerException( plugin, e.getMessage(), e ); + pluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null); + } catch (Exception e) { + throw new PluginManagerException(plugin, e.getMessage(), e); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( pluginDescriptor.getClassRealm() ); + try { + Thread.currentThread().setContextClassLoader(pluginDescriptor.getClassRealm()); - return container.lookup( role, roleHint ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); + return container.lookup(role, roleHint); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); } } - public Map getPluginComponents( Plugin plugin, String role ) - throws ComponentLookupException, PluginManagerException - { + public Map getPluginComponents(Plugin plugin, String role) + throws ComponentLookupException, PluginManagerException { MavenSession session = legacySupport.getSession(); PluginDescriptor pluginDescriptor; - try - { - pluginDescriptor = - pluginManager.getPluginDescriptor( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); + try { + pluginDescriptor = pluginManager.getPluginDescriptor( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); - pluginManager.setupPluginRealm( pluginDescriptor, session, null, null, null ); - } - catch ( Exception e ) - { - throw new PluginManagerException( plugin, e.getMessage(), e ); + pluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null); + } catch (Exception e) { + throw new PluginManagerException(plugin, e.getMessage(), e); } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( pluginDescriptor.getClassRealm() ); + try { + Thread.currentThread().setContextClassLoader(pluginDescriptor.getClassRealm()); - return container.lookupMap( role ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); + return container.lookupMap(role); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); } } - public Plugin getPluginDefinitionForPrefix( String prefix, MavenSession session, MavenProject project ) - { - PluginPrefixRequest request = new DefaultPluginPrefixRequest( prefix, session ); - request.setPom( project.getModel() ); + public Plugin getPluginDefinitionForPrefix(String prefix, MavenSession session, MavenProject project) { + PluginPrefixRequest request = new DefaultPluginPrefixRequest(prefix, session); + request.setPom(project.getModel()); - try - { - PluginPrefixResult result = pluginPrefixResolver.resolve( request ); + try { + PluginPrefixResult result = pluginPrefixResolver.resolve(request); Plugin plugin = new Plugin(); - plugin.setGroupId( result.getGroupId() ); - plugin.setArtifactId( result.getArtifactId() ); + plugin.setGroupId(result.getGroupId()); + plugin.setArtifactId(result.getArtifactId()); return plugin; - } - catch ( NoPluginFoundForPrefixException e ) - { + } catch (NoPluginFoundForPrefixException e) { return null; } } - public PluginDescriptor getPluginDescriptorForPrefix( String prefix ) - { + public PluginDescriptor getPluginDescriptorForPrefix(String prefix) { MavenSession session = legacySupport.getSession(); - PluginPrefixRequest request = new DefaultPluginPrefixRequest( prefix, session ); + PluginPrefixRequest request = new DefaultPluginPrefixRequest(prefix, session); - try - { - PluginPrefixResult result = pluginPrefixResolver.resolve( request ); + try { + PluginPrefixResult result = pluginPrefixResolver.resolve(request); Plugin plugin = new Plugin(); - plugin.setGroupId( result.getGroupId() ); - plugin.setArtifactId( result.getArtifactId() ); + plugin.setGroupId(result.getGroupId()); + plugin.setArtifactId(result.getArtifactId()); - return loadPluginDescriptor( plugin, session.getCurrentProject(), session ); - } - catch ( Exception e ) - { + return loadPluginDescriptor(plugin, session.getCurrentProject(), session); + } catch (Exception e) { return null; } } - public PluginDescriptor loadPluginDescriptor( Plugin plugin, MavenProject project, MavenSession session ) - throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, - InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, - PluginVersionNotFoundException - { - return verifyPlugin( plugin, project, session.getSettings(), session.getLocalRepository() ); + public PluginDescriptor loadPluginDescriptor(Plugin plugin, MavenProject project, MavenSession session) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, + PluginNotFoundException, PluginVersionNotFoundException { + return verifyPlugin(plugin, project, session.getSettings(), session.getLocalRepository()); } - public PluginDescriptor loadPluginFully( Plugin plugin, MavenProject project, MavenSession session ) - throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, - InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, - PluginVersionNotFoundException - { - PluginDescriptor pluginDescriptor = loadPluginDescriptor( plugin, project, session ); + public PluginDescriptor loadPluginFully(Plugin plugin, MavenProject project, MavenSession session) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, + PluginNotFoundException, PluginVersionNotFoundException { + PluginDescriptor pluginDescriptor = loadPluginDescriptor(plugin, project, session); - try - { - pluginManager.setupPluginRealm( pluginDescriptor, session, null, null, null ); - } - catch ( PluginResolutionException e ) - { - throw new PluginManagerException( plugin, e.getMessage(), e ); + try { + pluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null); + } catch (PluginResolutionException e) { + throw new PluginManagerException(plugin, e.getMessage(), e); } return pluginDescriptor; } - public PluginDescriptor verifyPlugin( Plugin plugin, MavenProject project, Settings settings, - ArtifactRepository localRepository ) - throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, - InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, - PluginVersionNotFoundException - { + public PluginDescriptor verifyPlugin( + Plugin plugin, MavenProject project, Settings settings, ArtifactRepository localRepository) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, + PluginNotFoundException, PluginVersionNotFoundException { MavenSession session = legacySupport.getSession(); - if ( plugin.getVersion() == null ) - { - PluginVersionRequest versionRequest = - new DefaultPluginVersionRequest( plugin, session.getRepositorySession(), - project.getRemotePluginRepositories() ); - plugin.setVersion( pluginVersionResolver.resolve( versionRequest ).getVersion() ); + if (plugin.getVersion() == null) { + PluginVersionRequest versionRequest = new DefaultPluginVersionRequest( + plugin, session.getRepositorySession(), project.getRemotePluginRepositories()); + plugin.setVersion(pluginVersionResolver.resolve(versionRequest).getVersion()); } - try - { - return pluginManager.getPluginDescriptor( plugin, project.getRemotePluginRepositories(), - session.getRepositorySession() ); - } - catch ( PluginResolutionException e ) - { - throw new PluginNotFoundException( plugin, project.getPluginArtifactRepositories() ); - } - catch ( PluginDescriptorParsingException | InvalidPluginDescriptorException e ) - { - throw new PluginManagerException( plugin, e.getMessage(), e ); + try { + return pluginManager.getPluginDescriptor( + plugin, project.getRemotePluginRepositories(), session.getRepositorySession()); + } catch (PluginResolutionException e) { + throw new PluginNotFoundException(plugin, project.getPluginArtifactRepositories()); + } catch (PluginDescriptorParsingException | InvalidPluginDescriptorException e) { + throw new PluginManagerException(plugin, e.getMessage(), e); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DeprecatedPluginValidator.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DeprecatedPluginValidator.java index 2f1291dd45..9027fce8b4 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DeprecatedPluginValidator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DeprecatedPluginValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; import org.apache.maven.shared.utils.logging.MessageUtils; @@ -37,64 +35,55 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -class DeprecatedPluginValidator extends AbstractMavenPluginParametersValidator -{ - private static final Logger LOGGER = LoggerFactory.getLogger( DeprecatedPluginValidator.class ); +class DeprecatedPluginValidator extends AbstractMavenPluginParametersValidator { + private static final Logger LOGGER = LoggerFactory.getLogger(DeprecatedPluginValidator.class); @Override - protected Logger getLogger() - { + protected Logger getLogger() { return LOGGER; } @Override - protected String getParameterLogReason( Parameter parameter ) - { + protected String getParameterLogReason(Parameter parameter) { return "is deprecated: " + parameter.getDeprecated(); } @Override - public void validate( MojoDescriptor mojoDescriptor, - PlexusConfiguration pomConfiguration, - ExpressionEvaluator expressionEvaluator ) - { - if ( !LOGGER.isWarnEnabled() ) - { + public void validate( + MojoDescriptor mojoDescriptor, + PlexusConfiguration pomConfiguration, + ExpressionEvaluator expressionEvaluator) { + if (!LOGGER.isWarnEnabled()) { return; } - if ( mojoDescriptor.getDeprecated() != null ) - { - logDeprecatedMojo( mojoDescriptor ); + if (mojoDescriptor.getDeprecated() != null) { + logDeprecatedMojo(mojoDescriptor); } mojoDescriptor.getParameters().stream() - .filter( parameter -> parameter.getDeprecated() != null ) - .filter( Parameter::isEditable ) - .forEach( parameter -> checkParameter( parameter, pomConfiguration, expressionEvaluator ) ); + .filter(parameter -> parameter.getDeprecated() != null) + .filter(Parameter::isEditable) + .forEach(parameter -> checkParameter(parameter, pomConfiguration, expressionEvaluator)); } - private void checkParameter( Parameter parameter, - PlexusConfiguration pomConfiguration, - ExpressionEvaluator expressionEvaluator ) - { - PlexusConfiguration config = pomConfiguration.getChild( parameter.getName(), false ); + private void checkParameter( + Parameter parameter, PlexusConfiguration pomConfiguration, ExpressionEvaluator expressionEvaluator) { + PlexusConfiguration config = pomConfiguration.getChild(parameter.getName(), false); - if ( isValueSet( config, expressionEvaluator ) ) - { - logParameter( parameter ); + if (isValueSet(config, expressionEvaluator)) { + logParameter(parameter); } } - private void logDeprecatedMojo( MojoDescriptor mojoDescriptor ) - { + private void logDeprecatedMojo(MojoDescriptor mojoDescriptor) { String message = MessageUtils.buffer() - .warning( "Goal '" ) - .warning( mojoDescriptor.getGoal() ) - .warning( "' is deprecated: " ) - .warning( mojoDescriptor.getDeprecated() ) - .toString(); + .warning("Goal '") + .warning(mojoDescriptor.getGoal()) + .warning("' is deprecated: ") + .warning(mojoDescriptor.getDeprecated()) + .toString(); - LOGGER.warn( message ); + LOGGER.warn(message); } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginConfigurationValidator.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginConfigurationValidator.java index 8252782d38..a79550c6fd 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginConfigurationValidator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginConfigurationValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; @@ -28,12 +27,12 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; * * @author Slawomir Jaranowski */ -interface MavenPluginConfigurationValidator -{ +interface MavenPluginConfigurationValidator { /** * Check mojo configuration. */ - void validate( MojoDescriptor mojoDescriptor, - PlexusConfiguration pomConfiguration, - ExpressionEvaluator expressionEvaluator ); + void validate( + MojoDescriptor mojoDescriptor, + PlexusConfiguration pomConfiguration, + ExpressionEvaluator expressionEvaluator); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginJavaPrerequisiteChecker.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginJavaPrerequisiteChecker.java index 234312494e..618d461811 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginJavaPrerequisiteChecker.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginJavaPrerequisiteChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.model.profile.activation.JdkVersionProfileActivator; import org.apache.maven.plugin.MavenPluginPrerequisitesChecker; import org.apache.maven.plugin.descriptor.PluginDescriptor; @@ -29,24 +27,17 @@ import org.codehaus.plexus.util.StringUtils; @Named @Singleton -public class MavenPluginJavaPrerequisiteChecker - implements MavenPluginPrerequisitesChecker -{ +public class MavenPluginJavaPrerequisiteChecker implements MavenPluginPrerequisitesChecker { @Override - public void accept( PluginDescriptor pluginDescriptor ) - { + public void accept(PluginDescriptor pluginDescriptor) { String requiredJavaVersion = pluginDescriptor.getRequiredJavaVersion(); - if ( StringUtils.isNotBlank( requiredJavaVersion ) ) - { - String currentJavaVersion = System.getProperty( "java.version" ); - if ( !JdkVersionProfileActivator.isJavaVersionCompatible( requiredJavaVersion, - currentJavaVersion ) ) - { - throw new IllegalStateException( "Required Java version " + requiredJavaVersion - + " is not met by current version: " + currentJavaVersion ); + if (StringUtils.isNotBlank(requiredJavaVersion)) { + String currentJavaVersion = System.getProperty("java.version"); + if (!JdkVersionProfileActivator.isJavaVersionCompatible(requiredJavaVersion, currentJavaVersion)) { + throw new IllegalStateException("Required Java version " + requiredJavaVersion + + " is not met by current version: " + currentJavaVersion); } } } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginMavenPrerequisiteChecker.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginMavenPrerequisiteChecker.java index 9d480615ab..d350e4bc86 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginMavenPrerequisiteChecker.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginMavenPrerequisiteChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.plugin.MavenPluginPrerequisitesChecker; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.rtinfo.RuntimeInformation; @@ -32,44 +30,34 @@ import org.slf4j.LoggerFactory; @Named @Singleton -public class MavenPluginMavenPrerequisiteChecker - implements MavenPluginPrerequisitesChecker -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class MavenPluginMavenPrerequisiteChecker implements MavenPluginPrerequisitesChecker { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final RuntimeInformation runtimeInformation; @Inject - public MavenPluginMavenPrerequisiteChecker( RuntimeInformation runtimeInformation ) - { + public MavenPluginMavenPrerequisiteChecker(RuntimeInformation runtimeInformation) { super(); this.runtimeInformation = runtimeInformation; } @Override - public void accept( PluginDescriptor pluginDescriptor ) - { + public void accept(PluginDescriptor pluginDescriptor) { String requiredMavenVersion = pluginDescriptor.getRequiredMavenVersion(); - if ( StringUtils.isNotBlank( requiredMavenVersion ) ) - { + if (StringUtils.isNotBlank(requiredMavenVersion)) { boolean isRequirementMet = false; - try - { - isRequirementMet = runtimeInformation.isMavenVersion( requiredMavenVersion ); - } - catch ( IllegalArgumentException e ) - { - logger.warn( "Could not verify plugin's Maven prerequisite as an invalid version is given in " - + requiredMavenVersion, e ); + try { + isRequirementMet = runtimeInformation.isMavenVersion(requiredMavenVersion); + } catch (IllegalArgumentException e) { + logger.warn( + "Could not verify plugin's Maven prerequisite as an invalid version is given in " + + requiredMavenVersion, + e); return; } - if ( !isRequirementMet ) - { - throw new IllegalStateException( - "Required Maven version " + requiredMavenVersion - + " is not met by current version " + runtimeInformation.getMavenVersion() ); + if (!isRequirementMet) { + throw new IllegalStateException("Required Maven version " + requiredMavenVersion + + " is not met by current version " + runtimeInformation.getMavenVersion()); } } } - - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginValidator.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginValidator.java index 2e36b4b6aa..86e79d1023 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginValidator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.List; import org.apache.maven.artifact.Artifact; @@ -26,9 +25,7 @@ import org.apache.maven.plugin.descriptor.PluginDescriptor; /** * MavenPluginValidator */ -interface MavenPluginValidator -{ - - void validate( Artifact pluginArtifact, PluginDescriptor pluginDescriptor, List errors ); +interface MavenPluginValidator { + void validate(Artifact pluginArtifact, PluginDescriptor pluginDescriptor, List errors); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/MojoLogWrapper.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/MojoLogWrapper.java index 060dffdbd8..2b8b4bbe30 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/MojoLogWrapper.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/MojoLogWrapper.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,129 +16,107 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; + +import static java.util.Objects.requireNonNull; import org.apache.maven.plugin.logging.Log; import org.slf4j.Logger; -import static java.util.Objects.requireNonNull; - /** * @author jdcasey */ -public class MojoLogWrapper - implements Log -{ +public class MojoLogWrapper implements Log { private final Logger logger; - public MojoLogWrapper( Logger logger ) - { - this.logger = requireNonNull( logger ); + public MojoLogWrapper(Logger logger) { + this.logger = requireNonNull(logger); } - public void debug( CharSequence content ) - { - logger.debug( toString( content ) ); + public void debug(CharSequence content) { + logger.debug(toString(content)); } - private String toString( CharSequence content ) - { - if ( content == null ) - { + private String toString(CharSequence content) { + if (content == null) { return ""; - } - else - { + } else { return content.toString(); } } @Override - public void debug( CharSequence content, Throwable error ) - { - logger.debug( toString( content ), error ); + public void debug(CharSequence content, Throwable error) { + logger.debug(toString(content), error); } @Override - public void debug( Throwable error ) - { - logger.debug( "", error ); + public void debug(Throwable error) { + logger.debug("", error); } @Override - public void info( CharSequence content ) - { - logger.info( toString( content ) ); + public void info(CharSequence content) { + logger.info(toString(content)); } @Override - public void info( CharSequence content, Throwable error ) - { - logger.info( toString( content ), error ); + public void info(CharSequence content, Throwable error) { + logger.info(toString(content), error); } @Override - public void info( Throwable error ) - { - logger.info( "", error ); + public void info(Throwable error) { + logger.info("", error); } @Override - public void warn( CharSequence content ) - { - logger.warn( toString( content ) ); + public void warn(CharSequence content) { + logger.warn(toString(content)); } @Override - public void warn( CharSequence content, Throwable error ) - { - logger.warn( toString( content ), error ); + public void warn(CharSequence content, Throwable error) { + logger.warn(toString(content), error); } @Override - public void warn( Throwable error ) - { - logger.warn( "", error ); + public void warn(Throwable error) { + logger.warn("", error); } @Override - public void error( CharSequence content ) - { - logger.error( toString( content ) ); + public void error(CharSequence content) { + logger.error(toString(content)); } @Override - public void error( CharSequence content, Throwable error ) - { - logger.error( toString( content ), error ); + public void error(CharSequence content, Throwable error) { + logger.error(toString(content), error); } @Override - public void error( Throwable error ) - { - logger.error( "", error ); + public void error(Throwable error) { + logger.error("", error); } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return logger.isErrorEnabled(); } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/PluginDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/PluginDependenciesResolver.java index 4194297897..d76f603447 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/PluginDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/PluginDependenciesResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.List; - import org.apache.maven.model.Plugin; import org.apache.maven.plugin.PluginResolutionException; import org.eclipse.aether.RepositorySystemSession; @@ -37,8 +35,7 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginDependenciesResolver -{ +public interface PluginDependenciesResolver { /** * Resolves the main artifact of the specified plugin. @@ -50,8 +47,8 @@ public interface PluginDependenciesResolver * @return The resolved plugin artifact, never {@code null}. * @throws PluginResolutionException If the plugin artifact could not be resolved. */ - Artifact resolve( Plugin plugin, List repositories, RepositorySystemSession session ) - throws PluginResolutionException; + Artifact resolve(Plugin plugin, List repositories, RepositorySystemSession session) + throws PluginResolutionException; /** * Resolves the runtime dependencies of the specified plugin. @@ -64,8 +61,11 @@ public interface PluginDependenciesResolver * @return The dependency tree denoting the resolved plugin class path, never {@code null}. * @throws PluginResolutionException If any dependency could not be resolved. */ - DependencyNode resolve( Plugin plugin, Artifact pluginArtifact, DependencyFilter dependencyFilter, - List repositories, RepositorySystemSession session ) - throws PluginResolutionException; - + DependencyNode resolve( + Plugin plugin, + Artifact pluginArtifact, + DependencyFilter dependencyFilter, + List repositories, + RepositorySystemSession session) + throws PluginResolutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator.java index 15419378fb..07f0325a70 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; @@ -36,45 +34,39 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class ReadOnlyPluginParametersValidator extends AbstractMavenPluginParametersValidator -{ - private static final Logger LOGGER = LoggerFactory.getLogger( ReadOnlyPluginParametersValidator.class ); +public class ReadOnlyPluginParametersValidator extends AbstractMavenPluginParametersValidator { + private static final Logger LOGGER = LoggerFactory.getLogger(ReadOnlyPluginParametersValidator.class); @Override - protected Logger getLogger() - { + protected Logger getLogger() { return LOGGER; } @Override - protected String getParameterLogReason( Parameter parameter ) - { + protected String getParameterLogReason(Parameter parameter) { return "is read-only, must not be used in configuration"; } @Override - public void validate( MojoDescriptor mojoDescriptor, PlexusConfiguration pomConfiguration, - ExpressionEvaluator expressionEvaluator ) - { - if ( !LOGGER.isWarnEnabled() ) - { + public void validate( + MojoDescriptor mojoDescriptor, + PlexusConfiguration pomConfiguration, + ExpressionEvaluator expressionEvaluator) { + if (!LOGGER.isWarnEnabled()) { return; } mojoDescriptor.getParameters().stream() - .filter( parameter -> !parameter.isEditable() ) - .forEach( parameter -> checkParameter( parameter, pomConfiguration, expressionEvaluator ) ); + .filter(parameter -> !parameter.isEditable()) + .forEach(parameter -> checkParameter(parameter, pomConfiguration, expressionEvaluator)); } - protected void checkParameter( Parameter parameter, - PlexusConfiguration pomConfiguration, - ExpressionEvaluator expressionEvaluator ) - { - PlexusConfiguration config = pomConfiguration.getChild( parameter.getName(), false ); + protected void checkParameter( + Parameter parameter, PlexusConfiguration pomConfiguration, ExpressionEvaluator expressionEvaluator) { + PlexusConfiguration config = pomConfiguration.getChild(parameter.getName(), false); - if ( isValueSet( config, expressionEvaluator ) ) - { - logParameter( parameter ); + if (isValueSet(config, expressionEvaluator)) { + logParameter(parameter); } } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/ValidatingConfigurationListener.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/ValidatingConfigurationListener.java index c04f44821e..a4f4f4a04e 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/ValidatingConfigurationListener.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/ValidatingConfigurationListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; import java.util.Collection; import java.util.HashMap; import java.util.Map; - import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; import org.codehaus.plexus.component.configurator.ConfigurationListener; @@ -33,63 +31,50 @@ import org.codehaus.plexus.component.configurator.ConfigurationListener; * * @author Benjamin Bentmann */ -class ValidatingConfigurationListener - implements ConfigurationListener -{ +class ValidatingConfigurationListener implements ConfigurationListener { private final Object mojo; private final ConfigurationListener delegate; private final Map missingParameters; - ValidatingConfigurationListener( Object mojo, MojoDescriptor mojoDescriptor, ConfigurationListener delegate ) - { + ValidatingConfigurationListener(Object mojo, MojoDescriptor mojoDescriptor, ConfigurationListener delegate) { this.mojo = mojo; this.delegate = delegate; this.missingParameters = new HashMap<>(); - if ( mojoDescriptor.getParameters() != null ) - { - for ( Parameter param : mojoDescriptor.getParameters() ) - { - if ( param.isRequired() ) - { - missingParameters.put( param.getName(), param ); + if (mojoDescriptor.getParameters() != null) { + for (Parameter param : mojoDescriptor.getParameters()) { + if (param.isRequired()) { + missingParameters.put(param.getName(), param); } } } } - public Collection getMissingParameters() - { + public Collection getMissingParameters() { return missingParameters.values(); } - public void notifyFieldChangeUsingSetter( String fieldName, Object value, Object target ) - { - delegate.notifyFieldChangeUsingSetter( fieldName, value, target ); + public void notifyFieldChangeUsingSetter(String fieldName, Object value, Object target) { + delegate.notifyFieldChangeUsingSetter(fieldName, value, target); - if ( mojo == target ) - { - notify( fieldName, value ); + if (mojo == target) { + notify(fieldName, value); } } - public void notifyFieldChangeUsingReflection( String fieldName, Object value, Object target ) - { - delegate.notifyFieldChangeUsingReflection( fieldName, value, target ); + public void notifyFieldChangeUsingReflection(String fieldName, Object value, Object target) { + delegate.notifyFieldChangeUsingReflection(fieldName, value, target); - if ( mojo == target ) - { - notify( fieldName, value ); + if (mojo == target) { + notify(fieldName, value); } } - private void notify( String fieldName, Object value ) - { - if ( value != null ) - { - missingParameters.remove( fieldName ); + private void notify(String fieldName, Object value) { + if (value != null) { + missingParameters.remove(fieldName); } } } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/DefaultPluginPrefixRequest.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/DefaultPluginPrefixRequest.java index 01194c866d..8113eb5f82 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/DefaultPluginPrefixRequest.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/DefaultPluginPrefixRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.plugin.prefix; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix; import java.util.Collections; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.project.MavenProject; @@ -34,9 +32,7 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public class DefaultPluginPrefixRequest - implements PluginPrefixRequest -{ +public class DefaultPluginPrefixRequest implements PluginPrefixRequest { private String prefix; @@ -51,9 +47,7 @@ public class DefaultPluginPrefixRequest /** * Creates an empty request. */ - public DefaultPluginPrefixRequest() - { - } + public DefaultPluginPrefixRequest() {} /** * Creates a request for the specified plugin prefix and build session. The provided build session will be used to @@ -63,94 +57,75 @@ public class DefaultPluginPrefixRequest * @param prefix The plugin prefix to resolve, must not be {@code null}. * @param session The build session from which to derive further settings, must not be {@code null}. */ - public DefaultPluginPrefixRequest( String prefix, MavenSession session ) - { - setPrefix( prefix ); + public DefaultPluginPrefixRequest(String prefix, MavenSession session) { + setPrefix(prefix); - setRepositorySession( session.getRepositorySession() ); + setRepositorySession(session.getRepositorySession()); MavenProject project = session.getCurrentProject(); - if ( project != null ) - { - setRepositories( project.getRemotePluginRepositories() ); - setPom( project.getModel() ); + if (project != null) { + setRepositories(project.getRemotePluginRepositories()); + setPom(project.getModel()); } - setPluginGroups( session.getPluginGroups() ); + setPluginGroups(session.getPluginGroups()); } - public String getPrefix() - { + public String getPrefix() { return prefix; } - public DefaultPluginPrefixRequest setPrefix( String prefix ) - { + public DefaultPluginPrefixRequest setPrefix(String prefix) { this.prefix = prefix; return this; } - public List getPluginGroups() - { + public List getPluginGroups() { return pluginGroups; } - public DefaultPluginPrefixRequest setPluginGroups( List pluginGroups ) - { - if ( pluginGroups != null ) - { - this.pluginGroups = Collections.unmodifiableList( pluginGroups ); - } - else - { + public DefaultPluginPrefixRequest setPluginGroups(List pluginGroups) { + if (pluginGroups != null) { + this.pluginGroups = Collections.unmodifiableList(pluginGroups); + } else { this.pluginGroups = Collections.emptyList(); } return this; } - public Model getPom() - { + public Model getPom() { return pom; } - public DefaultPluginPrefixRequest setPom( Model pom ) - { + public DefaultPluginPrefixRequest setPom(Model pom) { this.pom = pom; return this; } - public List getRepositories() - { + public List getRepositories() { return repositories; } - public DefaultPluginPrefixRequest setRepositories( List repositories ) - { - if ( repositories != null ) - { - this.repositories = Collections.unmodifiableList( repositories ); - } - else - { + public DefaultPluginPrefixRequest setRepositories(List repositories) { + if (repositories != null) { + this.repositories = Collections.unmodifiableList(repositories); + } else { this.repositories = Collections.emptyList(); } return this; } - public RepositorySystemSession getRepositorySession() - { + public RepositorySystemSession getRepositorySession() { return session; } - public DefaultPluginPrefixRequest setRepositorySession( RepositorySystemSession session ) - { + public DefaultPluginPrefixRequest setRepositorySession(RepositorySystemSession session) { this.session = session; return this; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/NoPluginFoundForPrefixException.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/NoPluginFoundForPrefixException.java index de53d51e6b..9a6d7e363e 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/NoPluginFoundForPrefixException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/NoPluginFoundForPrefixException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.prefix; * "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 + * 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 @@ -18,51 +16,51 @@ package org.apache.maven.plugin.prefix; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix; import java.util.List; - import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.RemoteRepository; /** * NoPluginFoundForPrefixException */ -public class NoPluginFoundForPrefixException - extends Exception -{ +public class NoPluginFoundForPrefixException extends Exception { - public NoPluginFoundForPrefixException( String prefix, List pluginGroups, LocalRepository localRepository, - List remoteRepositories ) - { - super( "No plugin found for prefix '" + prefix + "' in the current project and in the plugin groups " - + pluginGroups + " available from the repositories " + format( localRepository, remoteRepositories ) ); + public NoPluginFoundForPrefixException( + String prefix, + List pluginGroups, + LocalRepository localRepository, + List remoteRepositories) { + super("No plugin found for prefix '" + prefix + "' in the current project and in the plugin groups " + + pluginGroups + " available from the repositories " + format(localRepository, remoteRepositories)); } - private static String format( LocalRepository localRepository, List remoteRepositories ) - { - StringBuilder repos = new StringBuilder( "[" ); + private static String format(LocalRepository localRepository, List remoteRepositories) { + StringBuilder repos = new StringBuilder("["); - if ( localRepository != null ) - { - repos.append( localRepository.getId() ).append( " (" ).append( localRepository.getBasedir() ).append( ")" ); + if (localRepository != null) { + repos.append(localRepository.getId()) + .append(" (") + .append(localRepository.getBasedir()) + .append(")"); } - if ( remoteRepositories != null && !remoteRepositories.isEmpty() ) - { - for ( RemoteRepository repository : remoteRepositories ) - { - repos.append( ", " ); + if (remoteRepositories != null && !remoteRepositories.isEmpty()) { + for (RemoteRepository repository : remoteRepositories) { + repos.append(", "); - if ( repository != null ) - { - repos.append( repository.getId() ).append( " (" ).append( repository.getUrl() ).append( ")" ); + if (repository != null) { + repos.append(repository.getId()) + .append(" (") + .append(repository.getUrl()) + .append(")"); } } } - repos.append( "]" ); + repos.append("]"); return repos.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixRequest.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixRequest.java index 23df66eeb1..93bd47a800 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixRequest.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin.prefix; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix; import java.util.List; - import org.apache.maven.model.Model; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -31,8 +29,7 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginPrefixRequest -{ +public interface PluginPrefixRequest { /** * Gets the prefix of the plugin. @@ -47,7 +44,7 @@ public interface PluginPrefixRequest * @param prefix The prefix of the plugin. * @return This request, never {@code null}. */ - PluginPrefixRequest setPrefix( String prefix ); + PluginPrefixRequest setPrefix(String prefix); /** * Gets the list of group ids to scan for the plugin prefix. @@ -62,7 +59,7 @@ public interface PluginPrefixRequest * @param pluginGroups The list of group ids to scan for the plugin prefix, may be {@code null}. * @return This request, never {@code null}. */ - PluginPrefixRequest setPluginGroups( List pluginGroups ); + PluginPrefixRequest setPluginGroups(List pluginGroups); /** * Gets the POM whose build plugins are to be scanned for the prefix. @@ -79,7 +76,7 @@ public interface PluginPrefixRequest * plugin repositories. * @return This request, never {@code null}. */ - PluginPrefixRequest setPom( Model pom ); + PluginPrefixRequest setPom(Model pom); /** * Gets the remote repositories to use. @@ -95,7 +92,7 @@ public interface PluginPrefixRequest * @param repositories The remote repositories to use. * @return This request, never {@code null}. */ - PluginPrefixRequest setRepositories( List repositories ); + PluginPrefixRequest setRepositories(List repositories); /** * Gets the session to use for repository access. @@ -110,6 +107,5 @@ public interface PluginPrefixRequest * @param repositorySession The repository session to use. * @return This request, never {@code null}. */ - PluginPrefixRequest setRepositorySession( RepositorySystemSession repositorySession ); - + PluginPrefixRequest setRepositorySession(RepositorySystemSession repositorySession); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResolver.java index 943e683308..b72e54ced1 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin.prefix; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix; /** * Resolves a plugin prefix. @@ -25,8 +24,7 @@ package org.apache.maven.plugin.prefix; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginPrefixResolver -{ +public interface PluginPrefixResolver { /** * Resolves the plugin prefix for the specified request. @@ -36,7 +34,5 @@ public interface PluginPrefixResolver * @return The result of the prefix resolution, never {@code null}. * @throws NoPluginFoundForPrefixException If the plugin prefix could not be resolved. */ - PluginPrefixResult resolve( PluginPrefixRequest request ) - throws NoPluginFoundForPrefixException; - + PluginPrefixResult resolve(PluginPrefixRequest request) throws NoPluginFoundForPrefixException; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResult.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResult.java index 8fe1a71af8..a28e12a4ec 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResult.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/PluginPrefixResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.prefix; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.plugin.prefix; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix; import org.eclipse.aether.repository.ArtifactRepository; @@ -27,8 +26,7 @@ import org.eclipse.aether.repository.ArtifactRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginPrefixResult -{ +public interface PluginPrefixResult { /** * The resolved group id for the plugin. @@ -51,5 +49,4 @@ public interface PluginPrefixResult * the supplied POM. */ ArtifactRepository getRepository(); - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver.java index ef2cd83fdf..9e24594ee3 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,16 @@ package org.apache.maven.plugin.prefix.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix.internal; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.io.MetadataReader; import org.apache.maven.model.Build; @@ -63,103 +60,82 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultPluginPrefixResolver - implements PluginPrefixResolver -{ +public class DefaultPluginPrefixResolver implements PluginPrefixResolver { private static final String REPOSITORY_CONTEXT = "plugin"; - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final BuildPluginManager pluginManager; private final RepositorySystem repositorySystem; private final MetadataReader metadataReader; @Inject public DefaultPluginPrefixResolver( - BuildPluginManager pluginManager, - RepositorySystem repositorySystem, - MetadataReader metadataReader ) - { + BuildPluginManager pluginManager, RepositorySystem repositorySystem, MetadataReader metadataReader) { this.pluginManager = pluginManager; this.repositorySystem = repositorySystem; this.metadataReader = metadataReader; } - public PluginPrefixResult resolve( PluginPrefixRequest request ) - throws NoPluginFoundForPrefixException - { - logger.debug( "Resolving plugin prefix " + request.getPrefix() + " from " + request.getPluginGroups() ); + public PluginPrefixResult resolve(PluginPrefixRequest request) throws NoPluginFoundForPrefixException { + logger.debug("Resolving plugin prefix " + request.getPrefix() + " from " + request.getPluginGroups()); - PluginPrefixResult result = resolveFromProject( request ); + PluginPrefixResult result = resolveFromProject(request); - if ( result == null ) - { - result = resolveFromRepository( request ); + if (result == null) { + result = resolveFromRepository(request); - if ( result == null ) - { - throw new NoPluginFoundForPrefixException( request.getPrefix(), request.getPluginGroups(), - request.getRepositorySession().getLocalRepository(), - request.getRepositories() ); + if (result == null) { + throw new NoPluginFoundForPrefixException( + request.getPrefix(), + request.getPluginGroups(), + request.getRepositorySession().getLocalRepository(), + request.getRepositories()); + } else if (logger.isDebugEnabled()) { + logger.debug("Resolved plugin prefix " + request.getPrefix() + " to " + result.getGroupId() + ":" + + result.getArtifactId() + " from repository " + + (result.getRepository() != null + ? result.getRepository().getId() + : "null")); } - else if ( logger.isDebugEnabled() ) - { - logger.debug( "Resolved plugin prefix " + request.getPrefix() + " to " + result.getGroupId() + ":" - + result.getArtifactId() + " from repository " - + ( result.getRepository() != null ? result.getRepository().getId() : "null" ) ); - } - } - else if ( logger.isDebugEnabled() ) - { - logger.debug( "Resolved plugin prefix " + request.getPrefix() + " to " + result.getGroupId() + ":" - + result.getArtifactId() + " from POM " + request.getPom() ); + } else if (logger.isDebugEnabled()) { + logger.debug("Resolved plugin prefix " + request.getPrefix() + " to " + result.getGroupId() + ":" + + result.getArtifactId() + " from POM " + request.getPom()); } return result; } - private PluginPrefixResult resolveFromProject( PluginPrefixRequest request ) - { + private PluginPrefixResult resolveFromProject(PluginPrefixRequest request) { PluginPrefixResult result = null; - if ( request.getPom() != null && request.getPom().getBuild() != null ) - { + if (request.getPom() != null && request.getPom().getBuild() != null) { Build build = request.getPom().getBuild(); - result = resolveFromProject( request, build.getPlugins() ); + result = resolveFromProject(request, build.getPlugins()); - if ( result == null && build.getPluginManagement() != null ) - { - result = resolveFromProject( request, build.getPluginManagement().getPlugins() ); + if (result == null && build.getPluginManagement() != null) { + result = resolveFromProject(request, build.getPluginManagement().getPlugins()); } } return result; } - private PluginPrefixResult resolveFromProject( PluginPrefixRequest request, List plugins ) - { - for ( Plugin plugin : plugins ) - { - try - { + private PluginPrefixResult resolveFromProject(PluginPrefixRequest request, List plugins) { + for (Plugin plugin : plugins) { + try { PluginDescriptor pluginDescriptor = - pluginManager.loadPlugin( plugin, request.getRepositories(), request.getRepositorySession() ); + pluginManager.loadPlugin(plugin, request.getRepositories(), request.getRepositorySession()); - if ( request.getPrefix().equals( pluginDescriptor.getGoalPrefix() ) ) - { - return new DefaultPluginPrefixResult( plugin ); + if (request.getPrefix().equals(pluginDescriptor.getGoalPrefix())) { + return new DefaultPluginPrefixResult(plugin); } - } - catch ( Exception e ) - { - if ( logger.isDebugEnabled() ) - { - logger.warn( "Failed to retrieve plugin descriptor for " + plugin.getId() + ": " + e.getMessage(), - e ); - } - else - { - logger.warn( "Failed to retrieve plugin descriptor for " + plugin.getId() + ": " + e.getMessage() ); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.warn( + "Failed to retrieve plugin descriptor for " + plugin.getId() + ": " + e.getMessage(), e); + } else { + logger.warn("Failed to retrieve plugin descriptor for " + plugin.getId() + ": " + e.getMessage()); } } } @@ -167,135 +143,120 @@ public class DefaultPluginPrefixResolver return null; } - private PluginPrefixResult resolveFromRepository( PluginPrefixRequest request ) - { - RequestTrace trace = RequestTrace.newChild( null, request ); + private PluginPrefixResult resolveFromRepository(PluginPrefixRequest request) { + RequestTrace trace = RequestTrace.newChild(null, request); List requests = new ArrayList<>(); - for ( String pluginGroup : request.getPluginGroups() ) - { + for (String pluginGroup : request.getPluginGroups()) { org.eclipse.aether.metadata.Metadata metadata = - new DefaultMetadata( pluginGroup, "maven-metadata.xml", DefaultMetadata.Nature.RELEASE_OR_SNAPSHOT ); + new DefaultMetadata(pluginGroup, "maven-metadata.xml", DefaultMetadata.Nature.RELEASE_OR_SNAPSHOT); - requests.add( new MetadataRequest( metadata, null, REPOSITORY_CONTEXT ).setTrace( trace ) ); + requests.add(new MetadataRequest(metadata, null, REPOSITORY_CONTEXT).setTrace(trace)); - for ( RemoteRepository repository : request.getRepositories() ) - { - requests.add( new MetadataRequest( metadata, repository, REPOSITORY_CONTEXT ).setTrace( trace ) ); + for (RemoteRepository repository : request.getRepositories()) { + requests.add(new MetadataRequest(metadata, repository, REPOSITORY_CONTEXT).setTrace(trace)); } } // initial try, use locally cached metadata - List results = repositorySystem.resolveMetadata( request.getRepositorySession(), requests ); + List results = repositorySystem.resolveMetadata(request.getRepositorySession(), requests); requests.clear(); - PluginPrefixResult result = processResults( request, trace, results, requests ); + PluginPrefixResult result = processResults(request, trace, results, requests); - if ( result != null ) - { + if (result != null) { return result; } // second try, refetch all (possibly outdated) metadata that wasn't updated in the first attempt - if ( !request.getRepositorySession().isOffline() && !requests.isEmpty() ) - { - DefaultRepositorySystemSession session = - new DefaultRepositorySystemSession( request.getRepositorySession() ); - session.setUpdatePolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); + if (!request.getRepositorySession().isOffline() && !requests.isEmpty()) { + DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(request.getRepositorySession()); + session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); - results = repositorySystem.resolveMetadata( session, requests ); + results = repositorySystem.resolveMetadata(session, requests); - return processResults( request, trace, results, null ); + return processResults(request, trace, results, null); } return null; } - private PluginPrefixResult processResults( PluginPrefixRequest request, RequestTrace trace, - List results, List requests ) - { - for ( MetadataResult res : results ) - { + private PluginPrefixResult processResults( + PluginPrefixRequest request, + RequestTrace trace, + List results, + List requests) { + for (MetadataResult res : results) { org.eclipse.aether.metadata.Metadata metadata = res.getMetadata(); - if ( metadata != null ) - { + if (metadata != null) { ArtifactRepository repository = res.getRequest().getRepository(); - if ( repository == null ) - { + if (repository == null) { repository = request.getRepositorySession().getLocalRepository(); } PluginPrefixResult result = - resolveFromRepository( request, trace, metadata.getGroupId(), metadata, repository ); + resolveFromRepository(request, trace, metadata.getGroupId(), metadata, repository); - if ( result != null ) - { + if (result != null) { return result; } } - if ( requests != null && !res.isUpdated() ) - { - requests.add( res.getRequest() ); + if (requests != null && !res.isUpdated()) { + requests.add(res.getRequest()); } } return null; } - private PluginPrefixResult resolveFromRepository( PluginPrefixRequest request, RequestTrace trace, - String pluginGroup, - org.eclipse.aether.metadata.Metadata metadata, - ArtifactRepository repository ) - { - if ( metadata != null && metadata.getFile() != null && metadata.getFile().isFile() ) - { - try - { - Map options = Collections.singletonMap( MetadataReader.IS_STRICT, Boolean.FALSE ); + private PluginPrefixResult resolveFromRepository( + PluginPrefixRequest request, + RequestTrace trace, + String pluginGroup, + org.eclipse.aether.metadata.Metadata metadata, + ArtifactRepository repository) { + if (metadata != null && metadata.getFile() != null && metadata.getFile().isFile()) { + try { + Map options = Collections.singletonMap(MetadataReader.IS_STRICT, Boolean.FALSE); - Metadata pluginGroupMetadata = metadataReader.read( metadata.getFile(), options ); + Metadata pluginGroupMetadata = metadataReader.read(metadata.getFile(), options); List plugins = pluginGroupMetadata.getPlugins(); - if ( plugins != null ) - { - for ( org.apache.maven.artifact.repository.metadata.Plugin plugin : plugins ) - { - if ( request.getPrefix().equals( plugin.getPrefix() ) ) - { - return new DefaultPluginPrefixResult( pluginGroup, plugin.getArtifactId(), repository ); + if (plugins != null) { + for (org.apache.maven.artifact.repository.metadata.Plugin plugin : plugins) { + if (request.getPrefix().equals(plugin.getPrefix())) { + return new DefaultPluginPrefixResult(pluginGroup, plugin.getArtifactId(), repository); } } } - } - catch ( IOException e ) - { - invalidMetadata( request.getRepositorySession(), trace, metadata, repository, e ); + } catch (IOException e) { + invalidMetadata(request.getRepositorySession(), trace, metadata, repository, e); } } return null; } - private void invalidMetadata( RepositorySystemSession session, RequestTrace trace, - org.eclipse.aether.metadata.Metadata metadata, ArtifactRepository repository, - Exception exception ) - { + private void invalidMetadata( + RepositorySystemSession session, + RequestTrace trace, + org.eclipse.aether.metadata.Metadata metadata, + ArtifactRepository repository, + Exception exception) { RepositoryListener listener = session.getRepositoryListener(); - if ( listener != null ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_INVALID ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setException( exception ); - event.setRepository( repository ); - listener.metadataInvalid( event.build() ); + if (listener != null) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INVALID); + event.setTrace(trace); + event.setMetadata(metadata); + event.setException(exception); + event.setRepository(repository); + listener.metadataInvalid(event.build()); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResult.java b/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResult.java index 2adc6f37cc..aaa2f263d3 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResult.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.prefix.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin.prefix.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.prefix.internal; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.prefix.PluginPrefixResult; @@ -29,9 +28,7 @@ import org.eclipse.aether.repository.ArtifactRepository; * @since 3.0 * @author Benjamin Bentmann */ -class DefaultPluginPrefixResult - implements PluginPrefixResult -{ +class DefaultPluginPrefixResult implements PluginPrefixResult { private String groupId; @@ -39,52 +36,42 @@ class DefaultPluginPrefixResult private ArtifactRepository repository; - DefaultPluginPrefixResult() - { + DefaultPluginPrefixResult() { // does nothing } - DefaultPluginPrefixResult( Plugin plugin ) - { + DefaultPluginPrefixResult(Plugin plugin) { groupId = plugin.getGroupId(); artifactId = plugin.getArtifactId(); } - DefaultPluginPrefixResult( String groupId, String artifactId, ArtifactRepository repository ) - { + DefaultPluginPrefixResult(String groupId, String artifactId, ArtifactRepository repository) { this.groupId = groupId; this.artifactId = artifactId; this.repository = repository; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } - public void setRepository( ArtifactRepository repository ) - { + public void setRepository(ArtifactRepository repository) { this.repository = repository; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/DefaultPluginVersionRequest.java b/maven-core/src/main/java/org/apache/maven/plugin/version/DefaultPluginVersionRequest.java index 57f4250c63..af46eb18dd 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/DefaultPluginVersionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/DefaultPluginVersionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.plugin.version; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version; import java.util.Collections; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -35,9 +33,7 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public class DefaultPluginVersionRequest - implements PluginVersionRequest -{ +public class DefaultPluginVersionRequest implements PluginVersionRequest { private String groupId; @@ -52,9 +48,7 @@ public class DefaultPluginVersionRequest /** * Creates an empty request. */ - public DefaultPluginVersionRequest() - { - } + public DefaultPluginVersionRequest() {} /** * Creates a request for the specified plugin by copying settings from the specified build session. If the session @@ -63,17 +57,15 @@ public class DefaultPluginVersionRequest * @param plugin The plugin for which to resolve a version, must not be {@code null}. * @param session The Maven session to use, must not be {@code null}. */ - public DefaultPluginVersionRequest( Plugin plugin, MavenSession session ) - { - setGroupId( plugin.getGroupId() ); - setArtifactId( plugin.getArtifactId() ); + public DefaultPluginVersionRequest(Plugin plugin, MavenSession session) { + setGroupId(plugin.getGroupId()); + setArtifactId(plugin.getArtifactId()); - setRepositorySession( session.getRepositorySession() ); + setRepositorySession(session.getRepositorySession()); MavenProject project = session.getCurrentProject(); - if ( project != null ) - { - setRepositories( project.getRemotePluginRepositories() ); + if (project != null) { + setRepositories(project.getRemotePluginRepositories()); } } @@ -84,82 +76,67 @@ public class DefaultPluginVersionRequest * @param session The repository session to use, must not be {@code null}. * @param repositories The plugin repositories to query, may be {@code null}. */ - public DefaultPluginVersionRequest( Plugin plugin, RepositorySystemSession session, - List repositories ) - { - setGroupId( plugin.getGroupId() ); - setArtifactId( plugin.getArtifactId() ); + public DefaultPluginVersionRequest( + Plugin plugin, RepositorySystemSession session, List repositories) { + setGroupId(plugin.getGroupId()); + setArtifactId(plugin.getArtifactId()); - setRepositorySession( session ); + setRepositorySession(session); - setRepositories( repositories ); + setRepositories(repositories); } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public DefaultPluginVersionRequest setGroupId( String groupId ) - { + public DefaultPluginVersionRequest setGroupId(String groupId) { this.groupId = groupId; return this; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public DefaultPluginVersionRequest setArtifactId( String artifactId ) - { + public DefaultPluginVersionRequest setArtifactId(String artifactId) { this.artifactId = artifactId; return this; } - public Model getPom() - { + public Model getPom() { return pom; } - public DefaultPluginVersionRequest setPom( Model pom ) - { + public DefaultPluginVersionRequest setPom(Model pom) { this.pom = pom; return this; } - public List getRepositories() - { + public List getRepositories() { return repositories; } - public DefaultPluginVersionRequest setRepositories( List repositories ) - { - if ( repositories != null ) - { - this.repositories = Collections.unmodifiableList( repositories ); - } - else - { + public DefaultPluginVersionRequest setRepositories(List repositories) { + if (repositories != null) { + this.repositories = Collections.unmodifiableList(repositories); + } else { this.repositories = Collections.emptyList(); } return this; } - public RepositorySystemSession getRepositorySession() - { + public RepositorySystemSession getRepositorySession() { return session; } - public DefaultPluginVersionRequest setRepositorySession( RepositorySystemSession session ) - { + public DefaultPluginVersionRequest setRepositorySession(RepositorySystemSession session) { this.session = session; return this; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionNotFoundException.java b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionNotFoundException.java index b4864fc5d8..8299b8b006 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionNotFoundException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionNotFoundException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.version; * "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 + * 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 @@ -18,33 +16,28 @@ package org.apache.maven.plugin.version; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version; /** * PluginVersionNotFoundException */ -public class PluginVersionNotFoundException - extends Exception -{ +public class PluginVersionNotFoundException extends Exception { private final String groupId; private final String artifactId; - public PluginVersionNotFoundException( String groupId, String artifactId ) - { - super( "The plugin '" + groupId + ":" + artifactId + "' does not exist or no valid version could be found" ); + public PluginVersionNotFoundException(String groupId, String artifactId) { + super("The plugin '" + groupId + ":" + artifactId + "' does not exist or no valid version could be found"); this.groupId = groupId; this.artifactId = artifactId; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionRequest.java b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionRequest.java index d947b2acc1..4819de9857 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.plugin.version; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version; import java.util.List; - import org.apache.maven.model.Model; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -31,8 +29,7 @@ import org.eclipse.aether.repository.RemoteRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginVersionRequest -{ +public interface PluginVersionRequest { /** * Gets the group id of the plugin. @@ -47,7 +44,7 @@ public interface PluginVersionRequest * @param groupId The group id of the plugin. * @return This request, never {@code null}. */ - PluginVersionRequest setGroupId( String groupId ); + PluginVersionRequest setGroupId(String groupId); /** * Gets the artifact id of the plugin. @@ -62,7 +59,7 @@ public interface PluginVersionRequest * @param artifactId The artifact id of the plugin. * @return This request, never {@code null}. */ - PluginVersionRequest setArtifactId( String artifactId ); + PluginVersionRequest setArtifactId(String artifactId); /** * Gets the POM whose build plugins are to be scanned for the version. @@ -79,7 +76,7 @@ public interface PluginVersionRequest * plugin repositories. * @return This request, never {@code null}. */ - PluginVersionRequest setPom( Model pom ); + PluginVersionRequest setPom(Model pom); /** * Gets the remote repositories to use. @@ -95,7 +92,7 @@ public interface PluginVersionRequest * @param repositories The remote repositories to use. * @return This request, never {@code null}. */ - PluginVersionRequest setRepositories( List repositories ); + PluginVersionRequest setRepositories(List repositories); /** * Gets the session to use for repository access. @@ -110,6 +107,5 @@ public interface PluginVersionRequest * @param repositorySession The repository session to use. * @return This request, never {@code null}. */ - PluginVersionRequest setRepositorySession( RepositorySystemSession repositorySession ); - + PluginVersionRequest setRepositorySession(RepositorySystemSession repositorySession); } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolutionException.java b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolutionException.java index 6bde3f22e4..bec5137b89 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolutionException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin.version; * "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 + * 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 @@ -18,93 +16,89 @@ package org.apache.maven.plugin.version; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version; import java.util.List; - import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.RemoteRepository; /** * PluginVersionResolutionException */ -public class PluginVersionResolutionException - extends Exception -{ +public class PluginVersionResolutionException extends Exception { private final String groupId; private final String artifactId; private final String baseMessage; - public PluginVersionResolutionException( String groupId, String artifactId, String baseMessage, Throwable cause ) - { - super( "Error resolving version for plugin '" + groupId + ":" + artifactId + "': " + baseMessage, cause ); + public PluginVersionResolutionException(String groupId, String artifactId, String baseMessage, Throwable cause) { + super("Error resolving version for plugin '" + groupId + ":" + artifactId + "': " + baseMessage, cause); this.groupId = groupId; this.artifactId = artifactId; this.baseMessage = baseMessage; } - public PluginVersionResolutionException( String groupId, String artifactId, String baseMessage ) - { - super( "Error resolving version for plugin '" + groupId + ":" + artifactId + "': " + baseMessage ); + public PluginVersionResolutionException(String groupId, String artifactId, String baseMessage) { + super("Error resolving version for plugin '" + groupId + ":" + artifactId + "': " + baseMessage); this.groupId = groupId; this.artifactId = artifactId; this.baseMessage = baseMessage; } - public PluginVersionResolutionException( String groupId, String artifactId, LocalRepository localRepository, - List remoteRepositories, String baseMessage ) - { - super( "Error resolving version for plugin '" + groupId + ":" + artifactId + "' from the repositories " - + format( localRepository, remoteRepositories ) + ": " + baseMessage ); + public PluginVersionResolutionException( + String groupId, + String artifactId, + LocalRepository localRepository, + List remoteRepositories, + String baseMessage) { + super("Error resolving version for plugin '" + groupId + ":" + artifactId + "' from the repositories " + + format(localRepository, remoteRepositories) + ": " + baseMessage); this.groupId = groupId; this.artifactId = artifactId; this.baseMessage = baseMessage; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getBaseMessage() - { + public String getBaseMessage() { return baseMessage; } - private static String format( LocalRepository localRepository, List remoteRepositories ) - { - StringBuilder repos = new StringBuilder( "[" ); + private static String format(LocalRepository localRepository, List remoteRepositories) { + StringBuilder repos = new StringBuilder("["); - if ( localRepository != null ) - { - repos.append( localRepository.getId() ).append( " (" ).append( localRepository.getBasedir() ).append( ")" ); + if (localRepository != null) { + repos.append(localRepository.getId()) + .append(" (") + .append(localRepository.getBasedir()) + .append(")"); } - if ( remoteRepositories != null && !remoteRepositories.isEmpty() ) - { - for ( RemoteRepository repository : remoteRepositories ) - { - repos.append( ", " ); + if (remoteRepositories != null && !remoteRepositories.isEmpty()) { + for (RemoteRepository repository : remoteRepositories) { + repos.append(", "); - if ( repository != null ) - { - repos.append( repository.getId() ).append( " (" ).append( repository.getUrl() ).append( ")" ); + if (repository != null) { + repos.append(repository.getId()) + .append(" (") + .append(repository.getUrl()) + .append(")"); } } } - repos.append( "]" ); + repos.append("]"); return repos.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolver.java index 935fdfc5c2..4064081b5c 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin.version; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version; /** * Resolves a version for a plugin. @@ -25,8 +24,7 @@ package org.apache.maven.plugin.version; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginVersionResolver -{ +public interface PluginVersionResolver { /** * Resolves the version for the specified request. @@ -36,7 +34,5 @@ public interface PluginVersionResolver * @return The result of the version resolution, never {@code null}. * @throws PluginVersionResolutionException If the plugin version could not be resolved. */ - PluginVersionResult resolve( PluginVersionRequest request ) - throws PluginVersionResolutionException; - + PluginVersionResult resolve(PluginVersionRequest request) throws PluginVersionResolutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResult.java b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResult.java index 09a69e9609..cec8f9f6e9 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResult.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin.version; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version; import org.eclipse.aether.repository.ArtifactRepository; @@ -27,8 +26,7 @@ import org.eclipse.aether.repository.ArtifactRepository; * @since 3.0 * @author Benjamin Bentmann */ -public interface PluginVersionResult -{ +public interface PluginVersionResult { /** * The resolved plugin version. @@ -43,5 +41,4 @@ public interface PluginVersionResult * @return The repository from which the plugin version was resolved, never {@code null}. */ ArtifactRepository getRepository(); - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver.java index bffe536175..961310141f 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin.version.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version.internal; import java.io.IOException; import java.util.ArrayList; @@ -29,11 +28,9 @@ import java.util.Objects; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.Versioning; import org.apache.maven.artifact.repository.metadata.io.MetadataReader; @@ -73,14 +70,12 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultPluginVersionResolver - implements PluginVersionResolver -{ +public class DefaultPluginVersionResolver implements PluginVersionResolver { private static final String REPOSITORY_CONTEXT = "plugin"; private static final Object CACHE_KEY = new Object(); - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final RepositorySystem repositorySystem; private final MetadataReader metadataReader; private final MavenPluginManager pluginManager; @@ -91,8 +86,7 @@ public class DefaultPluginVersionResolver RepositorySystem repositorySystem, MetadataReader metadataReader, MavenPluginManager pluginManager, - VersionScheme versionScheme ) - { + VersionScheme versionScheme) { this.repositorySystem = repositorySystem; this.metadataReader = metadataReader; this.pluginManager = pluginManager; @@ -100,311 +94,256 @@ public class DefaultPluginVersionResolver } @Override - public PluginVersionResult resolve( PluginVersionRequest request ) - throws PluginVersionResolutionException - { - PluginVersionResult result = resolveFromProject( request ); + public PluginVersionResult resolve(PluginVersionRequest request) throws PluginVersionResolutionException { + PluginVersionResult result = resolveFromProject(request); - if ( result == null ) - { - ConcurrentMap cache = getCache( request.getRepositorySession().getData() ); - Key key = getKey( request ); - result = cache.get( key ); + if (result == null) { + ConcurrentMap cache = + getCache(request.getRepositorySession().getData()); + Key key = getKey(request); + result = cache.get(key); - if ( result == null ) - { - result = resolveFromRepository( request ); + if (result == null) { + result = resolveFromRepository(request); - if ( logger.isDebugEnabled() ) - { - logger.debug( "Resolved plugin version for " + request.getGroupId() + ":" + request.getArtifactId() - + " to " + result.getVersion() + " from repository " + result.getRepository() ); + if (logger.isDebugEnabled()) { + logger.debug("Resolved plugin version for " + request.getGroupId() + ":" + request.getArtifactId() + + " to " + result.getVersion() + " from repository " + result.getRepository()); } - cache.putIfAbsent( key, result ); + cache.putIfAbsent(key, result); + } else if (logger.isDebugEnabled()) { + logger.debug("Reusing cached resolved plugin version for " + request.getGroupId() + ":" + + request.getArtifactId() + " to " + result.getVersion() + " from POM " + request.getPom()); } - else if ( logger.isDebugEnabled() ) - { - logger.debug( "Reusing cached resolved plugin version for " + request.getGroupId() + ":" - + request.getArtifactId() + " to " + result.getVersion() + " from POM " + request.getPom() ); - } - } - else if ( logger.isDebugEnabled() ) - { - logger.debug( "Resolved plugin version for " + request.getGroupId() + ":" + request.getArtifactId() + " to " - + result.getVersion() + " from POM " + request.getPom() ); + } else if (logger.isDebugEnabled()) { + logger.debug("Resolved plugin version for " + request.getGroupId() + ":" + request.getArtifactId() + " to " + + result.getVersion() + " from POM " + request.getPom()); } return result; } - private PluginVersionResult resolveFromRepository( PluginVersionRequest request ) - throws PluginVersionResolutionException - { - RequestTrace trace = RequestTrace.newChild( null, request ); + private PluginVersionResult resolveFromRepository(PluginVersionRequest request) + throws PluginVersionResolutionException { + RequestTrace trace = RequestTrace.newChild(null, request); DefaultPluginVersionResult result = new DefaultPluginVersionResult(); - org.eclipse.aether.metadata.Metadata metadata = - new DefaultMetadata( request.getGroupId(), request.getArtifactId(), "maven-metadata.xml", - DefaultMetadata.Nature.RELEASE_OR_SNAPSHOT ); + org.eclipse.aether.metadata.Metadata metadata = new DefaultMetadata( + request.getGroupId(), + request.getArtifactId(), + "maven-metadata.xml", + DefaultMetadata.Nature.RELEASE_OR_SNAPSHOT); List requests = new ArrayList<>(); - requests.add( new MetadataRequest( metadata, null, REPOSITORY_CONTEXT ).setTrace( trace ) ); + requests.add(new MetadataRequest(metadata, null, REPOSITORY_CONTEXT).setTrace(trace)); - for ( RemoteRepository repository : request.getRepositories() ) - { - requests.add( new MetadataRequest( metadata, repository, REPOSITORY_CONTEXT ).setTrace( trace ) ); + for (RemoteRepository repository : request.getRepositories()) { + requests.add(new MetadataRequest(metadata, repository, REPOSITORY_CONTEXT).setTrace(trace)); } - List results = repositorySystem.resolveMetadata( request.getRepositorySession(), requests ); + List results = repositorySystem.resolveMetadata(request.getRepositorySession(), requests); Versions versions = new Versions(); - for ( MetadataResult res : results ) - { + for (MetadataResult res : results) { ArtifactRepository repository = res.getRequest().getRepository(); - if ( repository == null ) - { + if (repository == null) { repository = request.getRepositorySession().getLocalRepository(); } - mergeMetadata( request.getRepositorySession(), trace, versions, res.getMetadata(), repository ); + mergeMetadata(request.getRepositorySession(), trace, versions, res.getMetadata(), repository); } - selectVersion( result, request, versions ); + selectVersion(result, request, versions); return result; } - private void selectVersion( DefaultPluginVersionResult result, PluginVersionRequest request, Versions versions ) - throws PluginVersionResolutionException - { + private void selectVersion(DefaultPluginVersionResult result, PluginVersionRequest request, Versions versions) + throws PluginVersionResolutionException { String version = null; ArtifactRepository repo = null; - if ( StringUtils.isNotEmpty( versions.releaseVersion ) ) - { + if (StringUtils.isNotEmpty(versions.releaseVersion)) { version = versions.releaseVersion; repo = versions.releaseRepository; - } - else if ( StringUtils.isNotEmpty( versions.latestVersion ) ) - { + } else if (StringUtils.isNotEmpty(versions.latestVersion)) { version = versions.latestVersion; repo = versions.latestRepository; } - if ( version != null && !isCompatible( request, version ) ) - { - versions.versions.remove( version ); + if (version != null && !isCompatible(request, version)) { + versions.versions.remove(version); version = null; } - if ( version == null ) - { - TreeSet releases = new TreeSet<>( Collections.reverseOrder() ); - TreeSet snapshots = new TreeSet<>( Collections.reverseOrder() ); + if (version == null) { + TreeSet releases = new TreeSet<>(Collections.reverseOrder()); + TreeSet snapshots = new TreeSet<>(Collections.reverseOrder()); - for ( String ver : versions.versions.keySet() ) - { - try - { - Version v = versionScheme.parseVersion( ver ); + for (String ver : versions.versions.keySet()) { + try { + Version v = versionScheme.parseVersion(ver); - if ( ver.endsWith( "-SNAPSHOT" ) ) - { - snapshots.add( v ); + if (ver.endsWith("-SNAPSHOT")) { + snapshots.add(v); + } else { + releases.add(v); } - else - { - releases.add( v ); - } - } - catch ( InvalidVersionSpecificationException e ) - { + } catch (InvalidVersionSpecificationException e) { // ignore } } - for ( Version v : releases ) - { + for (Version v : releases) { String ver = v.toString(); - if ( isCompatible( request, ver ) ) - { + if (isCompatible(request, ver)) { version = ver; - repo = versions.versions.get( version ); + repo = versions.versions.get(version); break; } } - if ( version == null ) - { - for ( Version v : snapshots ) - { + if (version == null) { + for (Version v : snapshots) { String ver = v.toString(); - if ( isCompatible( request, ver ) ) - { + if (isCompatible(request, ver)) { version = ver; - repo = versions.versions.get( version ); + repo = versions.versions.get(version); break; } } } } - if ( version != null ) - { - result.setVersion( version ); - result.setRepository( repo ); - } - else - { - throw new PluginVersionResolutionException( request.getGroupId(), request.getArtifactId(), - request.getRepositorySession().getLocalRepository(), - request.getRepositories(), - "Plugin not found in any plugin repository" ); + if (version != null) { + result.setVersion(version); + result.setRepository(repo); + } else { + throw new PluginVersionResolutionException( + request.getGroupId(), + request.getArtifactId(), + request.getRepositorySession().getLocalRepository(), + request.getRepositories(), + "Plugin not found in any plugin repository"); } } - private boolean isCompatible( PluginVersionRequest request, String version ) - { + private boolean isCompatible(PluginVersionRequest request, String version) { Plugin plugin = new Plugin(); - plugin.setGroupId( request.getGroupId() ); - plugin.setArtifactId( request.getArtifactId() ); - plugin.setVersion( version ); + plugin.setGroupId(request.getGroupId()); + plugin.setArtifactId(request.getArtifactId()); + plugin.setVersion(version); PluginDescriptor pluginDescriptor; - try - { - pluginDescriptor = - pluginManager.getPluginDescriptor( plugin, request.getRepositories(), request.getRepositorySession() ); - } - catch ( PluginResolutionException e ) - { - logger.debug( "Ignoring unresolvable plugin version " + version, e ); + try { + pluginDescriptor = pluginManager.getPluginDescriptor( + plugin, request.getRepositories(), request.getRepositorySession()); + } catch (PluginResolutionException e) { + logger.debug("Ignoring unresolvable plugin version " + version, e); return false; - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore for now and delay failure to higher level processing return true; } - try - { - pluginManager.checkPrerequisites( pluginDescriptor ); - } - catch ( Exception e ) - { - logger.warn( "Ignoring incompatible plugin version " + version, e ); + try { + pluginManager.checkPrerequisites(pluginDescriptor); + } catch (Exception e) { + logger.warn("Ignoring incompatible plugin version " + version, e); return false; } return true; } - private void mergeMetadata( RepositorySystemSession session, RequestTrace trace, Versions versions, - org.eclipse.aether.metadata.Metadata metadata, ArtifactRepository repository ) - { - if ( metadata != null && metadata.getFile() != null && metadata.getFile().isFile() ) - { - try - { - Map options = Collections.singletonMap( MetadataReader.IS_STRICT, Boolean.FALSE ); + private void mergeMetadata( + RepositorySystemSession session, + RequestTrace trace, + Versions versions, + org.eclipse.aether.metadata.Metadata metadata, + ArtifactRepository repository) { + if (metadata != null && metadata.getFile() != null && metadata.getFile().isFile()) { + try { + Map options = Collections.singletonMap(MetadataReader.IS_STRICT, Boolean.FALSE); - Metadata repoMetadata = metadataReader.read( metadata.getFile(), options ); + Metadata repoMetadata = metadataReader.read(metadata.getFile(), options); - mergeMetadata( versions, repoMetadata, repository ); - } - catch ( IOException e ) - { - invalidMetadata( session, trace, metadata, repository, e ); + mergeMetadata(versions, repoMetadata, repository); + } catch (IOException e) { + invalidMetadata(session, trace, metadata, repository, e); } } } - private void invalidMetadata( RepositorySystemSession session, RequestTrace trace, - org.eclipse.aether.metadata.Metadata metadata, ArtifactRepository repository, - Exception exception ) - { + private void invalidMetadata( + RepositorySystemSession session, + RequestTrace trace, + org.eclipse.aether.metadata.Metadata metadata, + ArtifactRepository repository, + Exception exception) { RepositoryListener listener = session.getRepositoryListener(); - if ( listener != null ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_INVALID ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setException( exception ); - event.setRepository( repository ); - listener.metadataInvalid( event.build() ); + if (listener != null) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INVALID); + event.setTrace(trace); + event.setMetadata(metadata); + event.setException(exception); + event.setRepository(repository); + listener.metadataInvalid(event.build()); } } - private void mergeMetadata( Versions versions, Metadata source, ArtifactRepository repository ) - { + private void mergeMetadata(Versions versions, Metadata source, ArtifactRepository repository) { Versioning versioning = source.getVersioning(); - if ( versioning != null ) - { - String timestamp = StringUtils.clean( versioning.getLastUpdated() ); + if (versioning != null) { + String timestamp = StringUtils.clean(versioning.getLastUpdated()); - if ( StringUtils.isNotEmpty( versioning.getRelease() ) - && timestamp.compareTo( versions.releaseTimestamp ) > 0 ) - { + if (StringUtils.isNotEmpty(versioning.getRelease()) && timestamp.compareTo(versions.releaseTimestamp) > 0) { versions.releaseVersion = versioning.getRelease(); versions.releaseTimestamp = timestamp; versions.releaseRepository = repository; } - if ( StringUtils.isNotEmpty( versioning.getLatest() ) - && timestamp.compareTo( versions.latestTimestamp ) > 0 ) - { + if (StringUtils.isNotEmpty(versioning.getLatest()) && timestamp.compareTo(versions.latestTimestamp) > 0) { versions.latestVersion = versioning.getLatest(); versions.latestTimestamp = timestamp; versions.latestRepository = repository; } - for ( String version : versioning.getVersions() ) - { - if ( !versions.versions.containsKey( version ) ) - { - versions.versions.put( version, repository ); + for (String version : versioning.getVersions()) { + if (!versions.versions.containsKey(version)) { + versions.versions.put(version, repository); } } } } - private PluginVersionResult resolveFromProject( PluginVersionRequest request ) - { + private PluginVersionResult resolveFromProject(PluginVersionRequest request) { PluginVersionResult result = null; - if ( request.getPom() != null && request.getPom().getBuild() != null ) - { + if (request.getPom() != null && request.getPom().getBuild() != null) { Build build = request.getPom().getBuild(); - result = resolveFromProject( request, build.getPlugins() ); + result = resolveFromProject(request, build.getPlugins()); - if ( result == null && build.getPluginManagement() != null ) - { - result = resolveFromProject( request, build.getPluginManagement().getPlugins() ); + if (result == null && build.getPluginManagement() != null) { + result = resolveFromProject(request, build.getPluginManagement().getPlugins()); } } return result; } - private PluginVersionResult resolveFromProject( PluginVersionRequest request, List plugins ) - { - for ( Plugin plugin : plugins ) - { - if ( request.getGroupId().equals( plugin.getGroupId() ) - && request.getArtifactId().equals( plugin.getArtifactId() ) ) - { - if ( plugin.getVersion() != null ) - { - return new DefaultPluginVersionResult( plugin.getVersion() ); - } - else - { + private PluginVersionResult resolveFromProject(PluginVersionRequest request, List plugins) { + for (Plugin plugin : plugins) { + if (request.getGroupId().equals(plugin.getGroupId()) + && request.getArtifactId().equals(plugin.getArtifactId())) { + if (plugin.getVersion() != null) { + return new DefaultPluginVersionResult(plugin.getVersion()); + } else { return null; } } @@ -412,69 +351,57 @@ public class DefaultPluginVersionResolver return null; } - @SuppressWarnings( "unchecked" ) - private ConcurrentMap getCache( SessionData data ) - { - ConcurrentMap cache = - ( ConcurrentMap ) data.get( CACHE_KEY ); - while ( cache == null ) - { - cache = new ConcurrentHashMap<>( 256 ); - if ( data.set( CACHE_KEY, null, cache ) ) - { + @SuppressWarnings("unchecked") + private ConcurrentMap getCache(SessionData data) { + ConcurrentMap cache = (ConcurrentMap) data.get(CACHE_KEY); + while (cache == null) { + cache = new ConcurrentHashMap<>(256); + if (data.set(CACHE_KEY, null, cache)) { break; } - cache = ( ConcurrentMap ) data.get( CACHE_KEY ); + cache = (ConcurrentMap) data.get(CACHE_KEY); } return cache; } - private static Key getKey( PluginVersionRequest request ) - { - return new Key( request.getGroupId(), request.getArtifactId(), request.getRepositories() ); + private static Key getKey(PluginVersionRequest request) { + return new Key(request.getGroupId(), request.getArtifactId(), request.getRepositories()); } - static class Key - { + static class Key { final String groupId; final String artifactId; final List repositories; final int hash; - Key( String groupId, String artifactId, List repositories ) - { + Key(String groupId, String artifactId, List repositories) { this.groupId = groupId; this.artifactId = artifactId; this.repositories = repositories; - this.hash = Objects.hash( groupId, artifactId, repositories ); + this.hash = Objects.hash(groupId, artifactId, repositories); } @Override - 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; } - Key key = ( Key ) o; - return groupId.equals( key.groupId ) - && artifactId.equals( key.artifactId ) - && repositories.equals( key.repositories ); + Key key = (Key) o; + return groupId.equals(key.groupId) + && artifactId.equals(key.artifactId) + && repositories.equals(key.repositories); } @Override - public int hashCode() - { + public int hashCode() { return hash; } } - static class Versions - { + static class Versions { String releaseVersion = ""; @@ -489,7 +416,5 @@ public class DefaultPluginVersionResolver ArtifactRepository latestRepository; Map versions = new LinkedHashMap<>(); - } - } diff --git a/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResult.java b/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResult.java index 020d6e7a39..08c399e79f 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResult.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/version/internal/DefaultPluginVersionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.version.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.plugin.version.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.version.internal; import org.apache.maven.plugin.version.PluginVersionResult; import org.eclipse.aether.repository.ArtifactRepository; @@ -28,42 +27,33 @@ import org.eclipse.aether.repository.ArtifactRepository; * @since 3.0 * @author Benjamin Bentmann */ -class DefaultPluginVersionResult - implements PluginVersionResult -{ +class DefaultPluginVersionResult implements PluginVersionResult { private String version; private ArtifactRepository repository; - DefaultPluginVersionResult() - { + DefaultPluginVersionResult() { // does nothing } - DefaultPluginVersionResult( String version ) - { + DefaultPluginVersionResult(String version) { this.version = version; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } - public void setRepository( ArtifactRepository repository ) - { + public void setRepository(ArtifactRepository repository) { this.repository = repository; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionRequest.java b/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionRequest.java index cf5b0d70df..9e7e6812dc 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.graph.DependencyFilter; @@ -25,9 +24,7 @@ import org.eclipse.aether.graph.DependencyFilter; /** * @author Benjamin Bentmann */ -public class DefaultDependencyResolutionRequest - implements DependencyResolutionRequest -{ +public class DefaultDependencyResolutionRequest implements DependencyResolutionRequest { private MavenProject project; @@ -35,48 +32,39 @@ public class DefaultDependencyResolutionRequest private RepositorySystemSession session; - public DefaultDependencyResolutionRequest() - { + public DefaultDependencyResolutionRequest() { // enables default constructor } - public DefaultDependencyResolutionRequest( MavenProject project, RepositorySystemSession session ) - { - setMavenProject( project ); - setRepositorySession( session ); + public DefaultDependencyResolutionRequest(MavenProject project, RepositorySystemSession session) { + setMavenProject(project); + setRepositorySession(session); } - public DependencyFilter getResolutionFilter() - { + public DependencyFilter getResolutionFilter() { return filter; } - public MavenProject getMavenProject() - { + public MavenProject getMavenProject() { return project; } - public RepositorySystemSession getRepositorySession() - { + public RepositorySystemSession getRepositorySession() { return session; } - public DependencyResolutionRequest setResolutionFilter( DependencyFilter filter ) - { + public DependencyResolutionRequest setResolutionFilter(DependencyFilter filter) { this.filter = filter; return this; } - public DependencyResolutionRequest setMavenProject( MavenProject project ) - { + public DependencyResolutionRequest setMavenProject(MavenProject project) { this.project = project; return this; } - public DependencyResolutionRequest setRepositorySession( RepositorySystemSession repositorySession ) - { + public DependencyResolutionRequest setRepositorySession(RepositorySystemSession repositorySession) { this.session = repositorySession; return this; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionResult.java b/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionResult.java index 8e5a6ba9dc..91bee14357 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionResult.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultDependencyResolutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,22 +16,20 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; - import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; /** * @author Benjamin Bentmann */ -class DefaultDependencyResolutionResult - implements DependencyResolutionResult -{ +class DefaultDependencyResolutionResult implements DependencyResolutionResult { private DependencyNode root; @@ -47,68 +43,51 @@ class DefaultDependencyResolutionResult private Map> resolutionErrors = new IdentityHashMap<>(); - public DependencyNode getDependencyGraph() - { + public DependencyNode getDependencyGraph() { return root; } - public void setDependencyGraph( DependencyNode root ) - { + public void setDependencyGraph(DependencyNode root) { this.root = root; } - public List getDependencies() - { + public List getDependencies() { return dependencies; } - public List getResolvedDependencies() - { + public List getResolvedDependencies() { return resolvedDependencies; } - public void addResolvedDependency( Dependency dependency ) - { - dependencies.add( dependency ); - resolvedDependencies.add( dependency ); + public void addResolvedDependency(Dependency dependency) { + dependencies.add(dependency); + resolvedDependencies.add(dependency); } - public List getUnresolvedDependencies() - { + public List getUnresolvedDependencies() { return unresolvedDependencies; } - public List getCollectionErrors() - { + public List getCollectionErrors() { return collectionErrors; } - public void setCollectionErrors( List exceptions ) - { - if ( exceptions != null ) - { + public void setCollectionErrors(List exceptions) { + if (exceptions != null) { this.collectionErrors = exceptions; - } - else - { + } else { this.collectionErrors = new ArrayList<>(); } } - public List getResolutionErrors( Dependency dependency ) - { - List errors = resolutionErrors.get( dependency ); - return ( errors != null ) - ? Collections.unmodifiableList( errors ) - : Collections.emptyList(); - + public List getResolutionErrors(Dependency dependency) { + List errors = resolutionErrors.get(dependency); + return (errors != null) ? Collections.unmodifiableList(errors) : Collections.emptyList(); } - public void setResolutionErrors( Dependency dependency, List errors ) - { - dependencies.add( dependency ); - unresolvedDependencies.add( dependency ); - resolutionErrors.put( dependency, errors ); + public void setResolutionErrors(Dependency dependency, List errors) { + dependencies.add(dependency); + unresolvedDependencies.add(dependency); + resolutionErrors.put(dependency, errors); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultMavenProjectHelper.java b/maven-core/src/main/java/org/apache/maven/project/DefaultMavenProjectHelper.java index e2c3b5ca69..3d034e68c3 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultMavenProjectHelper.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultMavenProjectHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; @@ -36,68 +33,58 @@ import org.codehaus.plexus.logging.AbstractLogEnabled; /** * DefaultMavenProjectHelper */ -@SuppressWarnings( "deprecation" ) +@SuppressWarnings("deprecation") @Named @Singleton -public class DefaultMavenProjectHelper - extends AbstractLogEnabled - implements MavenProjectHelper -{ +public class DefaultMavenProjectHelper extends AbstractLogEnabled implements MavenProjectHelper { private final ArtifactHandlerManager artifactHandlerManager; @Inject - public DefaultMavenProjectHelper( ArtifactHandlerManager artifactHandlerManager ) - { + public DefaultMavenProjectHelper(ArtifactHandlerManager artifactHandlerManager) { this.artifactHandlerManager = artifactHandlerManager; } - public void attachArtifact( MavenProject project, String artifactType, String artifactClassifier, - File artifactFile ) - { + public void attachArtifact( + MavenProject project, String artifactType, String artifactClassifier, File artifactFile) { ArtifactHandler handler = null; - if ( artifactType != null ) - { - handler = artifactHandlerManager.getArtifactHandler( artifactType ); + if (artifactType != null) { + handler = artifactHandlerManager.getArtifactHandler(artifactType); } - if ( handler == null ) - { - handler = artifactHandlerManager.getArtifactHandler( "jar" ); + if (handler == null) { + handler = artifactHandlerManager.getArtifactHandler("jar"); } - Artifact artifact = new AttachedArtifact( project.getArtifact(), artifactType, artifactClassifier, handler ); + Artifact artifact = new AttachedArtifact(project.getArtifact(), artifactType, artifactClassifier, handler); - artifact.setFile( artifactFile ); - artifact.setResolved( true ); + artifact.setFile(artifactFile); + artifact.setResolved(true); - attachArtifact( project, artifact ); + attachArtifact(project, artifact); } - public void attachArtifact( MavenProject project, String artifactType, File artifactFile ) - { - ArtifactHandler handler = artifactHandlerManager.getArtifactHandler( artifactType ); + public void attachArtifact(MavenProject project, String artifactType, File artifactFile) { + ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(artifactType); - Artifact artifact = new AttachedArtifact( project.getArtifact(), artifactType, handler ); + Artifact artifact = new AttachedArtifact(project.getArtifact(), artifactType, handler); - artifact.setFile( artifactFile ); - artifact.setResolved( true ); + artifact.setFile(artifactFile); + artifact.setResolved(true); - attachArtifact( project, artifact ); + attachArtifact(project, artifact); } - public void attachArtifact( MavenProject project, File artifactFile, String artifactClassifier ) - { + public void attachArtifact(MavenProject project, File artifactFile, String artifactClassifier) { Artifact projectArtifact = project.getArtifact(); - Artifact artifact = - new AttachedArtifact( projectArtifact, projectArtifact.getType(), artifactClassifier, - projectArtifact.getArtifactHandler() ); + Artifact artifact = new AttachedArtifact( + projectArtifact, projectArtifact.getType(), artifactClassifier, projectArtifact.getArtifactHandler()); - artifact.setFile( artifactFile ); - artifact.setResolved( true ); + artifact.setFile(artifactFile); + artifact.setResolved(true); - attachArtifact( project, artifact ); + attachArtifact(project, artifact); } /** @@ -107,31 +94,27 @@ public class DefaultMavenProjectHelper * @param project project reference. * @param artifact artifact to add or replace. */ - public void attachArtifact( MavenProject project, Artifact artifact ) - { - project.addAttachedArtifact( artifact ); + public void attachArtifact(MavenProject project, Artifact artifact) { + project.addAttachedArtifact(artifact); } - public void addResource( MavenProject project, String resourceDirectory, List includes, - List excludes ) - { + public void addResource( + MavenProject project, String resourceDirectory, List includes, List excludes) { Resource resource = new Resource(); - resource.setDirectory( resourceDirectory ); - resource.setIncludes( includes ); - resource.setExcludes( excludes ); + resource.setDirectory(resourceDirectory); + resource.setIncludes(includes); + resource.setExcludes(excludes); - project.addResource( resource ); + project.addResource(resource); } - public void addTestResource( MavenProject project, String resourceDirectory, List includes, - List excludes ) - { + public void addTestResource( + MavenProject project, String resourceDirectory, List includes, List excludes) { Resource resource = new Resource(); - resource.setDirectory( resourceDirectory ); - resource.setIncludes( includes ); - resource.setExcludes( excludes ); + resource.setDirectory(resourceDirectory); + resource.setIncludes(includes); + resource.setExcludes(excludes); - project.addTestResource( resource ); + project.addTestResource(resource); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultModelBuildingListener.java b/maven-core/src/main/java/org/apache/maven/project/DefaultModelBuildingListener.java index ca6079426d..f7c8357d9f 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultModelBuildingListener.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultModelBuildingListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.List; import java.util.Objects; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Model; import org.apache.maven.model.building.AbstractModelBuildingListener; @@ -38,9 +36,7 @@ import org.apache.maven.plugin.version.PluginVersionResolutionException; * * @author Benjamin Bentmann */ -public class DefaultModelBuildingListener - extends AbstractModelBuildingListener -{ +public class DefaultModelBuildingListener extends AbstractModelBuildingListener { private MavenProject project; @@ -52,14 +48,15 @@ public class DefaultModelBuildingListener private List pluginRepositories; - public DefaultModelBuildingListener( MavenProject project, ProjectBuildingHelper projectBuildingHelper, - ProjectBuildingRequest projectBuildingRequest ) - { - this.project = Objects.requireNonNull( project, "project cannot be null" ); + public DefaultModelBuildingListener( + MavenProject project, + ProjectBuildingHelper projectBuildingHelper, + ProjectBuildingRequest projectBuildingRequest) { + this.project = Objects.requireNonNull(project, "project cannot be null"); this.projectBuildingHelper = - Objects.requireNonNull( projectBuildingHelper, "projectBuildingHelper cannot be null" ); + Objects.requireNonNull(projectBuildingHelper, "projectBuildingHelper cannot be null"); this.projectBuildingRequest = - Objects.requireNonNull( projectBuildingRequest, "projectBuildingRequest cannot be null" ); + Objects.requireNonNull(projectBuildingRequest, "projectBuildingRequest cannot be null"); this.remoteRepositories = projectBuildingRequest.getRemoteRepositories(); this.pluginRepositories = projectBuildingRequest.getPluginArtifactRepositories(); } @@ -69,64 +66,52 @@ public class DefaultModelBuildingListener * * @return The project, never {@code null}. */ - public MavenProject getProject() - { + public MavenProject getProject() { return project; } @Override - public void buildExtensionsAssembled( ModelBuildingEvent event ) - { + public void buildExtensionsAssembled(ModelBuildingEvent event) { Model model = event.getModel(); - try - { - pluginRepositories = - projectBuildingHelper.createArtifactRepositories( model.getPluginRepositories(), pluginRepositories, - projectBuildingRequest ); + try { + pluginRepositories = projectBuildingHelper.createArtifactRepositories( + model.getPluginRepositories(), pluginRepositories, projectBuildingRequest); + } catch (Exception e) { + event.getProblems() + .add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage("Invalid plugin repository: " + e.getMessage()) + .setException(e)); } - catch ( Exception e ) - { - event.getProblems().add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( "Invalid plugin repository: " + e.getMessage() ) - .setException( e ) ); - } - project.setPluginArtifactRepositories( pluginRepositories ); + project.setPluginArtifactRepositories(pluginRepositories); - if ( event.getRequest().isProcessPlugins() ) - { - try - { + if (event.getRequest().isProcessPlugins()) { + try { ProjectRealmCache.CacheRecord record = - projectBuildingHelper.createProjectRealm( project, model, projectBuildingRequest ); + projectBuildingHelper.createProjectRealm(project, model, projectBuildingRequest); - project.setClassRealm( record.getRealm() ); - project.setExtensionDependencyFilter( record.getExtensionArtifactFilter() ); - } - catch ( PluginResolutionException | PluginManagerException | PluginVersionResolutionException e ) - { - event.getProblems().add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( "Unresolvable build extension: " + e.getMessage() ) - .setException( e ) ); + project.setClassRealm(record.getRealm()); + project.setExtensionDependencyFilter(record.getExtensionArtifactFilter()); + } catch (PluginResolutionException | PluginManagerException | PluginVersionResolutionException e) { + event.getProblems() + .add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage("Unresolvable build extension: " + e.getMessage()) + .setException(e)); } - projectBuildingHelper.selectProjectRealm( project ); + projectBuildingHelper.selectProjectRealm(project); } // build the regular repos after extensions are loaded to allow for custom layouts - try - { - remoteRepositories = - projectBuildingHelper.createArtifactRepositories( model.getRepositories(), remoteRepositories, - projectBuildingRequest ); + try { + remoteRepositories = projectBuildingHelper.createArtifactRepositories( + model.getRepositories(), remoteRepositories, projectBuildingRequest); + } catch (Exception e) { + event.getProblems() + .add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage("Invalid artifact repository: " + e.getMessage()) + .setException(e)); } - catch ( Exception e ) - { - event.getProblems().add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( "Invalid artifact repository: " + e.getMessage() ) - .setException( e ) ); - } - project.setRemoteArtifactRepositories( remoteRepositories ); + project.setRemoteArtifactRepositories(remoteRepositories); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java index 7fe5a23b13..efc9311d01 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.io.IOException; @@ -33,11 +32,9 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidArtifactRTException; @@ -56,7 +53,6 @@ import org.apache.maven.model.Plugin; import org.apache.maven.model.Profile; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.building.ArtifactModelSource; -import org.apache.maven.model.building.TransformerContextBuilder; import org.apache.maven.model.building.DefaultModelBuildingRequest; import org.apache.maven.model.building.DefaultModelProblem; import org.apache.maven.model.building.FileModelSource; @@ -69,6 +65,7 @@ import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.building.ModelSource; import org.apache.maven.model.building.StringModelSource; import org.apache.maven.model.building.TransformerContext; +import org.apache.maven.model.building.TransformerContextBuilder; import org.apache.maven.model.resolution.ModelResolver; import org.apache.maven.repository.internal.ArtifactDescriptorUtils; import org.apache.maven.repository.internal.ModelCacheFactory; @@ -91,10 +88,8 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultProjectBuilder - implements ProjectBuilder -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultProjectBuilder implements ProjectBuilder { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final ModelBuilder modelBuilder; private final ModelProcessor modelProcessor; private final ProjectBuildingHelper projectBuildingHelper; @@ -104,7 +99,7 @@ public class DefaultProjectBuilder private final ProjectDependenciesResolver dependencyResolver; private final ModelCacheFactory modelCacheFactory; - @SuppressWarnings( "checkstyle:ParameterNumber" ) + @SuppressWarnings("checkstyle:ParameterNumber") @Inject public DefaultProjectBuilder( ModelBuilder modelBuilder, @@ -114,8 +109,7 @@ public class DefaultProjectBuilder RepositorySystem repoSystem, RemoteRepositoryManager repositoryManager, ProjectDependenciesResolver dependencyResolver, - ModelCacheFactory modelCacheFactory ) - { + ModelCacheFactory modelCacheFactory) { this.modelBuilder = modelBuilder; this.modelProcessor = modelProcessor; this.projectBuildingHelper = projectBuildingHelper; @@ -125,33 +119,26 @@ public class DefaultProjectBuilder this.dependencyResolver = dependencyResolver; this.modelCacheFactory = modelCacheFactory; } -// ---------------------------------------------------------------------- + // ---------------------------------------------------------------------- // MavenProjectBuilder Implementation // ---------------------------------------------------------------------- @Override - public ProjectBuildingResult build( File pomFile, ProjectBuildingRequest request ) - throws ProjectBuildingException - { - return build( pomFile, new FileModelSource( pomFile ), - new InternalConfig( request, null, null ) ); + public ProjectBuildingResult build(File pomFile, ProjectBuildingRequest request) throws ProjectBuildingException { + return build(pomFile, new FileModelSource(pomFile), new InternalConfig(request, null, null)); } @Override - public ProjectBuildingResult build( ModelSource modelSource, ProjectBuildingRequest request ) - throws ProjectBuildingException - { - return build( null, modelSource, - new InternalConfig( request, null, null ) ); + public ProjectBuildingResult build(ModelSource modelSource, ProjectBuildingRequest request) + throws ProjectBuildingException { + return build(null, modelSource, new InternalConfig(request, null, null)); } - private ProjectBuildingResult build( File pomFile, ModelSource modelSource, InternalConfig config ) - throws ProjectBuildingException - { + private ProjectBuildingResult build(File pomFile, ModelSource modelSource, InternalConfig config) + throws ProjectBuildingException { ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { ProjectBuildingRequest projectBuildingRequest = config.request; MavenProject project = projectBuildingRequest.getProject(); @@ -159,32 +146,27 @@ public class DefaultProjectBuilder List modelProblems = null; Throwable error = null; - if ( project == null ) - { - ModelBuildingRequest request = getModelBuildingRequest( config ); + if (project == null) { + ModelBuildingRequest request = getModelBuildingRequest(config); project = new MavenProject(); - project.setFile( pomFile ); + project.setFile(pomFile); DefaultModelBuildingListener listener = - new DefaultModelBuildingListener( project, projectBuildingHelper, projectBuildingRequest ); - request.setModelBuildingListener( listener ); + new DefaultModelBuildingListener(project, projectBuildingHelper, projectBuildingRequest); + request.setModelBuildingListener(listener); - request.setPomFile( pomFile ); - request.setModelSource( modelSource ); - request.setLocationTracking( true ); + request.setPomFile(pomFile); + request.setModelSource(modelSource); + request.setLocationTracking(true); ModelBuildingResult result; - try - { - result = modelBuilder.build( request ); - } - catch ( ModelBuildingException e ) - { + try { + result = modelBuilder.build(request); + } catch (ModelBuildingException e) { result = e.getResult(); - if ( result == null || result.getEffectiveModel() == null ) - { - throw new ProjectBuildingException( e.getModelId(), e.getMessage(), pomFile, e ); + if (result == null || result.getEffectiveModel() == null) { + throw new ProjectBuildingException(e.getModelId(), e.getMessage(), pomFile, e); } // validation error, continue project building and delay failing to help IDEs error = e; @@ -192,191 +174,171 @@ public class DefaultProjectBuilder modelProblems = result.getProblems(); - initProject( project, Collections.emptyMap(), true, - result, new HashMap<>(), projectBuildingRequest ); - } - else if ( projectBuildingRequest.isResolveDependencies() ) - { - projectBuildingHelper.selectProjectRealm( project ); + initProject(project, Collections.emptyMap(), true, result, new HashMap<>(), projectBuildingRequest); + } else if (projectBuildingRequest.isResolveDependencies()) { + projectBuildingHelper.selectProjectRealm(project); } DependencyResolutionResult resolutionResult = null; - if ( projectBuildingRequest.isResolveDependencies() ) - { - resolutionResult = resolveDependencies( project, config.session ); + if (projectBuildingRequest.isResolveDependencies()) { + resolutionResult = resolveDependencies(project, config.session); } - ProjectBuildingResult result = new DefaultProjectBuildingResult( project, modelProblems, resolutionResult ); + ProjectBuildingResult result = new DefaultProjectBuildingResult(project, modelProblems, resolutionResult); - if ( error != null ) - { - ProjectBuildingException e = new ProjectBuildingException( Arrays.asList( result ) ); - e.initCause( error ); + if (error != null) { + ProjectBuildingException e = new ProjectBuildingException(Arrays.asList(result)); + e.initCause(error); throw e; } return result; - } - finally - { - Thread.currentThread().setContextClassLoader( oldContextClassLoader ); + } finally { + Thread.currentThread().setContextClassLoader(oldContextClassLoader); } } - private DependencyResolutionResult resolveDependencies( MavenProject project, RepositorySystemSession session ) - { + private DependencyResolutionResult resolveDependencies(MavenProject project, RepositorySystemSession session) { DependencyResolutionResult resolutionResult; - try - { - DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest( project, session ); - resolutionResult = dependencyResolver.resolve( resolution ); - } - catch ( DependencyResolutionException e ) - { + try { + DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest(project, session); + resolutionResult = dependencyResolver.resolve(resolution); + } catch (DependencyResolutionException e) { resolutionResult = e.getResult(); } Set artifacts = new LinkedHashSet<>(); - if ( resolutionResult.getDependencyGraph() != null ) - { - RepositoryUtils.toArtifacts( artifacts, resolutionResult.getDependencyGraph().getChildren(), - Collections.singletonList( project.getArtifact().getId() ), null ); + if (resolutionResult.getDependencyGraph() != null) { + RepositoryUtils.toArtifacts( + artifacts, + resolutionResult.getDependencyGraph().getChildren(), + Collections.singletonList(project.getArtifact().getId()), + null); // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not LocalRepositoryManager lrm = session.getLocalRepositoryManager(); - for ( Artifact artifact : artifacts ) - { - if ( !artifact.isResolved() ) - { - String path = lrm.getPathForLocalArtifact( RepositoryUtils.toArtifact( artifact ) ); - artifact.setFile( new File( lrm.getRepository().getBasedir(), path ) ); + for (Artifact artifact : artifacts) { + if (!artifact.isResolved()) { + String path = lrm.getPathForLocalArtifact(RepositoryUtils.toArtifact(artifact)); + artifact.setFile(new File(lrm.getRepository().getBasedir(), path)); } } } - project.setResolvedArtifacts( artifacts ); - project.setArtifacts( artifacts ); + project.setResolvedArtifacts(artifacts); + project.setArtifacts(artifacts); return resolutionResult; } - private List getProfileIds( List profiles ) - { - return profiles.stream().map( org.apache.maven.model.Profile::getId ).collect( Collectors.toList() ); + private List getProfileIds(List profiles) { + return profiles.stream().map(org.apache.maven.model.Profile::getId).collect(Collectors.toList()); } - private ModelBuildingRequest getModelBuildingRequest( InternalConfig config ) - { + private ModelBuildingRequest getModelBuildingRequest(InternalConfig config) { ProjectBuildingRequest configuration = config.request; ModelBuildingRequest request = new DefaultModelBuildingRequest(); - RequestTrace trace = RequestTrace.newChild( null, configuration ).newChild( request ); + RequestTrace trace = RequestTrace.newChild(null, configuration).newChild(request); - ModelResolver resolver = - new ProjectModelResolver( config.session, trace, repoSystem, repositoryManager, config.repositories, - configuration.getRepositoryMerging(), config.modelPool ); + ModelResolver resolver = new ProjectModelResolver( + config.session, + trace, + repoSystem, + repositoryManager, + config.repositories, + configuration.getRepositoryMerging(), + config.modelPool); - request.setValidationLevel( configuration.getValidationLevel() ); - request.setProcessPlugins( configuration.isProcessPlugins() ); - request.setProfiles( configuration.getProfiles() ); - request.setActiveProfileIds( configuration.getActiveProfileIds() ); - request.setInactiveProfileIds( configuration.getInactiveProfileIds() ); - request.setSystemProperties( configuration.getSystemProperties() ); - request.setUserProperties( configuration.getUserProperties() ); - request.setBuildStartTime( configuration.getBuildStartTime() ); - request.setModelResolver( resolver ); + request.setValidationLevel(configuration.getValidationLevel()); + request.setProcessPlugins(configuration.isProcessPlugins()); + request.setProfiles(configuration.getProfiles()); + request.setActiveProfileIds(configuration.getActiveProfileIds()); + request.setInactiveProfileIds(configuration.getInactiveProfileIds()); + request.setSystemProperties(configuration.getSystemProperties()); + request.setUserProperties(configuration.getUserProperties()); + request.setBuildStartTime(configuration.getBuildStartTime()); + request.setModelResolver(resolver); // this is a hint that we want to build 1 file, so don't cache. See MNG-7063 - if ( config.modelPool != null ) - { - request.setModelCache( modelCacheFactory.createCache( config.session ) ); + if (config.modelPool != null) { + request.setModelCache(modelCacheFactory.createCache(config.session)); } - request.setTransformerContextBuilder( config.transformerContextBuilder ); + request.setTransformerContextBuilder(config.transformerContextBuilder); return request; } @Override - public ProjectBuildingResult build( Artifact artifact, ProjectBuildingRequest request ) - throws ProjectBuildingException - { - return build( artifact, false, request ); + public ProjectBuildingResult build(Artifact artifact, ProjectBuildingRequest request) + throws ProjectBuildingException { + return build(artifact, false, request); } @Override - public ProjectBuildingResult build( Artifact artifact, boolean allowStubModel, ProjectBuildingRequest request ) - throws ProjectBuildingException - { - org.eclipse.aether.artifact.Artifact pomArtifact = RepositoryUtils.toArtifact( artifact ); - pomArtifact = ArtifactDescriptorUtils.toPomArtifact( pomArtifact ); + public ProjectBuildingResult build(Artifact artifact, boolean allowStubModel, ProjectBuildingRequest request) + throws ProjectBuildingException { + org.eclipse.aether.artifact.Artifact pomArtifact = RepositoryUtils.toArtifact(artifact); + pomArtifact = ArtifactDescriptorUtils.toPomArtifact(pomArtifact); - InternalConfig config = - new InternalConfig( request, null, null ); + InternalConfig config = new InternalConfig(request, null, null); boolean localProject; - try - { + try { ArtifactRequest pomRequest = new ArtifactRequest(); - pomRequest.setArtifact( pomArtifact ); - pomRequest.setRepositories( config.repositories ); - ArtifactResult pomResult = repoSystem.resolveArtifact( config.session, pomRequest ); + pomRequest.setArtifact(pomArtifact); + pomRequest.setRepositories(config.repositories); + ArtifactResult pomResult = repoSystem.resolveArtifact(config.session, pomRequest); pomArtifact = pomResult.getArtifact(); localProject = pomResult.getRepository() instanceof WorkspaceRepository; - } - catch ( org.eclipse.aether.resolution.ArtifactResolutionException e ) - { - if ( e.getResults().get( 0 ).isMissing() && allowStubModel ) - { - return build( null, createStubModelSource( artifact ), config ); + } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) { + if (e.getResults().get(0).isMissing() && allowStubModel) { + return build(null, createStubModelSource(artifact), config); } - throw new ProjectBuildingException( artifact.getId(), - "Error resolving project artifact: " + e.getMessage(), e ); + throw new ProjectBuildingException( + artifact.getId(), "Error resolving project artifact: " + e.getMessage(), e); } File pomFile = pomArtifact.getFile(); - if ( "pom".equals( artifact.getType() ) ) - { - artifact.selectVersion( pomArtifact.getVersion() ); - artifact.setFile( pomFile ); - artifact.setResolved( true ); + if ("pom".equals(artifact.getType())) { + artifact.selectVersion(pomArtifact.getVersion()); + artifact.setFile(pomFile); + artifact.setResolved(true); } - if ( localProject ) - { - return build( pomFile, new FileModelSource( pomFile ), config ); - } - else - { - return build( null, new ArtifactModelSource( pomFile, artifact.getGroupId(), artifact.getArtifactId(), - artifact.getVersion() ), - config ); + if (localProject) { + return build(pomFile, new FileModelSource(pomFile), config); + } else { + return build( + null, + new ArtifactModelSource( + pomFile, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()), + config); } } - private ModelSource createStubModelSource( Artifact artifact ) - { - StringBuilder buffer = new StringBuilder( 1024 ); + private ModelSource createStubModelSource(Artifact artifact) { + StringBuilder buffer = new StringBuilder(1024); - buffer.append( "" ); - buffer.append( "" ); - buffer.append( "4.0.0" ); - buffer.append( "" ).append( artifact.getGroupId() ).append( "" ); - buffer.append( "" ).append( artifact.getArtifactId() ).append( "" ); - buffer.append( "" ).append( artifact.getBaseVersion() ).append( "" ); - buffer.append( "" ).append( artifact.getType() ).append( "" ); - buffer.append( "" ); + buffer.append(""); + buffer.append(""); + buffer.append("4.0.0"); + buffer.append("").append(artifact.getGroupId()).append(""); + buffer.append("").append(artifact.getArtifactId()).append(""); + buffer.append("").append(artifact.getBaseVersion()).append(""); + buffer.append("").append(artifact.getType()).append(""); + buffer.append(""); - return new StringModelSource( buffer, artifact.getId() ); + return new StringModelSource(buffer, artifact.getId()); } @Override - public List build( List pomFiles, boolean recursive, ProjectBuildingRequest request ) - throws ProjectBuildingException - { + public List build(List pomFiles, boolean recursive, ProjectBuildingRequest request) + throws ProjectBuildingException { List results = new ArrayList<>(); List interimResults = new ArrayList<>(); @@ -384,101 +346,121 @@ public class DefaultProjectBuilder ReactorModelPool.Builder poolBuilder = new ReactorModelPool.Builder(); final ReactorModelPool modelPool = poolBuilder.build(); - InternalConfig config = - new InternalConfig( request, modelPool, modelBuilder.newTransformerContextBuilder() ); + InternalConfig config = new InternalConfig(request, modelPool, modelBuilder.newTransformerContextBuilder()); - Map projectIndex = new HashMap<>( 256 ); + Map projectIndex = new HashMap<>(256); // phase 1: get file Models from the reactor. - boolean noErrors = - build( results, interimResults, projectIndex, pomFiles, new LinkedHashSet<>(), true, recursive, - config, poolBuilder ); + boolean noErrors = build( + results, + interimResults, + projectIndex, + pomFiles, + new LinkedHashSet<>(), + true, + recursive, + config, + poolBuilder); ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { // Phase 2: get effective models from the reactor - noErrors = - build( results, new ArrayList<>(), projectIndex, interimResults, request, - new HashMap<>(), config.session ) && noErrors; - } - finally - { - Thread.currentThread().setContextClassLoader( oldContextClassLoader ); + noErrors = build( + results, + new ArrayList<>(), + projectIndex, + interimResults, + request, + new HashMap<>(), + config.session) + && noErrors; + } finally { + Thread.currentThread().setContextClassLoader(oldContextClassLoader); } - if ( Features.buildConsumer( request.getUserProperties() ).isActive() ) - { - request.getRepositorySession().getData().set( TransformerContext.KEY, - config.transformerContextBuilder.build() ); + if (Features.buildConsumer(request.getUserProperties()).isActive()) { + request.getRepositorySession() + .getData() + .set(TransformerContext.KEY, config.transformerContextBuilder.build()); } - if ( !noErrors ) - { - throw new ProjectBuildingException( results ); + if (!noErrors) { + throw new ProjectBuildingException(results); } return results; } - @SuppressWarnings( "checkstyle:parameternumber" ) - private boolean build( List results, List interimResults, - Map projectIndex, List pomFiles, Set aggregatorFiles, - boolean root, boolean recursive, InternalConfig config, - ReactorModelPool.Builder poolBuilder ) - { + @SuppressWarnings("checkstyle:parameternumber") + private boolean build( + List results, + List interimResults, + Map projectIndex, + List pomFiles, + Set aggregatorFiles, + boolean root, + boolean recursive, + InternalConfig config, + ReactorModelPool.Builder poolBuilder) { boolean noErrors = true; - for ( File pomFile : pomFiles ) - { - aggregatorFiles.add( pomFile ); + for (File pomFile : pomFiles) { + aggregatorFiles.add(pomFile); - if ( !build( results, interimResults, projectIndex, pomFile, aggregatorFiles, root, recursive, config, - poolBuilder ) ) - { + if (!build( + results, + interimResults, + projectIndex, + pomFile, + aggregatorFiles, + root, + recursive, + config, + poolBuilder)) { noErrors = false; } - aggregatorFiles.remove( pomFile ); + aggregatorFiles.remove(pomFile); } return noErrors; } - @SuppressWarnings( "checkstyle:parameternumber" ) - private boolean build( List results, List interimResults, - Map projectIndex, File pomFile, Set aggregatorFiles, - boolean isRoot, boolean recursive, InternalConfig config, - ReactorModelPool.Builder poolBuilder ) - { + @SuppressWarnings("checkstyle:parameternumber") + private boolean build( + List results, + List interimResults, + Map projectIndex, + File pomFile, + Set aggregatorFiles, + boolean isRoot, + boolean recursive, + InternalConfig config, + ReactorModelPool.Builder poolBuilder) { boolean noErrors = true; MavenProject project = new MavenProject(); - project.setFile( pomFile ); + project.setFile(pomFile); - ModelBuildingRequest request = getModelBuildingRequest( config ) - .setPomFile( pomFile ) - .setTwoPhaseBuilding( true ) - .setLocationTracking( true ); + ModelBuildingRequest request = getModelBuildingRequest(config) + .setPomFile(pomFile) + .setTwoPhaseBuilding(true) + .setLocationTracking(true); DefaultModelBuildingListener listener = - new DefaultModelBuildingListener( project, projectBuildingHelper, config.request ); - request.setModelBuildingListener( listener ); + new DefaultModelBuildingListener(project, projectBuildingHelper, config.request); + request.setModelBuildingListener(listener); ModelBuildingResult result; - try - { - result = modelBuilder.build( request ); - } - catch ( ModelBuildingException e ) - { + try { + result = modelBuilder.build(request); + } catch (ModelBuildingException e) { result = e.getResult(); - if ( result == null || result.getFileModel() == null ) - { - results.add( new DefaultProjectBuildingResult( e.getModelId(), pomFile, e.getProblems() ) ); + if (result == null || result.getFileModel() == null) { + results.add(new DefaultProjectBuildingResult(e.getModelId(), pomFile, e.getProblems())); - return false; + return false; } // validation error, continue project building and delay failing to help IDEs // result.getProblems().addAll(e.getProblems()) ? @@ -487,100 +469,101 @@ public class DefaultProjectBuilder Model model = result.getFileModel(); - poolBuilder.put( model.getPomFile().toPath(), model ); + poolBuilder.put(model.getPomFile().toPath(), model); - InterimResult interimResult = new InterimResult( pomFile, request, result, listener, isRoot ); - interimResults.add( interimResult ); + InterimResult interimResult = new InterimResult(pomFile, request, result, listener, isRoot); + interimResults.add(interimResult); - if ( recursive ) - { + if (recursive) { File basedir = pomFile.getParentFile(); List moduleFiles = new ArrayList<>(); - for ( String module : model.getModules() ) - { - if ( StringUtils.isEmpty( module ) ) - { + for (String module : model.getModules()) { + if (StringUtils.isEmpty(module)) { continue; } - module = module.replace( '\\', File.separatorChar ).replace( '/', File.separatorChar ); + module = module.replace('\\', File.separatorChar).replace('/', File.separatorChar); - File moduleFile = new File( basedir, module ); + File moduleFile = new File(basedir, module); - if ( moduleFile.isDirectory() ) - { - moduleFile = modelProcessor.locatePom( moduleFile ); + if (moduleFile.isDirectory()) { + moduleFile = modelProcessor.locatePom(moduleFile); } - if ( !moduleFile.isFile() ) - { - ModelProblem problem = - new DefaultModelProblem( "Child module " + moduleFile + " of " + pomFile - + " does not exist", ModelProblem.Severity.ERROR, ModelProblem.Version.BASE, - model, -1, -1, null ); - result.getProblems().add( problem ); + if (!moduleFile.isFile()) { + ModelProblem problem = new DefaultModelProblem( + "Child module " + moduleFile + " of " + pomFile + " does not exist", + ModelProblem.Severity.ERROR, + ModelProblem.Version.BASE, + model, + -1, + -1, + null); + result.getProblems().add(problem); noErrors = false; continue; } - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { // we don't canonicalize on unix to avoid interfering with symlinks - try - { + try { moduleFile = moduleFile.getCanonicalFile(); - } - catch ( IOException e ) - { + } catch (IOException e) { moduleFile = moduleFile.getAbsoluteFile(); } - } - else - { - moduleFile = new File( moduleFile.toURI().normalize() ); + } else { + moduleFile = new File(moduleFile.toURI().normalize()); } - if ( aggregatorFiles.contains( moduleFile ) ) - { - StringBuilder buffer = new StringBuilder( 256 ); - for ( File aggregatorFile : aggregatorFiles ) - { - buffer.append( aggregatorFile ).append( " -> " ); + if (aggregatorFiles.contains(moduleFile)) { + StringBuilder buffer = new StringBuilder(256); + for (File aggregatorFile : aggregatorFiles) { + buffer.append(aggregatorFile).append(" -> "); } - buffer.append( moduleFile ); + buffer.append(moduleFile); - ModelProblem problem = - new DefaultModelProblem( "Child module " + moduleFile + " of " + pomFile - + " forms aggregation cycle " + buffer, ModelProblem.Severity.ERROR, - ModelProblem.Version.BASE, model, -1, -1, null ); - result.getProblems().add( problem ); + ModelProblem problem = new DefaultModelProblem( + "Child module " + moduleFile + " of " + pomFile + " forms aggregation cycle " + buffer, + ModelProblem.Severity.ERROR, + ModelProblem.Version.BASE, + model, + -1, + -1, + null); + result.getProblems().add(problem); noErrors = false; continue; } - moduleFiles.add( moduleFile ); + moduleFiles.add(moduleFile); } interimResult.modules = new ArrayList<>(); - if ( !build( results, interimResult.modules, projectIndex, moduleFiles, aggregatorFiles, false, - recursive, config, poolBuilder ) ) - { + if (!build( + results, + interimResult.modules, + projectIndex, + moduleFiles, + aggregatorFiles, + false, + recursive, + config, + poolBuilder)) { noErrors = false; } } - projectIndex.put( pomFile, project ); + projectIndex.put(pomFile, project); return noErrors; } - static class InterimResult - { + static class InterimResult { File pomFile; @@ -594,75 +577,75 @@ public class DefaultProjectBuilder List modules = Collections.emptyList(); - InterimResult( File pomFile, ModelBuildingRequest request, ModelBuildingResult result, - DefaultModelBuildingListener listener, boolean root ) - { + InterimResult( + File pomFile, + ModelBuildingRequest request, + ModelBuildingResult result, + DefaultModelBuildingListener listener, + boolean root) { this.pomFile = pomFile; this.request = request; this.result = result; this.listener = listener; this.root = root; } - } - private boolean build( List results, List projects, - Map projectIndex, List interimResults, - ProjectBuildingRequest request, Map profilesXmls, - RepositorySystemSession session ) - { + private boolean build( + List results, + List projects, + Map projectIndex, + List interimResults, + ProjectBuildingRequest request, + Map profilesXmls, + RepositorySystemSession session) { boolean noErrors = true; - for ( InterimResult interimResult : interimResults ) - { + for (InterimResult interimResult : interimResults) { MavenProject project = interimResult.listener.getProject(); - try - { - ModelBuildingResult result = modelBuilder.build( interimResult.request, interimResult.result ); + try { + ModelBuildingResult result = modelBuilder.build(interimResult.request, interimResult.result); // 2nd pass of initialization: resolve and build parent if necessary - try - { - initProject( project, projectIndex, true, result, profilesXmls, request ); - } - catch ( InvalidArtifactRTException iarte ) - { - result.getProblems().add( new DefaultModelProblem( null, ModelProblem.Severity.ERROR, null, - result.getEffectiveModel(), -1, -1, iarte ) ); + try { + initProject(project, projectIndex, true, result, profilesXmls, request); + } catch (InvalidArtifactRTException iarte) { + result.getProblems() + .add(new DefaultModelProblem( + null, + ModelProblem.Severity.ERROR, + null, + result.getEffectiveModel(), + -1, + -1, + iarte)); } List modules = new ArrayList<>(); - noErrors = - build( results, modules, projectIndex, interimResult.modules, request, profilesXmls, session ) - && noErrors; + noErrors = build(results, modules, projectIndex, interimResult.modules, request, profilesXmls, session) + && noErrors; - projects.addAll( modules ); - projects.add( project ); + projects.addAll(modules); + projects.add(project); - project.setExecutionRoot( interimResult.root ); - project.setCollectedProjects( modules ); + project.setExecutionRoot(interimResult.root); + project.setCollectedProjects(modules); DependencyResolutionResult resolutionResult = null; - if ( request.isResolveDependencies() ) - { - resolutionResult = resolveDependencies( project, session ); + if (request.isResolveDependencies()) { + resolutionResult = resolveDependencies(project, session); } - results.add( new DefaultProjectBuildingResult( project, result.getProblems(), resolutionResult ) ); - } - catch ( ModelBuildingException e ) - { + results.add(new DefaultProjectBuildingResult(project, result.getProblems(), resolutionResult)); + } catch (ModelBuildingException e) { DefaultProjectBuildingResult result = null; - if ( project == null || interimResult.result.getEffectiveModel() == null ) - { - result = new DefaultProjectBuildingResult( e.getModelId(), interimResult.pomFile, e.getProblems() ); - } - else - { - project.setModel( interimResult.result.getEffectiveModel() ); + if (project == null || interimResult.result.getEffectiveModel() == null) { + result = new DefaultProjectBuildingResult(e.getModelId(), interimResult.pomFile, e.getProblems()); + } else { + project.setModel(interimResult.result.getEffectiveModel()); - result = new DefaultProjectBuildingResult( project, e.getProblems(), null ); + result = new DefaultProjectBuildingResult(project, e.getProblems(), null); } - results.add( result ); + results.add(result); noErrors = false; } @@ -671,165 +654,144 @@ public class DefaultProjectBuilder return noErrors; } - @SuppressWarnings( "checkstyle:methodlength" ) - private void initProject( MavenProject project, Map projects, - boolean buildParentIfNotExisting, ModelBuildingResult result, - Map profilesXmls, ProjectBuildingRequest projectBuildingRequest ) - { - project.setModel( result.getEffectiveModel() ); - project.setOriginalModel( result.getFileModel() ); + @SuppressWarnings("checkstyle:methodlength") + private void initProject( + MavenProject project, + Map projects, + boolean buildParentIfNotExisting, + ModelBuildingResult result, + Map profilesXmls, + ProjectBuildingRequest projectBuildingRequest) { + project.setModel(result.getEffectiveModel()); + project.setOriginalModel(result.getFileModel()); - initParent( project, projects, buildParentIfNotExisting, result, projectBuildingRequest ); + initParent(project, projects, buildParentIfNotExisting, result, projectBuildingRequest); - Artifact projectArtifact = - repositorySystem.createArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), null, - project.getPackaging() ); - project.setArtifact( projectArtifact ); + Artifact projectArtifact = repositorySystem.createArtifact( + project.getGroupId(), project.getArtifactId(), project.getVersion(), null, project.getPackaging()); + project.setArtifact(projectArtifact); - if ( project.getFile() != null && buildParentIfNotExisting ) // only set those on 2nd phase, ignore on 1st pass + if (project.getFile() != null && buildParentIfNotExisting) // only set those on 2nd phase, ignore on 1st pass { Build build = project.getBuild(); - project.addScriptSourceRoot( build.getScriptSourceDirectory() ); - project.addCompileSourceRoot( build.getSourceDirectory() ); - project.addTestCompileSourceRoot( build.getTestSourceDirectory() ); + project.addScriptSourceRoot(build.getScriptSourceDirectory()); + project.addCompileSourceRoot(build.getSourceDirectory()); + project.addTestCompileSourceRoot(build.getTestSourceDirectory()); } List activeProfiles = new ArrayList<>(); - activeProfiles.addAll( result.getActivePomProfiles( result.getModelIds().get( 0 ) ) ); - activeProfiles.addAll( result.getActiveExternalProfiles() ); - project.setActiveProfiles( activeProfiles ); + activeProfiles.addAll(result.getActivePomProfiles(result.getModelIds().get(0))); + activeProfiles.addAll(result.getActiveExternalProfiles()); + project.setActiveProfiles(activeProfiles); - project.setInjectedProfileIds( "external", getProfileIds( result.getActiveExternalProfiles() ) ); - for ( String modelId : result.getModelIds() ) - { - project.setInjectedProfileIds( modelId, getProfileIds( result.getActivePomProfiles( modelId ) ) ); + project.setInjectedProfileIds("external", getProfileIds(result.getActiveExternalProfiles())); + for (String modelId : result.getModelIds()) { + project.setInjectedProfileIds(modelId, getProfileIds(result.getActivePomProfiles(modelId))); } // // All the parts that were taken out of MavenProject for Maven 4.0.0 // - project.setProjectBuildingRequest( projectBuildingRequest ); + project.setProjectBuildingRequest(projectBuildingRequest); // pluginArtifacts Set pluginArtifacts = new HashSet<>(); - for ( Plugin plugin : project.getBuildPlugins() ) - { - Artifact artifact = repositorySystem.createPluginArtifact( plugin ); + for (Plugin plugin : project.getBuildPlugins()) { + Artifact artifact = repositorySystem.createPluginArtifact(plugin); - if ( artifact != null ) - { - pluginArtifacts.add( artifact ); + if (artifact != null) { + pluginArtifacts.add(artifact); } } - project.setPluginArtifacts( pluginArtifacts ); + project.setPluginArtifacts(pluginArtifacts); // reportArtifacts Set reportArtifacts = new HashSet<>(); - for ( ReportPlugin report : project.getReportPlugins() ) - { + for (ReportPlugin report : project.getReportPlugins()) { Plugin pp = new Plugin(); - pp.setGroupId( report.getGroupId() ); - pp.setArtifactId( report.getArtifactId() ); - pp.setVersion( report.getVersion() ); + pp.setGroupId(report.getGroupId()); + pp.setArtifactId(report.getArtifactId()); + pp.setVersion(report.getVersion()); - Artifact artifact = repositorySystem.createPluginArtifact( pp ); + Artifact artifact = repositorySystem.createPluginArtifact(pp); - if ( artifact != null ) - { - reportArtifacts.add( artifact ); + if (artifact != null) { + reportArtifacts.add(artifact); } } - project.setReportArtifacts( reportArtifacts ); + project.setReportArtifacts(reportArtifacts); // extensionArtifacts Set extensionArtifacts = new HashSet<>(); List extensions = project.getBuildExtensions(); - if ( extensions != null ) - { - for ( Extension ext : extensions ) - { + if (extensions != null) { + for (Extension ext : extensions) { String version; - if ( StringUtils.isEmpty( ext.getVersion() ) ) - { + if (StringUtils.isEmpty(ext.getVersion())) { version = "RELEASE"; - } - else - { + } else { version = ext.getVersion(); } Artifact artifact = - repositorySystem.createArtifact( ext.getGroupId(), ext.getArtifactId(), version, null, "jar" ); + repositorySystem.createArtifact(ext.getGroupId(), ext.getArtifactId(), version, null, "jar"); - if ( artifact != null ) - { - extensionArtifacts.add( artifact ); + if (artifact != null) { + extensionArtifacts.add(artifact); } } } - project.setExtensionArtifacts( extensionArtifacts ); + project.setExtensionArtifacts(extensionArtifacts); // managedVersionMap Map map = null; - if ( repositorySystem != null ) - { + if (repositorySystem != null) { final DependencyManagement dependencyManagement = project.getDependencyManagement(); - if ( ( dependencyManagement != null ) && ( ( dependencyManagement.getDependencies() ) != null ) - && ( dependencyManagement.getDependencies().size() > 0 ) ) - { - map = new AbstractMap() - { + if ((dependencyManagement != null) + && ((dependencyManagement.getDependencies()) != null) + && (dependencyManagement.getDependencies().size() > 0)) { + map = new AbstractMap() { HashMap delegate; @Override - public Set> entrySet() - { - return Collections.unmodifiableSet( compute().entrySet() ); + public Set> entrySet() { + return Collections.unmodifiableSet(compute().entrySet()); } @Override - public Set keySet() - { - return Collections.unmodifiableSet( compute().keySet() ); + public Set keySet() { + return Collections.unmodifiableSet(compute().keySet()); } @Override - public Collection values() - { - return Collections.unmodifiableCollection( compute().values() ); + public Collection values() { + return Collections.unmodifiableCollection(compute().values()); } @Override - public boolean containsValue( Object value ) - { - return compute().containsValue( value ); + public boolean containsValue(Object value) { + return compute().containsValue(value); } @Override - public boolean containsKey( Object key ) - { - return compute().containsKey( key ); + public boolean containsKey(Object key) { + return compute().containsKey(key); } @Override - public Artifact get( Object key ) - { - return compute().get( key ); + public Artifact get(Object key) { + return compute().get(key); } - HashMap compute() - { - if ( delegate == null ) - { + HashMap compute() { + if (delegate == null) { delegate = new HashMap<>(); - for ( Dependency d : dependencyManagement.getDependencies() ) - { - Artifact artifact = repositorySystem.createDependencyArtifact( d ); + for (Dependency d : dependencyManagement.getDependencies()) { + Artifact artifact = repositorySystem.createDependencyArtifact(d); - if ( artifact != null ) - { - delegate.put( d.getManagementKey(), artifact ); + if (artifact != null) { + delegate.put(d.getManagementKey(), artifact); } } } @@ -837,172 +799,135 @@ public class DefaultProjectBuilder return delegate; } }; - } - else - { + } else { map = Collections.emptyMap(); } } - project.setManagedVersionMap( map ); + project.setManagedVersionMap(map); // release artifact repository - if ( project.getDistributionManagement() != null - && project.getDistributionManagement().getRepository() != null ) - { - try - { + if (project.getDistributionManagement() != null + && project.getDistributionManagement().getRepository() != null) { + try { DeploymentRepository r = project.getDistributionManagement().getRepository(); - if ( !StringUtils.isEmpty( r.getId() ) && !StringUtils.isEmpty( r.getUrl() ) ) - { - ArtifactRepository repo = MavenRepositorySystem.buildArtifactRepository( r ); - repositorySystem.injectProxy( projectBuildingRequest.getRepositorySession(), - Arrays.asList( repo ) ); - repositorySystem.injectAuthentication( projectBuildingRequest.getRepositorySession(), - Arrays.asList( repo ) ); - project.setReleaseArtifactRepository( repo ); + if (!StringUtils.isEmpty(r.getId()) && !StringUtils.isEmpty(r.getUrl())) { + ArtifactRepository repo = MavenRepositorySystem.buildArtifactRepository(r); + repositorySystem.injectProxy(projectBuildingRequest.getRepositorySession(), Arrays.asList(repo)); + repositorySystem.injectAuthentication( + projectBuildingRequest.getRepositorySession(), Arrays.asList(repo)); + project.setReleaseArtifactRepository(repo); } - } - catch ( InvalidRepositoryException e ) - { - throw new IllegalStateException( "Failed to create release distribution repository for " - + project.getId(), e ); + } catch (InvalidRepositoryException e) { + throw new IllegalStateException( + "Failed to create release distribution repository for " + project.getId(), e); } } // snapshot artifact repository - if ( project.getDistributionManagement() != null - && project.getDistributionManagement().getSnapshotRepository() != null ) - { - try - { + if (project.getDistributionManagement() != null + && project.getDistributionManagement().getSnapshotRepository() != null) { + try { DeploymentRepository r = project.getDistributionManagement().getSnapshotRepository(); - if ( !StringUtils.isEmpty( r.getId() ) && !StringUtils.isEmpty( r.getUrl() ) ) - { - ArtifactRepository repo = MavenRepositorySystem.buildArtifactRepository( r ); - repositorySystem.injectProxy( projectBuildingRequest.getRepositorySession(), - Arrays.asList( repo ) ); - repositorySystem.injectAuthentication( projectBuildingRequest.getRepositorySession(), - Arrays.asList( repo ) ); - project.setSnapshotArtifactRepository( repo ); + if (!StringUtils.isEmpty(r.getId()) && !StringUtils.isEmpty(r.getUrl())) { + ArtifactRepository repo = MavenRepositorySystem.buildArtifactRepository(r); + repositorySystem.injectProxy(projectBuildingRequest.getRepositorySession(), Arrays.asList(repo)); + repositorySystem.injectAuthentication( + projectBuildingRequest.getRepositorySession(), Arrays.asList(repo)); + project.setSnapshotArtifactRepository(repo); } - } - catch ( InvalidRepositoryException e ) - { - throw new IllegalStateException( "Failed to create snapshot distribution repository for " - + project.getId(), e ); + } catch (InvalidRepositoryException e) { + throw new IllegalStateException( + "Failed to create snapshot distribution repository for " + project.getId(), e); } } } - private void initParent( MavenProject project, Map projects, boolean buildParentIfNotExisting, - ModelBuildingResult result, ProjectBuildingRequest projectBuildingRequest ) - { - Model parentModel = result.getModelIds().size() > 1 && !result.getModelIds().get( 1 ).isEmpty() - ? result.getRawModel( result.getModelIds().get( 1 ) ) - : null; + private void initParent( + MavenProject project, + Map projects, + boolean buildParentIfNotExisting, + ModelBuildingResult result, + ProjectBuildingRequest projectBuildingRequest) { + Model parentModel = + result.getModelIds().size() > 1 && !result.getModelIds().get(1).isEmpty() + ? result.getRawModel(result.getModelIds().get(1)) + : null; - if ( parentModel != null ) - { - final String parentGroupId = inheritedGroupId( result, 1 ); - final String parentVersion = inheritedVersion( result, 1 ); + if (parentModel != null) { + final String parentGroupId = inheritedGroupId(result, 1); + final String parentVersion = inheritedVersion(result, 1); - project.setParentArtifact( repositorySystem.createProjectArtifact( parentGroupId, - parentModel.getArtifactId(), - parentVersion ) ); + project.setParentArtifact( + repositorySystem.createProjectArtifact(parentGroupId, parentModel.getArtifactId(), parentVersion)); // org.apache.maven.its.mng4834:parent:0.1 - String parentModelId = result.getModelIds().get( 1 ); - File parentPomFile = result.getRawModel( parentModelId ).getPomFile(); - MavenProject parent = projects.get( parentPomFile ); - if ( parent == null && buildParentIfNotExisting ) - { + String parentModelId = result.getModelIds().get(1); + File parentPomFile = result.getRawModel(parentModelId).getPomFile(); + MavenProject parent = projects.get(parentPomFile); + if (parent == null && buildParentIfNotExisting) { // // At this point the DefaultModelBuildingListener has fired and it populates the // remote repositories with those found in the pom.xml, along with the existing externally // defined repositories. // - projectBuildingRequest.setRemoteRepositories( project.getRemoteArtifactRepositories() ); - if ( parentPomFile != null ) - { - project.setParentFile( parentPomFile ); - try - { - parent = build( parentPomFile, projectBuildingRequest ).getProject(); - } - catch ( ProjectBuildingException e ) - { + projectBuildingRequest.setRemoteRepositories(project.getRemoteArtifactRepositories()); + if (parentPomFile != null) { + project.setParentFile(parentPomFile); + try { + parent = build(parentPomFile, projectBuildingRequest).getProject(); + } catch (ProjectBuildingException e) { // MNG-4488 where let invalid parents slide on by - if ( logger.isDebugEnabled() ) - { + if (logger.isDebugEnabled()) { // Message below is checked for in the MNG-2199 core IT. - logger.warn( "Failed to build parent project for " + project.getId(), e ); - } - else - { + logger.warn("Failed to build parent project for " + project.getId(), e); + } else { // Message below is checked for in the MNG-2199 core IT. - logger.warn( "Failed to build parent project for " + project.getId() ); + logger.warn("Failed to build parent project for " + project.getId()); } } - } - else - { + } else { Artifact parentArtifact = project.getParentArtifact(); - try - { - parent = build( parentArtifact, projectBuildingRequest ).getProject(); - } - catch ( ProjectBuildingException e ) - { + try { + parent = build(parentArtifact, projectBuildingRequest).getProject(); + } catch (ProjectBuildingException e) { // MNG-4488 where let invalid parents slide on by - if ( logger.isDebugEnabled() ) - { + if (logger.isDebugEnabled()) { // Message below is checked for in the MNG-2199 core IT. - logger.warn( "Failed to build parent project for " + project.getId(), e ); - } - else - { + logger.warn("Failed to build parent project for " + project.getId(), e); + } else { // Message below is checked for in the MNG-2199 core IT. - logger.warn( "Failed to build parent project for " + project.getId() ); + logger.warn("Failed to build parent project for " + project.getId()); } } } } - project.setParent( parent ); - if ( project.getParentFile() == null && parent != null ) - { - project.setParentFile( parent.getFile() ); + project.setParent(parent); + if (project.getParentFile() == null && parent != null) { + project.setParentFile(parent.getFile()); } } } - private static String inheritedGroupId( final ModelBuildingResult result, final int modelIndex ) - { + private static String inheritedGroupId(final ModelBuildingResult result, final int modelIndex) { String groupId = null; - final String modelId = result.getModelIds().get( modelIndex ); - - if ( !modelId.isEmpty() ) - { - final Model model = result.getRawModel( modelId ); - groupId = model.getGroupId() != null - ? model.getGroupId() - : inheritedGroupId( result, modelIndex + 1 ); + final String modelId = result.getModelIds().get(modelIndex); + if (!modelId.isEmpty()) { + final Model model = result.getRawModel(modelId); + groupId = model.getGroupId() != null ? model.getGroupId() : inheritedGroupId(result, modelIndex + 1); } return groupId; } - private static String inheritedVersion( final ModelBuildingResult result, final int modelIndex ) - { + private static String inheritedVersion(final ModelBuildingResult result, final int modelIndex) { String version = null; - final String modelId = result.getModelIds().get( modelIndex ); + final String modelId = result.getModelIds().get(modelIndex); - if ( !modelId.isEmpty() ) - { - version = result.getRawModel( modelId ).getVersion(); - if ( version == null ) - { - version = inheritedVersion( result, modelIndex + 1 ); + if (!modelId.isEmpty()) { + version = result.getRawModel(modelId).getVersion(); + if (version == null) { + version = inheritedVersion(result, modelIndex + 1); } } @@ -1012,8 +937,7 @@ public class DefaultProjectBuilder /** * InternalConfig */ - class InternalConfig - { + class InternalConfig { private final ProjectBuildingRequest request; @@ -1025,20 +949,17 @@ public class DefaultProjectBuilder private final TransformerContextBuilder transformerContextBuilder; - InternalConfig( ProjectBuildingRequest request, ReactorModelPool modelPool, - TransformerContextBuilder transformerContextBuilder ) - { + InternalConfig( + ProjectBuildingRequest request, + ReactorModelPool modelPool, + TransformerContextBuilder transformerContextBuilder) { this.request = request; this.modelPool = modelPool; this.transformerContextBuilder = transformerContextBuilder; - session = - LegacyLocalRepositoryManager.overlay( request.getLocalRepository(), request.getRepositorySession(), - repoSystem ); - repositories = RepositoryUtils.toRepos( request.getRemoteRepositories() ); - + session = LegacyLocalRepositoryManager.overlay( + request.getLocalRepository(), request.getRepositorySession(), repoSystem); + repositories = RepositoryUtils.toRepos(request.getRemoteRepositories()); } - } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingHelper.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingHelper.java index 690dcd19d6..60797d8fda 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingHelper.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.Arrays; @@ -28,11 +27,9 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; @@ -65,10 +62,8 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultProjectBuildingHelper - implements ProjectBuildingHelper -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultProjectBuildingHelper implements ProjectBuildingHelper { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final PlexusContainer container; // TODO not used? Then remove private final ClassRealmManager classRealmManager; private final ProjectRealmCache projectRealmCache; @@ -81,8 +76,7 @@ public class DefaultProjectBuildingHelper ClassRealmManager classRealmManager, ProjectRealmCache projectRealmCache, RepositorySystem repositorySystem, - MavenPluginManager pluginManager ) - { + MavenPluginManager pluginManager) { this.container = container; this.classRealmManager = classRealmManager; this.projectRealmCache = projectRealmCache; @@ -90,34 +84,30 @@ public class DefaultProjectBuildingHelper this.pluginManager = pluginManager; } - public List createArtifactRepositories( List pomRepositories, - List externalRepositories, - ProjectBuildingRequest request ) - throws InvalidRepositoryException - { + public List createArtifactRepositories( + List pomRepositories, + List externalRepositories, + ProjectBuildingRequest request) + throws InvalidRepositoryException { List internalRepositories = new ArrayList<>(); - for ( Repository repository : pomRepositories ) - { - internalRepositories.add( repositorySystem.buildArtifactRepository( repository ) ); + for (Repository repository : pomRepositories) { + internalRepositories.add(repositorySystem.buildArtifactRepository(repository)); } - repositorySystem.injectMirror( request.getRepositorySession(), internalRepositories ); + repositorySystem.injectMirror(request.getRepositorySession(), internalRepositories); - repositorySystem.injectProxy( request.getRepositorySession(), internalRepositories ); + repositorySystem.injectProxy(request.getRepositorySession(), internalRepositories); - repositorySystem.injectAuthentication( request.getRepositorySession(), internalRepositories ); + repositorySystem.injectAuthentication(request.getRepositorySession(), internalRepositories); List dominantRepositories; List recessiveRepositories; - if ( ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT.equals( request.getRepositoryMerging() ) ) - { + if (ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT.equals(request.getRepositoryMerging())) { dominantRepositories = externalRepositories; recessiveRepositories = internalRepositories; - } - else - { + } else { dominantRepositories = internalRepositories; recessiveRepositories = externalRepositories; } @@ -125,69 +115,57 @@ public class DefaultProjectBuildingHelper List artifactRepositories = new ArrayList<>(); Collection repoIds = new HashSet<>(); - if ( dominantRepositories != null ) - { - for ( ArtifactRepository repository : dominantRepositories ) - { - repoIds.add( repository.getId() ); - artifactRepositories.add( repository ); + if (dominantRepositories != null) { + for (ArtifactRepository repository : dominantRepositories) { + repoIds.add(repository.getId()); + artifactRepositories.add(repository); } } - if ( recessiveRepositories != null ) - { - for ( ArtifactRepository repository : recessiveRepositories ) - { - if ( repoIds.add( repository.getId() ) ) - { - artifactRepositories.add( repository ); + if (recessiveRepositories != null) { + for (ArtifactRepository repository : recessiveRepositories) { + if (repoIds.add(repository.getId())) { + artifactRepositories.add(repository); } } } - artifactRepositories = repositorySystem.getEffectiveRepositories( artifactRepositories ); + artifactRepositories = repositorySystem.getEffectiveRepositories(artifactRepositories); return artifactRepositories; } - public synchronized ProjectRealmCache.CacheRecord createProjectRealm( MavenProject project, Model model, - ProjectBuildingRequest request ) - throws PluginResolutionException, PluginVersionResolutionException, PluginManagerException - { + public synchronized ProjectRealmCache.CacheRecord createProjectRealm( + MavenProject project, Model model, ProjectBuildingRequest request) + throws PluginResolutionException, PluginVersionResolutionException, PluginManagerException { ClassRealm projectRealm; List extensionPlugins = new ArrayList<>(); Build build = model.getBuild(); - if ( build != null ) - { - for ( Extension extension : build.getExtensions() ) - { + if (build != null) { + for (Extension extension : build.getExtensions()) { Plugin plugin = new Plugin(); - plugin.setGroupId( extension.getGroupId() ); - plugin.setArtifactId( extension.getArtifactId() ); - plugin.setVersion( extension.getVersion() ); - extensionPlugins.add( plugin ); + plugin.setGroupId(extension.getGroupId()); + plugin.setArtifactId(extension.getArtifactId()); + plugin.setVersion(extension.getVersion()); + extensionPlugins.add(plugin); } - for ( Plugin plugin : build.getPlugins() ) - { - if ( plugin.isExtensions() ) - { - extensionPlugins.add( plugin ); + for (Plugin plugin : build.getPlugins()) { + if (plugin.isExtensions()) { + extensionPlugins.add(plugin); } } } - if ( extensionPlugins.isEmpty() ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Extension realms for project " + model.getId() + ": (none)" ); + if (extensionPlugins.isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug("Extension realms for project " + model.getId() + ": (none)"); } - return new ProjectRealmCache.CacheRecord( null, null ); + return new ProjectRealmCache.CacheRecord(null, null); } List extensionRealms = new ArrayList<>(); @@ -198,104 +176,92 @@ public class DefaultProjectBuildingHelper List publicArtifacts = new ArrayList<>(); - for ( Plugin plugin : extensionPlugins ) - { + for (Plugin plugin : extensionPlugins) { ExtensionRealmCache.CacheRecord recordRealm = - pluginManager.setupExtensionsRealm( project, plugin, request.getRepositorySession() ); + pluginManager.setupExtensionsRealm(project, plugin, request.getRepositorySession()); final ClassRealm extensionRealm = recordRealm.getRealm(); final ExtensionDescriptor extensionDescriptor = recordRealm.getDescriptor(); final List artifacts = recordRealm.getArtifacts(); - extensionRealms.add( extensionRealm ); - if ( extensionDescriptor != null ) - { - exportedPackages.put( extensionRealm, extensionDescriptor.getExportedPackages() ); - exportedArtifacts.put( extensionRealm, extensionDescriptor.getExportedArtifacts() ); + extensionRealms.add(extensionRealm); + if (extensionDescriptor != null) { + exportedPackages.put(extensionRealm, extensionDescriptor.getExportedPackages()); + exportedArtifacts.put(extensionRealm, extensionDescriptor.getExportedArtifacts()); } - if ( !plugin.isExtensions() && artifacts.size() == 1 && artifacts.get( 0 ).getFile() != null ) - { + if (!plugin.isExtensions() + && artifacts.size() == 1 + && artifacts.get(0).getFile() != null) { /* * This is purely for backward-compat with 2.x where consisting of a single artifact where * loaded into the core and hence available to plugins, in contrast to bigger extensions that were * loaded into a dedicated realm which is invisible to plugins (MNG-2749). */ - publicArtifacts.addAll( artifacts ); + publicArtifacts.addAll(artifacts); } } - if ( logger.isDebugEnabled() ) - { - logger.debug( "Extension realms for project " + model.getId() + ": " + extensionRealms ); + if (logger.isDebugEnabled()) { + logger.debug("Extension realms for project " + model.getId() + ": " + extensionRealms); } - ProjectRealmCache.Key projectRealmKey = projectRealmCache.createKey( extensionRealms ); + ProjectRealmCache.Key projectRealmKey = projectRealmCache.createKey(extensionRealms); - ProjectRealmCache.CacheRecord record = projectRealmCache.get( projectRealmKey ); + ProjectRealmCache.CacheRecord record = projectRealmCache.get(projectRealmKey); - if ( record == null ) - { - projectRealm = classRealmManager.createProjectRealm( model, toAetherArtifacts( publicArtifacts ) ); + if (record == null) { + projectRealm = classRealmManager.createProjectRealm(model, toAetherArtifacts(publicArtifacts)); Set exclusions = new LinkedHashSet<>(); - for ( ClassRealm extensionRealm : extensionRealms ) - { - List excludes = exportedArtifacts.get( extensionRealm ); + for (ClassRealm extensionRealm : extensionRealms) { + List excludes = exportedArtifacts.get(extensionRealm); - if ( excludes != null ) - { - exclusions.addAll( excludes ); + if (excludes != null) { + exclusions.addAll(excludes); } - List exports = exportedPackages.get( extensionRealm ); + List exports = exportedPackages.get(extensionRealm); - if ( exports == null || exports.isEmpty() ) - { + if (exports == null || exports.isEmpty()) { /* * Most existing extensions don't define exported packages, i.e. no classes are to be exposed to * plugins, yet the components provided by the extension (e.g. artifact handlers) must be * accessible, i.e. we still must import the extension realm into the project realm. */ - exports = Arrays.asList( extensionRealm.getId() ); + exports = Arrays.asList(extensionRealm.getId()); } - for ( String export : exports ) - { - projectRealm.importFrom( extensionRealm, export ); + for (String export : exports) { + projectRealm.importFrom(extensionRealm, export); } } DependencyFilter extensionArtifactFilter = null; - if ( !exclusions.isEmpty() ) - { - extensionArtifactFilter = new ExclusionsDependencyFilter( exclusions ); + if (!exclusions.isEmpty()) { + extensionArtifactFilter = new ExclusionsDependencyFilter(exclusions); } - record = projectRealmCache.put( projectRealmKey, projectRealm, extensionArtifactFilter ); + record = projectRealmCache.put(projectRealmKey, projectRealm, extensionArtifactFilter); } - projectRealmCache.register( project, projectRealmKey, record ); + projectRealmCache.register(project, projectRealmKey, record); return record; } - public void selectProjectRealm( MavenProject project ) - { + public void selectProjectRealm(MavenProject project) { ClassLoader projectRealm = project.getClassRealm(); - if ( projectRealm == null ) - { + if (projectRealm == null) { projectRealm = classRealmManager.getCoreRealm(); } - Thread.currentThread().setContextClassLoader( projectRealm ); + Thread.currentThread().setContextClassLoader(projectRealm); } - private List toAetherArtifacts( final List pluginArtifacts ) - { - return new ArrayList<>( RepositoryUtils.toArtifacts( pluginArtifacts ) ); + private List toAetherArtifacts(final List pluginArtifacts) { + return new ArrayList<>(RepositoryUtils.toArtifacts(pluginArtifacts)); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingRequest.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingRequest.java index 39ccf965fe..872c15b86a 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingRequest.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Properties; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Profile; import org.apache.maven.model.building.ModelBuildingRequest; @@ -34,9 +32,7 @@ import org.eclipse.aether.RepositorySystemSession; /** * DefaultProjectBuildingRequest */ -public class DefaultProjectBuildingRequest - implements ProjectBuildingRequest -{ +public class DefaultProjectBuildingRequest implements ProjectBuildingRequest { private RepositorySystemSession repositorySession; @@ -71,8 +67,7 @@ public class DefaultProjectBuildingRequest private RepositoryMerging repositoryMerging = RepositoryMerging.POM_DOMINANT; - public DefaultProjectBuildingRequest() - { + public DefaultProjectBuildingRequest() { processPlugins = true; profiles = new ArrayList<>(); activeProfileIds = new ArrayList<>(); @@ -83,144 +78,115 @@ public class DefaultProjectBuildingRequest pluginArtifactRepositories = new ArrayList<>(); } - public DefaultProjectBuildingRequest( ProjectBuildingRequest request ) - { + public DefaultProjectBuildingRequest(ProjectBuildingRequest request) { this(); - setProcessPlugins( request.isProcessPlugins() ); - setProfiles( request.getProfiles() ); - setActiveProfileIds( request.getActiveProfileIds() ); - setInactiveProfileIds( request.getInactiveProfileIds() ); - setSystemProperties( request.getSystemProperties() ); - setUserProperties( request.getUserProperties() ); - setRemoteRepositories( request.getRemoteRepositories() ); - setPluginArtifactRepositories( request.getPluginArtifactRepositories() ); - setRepositorySession( request.getRepositorySession() ); - setLocalRepository( request.getLocalRepository() ); - setBuildStartTime( request.getBuildStartTime() ); - setProject( request.getProject() ); - setResolveDependencies( request.isResolveDependencies() ); - setValidationLevel( request.getValidationLevel() ); - setResolveVersionRanges( request.isResolveVersionRanges() ); - setRepositoryMerging( request.getRepositoryMerging() ); + setProcessPlugins(request.isProcessPlugins()); + setProfiles(request.getProfiles()); + setActiveProfileIds(request.getActiveProfileIds()); + setInactiveProfileIds(request.getInactiveProfileIds()); + setSystemProperties(request.getSystemProperties()); + setUserProperties(request.getUserProperties()); + setRemoteRepositories(request.getRemoteRepositories()); + setPluginArtifactRepositories(request.getPluginArtifactRepositories()); + setRepositorySession(request.getRepositorySession()); + setLocalRepository(request.getLocalRepository()); + setBuildStartTime(request.getBuildStartTime()); + setProject(request.getProject()); + setResolveDependencies(request.isResolveDependencies()); + setValidationLevel(request.getValidationLevel()); + setResolveVersionRanges(request.isResolveVersionRanges()); + setRepositoryMerging(request.getRepositoryMerging()); } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public void setProject( MavenProject mavenProject ) - { + public void setProject(MavenProject mavenProject) { this.project = mavenProject; } - public ProjectBuildingRequest setLocalRepository( ArtifactRepository localRepository ) - { + public ProjectBuildingRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; return this; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - public ProjectBuildingRequest setRemoteRepositories( List remoteRepositories ) - { - if ( remoteRepositories != null ) - { - this.remoteRepositories = new ArrayList<>( remoteRepositories ); - } - else - { + public ProjectBuildingRequest setRemoteRepositories(List remoteRepositories) { + if (remoteRepositories != null) { + this.remoteRepositories = new ArrayList<>(remoteRepositories); + } else { this.remoteRepositories.clear(); } return this; } - public List getPluginArtifactRepositories() - { + public List getPluginArtifactRepositories() { return pluginArtifactRepositories; } - public ProjectBuildingRequest setPluginArtifactRepositories( List pluginArtifactRepositories ) - { - if ( pluginArtifactRepositories != null ) - { - this.pluginArtifactRepositories = new ArrayList<>( pluginArtifactRepositories ); - } - else - { + public ProjectBuildingRequest setPluginArtifactRepositories(List pluginArtifactRepositories) { + if (pluginArtifactRepositories != null) { + this.pluginArtifactRepositories = new ArrayList<>(pluginArtifactRepositories); + } else { this.pluginArtifactRepositories.clear(); } return this; } - public Properties getSystemProperties() - { + public Properties getSystemProperties() { return systemProperties; } - public ProjectBuildingRequest setSystemProperties( Properties systemProperties ) - { - if ( systemProperties != null ) - { - this.systemProperties = SystemProperties.copyProperties( systemProperties ); - } - else - { + public ProjectBuildingRequest setSystemProperties(Properties systemProperties) { + if (systemProperties != null) { + this.systemProperties = SystemProperties.copyProperties(systemProperties); + } else { this.systemProperties.clear(); } return this; } - public Properties getUserProperties() - { + public Properties getUserProperties() { return userProperties; } - public ProjectBuildingRequest setUserProperties( Properties userProperties ) - { - if ( userProperties != null ) - { + public ProjectBuildingRequest setUserProperties(Properties userProperties) { + if (userProperties != null) { this.userProperties = new Properties(); - this.userProperties.putAll( userProperties ); - } - else - { + this.userProperties.putAll(userProperties); + } else { this.userProperties.clear(); } return this; } - public boolean isProcessPlugins() - { + public boolean isProcessPlugins() { return processPlugins; } - public ProjectBuildingRequest setProcessPlugins( boolean processPlugins ) - { + public ProjectBuildingRequest setProcessPlugins(boolean processPlugins) { this.processPlugins = processPlugins; return this; } - public ProjectBuildingRequest setResolveDependencies( boolean resolveDependencies ) - { + public ProjectBuildingRequest setResolveDependencies(boolean resolveDependencies) { this.resolveDependencies = resolveDependencies; return this; } - public boolean isResolveDependencies() - { + public boolean isResolveDependencies() { return resolveDependencies; } @@ -230,8 +196,7 @@ public class DefaultProjectBuildingRequest * Commit 6cf9320942c34bc68205425ab696b1712ace9ba4 updated the way 'MavenProject' objects are initialized. */ @Deprecated - public ProjectBuildingRequest setResolveVersionRanges( boolean value ) - { + public ProjectBuildingRequest setResolveVersionRanges(boolean value) { this.resolveVersionRanges = value; return this; } @@ -242,108 +207,82 @@ public class DefaultProjectBuildingRequest * Commit 6cf9320942c34bc68205425ab696b1712ace9ba4 updated the way 'MavenProject' objects are initialized. */ @Deprecated - public boolean isResolveVersionRanges() - { + public boolean isResolveVersionRanges() { return this.resolveVersionRanges; } - public ProjectBuildingRequest setValidationLevel( int validationLevel ) - { + public ProjectBuildingRequest setValidationLevel(int validationLevel) { this.validationLevel = validationLevel; return this; } - public int getValidationLevel() - { + public int getValidationLevel() { return validationLevel; } - public List getActiveProfileIds() - { + public List getActiveProfileIds() { return activeProfileIds; } - public void setActiveProfileIds( List activeProfileIds ) - { - if ( activeProfileIds != null ) - { - this.activeProfileIds = new ArrayList<>( activeProfileIds ); - } - else - { + public void setActiveProfileIds(List activeProfileIds) { + if (activeProfileIds != null) { + this.activeProfileIds = new ArrayList<>(activeProfileIds); + } else { this.activeProfileIds.clear(); } } - public List getInactiveProfileIds() - { + public List getInactiveProfileIds() { return inactiveProfileIds; } - public void setInactiveProfileIds( List inactiveProfileIds ) - { - if ( inactiveProfileIds != null ) - { - this.inactiveProfileIds = new ArrayList<>( inactiveProfileIds ); - } - else - { + public void setInactiveProfileIds(List inactiveProfileIds) { + if (inactiveProfileIds != null) { + this.inactiveProfileIds = new ArrayList<>(inactiveProfileIds); + } else { this.inactiveProfileIds.clear(); } } - public void setProfiles( List profiles ) - { - if ( profiles != null ) - { - this.profiles = new ArrayList<>( profiles ); - } - else - { + public void setProfiles(List profiles) { + if (profiles != null) { + this.profiles = new ArrayList<>(profiles); + } else { this.profiles.clear(); } } - public void addProfile( Profile profile ) - { - profiles.add( profile ); + public void addProfile(Profile profile) { + profiles.add(profile); } - public List getProfiles() - { + public List getProfiles() { return profiles; } - public Date getBuildStartTime() - { + public Date getBuildStartTime() { return buildStartTime; } - public void setBuildStartTime( Date buildStartTime ) - { + public void setBuildStartTime(Date buildStartTime) { this.buildStartTime = buildStartTime; } - public RepositorySystemSession getRepositorySession() - { + public RepositorySystemSession getRepositorySession() { return repositorySession; } - public DefaultProjectBuildingRequest setRepositorySession( RepositorySystemSession repositorySession ) - { + public DefaultProjectBuildingRequest setRepositorySession(RepositorySystemSession repositorySession) { this.repositorySession = repositorySession; return this; } - public DefaultProjectBuildingRequest setRepositoryMerging( RepositoryMerging repositoryMerging ) - { - this.repositoryMerging = Objects.requireNonNull( repositoryMerging, "repositoryMerging cannot be null" ); + public DefaultProjectBuildingRequest setRepositoryMerging(RepositoryMerging repositoryMerging) { + this.repositoryMerging = Objects.requireNonNull(repositoryMerging, "repositoryMerging cannot be null"); return this; } - public RepositoryMerging getRepositoryMerging() - { + public RepositoryMerging getRepositoryMerging() { return repositoryMerging; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java index bcc6b4faef..2fcaf451de 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuildingResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.ArrayList; import java.util.List; - import org.apache.maven.model.building.ModelProblem; /** @@ -30,9 +28,7 @@ import org.apache.maven.model.building.ModelProblem; * * @author Benjamin Bentmann */ -class DefaultProjectBuildingResult - implements ProjectBuildingResult -{ +class DefaultProjectBuildingResult implements ProjectBuildingResult { private String projectId; @@ -51,13 +47,12 @@ class DefaultProjectBuildingResult * @param problems The problems that were encountered, may be {@code null}. * @param dependencyResolutionResult The result of the resolution for the project dependencies, may be {@code null}. */ - DefaultProjectBuildingResult( MavenProject project, List problems, - DependencyResolutionResult dependencyResolutionResult ) - { - this.projectId = - ( project != null ) ? project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion() - : ""; - this.pomFile = ( project != null ) ? project.getFile() : null; + DefaultProjectBuildingResult( + MavenProject project, List problems, DependencyResolutionResult dependencyResolutionResult) { + this.projectId = (project != null) + ? project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion() + : ""; + this.pomFile = (project != null) ? project.getFile() : null; this.project = project; this.problems = problems; this.dependencyResolutionResult = dependencyResolutionResult; @@ -70,41 +65,33 @@ class DefaultProjectBuildingResult * @param pomFile The POM file from which the project was built, may be {@code null}. * @param problems The problems that were encountered, may be {@code null}. */ - DefaultProjectBuildingResult( String projectId, File pomFile, List problems ) - { - this.projectId = ( projectId != null ) ? projectId : ""; + DefaultProjectBuildingResult(String projectId, File pomFile, List problems) { + this.projectId = (projectId != null) ? projectId : ""; this.pomFile = pomFile; this.problems = problems; } - public String getProjectId() - { + public String getProjectId() { return projectId; } - public File getPomFile() - { + public File getPomFile() { return pomFile; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public List getProblems() - { - if ( problems == null ) - { + public List getProblems() { + if (problems == null) { problems = new ArrayList<>(); } return problems; } - public DependencyResolutionResult getDependencyResolutionResult() - { + public DependencyResolutionResult getDependencyResolutionResult() { return dependencyResolutionResult; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectDependenciesResolver.java index c20b9aa886..aa69f0123a 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectDependenciesResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,16 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; @@ -59,26 +56,21 @@ import org.slf4j.LoggerFactory; */ @Named @Singleton -public class DefaultProjectDependenciesResolver - implements ProjectDependenciesResolver -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultProjectDependenciesResolver implements ProjectDependenciesResolver { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final RepositorySystem repoSystem; private final List decorators; @Inject public DefaultProjectDependenciesResolver( - RepositorySystem repoSystem, - List decorators ) - { + RepositorySystem repoSystem, List decorators) { this.repoSystem = repoSystem; this.decorators = decorators; } - public DependencyResolutionResult resolve( DependencyResolutionRequest request ) - throws DependencyResolutionException - { - final RequestTrace trace = RequestTrace.newChild( null, request ); + public DependencyResolutionResult resolve(DependencyResolutionRequest request) + throws DependencyResolutionException { + final RequestTrace trace = RequestTrace.newChild(null, request); final DefaultDependencyResolutionResult result = new DefaultDependencyResolutionResult(); @@ -87,261 +79,214 @@ public class DefaultProjectDependenciesResolver RepositorySystemSession session = request.getRepositorySession(); ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry(); - if ( logger.isDebugEnabled() - && session.getConfigProperties().get( DependencyManagerUtils.CONFIG_PROP_VERBOSE ) == null ) - { - DefaultRepositorySystemSession verbose = new DefaultRepositorySystemSession( session ); - verbose.setConfigProperty( DependencyManagerUtils.CONFIG_PROP_VERBOSE, Boolean.TRUE ); + if (logger.isDebugEnabled() + && session.getConfigProperties().get(DependencyManagerUtils.CONFIG_PROP_VERBOSE) == null) { + DefaultRepositorySystemSession verbose = new DefaultRepositorySystemSession(session); + verbose.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, Boolean.TRUE); session = verbose; } - for ( RepositorySessionDecorator decorator : decorators ) - { - RepositorySystemSession decorated = decorator.decorate( project, session ); - if ( decorated != null ) - { + for (RepositorySessionDecorator decorator : decorators) { + RepositorySystemSession decorated = decorator.decorate(project, session); + if (decorated != null) { session = decorated; } } CollectRequest collect = new CollectRequest(); - collect.setRootArtifact( RepositoryUtils.toArtifact( project.getArtifact() ) ); - collect.setRequestContext( "project" ); - collect.setRepositories( project.getRemoteProjectRepositories() ); + collect.setRootArtifact(RepositoryUtils.toArtifact(project.getArtifact())); + collect.setRequestContext("project"); + collect.setRepositories(project.getRemoteProjectRepositories()); - if ( project.getDependencyArtifacts() == null ) - { - for ( Dependency dependency : project.getDependencies() ) - { - if ( StringUtils.isEmpty( dependency.getGroupId() ) || StringUtils.isEmpty( dependency.getArtifactId() ) - || StringUtils.isEmpty( dependency.getVersion() ) ) - { + if (project.getDependencyArtifacts() == null) { + for (Dependency dependency : project.getDependencies()) { + if (StringUtils.isEmpty(dependency.getGroupId()) + || StringUtils.isEmpty(dependency.getArtifactId()) + || StringUtils.isEmpty(dependency.getVersion())) { // guard against case where best-effort resolution for invalid models is requested continue; } - collect.addDependency( RepositoryUtils.toDependency( dependency, stereotypes ) ); + collect.addDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } - } - else - { + } else { Map dependencies = new HashMap<>(); - for ( Dependency dependency : project.getDependencies() ) - { + for (Dependency dependency : project.getDependencies()) { String classifier = dependency.getClassifier(); - if ( classifier == null ) - { - ArtifactType type = stereotypes.get( dependency.getType() ); - if ( type != null ) - { + if (classifier == null) { + ArtifactType type = stereotypes.get(dependency.getType()); + if (type != null) { classifier = type.getClassifier(); } } - String key = - ArtifactIdUtils.toVersionlessId( dependency.getGroupId(), dependency.getArtifactId(), - dependency.getType(), classifier ); - dependencies.put( key, dependency ); + String key = ArtifactIdUtils.toVersionlessId( + dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), classifier); + dependencies.put(key, dependency); } - for ( Artifact artifact : project.getDependencyArtifacts() ) - { + for (Artifact artifact : project.getDependencyArtifacts()) { String key = artifact.getDependencyConflictId(); - Dependency dependency = dependencies.get( key ); + Dependency dependency = dependencies.get(key); Collection exclusions = dependency != null ? dependency.getExclusions() : null; - org.eclipse.aether.graph.Dependency dep = RepositoryUtils.toDependency( artifact, exclusions ); - if ( !JavaScopes.SYSTEM.equals( dep.getScope() ) && dep.getArtifact().getFile() != null ) - { + org.eclipse.aether.graph.Dependency dep = RepositoryUtils.toDependency(artifact, exclusions); + if (!JavaScopes.SYSTEM.equals(dep.getScope()) + && dep.getArtifact().getFile() != null) { // enable re-resolution org.eclipse.aether.artifact.Artifact art = dep.getArtifact(); - art = art.setFile( null ).setVersion( art.getBaseVersion() ); - dep = dep.setArtifact( art ); + art = art.setFile(null).setVersion(art.getBaseVersion()); + dep = dep.setArtifact(art); } - collect.addDependency( dep ); + collect.addDependency(dep); } } DependencyManagement depMgmt = project.getDependencyManagement(); - if ( depMgmt != null ) - { - for ( Dependency dependency : depMgmt.getDependencies() ) - { - collect.addManagedDependency( RepositoryUtils.toDependency( dependency, stereotypes ) ); + if (depMgmt != null) { + for (Dependency dependency : depMgmt.getDependencies()) { + collect.addManagedDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } } - DependencyRequest depRequest = new DependencyRequest( collect, filter ); - depRequest.setTrace( trace ); + DependencyRequest depRequest = new DependencyRequest(collect, filter); + depRequest.setTrace(trace); DependencyNode node; - try - { - collect.setTrace( RequestTrace.newChild( trace, depRequest ) ); - node = repoSystem.collectDependencies( session, collect ).getRoot(); - result.setDependencyGraph( node ); - } - catch ( DependencyCollectionException e ) - { - result.setDependencyGraph( e.getResult().getRoot() ); - result.setCollectionErrors( e.getResult().getExceptions() ); + try { + collect.setTrace(RequestTrace.newChild(trace, depRequest)); + node = repoSystem.collectDependencies(session, collect).getRoot(); + result.setDependencyGraph(node); + } catch (DependencyCollectionException e) { + result.setDependencyGraph(e.getResult().getRoot()); + result.setCollectionErrors(e.getResult().getExceptions()); - throw new DependencyResolutionException( result, "Could not resolve dependencies for project " - + project.getId() + ": " + e.getMessage(), e ); + throw new DependencyResolutionException( + result, "Could not resolve dependencies for project " + project.getId() + ": " + e.getMessage(), e); } - depRequest.setRoot( node ); + depRequest.setRoot(node); - if ( logger.isWarnEnabled() ) - { - for ( DependencyNode child : node.getChildren() ) - { - if ( !child.getRelocations().isEmpty() ) - { - org.eclipse.aether.artifact.Artifact relocated = child.getDependency().getArtifact(); + if (logger.isWarnEnabled()) { + for (DependencyNode child : node.getChildren()) { + if (!child.getRelocations().isEmpty()) { + org.eclipse.aether.artifact.Artifact relocated = + child.getDependency().getArtifact(); String message = relocated instanceof org.apache.maven.repository.internal.RelocatedArtifact - ? ( ( org.apache.maven.repository.internal.RelocatedArtifact ) relocated ).getMessage() + ? ((org.apache.maven.repository.internal.RelocatedArtifact) relocated).getMessage() : null; - logger.warn( "The artifact " + child.getRelocations().get( 0 ) + " has been relocated to " - + relocated + ( message != null ? ": " + message : "" ) ); + logger.warn("The artifact " + child.getRelocations().get(0) + " has been relocated to " + relocated + + (message != null ? ": " + message : "")); } } } - if ( logger.isDebugEnabled() ) - { - node.accept( new GraphLogger( project ) ); + if (logger.isDebugEnabled()) { + node.accept(new GraphLogger(project)); } - try - { - process( result, repoSystem.resolveDependencies( session, depRequest ).getArtifactResults() ); - } - catch ( org.eclipse.aether.resolution.DependencyResolutionException e ) - { - process( result, e.getResult().getArtifactResults() ); + try { + process(result, repoSystem.resolveDependencies(session, depRequest).getArtifactResults()); + } catch (org.eclipse.aether.resolution.DependencyResolutionException e) { + process(result, e.getResult().getArtifactResults()); - throw new DependencyResolutionException( result, "Could not resolve dependencies for project " - + project.getId() + ": " + e.getMessage(), e ); + throw new DependencyResolutionException( + result, "Could not resolve dependencies for project " + project.getId() + ": " + e.getMessage(), e); } return result; } - private void process( DefaultDependencyResolutionResult result, Collection results ) - { - for ( ArtifactResult ar : results ) - { + private void process(DefaultDependencyResolutionResult result, Collection results) { + for (ArtifactResult ar : results) { DependencyNode node = ar.getRequest().getDependencyNode(); - if ( ar.isResolved() ) - { - result.addResolvedDependency( node.getDependency() ); - } - else - { - result.setResolutionErrors( node.getDependency(), ar.getExceptions() ); + if (ar.isResolved()) { + result.addResolvedDependency(node.getDependency()); + } else { + result.setResolutionErrors(node.getDependency(), ar.getExceptions()); } } } // Keep this class in sync with org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.GraphLogger - class GraphLogger - implements DependencyVisitor - { + class GraphLogger implements DependencyVisitor { private final MavenProject project; private String indent = ""; - GraphLogger( MavenProject project ) - { + GraphLogger(MavenProject project) { this.project = project; } - public boolean visitEnter( DependencyNode node ) - { - StringBuilder buffer = new StringBuilder( 128 ); - buffer.append( indent ); + public boolean visitEnter(DependencyNode node) { + StringBuilder buffer = new StringBuilder(128); + buffer.append(indent); org.eclipse.aether.graph.Dependency dep = node.getDependency(); - if ( dep != null ) - { + if (dep != null) { org.eclipse.aether.artifact.Artifact art = dep.getArtifact(); - buffer.append( art ); - if ( StringUtils.isNotEmpty( dep.getScope() ) ) - { - buffer.append( ':' ).append( dep.getScope() ); + buffer.append(art); + if (StringUtils.isNotEmpty(dep.getScope())) { + buffer.append(':').append(dep.getScope()); } - if ( dep.isOptional() ) - { - buffer.append( " (optional)" ); + if (dep.isOptional()) { + buffer.append(" (optional)"); } // TODO We currently cannot tell which section contained the management // information. When the resolver provides this information, these log messages should be updated // to contain it. - if ( ( node.getManagedBits() & DependencyNode.MANAGED_SCOPE ) == DependencyNode.MANAGED_SCOPE ) - { - final String premanagedScope = DependencyManagerUtils.getPremanagedScope( node ); - buffer.append( " (scope managed from " ); - buffer.append( Objects.toString( premanagedScope, "default" ) ); - buffer.append( ')' ); + if ((node.getManagedBits() & DependencyNode.MANAGED_SCOPE) == DependencyNode.MANAGED_SCOPE) { + final String premanagedScope = DependencyManagerUtils.getPremanagedScope(node); + buffer.append(" (scope managed from "); + buffer.append(Objects.toString(premanagedScope, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_VERSION ) == DependencyNode.MANAGED_VERSION ) - { - final String premanagedVersion = DependencyManagerUtils.getPremanagedVersion( node ); - buffer.append( " (version managed from " ); - buffer.append( Objects.toString( premanagedVersion, "default" ) ); - buffer.append( ')' ); + if ((node.getManagedBits() & DependencyNode.MANAGED_VERSION) == DependencyNode.MANAGED_VERSION) { + final String premanagedVersion = DependencyManagerUtils.getPremanagedVersion(node); + buffer.append(" (version managed from "); + buffer.append(Objects.toString(premanagedVersion, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL ) == DependencyNode.MANAGED_OPTIONAL ) - { - final Boolean premanagedOptional = DependencyManagerUtils.getPremanagedOptional( node ); - buffer.append( " (optionality managed from " ); - buffer.append( Objects.toString( premanagedOptional, "default" ) ); - buffer.append( ')' ); + if ((node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL) == DependencyNode.MANAGED_OPTIONAL) { + final Boolean premanagedOptional = DependencyManagerUtils.getPremanagedOptional(node); + buffer.append(" (optionality managed from "); + buffer.append(Objects.toString(premanagedOptional, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_EXCLUSIONS ) - == DependencyNode.MANAGED_EXCLUSIONS ) - { + if ((node.getManagedBits() & DependencyNode.MANAGED_EXCLUSIONS) == DependencyNode.MANAGED_EXCLUSIONS) { final Collection premanagedExclusions = - DependencyManagerUtils.getPremanagedExclusions( node ); + DependencyManagerUtils.getPremanagedExclusions(node); - buffer.append( " (exclusions managed from " ); - buffer.append( Objects.toString( premanagedExclusions, "default" ) ); - buffer.append( ')' ); + buffer.append(" (exclusions managed from "); + buffer.append(Objects.toString(premanagedExclusions, "default")); + buffer.append(')'); } - if ( ( node.getManagedBits() & DependencyNode.MANAGED_PROPERTIES ) - == DependencyNode.MANAGED_PROPERTIES ) - { + if ((node.getManagedBits() & DependencyNode.MANAGED_PROPERTIES) == DependencyNode.MANAGED_PROPERTIES) { final Map premanagedProperties = - DependencyManagerUtils.getPremanagedProperties( node ); + DependencyManagerUtils.getPremanagedProperties(node); - buffer.append( " (properties managed from " ); - buffer.append( Objects.toString( premanagedProperties, "default" ) ); - buffer.append( ')' ); + buffer.append(" (properties managed from "); + buffer.append(Objects.toString(premanagedProperties, "default")); + buffer.append(')'); } - } - else - { - buffer.append( project.getGroupId() ); - buffer.append( ':' ).append( project.getArtifactId() ); - buffer.append( ':' ).append( project.getPackaging() ); - buffer.append( ':' ).append( project.getVersion() ); + } else { + buffer.append(project.getGroupId()); + buffer.append(':').append(project.getArtifactId()); + buffer.append(':').append(project.getPackaging()); + buffer.append(':').append(project.getVersion()); } - logger.debug( buffer.toString() ); + logger.debug(buffer.toString()); indent += " "; return true; } - public boolean visitLeave( DependencyNode node ) - { - indent = indent.substring( 0, indent.length() - 3 ); + public boolean visitLeave(DependencyNode node) { + indent = indent.substring(0, indent.length() - 3); return true; } - } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectRealmCache.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectRealmCache.java index d67e5a6070..8840d6f946 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectRealmCache.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectRealmCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,16 +16,15 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable; @@ -38,56 +35,45 @@ import org.eclipse.aether.graph.DependencyFilter; */ @Named @Singleton -public class DefaultProjectRealmCache - implements ProjectRealmCache, Disposable -{ +public class DefaultProjectRealmCache implements ProjectRealmCache, Disposable { /** * CacheKey */ - protected static class CacheKey - implements Key - { + protected static class CacheKey implements Key { private final List extensionRealms; private final int hashCode; - public CacheKey( List extensionRealms ) - { - this.extensionRealms = ( extensionRealms != null ) - ? Collections.unmodifiableList( extensionRealms ) - : Collections.emptyList(); + public CacheKey(List extensionRealms) { + this.extensionRealms = + (extensionRealms != null) ? Collections.unmodifiableList(extensionRealms) : Collections.emptyList(); this.hashCode = this.extensionRealms.hashCode(); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof CacheKey ) ) - { + if (!(o instanceof CacheKey)) { return false; } CacheKey other = (CacheKey) o; - return extensionRealms.equals( other.extensionRealms ); + return extensionRealms.equals(other.extensionRealms); } @Override - public String toString() - { + public String toString() { return extensionRealms.toString(); } } @@ -95,58 +81,46 @@ public class DefaultProjectRealmCache protected final Map cache = new ConcurrentHashMap<>(); @Override - public Key createKey( List extensionRealms ) - { - return new CacheKey( extensionRealms ); + public Key createKey(List extensionRealms) { + return new CacheKey(extensionRealms); } - public CacheRecord get( Key key ) - { - return cache.get( key ); + public CacheRecord get(Key key) { + return cache.get(key); } - public CacheRecord put( Key key, ClassRealm projectRealm, DependencyFilter extensionArtifactFilter ) - { - Objects.requireNonNull( projectRealm, "projectRealm cannot be null" ); + public CacheRecord put(Key key, ClassRealm projectRealm, DependencyFilter extensionArtifactFilter) { + Objects.requireNonNull(projectRealm, "projectRealm cannot be null"); - if ( cache.containsKey( key ) ) - { - throw new IllegalStateException( "Duplicate project realm for extensions " + key ); + if (cache.containsKey(key)) { + throw new IllegalStateException("Duplicate project realm for extensions " + key); } - CacheRecord record = new CacheRecord( projectRealm, extensionArtifactFilter ); + CacheRecord record = new CacheRecord(projectRealm, extensionArtifactFilter); - cache.put( key, record ); + cache.put(key, record); return record; } - public void flush() - { - for ( CacheRecord record : cache.values() ) - { + public void flush() { + for (CacheRecord record : cache.values()) { ClassRealm realm = record.getRealm(); - try - { - realm.getWorld().disposeRealm( realm.getId() ); - } - catch ( NoSuchRealmException e ) - { + try { + realm.getWorld().disposeRealm(realm.getId()); + } catch (NoSuchRealmException e) { // ignore } } cache.clear(); } - public void register( MavenProject project, Key key, CacheRecord record ) - { + public void register(MavenProject project, Key key, CacheRecord record) { // default cache does not track record usage } @Override - public void dispose() - { + public void dispose() { flush(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionException.java b/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionException.java index ecd0151823..c4e17ea945 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionException.java +++ b/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,25 +16,21 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; /** * @author Benjamin Bentmann */ -public class DependencyResolutionException - extends Exception -{ +public class DependencyResolutionException extends Exception { private final transient DependencyResolutionResult result; - public DependencyResolutionException( DependencyResolutionResult result, String message, Throwable cause ) - { - super( message, cause ); + public DependencyResolutionException(DependencyResolutionResult result, String message, Throwable cause) { + super(message, cause); this.result = result; } - public DependencyResolutionResult getResult() - { + public DependencyResolutionResult getResult() { return result; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionRequest.java b/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionRequest.java index c120a1379b..388daa92fe 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.graph.DependencyFilter; @@ -27,8 +26,7 @@ import org.eclipse.aether.graph.DependencyFilter; * * @author Benjamin Bentmann */ -public interface DependencyResolutionRequest -{ +public interface DependencyResolutionRequest { /** * Gets the project to resolve dependencies for. @@ -43,7 +41,7 @@ public interface DependencyResolutionRequest * @param project The project to resolve dependencies for, may be {@code null}. * @return This request for chaining, never {@code null}. */ - DependencyResolutionRequest setMavenProject( MavenProject project ); + DependencyResolutionRequest setMavenProject(MavenProject project); /** * Gets the filter used to exclude some dependencies from resolution. @@ -61,7 +59,7 @@ public interface DependencyResolutionRequest * dependencies. * @return This request for chaining, never {@code null}. */ - DependencyResolutionRequest setResolutionFilter( DependencyFilter filter ); + DependencyResolutionRequest setResolutionFilter(DependencyFilter filter); /** * Gets the session to use for repository access. @@ -76,6 +74,5 @@ public interface DependencyResolutionRequest * @param repositorySession The repository session to use. * @return This request for chaining, never {@code null}. */ - DependencyResolutionRequest setRepositorySession( RepositorySystemSession repositorySession ); - + DependencyResolutionRequest setRepositorySession(RepositorySystemSession repositorySession); } diff --git a/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionResult.java b/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionResult.java index 6ad55fae74..a900c04a5f 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionResult.java +++ b/maven-core/src/main/java/org/apache/maven/project/DependencyResolutionResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.List; - import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; @@ -29,8 +27,7 @@ import org.eclipse.aether.graph.DependencyNode; * * @author Benjamin Bentmann */ -public interface DependencyResolutionResult -{ +public interface DependencyResolutionResult { /** * Gets the dependency graph of the project. @@ -75,6 +72,5 @@ public interface DependencyResolutionResult * @param dependency The dependency for which to retrieve the errors, must not be {@code null}. * @return The resolution errors for the specified dependency, never {@code null}. */ - List getResolutionErrors( Dependency dependency ); - + List getResolutionErrors(Dependency dependency); } diff --git a/maven-core/src/main/java/org/apache/maven/project/DuplicateArtifactAttachmentException.java b/maven-core/src/main/java/org/apache/maven/project/DuplicateArtifactAttachmentException.java index d263c28471..551acbc3c7 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DuplicateArtifactAttachmentException.java +++ b/maven-core/src/main/java/org/apache/maven/project/DuplicateArtifactAttachmentException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import org.apache.maven.artifact.Artifact; @@ -30,9 +29,7 @@ import org.apache.maven.artifact.Artifact; * TODO Make this a checked exception, and modify the API of MavenProjectHelper. * Currently, this modification would create compatibility problems for existing plugins. */ -public class DuplicateArtifactAttachmentException - extends RuntimeException -{ +public class DuplicateArtifactAttachmentException extends RuntimeException { private static final String DEFAULT_MESSAGE = "Duplicate artifact attachment detected."; @@ -40,25 +37,21 @@ public class DuplicateArtifactAttachmentException private final MavenProject project; - public DuplicateArtifactAttachmentException( MavenProject project, Artifact artifact ) - { - super( constructMessage( project, artifact ) ); + public DuplicateArtifactAttachmentException(MavenProject project, Artifact artifact) { + super(constructMessage(project, artifact)); this.project = project; this.artifact = artifact; } - private static String constructMessage( MavenProject project, Artifact artifact ) - { + private static String constructMessage(MavenProject project, Artifact artifact) { return DEFAULT_MESSAGE + " (project: " + project.getId() + "; illegal attachment: " + artifact.getId() + ")"; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } } diff --git a/maven-core/src/main/java/org/apache/maven/project/DuplicateProjectException.java b/maven-core/src/main/java/org/apache/maven/project/DuplicateProjectException.java index f73c46b284..a19c25755a 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DuplicateProjectException.java +++ b/maven-core/src/main/java/org/apache/maven/project/DuplicateProjectException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; @@ -26,9 +25,7 @@ import java.io.File; * * @author Brett Porter */ -public class DuplicateProjectException - extends Exception -{ +public class DuplicateProjectException extends Exception { private final String projectId; private final File existingProjectFile; @@ -38,43 +35,37 @@ public class DuplicateProjectException /** * @deprecated use {@link #DuplicateProjectException(String, File, File, String)} */ - public DuplicateProjectException( String message ) - { - this( null, null, null, message ); + public DuplicateProjectException(String message) { + this(null, null, null, message); } /** * @deprecated use {@link #DuplicateProjectException(String, File, File, String)} */ - public DuplicateProjectException( String message, Exception e ) - { - super( message, e ); + public DuplicateProjectException(String message, Exception e) { + super(message, e); this.projectId = null; this.existingProjectFile = null; this.conflictingProjectFile = null; } - public DuplicateProjectException( String projectId, File existingProjectFile, File conflictingProjectFile, - String message ) - { - super( message ); + public DuplicateProjectException( + String projectId, File existingProjectFile, File conflictingProjectFile, String message) { + super(message); this.projectId = projectId; this.existingProjectFile = existingProjectFile; this.conflictingProjectFile = conflictingProjectFile; } - public String getProjectId() - { + public String getProjectId() { return projectId; } - public File getExistingProjectFile() - { + public File getExistingProjectFile() { return existingProjectFile; } - public File getConflictingProjectFile() - { + public File getConflictingProjectFile() { return conflictingProjectFile; } } diff --git a/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptor.java b/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptor.java index 9602c008f7..66b4eba6e6 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptor.java +++ b/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptor.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.List; @@ -29,60 +28,45 @@ import java.util.List; * * @author Benjamin Bentmann */ -public class ExtensionDescriptor -{ +public class ExtensionDescriptor { private List exportedPackages; private List exportedArtifacts; - ExtensionDescriptor() - { + ExtensionDescriptor() { // hide constructor } - public List getExportedPackages() - { - if ( exportedPackages == null ) - { + public List getExportedPackages() { + if (exportedPackages == null) { exportedPackages = new ArrayList<>(); } return exportedPackages; } - public void setExportedPackages( List exportedPackages ) - { - if ( exportedPackages == null ) - { + public void setExportedPackages(List exportedPackages) { + if (exportedPackages == null) { this.exportedPackages = null; - } - else - { - this.exportedPackages = new ArrayList<>( exportedPackages ); + } else { + this.exportedPackages = new ArrayList<>(exportedPackages); } } - public List getExportedArtifacts() - { - if ( exportedArtifacts == null ) - { + public List getExportedArtifacts() { + if (exportedArtifacts == null) { exportedArtifacts = new ArrayList<>(); } return exportedArtifacts; } - public void setExportedArtifacts( List exportedArtifacts ) - { - if ( exportedArtifacts == null ) - { + public void setExportedArtifacts(List exportedArtifacts) { + if (exportedArtifacts == null) { this.exportedArtifacts = null; - } - else - { - this.exportedArtifacts = new ArrayList<>( exportedArtifacts ); + } else { + this.exportedArtifacts = new ArrayList<>(exportedArtifacts); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java b/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java index 1eb3e33e79..963555ca3f 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.api.xml.Dom; -import org.apache.maven.internal.xml.Xpp3DomBuilder; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +package org.apache.maven.project; import java.io.BufferedInputStream; import java.io.File; @@ -33,20 +27,22 @@ import java.util.ArrayList; import java.util.List; import java.util.jar.JarFile; import java.util.zip.ZipEntry; +import org.apache.maven.api.xml.Dom; +import org.apache.maven.internal.xml.Xpp3DomBuilder; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * Creates an extension descriptor from some XML stream. * * @author Benjamin Bentmann */ -public class ExtensionDescriptorBuilder -{ +public class ExtensionDescriptorBuilder { /** * @since 3.3.0 */ - public String getExtensionDescriptorLocation() - { + public String getExtensionDescriptorLocation() { return "META-INF/maven/extension.xml"; } @@ -57,35 +53,25 @@ public class ExtensionDescriptorBuilder * @return The extracted descriptor or {@code null} if no descriptor was found. * @throws IOException If the descriptor is present but could not be parsed. */ - public ExtensionDescriptor build( File extensionJar ) - throws IOException - { + public ExtensionDescriptor build(File extensionJar) throws IOException { ExtensionDescriptor extensionDescriptor = null; - if ( extensionJar.isFile() ) - { - try ( JarFile pluginJar = new JarFile( extensionJar, false ) ) - { - ZipEntry pluginDescriptorEntry = pluginJar.getEntry( getExtensionDescriptorLocation() ); + if (extensionJar.isFile()) { + try (JarFile pluginJar = new JarFile(extensionJar, false)) { + ZipEntry pluginDescriptorEntry = pluginJar.getEntry(getExtensionDescriptorLocation()); - if ( pluginDescriptorEntry != null ) - { - try ( InputStream is = pluginJar.getInputStream( pluginDescriptorEntry ) ) - { - extensionDescriptor = build( is ); + if (pluginDescriptorEntry != null) { + try (InputStream is = pluginJar.getInputStream(pluginDescriptorEntry)) { + extensionDescriptor = build(is); } } } - } - else - { - File pluginXml = new File( extensionJar, getExtensionDescriptorLocation() ); + } else { + File pluginXml = new File(extensionJar, getExtensionDescriptorLocation()); - if ( pluginXml.canRead() ) - { - try ( InputStream is = new BufferedInputStream( new FileInputStream( pluginXml ) ) ) - { - extensionDescriptor = build( is ); + if (pluginXml.canRead()) { + try (InputStream is = new BufferedInputStream(new FileInputStream(pluginXml))) { + extensionDescriptor = build(is); } } } @@ -96,50 +82,39 @@ public class ExtensionDescriptorBuilder /** * @since 3.3.0 */ - public ExtensionDescriptor build( InputStream is ) - throws IOException - { + public ExtensionDescriptor build(InputStream is) throws IOException { ExtensionDescriptor extensionDescriptor = new ExtensionDescriptor(); Dom dom; - try - { - dom = Xpp3DomBuilder.build( ReaderFactory.newXmlReader( is ) ); - } - catch ( XmlPullParserException e ) - { - throw new IOException( e.getMessage(), e ); + try { + dom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(is)); + } catch (XmlPullParserException e) { + throw new IOException(e.getMessage(), e); } - if ( !"extension".equals( dom.getName() ) ) - { - throw new IOException( "Unexpected root element \"" + dom.getName() + "\", expected \"extension\"" ); + if (!"extension".equals(dom.getName())) { + throw new IOException("Unexpected root element \"" + dom.getName() + "\", expected \"extension\""); } - extensionDescriptor.setExportedPackages( parseStrings( dom.getChild( "exportedPackages" ) ) ); + extensionDescriptor.setExportedPackages(parseStrings(dom.getChild("exportedPackages"))); - extensionDescriptor.setExportedArtifacts( parseStrings( dom.getChild( "exportedArtifacts" ) ) ); + extensionDescriptor.setExportedArtifacts(parseStrings(dom.getChild("exportedArtifacts"))); return extensionDescriptor; } - private List parseStrings( Dom dom ) - { + private List parseStrings(Dom dom) { List strings = null; - if ( dom != null ) - { + if (dom != null) { strings = new ArrayList<>(); - for ( Dom child : dom.getChildren() ) - { + for (Dom child : dom.getChildren()) { String string = child.getValue(); - if ( string != null ) - { + if (string != null) { string = string.trim(); - if ( string.length() > 0 ) - { - strings.add( string ); + if (string.length() > 0) { + strings.add(string); } } } @@ -147,5 +122,4 @@ public class ExtensionDescriptorBuilder return strings; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/InvalidProjectVersionException.java b/maven-core/src/main/java/org/apache/maven/project/InvalidProjectVersionException.java index 8080f6e022..e0689353c1 100644 --- a/maven-core/src/main/java/org/apache/maven/project/InvalidProjectVersionException.java +++ b/maven-core/src/main/java/org/apache/maven/project/InvalidProjectVersionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,45 +16,45 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; - import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; /** * InvalidProjectVersionException */ -public class InvalidProjectVersionException - extends ProjectBuildingException -{ +public class InvalidProjectVersionException extends ProjectBuildingException { private final String locationInPom; private final String offendingVersion; - public InvalidProjectVersionException( String projectId, String locationInPom, String offendingVersion, - File pomFile, InvalidVersionSpecificationException cause ) - { - super( projectId, formatMessage( projectId, locationInPom, offendingVersion, cause ), pomFile, cause ); + public InvalidProjectVersionException( + String projectId, + String locationInPom, + String offendingVersion, + File pomFile, + InvalidVersionSpecificationException cause) { + super(projectId, formatMessage(projectId, locationInPom, offendingVersion, cause), pomFile, cause); this.locationInPom = locationInPom; this.offendingVersion = offendingVersion; } - private static String formatMessage( String projectId, String locationInPom, String offendingVersion, - InvalidVersionSpecificationException cause ) - { + private static String formatMessage( + String projectId, + String locationInPom, + String offendingVersion, + InvalidVersionSpecificationException cause) { return "Invalid version: " + offendingVersion + " found for: " + locationInPom + " in project: " + projectId - + ". Reason: " + cause.getMessage(); + + ". Reason: " + cause.getMessage(); } - public String getOffendingVersion() - { + public String getOffendingVersion() { return offendingVersion; } - public String getLocationInPom() - { + public String getLocationInPom() { return locationInPom; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java index 99b175cae5..d9307dae71 100644 --- a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java +++ b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.io.IOException; @@ -29,15 +28,13 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; -import java.util.Objects; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.DependencyResolutionRequiredException; -// remove once createArtifacts() is removed import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; @@ -89,11 +86,9 @@ import org.slf4j.LoggerFactory; * directories but I hope to take care of this during the Maven 4.0 release (jvz). *

    */ -public class MavenProject - implements Cloneable -{ +public class MavenProject implements Cloneable { - private static final Logger LOGGER = LoggerFactory.getLogger( MavenProject.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(MavenProject.class); public static final String EMPTY_PROJECT_GROUP_ID = "unknown"; @@ -180,41 +175,35 @@ public class MavenProject private DependencyFilter extensionDependencyFilter; - private final Set lifecyclePhases = Collections.synchronizedSet( new LinkedHashSet<>() ); + private final Set lifecyclePhases = Collections.synchronizedSet(new LinkedHashSet<>()); - public MavenProject() - { + public MavenProject() { Model model = new Model(); - model.setGroupId( EMPTY_PROJECT_GROUP_ID ); - model.setArtifactId( EMPTY_PROJECT_ARTIFACT_ID ); - model.setVersion( EMPTY_PROJECT_VERSION ); + model.setGroupId(EMPTY_PROJECT_GROUP_ID); + model.setArtifactId(EMPTY_PROJECT_ARTIFACT_ID); + model.setVersion(EMPTY_PROJECT_VERSION); - setModel( model ); + setModel(model); } - public MavenProject( org.apache.maven.api.model.Model model ) - { - this( new Model( model ) ); + public MavenProject(org.apache.maven.api.model.Model model) { + this(new Model(model)); } - public MavenProject( Model model ) - { - setModel( model ); + public MavenProject(Model model) { + setModel(model); } - public MavenProject( MavenProject project ) - { - deepCopy( project ); + public MavenProject(MavenProject project) { + deepCopy(project); } - public File getParentFile() - { + public File getParentFile() { return parentFile; } - public void setParentFile( File parentFile ) - { + public void setParentFile(File parentFile) { this.parentFile = parentFile; } @@ -222,19 +211,16 @@ public class MavenProject // Accessors // ---------------------------------------------------------------------- - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public void setArtifact( Artifact artifact ) - { + public void setArtifact(Artifact artifact) { this.artifact = artifact; } // TODO I would like to get rid of this. jvz. - public Model getModel() - { + public Model getModel() { return model; } @@ -243,28 +229,23 @@ public class MavenProject * * @return the parent, or null if no parent is declared or there was an error building it */ - public MavenProject getParent() - { + public MavenProject getParent() { return parent; } - public void setParent( MavenProject parent ) - { + public void setParent(MavenProject parent) { this.parent = parent; } - public boolean hasParent() - { + public boolean hasParent() { return getParent() != null; } - public File getFile() - { + public File getFile() { return file; } - public void setFile( File file ) - { + public void setFile(File file) { this.file = file; this.basedir = file != null ? file.getParentFile() : null; } @@ -274,28 +255,23 @@ public class MavenProject * * @since 3.2.4 */ - public void setPomFile( File file ) - { + public void setPomFile(File file) { this.file = file; } - public File getBasedir() - { + public File getBasedir() { return basedir; } - public void setDependencies( List dependencies ) - { - getModel().setDependencies( dependencies ); + public void setDependencies(List dependencies) { + getModel().setDependencies(dependencies); } - public List getDependencies() - { + public List getDependencies() { return getModel().getDependencies(); } - public DependencyManagement getDependencyManagement() - { + public DependencyManagement getDependencyManagement() { return getModel().getDependencyManagement(); } @@ -303,75 +279,57 @@ public class MavenProject // Test and compile source roots. // ---------------------------------------------------------------------- - private void addPath( List paths, String path ) - { - if ( path != null ) - { + private void addPath(List paths, String path) { + if (path != null) { path = path.trim(); - if ( path.length() > 0 ) - { - File file = new File( path ); - if ( file.isAbsolute() ) - { + if (path.length() > 0) { + File file = new File(path); + if (file.isAbsolute()) { path = file.getAbsolutePath(); - } - else if ( ".".equals( path ) ) - { + } else if (".".equals(path)) { path = getBasedir().getAbsolutePath(); - } - else - { - path = new File( getBasedir(), path ).getAbsolutePath(); + } else { + path = new File(getBasedir(), path).getAbsolutePath(); } - if ( !paths.contains( path ) ) - { - paths.add( path ); + if (!paths.contains(path)) { + paths.add(path); } } } } - public void addCompileSourceRoot( String path ) - { - addPath( getCompileSourceRoots(), path ); + public void addCompileSourceRoot(String path) { + addPath(getCompileSourceRoots(), path); } - public void addTestCompileSourceRoot( String path ) - { - addPath( getTestCompileSourceRoots(), path ); + public void addTestCompileSourceRoot(String path) { + addPath(getTestCompileSourceRoots(), path); } - public List getCompileSourceRoots() - { + public List getCompileSourceRoots() { return compileSourceRoots; } - public List getTestCompileSourceRoots() - { + public List getTestCompileSourceRoots() { return testCompileSourceRoots; } - public List getCompileClasspathElements() - throws DependencyResolutionRequiredException - { - List list = new ArrayList<>( getArtifacts().size() + 1 ); + public List getCompileClasspathElements() throws DependencyResolutionRequiredException { + List list = new ArrayList<>(getArtifacts().size() + 1); String d = getBuild().getOutputDirectory(); - if ( d != null ) - { - list.add( d ); + if (d != null) { + list.add(d); } - for ( Artifact a : getArtifacts() ) - { - if ( a.getArtifactHandler().isAddedToClasspath() ) - { + for (Artifact a : getArtifacts()) { + if (a.getArtifactHandler().isAddedToClasspath()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_COMPILE.equals( a.getScope() ) || Artifact.SCOPE_PROVIDED.equals( a.getScope() ) - || Artifact.SCOPE_SYSTEM.equals( a.getScope() ) ) - { - addArtifactPath( a, list ); + if (Artifact.SCOPE_COMPILE.equals(a.getScope()) + || Artifact.SCOPE_PROVIDED.equals(a.getScope()) + || Artifact.SCOPE_SYSTEM.equals(a.getScope())) { + addArtifactPath(a, list); } } } @@ -381,52 +339,41 @@ public class MavenProject // TODO this checking for file == null happens because the resolver has been confused about the root // artifact or not. things like the stupid dummy artifact coming from surefire. - public List getTestClasspathElements() - throws DependencyResolutionRequiredException - { - List list = new ArrayList<>( getArtifacts().size() + 2 ); + public List getTestClasspathElements() throws DependencyResolutionRequiredException { + List list = new ArrayList<>(getArtifacts().size() + 2); String d = getBuild().getTestOutputDirectory(); - if ( d != null ) - { - list.add( d ); + if (d != null) { + list.add(d); } d = getBuild().getOutputDirectory(); - if ( d != null ) - { - list.add( d ); + if (d != null) { + list.add(d); } - for ( Artifact a : getArtifacts() ) - { - if ( a.getArtifactHandler().isAddedToClasspath() ) - { - addArtifactPath( a, list ); + for (Artifact a : getArtifacts()) { + if (a.getArtifactHandler().isAddedToClasspath()) { + addArtifactPath(a, list); } } return list; } - public List getRuntimeClasspathElements() - throws DependencyResolutionRequiredException - { - List list = new ArrayList<>( getArtifacts().size() + 1 ); + public List getRuntimeClasspathElements() throws DependencyResolutionRequiredException { + List list = new ArrayList<>(getArtifacts().size() + 1); String d = getBuild().getOutputDirectory(); - if ( d != null ) - { - list.add( d ); + if (d != null) { + list.add(d); } - for ( Artifact a : getArtifacts() ) - { - if ( a.getArtifactHandler().isAddedToClasspath() - // TODO let the scope handler deal with this - && ( Artifact.SCOPE_COMPILE.equals( a.getScope() ) || Artifact.SCOPE_RUNTIME.equals( a.getScope() ) ) ) - { - addArtifactPath( a, list ); + for (Artifact a : getArtifacts()) { + if (a.getArtifactHandler().isAddedToClasspath() + // TODO let the scope handler deal with this + && (Artifact.SCOPE_COMPILE.equals(a.getScope()) || Artifact.SCOPE_RUNTIME.equals(a.getScope()))) { + addArtifactPath(a, list); } } return list; @@ -436,270 +383,216 @@ public class MavenProject // Delegate to the model // ---------------------------------------------------------------------- - public void setModelVersion( String pomVersion ) - { - getModel().setModelVersion( pomVersion ); + public void setModelVersion(String pomVersion) { + getModel().setModelVersion(pomVersion); } - public String getModelVersion() - { + public String getModelVersion() { return getModel().getModelVersion(); } - public String getId() - { + public String getId() { return getModel().getId(); } - public void setGroupId( String groupId ) - { - getModel().setGroupId( groupId ); + public void setGroupId(String groupId) { + getModel().setGroupId(groupId); } - public String getGroupId() - { + public String getGroupId() { String groupId = getModel().getGroupId(); - if ( ( groupId == null ) && ( getModel().getParent() != null ) ) - { + if ((groupId == null) && (getModel().getParent() != null)) { groupId = getModel().getParent().getGroupId(); } return groupId; } - public void setArtifactId( String artifactId ) - { - getModel().setArtifactId( artifactId ); + public void setArtifactId(String artifactId) { + getModel().setArtifactId(artifactId); } - public String getArtifactId() - { + public String getArtifactId() { return getModel().getArtifactId(); } - public void setName( String name ) - { - getModel().setName( name ); + public void setName(String name) { + getModel().setName(name); } - public String getName() - { + public String getName() { // TODO this should not be allowed to be null. - if ( getModel().getName() != null ) - { + if (getModel().getName() != null) { return getModel().getName(); - } - else - { + } else { return getArtifactId(); } } - public void setVersion( String version ) - { - getModel().setVersion( version ); + public void setVersion(String version) { + getModel().setVersion(version); } - public String getVersion() - { + public String getVersion() { String version = getModel().getVersion(); - if ( ( version == null ) && ( getModel().getParent() != null ) ) - { + if ((version == null) && (getModel().getParent() != null)) { version = getModel().getParent().getVersion(); } return version; } - public String getPackaging() - { + public String getPackaging() { return getModel().getPackaging(); } - public void setPackaging( String packaging ) - { - getModel().setPackaging( packaging ); + public void setPackaging(String packaging) { + getModel().setPackaging(packaging); } - public void setInceptionYear( String inceptionYear ) - { - getModel().setInceptionYear( inceptionYear ); + public void setInceptionYear(String inceptionYear) { + getModel().setInceptionYear(inceptionYear); } - public String getInceptionYear() - { + public String getInceptionYear() { return getModel().getInceptionYear(); } - public void setUrl( String url ) - { - getModel().setUrl( url ); + public void setUrl(String url) { + getModel().setUrl(url); } - public String getUrl() - { + public String getUrl() { return getModel().getUrl(); } - public Prerequisites getPrerequisites() - { + public Prerequisites getPrerequisites() { return getModel().getPrerequisites(); } - public void setIssueManagement( IssueManagement issueManagement ) - { - getModel().setIssueManagement( issueManagement ); + public void setIssueManagement(IssueManagement issueManagement) { + getModel().setIssueManagement(issueManagement); } - public CiManagement getCiManagement() - { + public CiManagement getCiManagement() { return getModel().getCiManagement(); } - public void setCiManagement( CiManagement ciManagement ) - { - getModel().setCiManagement( ciManagement ); + public void setCiManagement(CiManagement ciManagement) { + getModel().setCiManagement(ciManagement); } - public IssueManagement getIssueManagement() - { + public IssueManagement getIssueManagement() { return getModel().getIssueManagement(); } - public void setDistributionManagement( DistributionManagement distributionManagement ) - { - getModel().setDistributionManagement( distributionManagement ); + public void setDistributionManagement(DistributionManagement distributionManagement) { + getModel().setDistributionManagement(distributionManagement); } - public DistributionManagement getDistributionManagement() - { + public DistributionManagement getDistributionManagement() { return getModel().getDistributionManagement(); } - public void setDescription( String description ) - { - getModel().setDescription( description ); + public void setDescription(String description) { + getModel().setDescription(description); } - public String getDescription() - { + public String getDescription() { return getModel().getDescription(); } - public void setOrganization( Organization organization ) - { - getModel().setOrganization( organization ); + public void setOrganization(Organization organization) { + getModel().setOrganization(organization); } - public Organization getOrganization() - { + public Organization getOrganization() { return getModel().getOrganization(); } - public void setScm( Scm scm ) - { - getModel().setScm( scm ); + public void setScm(Scm scm) { + getModel().setScm(scm); } - public Scm getScm() - { + public Scm getScm() { return getModel().getScm(); } - public void setMailingLists( List mailingLists ) - { - getModel().setMailingLists( mailingLists ); + public void setMailingLists(List mailingLists) { + getModel().setMailingLists(mailingLists); } - public List getMailingLists() - { + public List getMailingLists() { return getModel().getMailingLists(); } - public void addMailingList( MailingList mailingList ) - { - getModel().addMailingList( mailingList ); + public void addMailingList(MailingList mailingList) { + getModel().addMailingList(mailingList); } - public void setDevelopers( List developers ) - { - getModel().setDevelopers( developers ); + public void setDevelopers(List developers) { + getModel().setDevelopers(developers); } - public List getDevelopers() - { + public List getDevelopers() { return getModel().getDevelopers(); } - public void addDeveloper( Developer developer ) - { - getModel().addDeveloper( developer ); + public void addDeveloper(Developer developer) { + getModel().addDeveloper(developer); } - public void setContributors( List contributors ) - { - getModel().setContributors( contributors ); + public void setContributors(List contributors) { + getModel().setContributors(contributors); } - public List getContributors() - { + public List getContributors() { return getModel().getContributors(); } - public void addContributor( Contributor contributor ) - { - getModel().addContributor( contributor ); + public void addContributor(Contributor contributor) { + getModel().addContributor(contributor); } - public void setBuild( Build build ) - { - getModel().setBuild( build ); + public void setBuild(Build build) { + getModel().setBuild(build); } - public Build getBuild() - { + public Build getBuild() { return getModelBuild(); } - public List getResources() - { + public List getResources() { return getBuild().getResources(); } - public List getTestResources() - { + public List getTestResources() { return getBuild().getTestResources(); } - public void addResource( Resource resource ) - { - getBuild().addResource( resource ); + public void addResource(Resource resource) { + getBuild().addResource(resource); } - public void addTestResource( Resource testResource ) - { - getBuild().addTestResource( testResource ); + public void addTestResource(Resource testResource) { + getBuild().addTestResource(testResource); } - public void setLicenses( List licenses ) - { - getModel().setLicenses( licenses ); + public void setLicenses(List licenses) { + getModel().setLicenses(licenses); } - public List getLicenses() - { + public List getLicenses() { return getModel().getLicenses(); } - public void addLicense( License license ) - { - getModel().addLicense( license ); + public void addLicense(License license) { + getModel().addLicense(license); } - public void setArtifacts( Set artifacts ) - { + public void setArtifacts(Set artifacts) { this.artifacts = artifacts; // flush the calculated artifactMap @@ -714,22 +607,15 @@ public class MavenProject * @return {@link Set} < {@link Artifact} > * @see #getDependencyArtifacts() to get only direct dependencies */ - public Set getArtifacts() - { - if ( artifacts == null ) - { - if ( artifactFilter == null || resolvedArtifacts == null ) - { + public Set getArtifacts() { + if (artifacts == null) { + if (artifactFilter == null || resolvedArtifacts == null) { artifacts = new LinkedHashSet<>(); - } - else - { - artifacts = new LinkedHashSet<>( resolvedArtifacts.size() * 2 ); - for ( Artifact artifact : resolvedArtifacts ) - { - if ( artifactFilter.include( artifact ) ) - { - artifacts.add( artifact ); + } else { + artifacts = new LinkedHashSet<>(resolvedArtifacts.size() * 2); + for (Artifact artifact : resolvedArtifacts) { + if (artifactFilter.include(artifact)) { + artifacts.add(artifact); } } } @@ -737,49 +623,40 @@ public class MavenProject return artifacts; } - public Map getArtifactMap() - { - if ( artifactMap == null ) - { - artifactMap = ArtifactUtils.artifactMapByVersionlessId( getArtifacts() ); + public Map getArtifactMap() { + if (artifactMap == null) { + artifactMap = ArtifactUtils.artifactMapByVersionlessId(getArtifacts()); } return artifactMap; } - public void setPluginArtifacts( Set pluginArtifacts ) - { + public void setPluginArtifacts(Set pluginArtifacts) { this.pluginArtifacts = pluginArtifacts; this.pluginArtifactMap = null; } - public Set getPluginArtifacts() - { + public Set getPluginArtifacts() { return pluginArtifacts; } - public Map getPluginArtifactMap() - { - if ( pluginArtifactMap == null ) - { - pluginArtifactMap = ArtifactUtils.artifactMapByVersionlessId( getPluginArtifacts() ); + public Map getPluginArtifactMap() { + if (pluginArtifactMap == null) { + pluginArtifactMap = ArtifactUtils.artifactMapByVersionlessId(getPluginArtifacts()); } return pluginArtifactMap; } - public void setParentArtifact( Artifact parentArtifact ) - { + public void setParentArtifact(Artifact parentArtifact) { this.parentArtifact = parentArtifact; } - public Artifact getParentArtifact() - { + public Artifact getParentArtifact() { return parentArtifact; } - public List getRepositories() - { + public List getRepositories() { return getModel().getRepositories(); } @@ -787,124 +664,101 @@ public class MavenProject // Plugins // ---------------------------------------------------------------------- - public List getBuildPlugins() - { - if ( getModel().getBuild() == null ) - { + public List getBuildPlugins() { + if (getModel().getBuild() == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( getModel().getBuild().getPlugins() ); + return Collections.unmodifiableList(getModel().getBuild().getPlugins()); } - public List getModules() - { + public List getModules() { return getModel().getModules(); } - public PluginManagement getPluginManagement() - { + public PluginManagement getPluginManagement() { PluginManagement pluginMgmt = null; Build build = getModel().getBuild(); - if ( build != null ) - { + if (build != null) { pluginMgmt = build.getPluginManagement(); } return pluginMgmt; } - private Build getModelBuild() - { + private Build getModelBuild() { Build build = getModel().getBuild(); - if ( build == null ) - { + if (build == null) { build = new Build(); - getModel().setBuild( build ); + getModel().setBuild(build); } return build; } - public void setRemoteArtifactRepositories( List remoteArtifactRepositories ) - { + public void setRemoteArtifactRepositories(List remoteArtifactRepositories) { this.remoteArtifactRepositories = remoteArtifactRepositories; - this.remoteProjectRepositories = RepositoryUtils.toRepos( getRemoteArtifactRepositories() ); + this.remoteProjectRepositories = RepositoryUtils.toRepos(getRemoteArtifactRepositories()); } - public List getRemoteArtifactRepositories() - { - if ( remoteArtifactRepositories == null ) - { + public List getRemoteArtifactRepositories() { + if (remoteArtifactRepositories == null) { remoteArtifactRepositories = new ArrayList<>(); } return remoteArtifactRepositories; } - public void setPluginArtifactRepositories( List pluginArtifactRepositories ) - { + public void setPluginArtifactRepositories(List pluginArtifactRepositories) { this.pluginArtifactRepositories = pluginArtifactRepositories; - this.remotePluginRepositories = RepositoryUtils.toRepos( getPluginArtifactRepositories() ); + this.remotePluginRepositories = RepositoryUtils.toRepos(getPluginArtifactRepositories()); } /** * @return a list of ArtifactRepository objects constructed from the Repository objects returned by * getPluginRepositories. */ - public List getPluginArtifactRepositories() - { - if ( pluginArtifactRepositories == null ) - { + public List getPluginArtifactRepositories() { + if (pluginArtifactRepositories == null) { pluginArtifactRepositories = new ArrayList<>(); } return pluginArtifactRepositories; } - public ArtifactRepository getDistributionManagementArtifactRepository() - { - return getArtifact().isSnapshot() && ( getSnapshotArtifactRepository() != null ) - ? getSnapshotArtifactRepository() - : getReleaseArtifactRepository(); + public ArtifactRepository getDistributionManagementArtifactRepository() { + return getArtifact().isSnapshot() && (getSnapshotArtifactRepository() != null) + ? getSnapshotArtifactRepository() + : getReleaseArtifactRepository(); } - public List getPluginRepositories() - { + public List getPluginRepositories() { return getModel().getPluginRepositories(); } - public List getRemoteProjectRepositories() - { + public List getRemoteProjectRepositories() { return remoteProjectRepositories; } - public List getRemotePluginRepositories() - { + public List getRemotePluginRepositories() { return remotePluginRepositories; } - public void setActiveProfiles( List activeProfiles ) - { + public void setActiveProfiles(List activeProfiles) { this.activeProfiles = activeProfiles; } - public List getActiveProfiles() - { + public List getActiveProfiles() { return activeProfiles; } - public void setInjectedProfileIds( String source, List injectedProfileIds ) - { - if ( injectedProfileIds != null ) - { - this.injectedProfileIds.put( source, new ArrayList<>( injectedProfileIds ) ); - } - else - { - this.injectedProfileIds.remove( source ); + public void setInjectedProfileIds(String source, List injectedProfileIds) { + if (injectedProfileIds != null) { + this.injectedProfileIds.put(source, new ArrayList<>(injectedProfileIds)); + } else { + this.injectedProfileIds.remove(source); } } @@ -918,8 +772,7 @@ public class MavenProject * @return The identifiers of all injected profiles, indexed by the source from which the profiles originated, never * {@code null}. */ - public Map> getInjectedProfileIds() - { + public Map> getInjectedProfileIds() { return this.injectedProfileIds; } @@ -934,50 +787,36 @@ public class MavenProject * @deprecated Please use {@link MavenProjectHelper} * @throws DuplicateArtifactAttachmentException will never happen but leave it for backward compatibility */ - public void addAttachedArtifact( Artifact artifact ) - throws DuplicateArtifactAttachmentException - { + public void addAttachedArtifact(Artifact artifact) throws DuplicateArtifactAttachmentException { // if already there we remove it and add again - int index = attachedArtifacts.indexOf( artifact ); - if ( index >= 0 ) - { - LOGGER.warn( "artifact '{}' already attached, replacing previous instance", artifact ); - attachedArtifacts.set( index, artifact ); - } - else - { - attachedArtifacts.add( artifact ); + int index = attachedArtifacts.indexOf(artifact); + if (index >= 0) { + LOGGER.warn("artifact '{}' already attached, replacing previous instance", artifact); + attachedArtifacts.set(index, artifact); + } else { + attachedArtifacts.add(artifact); } } - public List getAttachedArtifacts() - { - if ( attachedArtifacts == null ) - { + public List getAttachedArtifacts() { + if (attachedArtifacts == null) { attachedArtifacts = new ArrayList<>(); } - return Collections.unmodifiableList( attachedArtifacts ); + return Collections.unmodifiableList(attachedArtifacts); } - public Xpp3Dom getGoalConfiguration( String pluginGroupId, String pluginArtifactId, String executionId, - String goalId ) - { + public Xpp3Dom getGoalConfiguration( + String pluginGroupId, String pluginArtifactId, String executionId, String goalId) { Xpp3Dom dom = null; - if ( getBuildPlugins() != null ) - { - for ( Plugin plugin : getBuildPlugins() ) - { - if ( pluginGroupId.equals( plugin.getGroupId() ) && pluginArtifactId.equals( plugin.getArtifactId() ) ) - { + if (getBuildPlugins() != null) { + for (Plugin plugin : getBuildPlugins()) { + if (pluginGroupId.equals(plugin.getGroupId()) && pluginArtifactId.equals(plugin.getArtifactId())) { dom = (Xpp3Dom) plugin.getConfiguration(); - if ( executionId != null ) - { - for ( PluginExecution execution : plugin.getExecutions() ) - { - if ( executionId.equals( execution.getId() ) ) - { + if (executionId != null) { + for (PluginExecution execution : plugin.getExecutions()) { + if (executionId.equals(execution.getId())) { // NOTE: The PluginConfigurationExpander already merged the plugin-level config in dom = (Xpp3Dom) execution.getConfiguration(); break; @@ -989,32 +828,27 @@ public class MavenProject } } - if ( dom != null ) - { + if (dom != null) { // make a copy so the original in the POM doesn't get messed with - dom = new Xpp3Dom( dom ); + dom = new Xpp3Dom(dom); } return dom; } - public MavenProject getExecutionProject() - { - return ( executionProject == null ? this : executionProject ); + public MavenProject getExecutionProject() { + return (executionProject == null ? this : executionProject); } - public void setExecutionProject( MavenProject executionProject ) - { + public void setExecutionProject(MavenProject executionProject) { this.executionProject = executionProject; } - public List getCollectedProjects() - { + public List getCollectedProjects() { return collectedProjects; } - public void setCollectedProjects( List collectedProjects ) - { + public void setCollectedProjects(List collectedProjects) { this.collectedProjects = collectedProjects; } @@ -1025,69 +859,56 @@ public class MavenProject * @see #getArtifacts() to get all transitive dependencies */ @Deprecated - public Set getDependencyArtifacts() - { + public Set getDependencyArtifacts() { return dependencyArtifacts; } @Deprecated - public void setDependencyArtifacts( Set dependencyArtifacts ) - { + public void setDependencyArtifacts(Set dependencyArtifacts) { this.dependencyArtifacts = dependencyArtifacts; } - public void setReleaseArtifactRepository( ArtifactRepository releaseArtifactRepository ) - { + public void setReleaseArtifactRepository(ArtifactRepository releaseArtifactRepository) { this.releaseArtifactRepository = releaseArtifactRepository; } - public void setSnapshotArtifactRepository( ArtifactRepository snapshotArtifactRepository ) - { + public void setSnapshotArtifactRepository(ArtifactRepository snapshotArtifactRepository) { this.snapshotArtifactRepository = snapshotArtifactRepository; } - public void setOriginalModel( Model originalModel ) - { + public void setOriginalModel(Model originalModel) { this.originalModel = originalModel; } - public Model getOriginalModel() - { + public Model getOriginalModel() { return originalModel; } - public void setManagedVersionMap( Map map ) - { + public void setManagedVersionMap(Map map) { managedVersionMap = map; } - public Map getManagedVersionMap() - { + public Map getManagedVersionMap() { return managedVersionMap; } @Override - public boolean equals( Object other ) - { - if ( other == this ) - { + public boolean equals(Object other) { + if (other == this) { return true; - } - else if ( !( other instanceof MavenProject ) ) - { + } else if (!(other instanceof MavenProject)) { return false; } MavenProject that = (MavenProject) other; - return Objects.equals( getArtifactId(), that.getArtifactId() ) - && Objects.equals( getGroupId(), that.getGroupId() ) - && Objects.equals( getVersion(), that.getVersion() ); + return Objects.equals(getArtifactId(), that.getArtifactId()) + && Objects.equals(getGroupId(), that.getGroupId()) + && Objects.equals(getVersion(), that.getVersion()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = 31 * hash + getGroupId().hashCode(); hash = 31 * hash + getArtifactId().hashCode(); @@ -1095,77 +916,63 @@ public class MavenProject return hash; } - public List getBuildExtensions() - { + public List getBuildExtensions() { Build build = getBuild(); - if ( ( build == null ) || ( build.getExtensions() == null ) ) - { + if ((build == null) || (build.getExtensions() == null)) { return Collections.emptyList(); - } - else - { - return Collections.unmodifiableList( build.getExtensions() ); + } else { + return Collections.unmodifiableList(build.getExtensions()); } } - public void addProjectReference( MavenProject project ) - { - projectReferences.put( getProjectReferenceId( project.getGroupId(), project.getArtifactId(), - project.getVersion() ), project ); + public void addProjectReference(MavenProject project) { + projectReferences.put( + getProjectReferenceId(project.getGroupId(), project.getArtifactId(), project.getVersion()), project); } - public Properties getProperties() - { + public Properties getProperties() { return getModel().getProperties(); } - public List getFilters() - { + public List getFilters() { return getBuild().getFilters(); } - public Map getProjectReferences() - { + public Map getProjectReferences() { return projectReferences; } - public boolean isExecutionRoot() - { + public boolean isExecutionRoot() { return executionRoot; } - public void setExecutionRoot( boolean executionRoot ) - { + public void setExecutionRoot(boolean executionRoot) { this.executionRoot = executionRoot; } - public String getDefaultGoal() - { + public String getDefaultGoal() { return getBuild() != null ? getBuild().getDefaultGoal() : null; } - public Plugin getPlugin( String pluginKey ) - { - return getBuild().getPluginsAsMap().get( pluginKey ); + public Plugin getPlugin(String pluginKey) { + return getBuild().getPluginsAsMap().get(pluginKey); } /** * Default toString */ @Override - public String toString() - { - StringBuilder sb = new StringBuilder( 128 ); - sb.append( "MavenProject: " ); - sb.append( getGroupId() ); - sb.append( ':' ); - sb.append( getArtifactId() ); - sb.append( ':' ); - sb.append( getVersion() ); - if ( getFile() != null ) - { - sb.append( " @ " ); - sb.append( getFile().getPath() ); + public String toString() { + StringBuilder sb = new StringBuilder(128); + sb.append("MavenProject: "); + sb.append(getGroupId()); + sb.append(':'); + sb.append(getArtifactId()); + sb.append(':'); + sb.append(getVersion()); + if (getFile() != null) { + sb.append(" @ "); + sb.append(getFile().getPath()); } return sb.toString(); @@ -1175,55 +982,44 @@ public class MavenProject * @since 2.0.9 */ @Override - public MavenProject clone() - { + public MavenProject clone() { MavenProject clone; - try - { + try { clone = (MavenProject) super.clone(); - } - catch ( CloneNotSupportedException e ) - { - throw new UnsupportedOperationException( e ); + } catch (CloneNotSupportedException e) { + throw new UnsupportedOperationException(e); } - clone.deepCopy( this ); + clone.deepCopy(this); return clone; } - public void setModel( Model model ) - { + public void setModel(Model model) { this.model = model; } - protected void setAttachedArtifacts( List attachedArtifacts ) - { + protected void setAttachedArtifacts(List attachedArtifacts) { this.attachedArtifacts = attachedArtifacts; } - protected void setCompileSourceRoots( List compileSourceRoots ) - { + protected void setCompileSourceRoots(List compileSourceRoots) { this.compileSourceRoots = compileSourceRoots; } - protected void setTestCompileSourceRoots( List testCompileSourceRoots ) - { + protected void setTestCompileSourceRoots(List testCompileSourceRoots) { this.testCompileSourceRoots = testCompileSourceRoots; } - protected ArtifactRepository getReleaseArtifactRepository() - { + protected ArtifactRepository getReleaseArtifactRepository() { return releaseArtifactRepository; } - protected ArtifactRepository getSnapshotArtifactRepository() - { + protected ArtifactRepository getSnapshotArtifactRepository() { return snapshotArtifactRepository; } - private void deepCopy( MavenProject project ) - { + private void deepCopy(MavenProject project) { // disown the parent // copy fields @@ -1232,113 +1028,93 @@ public class MavenProject // don't need a deep copy, they don't get modified or added/removed to/from - but make them unmodifiable to be // sure! - if ( project.getDependencyArtifacts() != null ) - { - setDependencyArtifacts( Collections.unmodifiableSet( project.getDependencyArtifacts() ) ); + if (project.getDependencyArtifacts() != null) { + setDependencyArtifacts(Collections.unmodifiableSet(project.getDependencyArtifacts())); } - if ( project.getArtifacts() != null ) - { - setArtifacts( Collections.unmodifiableSet( project.getArtifacts() ) ); + if (project.getArtifacts() != null) { + setArtifacts(Collections.unmodifiableSet(project.getArtifacts())); } - if ( project.getParentFile() != null ) - { - parentFile = new File( project.getParentFile().getAbsolutePath() ); + if (project.getParentFile() != null) { + parentFile = new File(project.getParentFile().getAbsolutePath()); } - if ( project.getPluginArtifacts() != null ) - { - setPluginArtifacts( Collections.unmodifiableSet( project.getPluginArtifacts() ) ); + if (project.getPluginArtifacts() != null) { + setPluginArtifacts(Collections.unmodifiableSet(project.getPluginArtifacts())); } - if ( project.getReportArtifacts() != null ) - { - setReportArtifacts( Collections.unmodifiableSet( project.getReportArtifacts() ) ); + if (project.getReportArtifacts() != null) { + setReportArtifacts(Collections.unmodifiableSet(project.getReportArtifacts())); } - if ( project.getExtensionArtifacts() != null ) - { - setExtensionArtifacts( Collections.unmodifiableSet( project.getExtensionArtifacts() ) ); + if (project.getExtensionArtifacts() != null) { + setExtensionArtifacts(Collections.unmodifiableSet(project.getExtensionArtifacts())); } - setParentArtifact( ( project.getParentArtifact() ) ); + setParentArtifact((project.getParentArtifact())); - if ( project.getRemoteArtifactRepositories() != null ) - { - setRemoteArtifactRepositories( Collections.unmodifiableList( project.getRemoteArtifactRepositories() ) ); + if (project.getRemoteArtifactRepositories() != null) { + setRemoteArtifactRepositories(Collections.unmodifiableList(project.getRemoteArtifactRepositories())); } - if ( project.getPluginArtifactRepositories() != null ) - { - setPluginArtifactRepositories( Collections.unmodifiableList( project.getPluginArtifactRepositories() ) ); + if (project.getPluginArtifactRepositories() != null) { + setPluginArtifactRepositories(Collections.unmodifiableList(project.getPluginArtifactRepositories())); } - if ( project.getActiveProfiles() != null ) - { - setActiveProfiles( ( Collections.unmodifiableList( project.getActiveProfiles() ) ) ); + if (project.getActiveProfiles() != null) { + setActiveProfiles((Collections.unmodifiableList(project.getActiveProfiles()))); } - if ( project.getAttachedArtifacts() != null ) - { + if (project.getAttachedArtifacts() != null) { // clone properties modifiable by plugins in a forked lifecycle - setAttachedArtifacts( new ArrayList<>( project.getAttachedArtifacts() ) ); + setAttachedArtifacts(new ArrayList<>(project.getAttachedArtifacts())); } - if ( project.getCompileSourceRoots() != null ) - { + if (project.getCompileSourceRoots() != null) { // clone source roots - setCompileSourceRoots( ( new ArrayList<>( project.getCompileSourceRoots() ) ) ); + setCompileSourceRoots((new ArrayList<>(project.getCompileSourceRoots()))); } - if ( project.getTestCompileSourceRoots() != null ) - { - setTestCompileSourceRoots( ( new ArrayList<>( project.getTestCompileSourceRoots() ) ) ); + if (project.getTestCompileSourceRoots() != null) { + setTestCompileSourceRoots((new ArrayList<>(project.getTestCompileSourceRoots()))); } - if ( project.getScriptSourceRoots() != null ) - { - setScriptSourceRoots( ( new ArrayList<>( project.getScriptSourceRoots() ) ) ); + if (project.getScriptSourceRoots() != null) { + setScriptSourceRoots((new ArrayList<>(project.getScriptSourceRoots()))); } - if ( project.getModel() != null ) - { - setModel( project.getModel().clone() ); + if (project.getModel() != null) { + setModel(project.getModel().clone()); } - if ( project.getOriginalModel() != null ) - { - setOriginalModel( project.getOriginalModel() ); + if (project.getOriginalModel() != null) { + setOriginalModel(project.getOriginalModel()); } - setExecutionRoot( project.isExecutionRoot() ); + setExecutionRoot(project.isExecutionRoot()); - if ( project.getArtifact() != null ) - { - setArtifact( ArtifactUtils.copyArtifact( project.getArtifact() ) ); + if (project.getArtifact() != null) { + setArtifact(ArtifactUtils.copyArtifact(project.getArtifact())); } - if ( project.getManagedVersionMap() != null ) - { - setManagedVersionMap( project.getManagedVersionMap() ); + if (project.getManagedVersionMap() != null) { + setManagedVersionMap(project.getManagedVersionMap()); } - lifecyclePhases.addAll( project.lifecyclePhases ); + lifecyclePhases.addAll(project.lifecyclePhases); } - private void addArtifactPath( Artifact artifact, List classpath ) - { + private void addArtifactPath(Artifact artifact, List classpath) { File file = artifact.getFile(); - if ( file != null ) - { - classpath.add( file.getPath() ); + if (file != null) { + classpath.add(file.getPath()); } } - private static String getProjectReferenceId( String groupId, String artifactId, String version ) - { - StringBuilder buffer = new StringBuilder( 128 ); - buffer.append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( version ); + private static String getProjectReferenceId(String groupId, String artifactId, String version) { + StringBuilder buffer = new StringBuilder(128); + buffer.append(groupId).append(':').append(artifactId).append(':').append(version); return buffer.toString(); } @@ -1347,32 +1123,25 @@ public class MavenProject * null, the context value is removed from this project. Context values are intended to allow core * extensions to associate derived state with project instances. */ - public void setContextValue( String key, Object value ) - { - if ( context == null ) - { + public void setContextValue(String key, Object value) { + if (context == null) { context = new HashMap<>(); } - if ( value != null ) - { - context.put( key, value ); - } - else - { - context.remove( key ); + if (value != null) { + context.put(key, value); + } else { + context.remove(key); } } /** * Returns context value of this project associated with the given key or null if this project has no such value. */ - public Object getContextValue( String key ) - { - if ( context == null ) - { + public Object getContextValue(String key) { + if (context == null) { return null; } - return context.get( key ); + return context.get(key); } /** @@ -1382,8 +1151,7 @@ public class MavenProject * * @param classRealm The class realm hosting the build extensions of this project, may be {@code null}. */ - public void setClassRealm( ClassRealm classRealm ) - { + public void setClassRealm(ClassRealm classRealm) { this.classRealm = classRealm; } @@ -1395,8 +1163,7 @@ public class MavenProject * * @return The project's class realm or {@code null}. */ - public ClassRealm getClassRealm() - { + public ClassRealm getClassRealm() { return classRealm; } @@ -1407,8 +1174,7 @@ public class MavenProject * * @param extensionDependencyFilter The dependency filter to apply to plugins, may be {@code null}. */ - public void setExtensionDependencyFilter( DependencyFilter extensionDependencyFilter ) - { + public void setExtensionDependencyFilter(DependencyFilter extensionDependencyFilter) { this.extensionDependencyFilter = extensionDependencyFilter; } @@ -1420,8 +1186,7 @@ public class MavenProject * * @return The dependency filter or {@code null}. */ - public DependencyFilter getExtensionDependencyFilter() - { + public DependencyFilter getExtensionDependencyFilter() { return extensionDependencyFilter; } @@ -1433,9 +1198,8 @@ public class MavenProject * * @param artifacts The set of artifacts, may be {@code null}. */ - public void setResolvedArtifacts( Set artifacts ) - { - this.resolvedArtifacts = ( artifacts != null ) ? artifacts : Collections.emptySet(); + public void setResolvedArtifacts(Set artifacts) { + this.resolvedArtifacts = (artifacts != null) ? artifacts : Collections.emptySet(); this.artifacts = null; this.artifactMap = null; } @@ -1448,8 +1212,7 @@ public class MavenProject * * @param artifactFilter The artifact filter, may be {@code null} to exclude all artifacts. */ - public void setArtifactFilter( ArtifactFilter artifactFilter ) - { + public void setArtifactFilter(ArtifactFilter artifactFilter) { this.artifactFilter = artifactFilter; this.artifacts = null; this.artifactMap = null; @@ -1463,9 +1226,8 @@ public class MavenProject * @param phase The phase to check for, must not be {@code null}. * @return {@code true} if the phase has been seen. */ - public boolean hasLifecyclePhase( String phase ) - { - return lifecyclePhases.contains( phase ); + public boolean hasLifecyclePhase(String phase) { + return lifecyclePhases.contains(phase); } /** @@ -1475,9 +1237,8 @@ public class MavenProject * * @param lifecyclePhase The lifecycle phase to add, must not be {@code null}. */ - public void addLifecyclePhase( String lifecyclePhase ) - { - lifecyclePhases.add( lifecyclePhase ); + public void addLifecyclePhase(String lifecyclePhase) { + lifecyclePhases.add(lifecyclePhase); } // ---------------------------------------------------------------------------------------------------------------- @@ -1497,113 +1258,93 @@ public class MavenProject private Map moduleAdjustments; @Deprecated // This appears only to be used in test code - public String getModulePathAdjustment( MavenProject moduleProject ) - throws IOException - { + public String getModulePathAdjustment(MavenProject moduleProject) throws IOException { // FIXME: This is hacky. What if module directory doesn't match artifactid, and parent // is coming from the repository?? String module = moduleProject.getArtifactId(); File moduleFile = moduleProject.getFile(); - if ( moduleFile != null ) - { + if (moduleFile != null) { File moduleDir = moduleFile.getCanonicalFile().getParentFile(); module = moduleDir.getName(); } - if ( moduleAdjustments == null ) - { + if (moduleAdjustments == null) { moduleAdjustments = new HashMap<>(); List modules = getModules(); - if ( modules != null ) - { - for ( String modulePath : modules ) - { + if (modules != null) { + for (String modulePath : modules) { String moduleName = modulePath; - if ( moduleName.endsWith( "/" ) || moduleName.endsWith( "\\" ) ) - { - moduleName = moduleName.substring( 0, moduleName.length() - 1 ); + if (moduleName.endsWith("/") || moduleName.endsWith("\\")) { + moduleName = moduleName.substring(0, moduleName.length() - 1); } - int lastSlash = moduleName.lastIndexOf( '/' ); + int lastSlash = moduleName.lastIndexOf('/'); - if ( lastSlash < 0 ) - { - lastSlash = moduleName.lastIndexOf( '\\' ); + if (lastSlash < 0) { + lastSlash = moduleName.lastIndexOf('\\'); } String adjustment = null; - if ( lastSlash > -1 ) - { - moduleName = moduleName.substring( lastSlash + 1 ); - adjustment = modulePath.substring( 0, lastSlash ); + if (lastSlash > -1) { + moduleName = moduleName.substring(lastSlash + 1); + adjustment = modulePath.substring(0, lastSlash); } - moduleAdjustments.put( moduleName, adjustment ); + moduleAdjustments.put(moduleName, adjustment); } } } - return moduleAdjustments.get( module ); + return moduleAdjustments.get(module); } @Deprecated - public Set createArtifacts( ArtifactFactory artifactFactory, String inheritedScope, - ArtifactFilter filter ) - throws InvalidDependencyVersionException - { - return MavenMetadataSource.createArtifacts( artifactFactory, getModel().getDependencies(), - inheritedScope, filter, this ); + public Set createArtifacts(ArtifactFactory artifactFactory, String inheritedScope, ArtifactFilter filter) + throws InvalidDependencyVersionException { + return MavenMetadataSource.createArtifacts( + artifactFactory, getModel().getDependencies(), inheritedScope, filter, this); } @Deprecated - protected void setScriptSourceRoots( List scriptSourceRoots ) - { + protected void setScriptSourceRoots(List scriptSourceRoots) { this.scriptSourceRoots = scriptSourceRoots; } @Deprecated - public void addScriptSourceRoot( String path ) - { - if ( path != null ) - { + public void addScriptSourceRoot(String path) { + if (path != null) { path = path.trim(); - if ( path.length() != 0 ) - { - if ( !getScriptSourceRoots().contains( path ) ) - { - getScriptSourceRoots().add( path ); + if (path.length() != 0) { + if (!getScriptSourceRoots().contains(path)) { + getScriptSourceRoots().add(path); } } } } @Deprecated - public List getScriptSourceRoots() - { + public List getScriptSourceRoots() { return scriptSourceRoots; } @Deprecated - public List getCompileArtifacts() - { - List list = new ArrayList<>( getArtifacts().size() ); + public List getCompileArtifacts() { + List list = new ArrayList<>(getArtifacts().size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO classpath check doesn't belong here - that's the other method - if ( a.getArtifactHandler().isAddedToClasspath() ) - { + if (a.getArtifactHandler().isAddedToClasspath()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_COMPILE.equals( a.getScope() ) || Artifact.SCOPE_PROVIDED.equals( a.getScope() ) - || Artifact.SCOPE_SYSTEM.equals( a.getScope() ) ) - { - list.add( a ); + if (Artifact.SCOPE_COMPILE.equals(a.getScope()) + || Artifact.SCOPE_PROVIDED.equals(a.getScope()) + || Artifact.SCOPE_SYSTEM.equals(a.getScope())) { + list.add(a); } } } @@ -1611,152 +1352,130 @@ public class MavenProject } @Deprecated - public List getCompileDependencies() - { + public List getCompileDependencies() { Set artifacts = getArtifacts(); - if ( ( artifacts == null ) || artifacts.isEmpty() ) - { + if ((artifacts == null) || artifacts.isEmpty()) { return Collections.emptyList(); } - List list = new ArrayList<>( artifacts.size() ); + List list = new ArrayList<>(artifacts.size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_COMPILE.equals( a.getScope() ) || Artifact.SCOPE_PROVIDED.equals( a.getScope() ) - || Artifact.SCOPE_SYSTEM.equals( a.getScope() ) ) - { + if (Artifact.SCOPE_COMPILE.equals(a.getScope()) + || Artifact.SCOPE_PROVIDED.equals(a.getScope()) + || Artifact.SCOPE_SYSTEM.equals(a.getScope())) { Dependency dependency = new Dependency(); - dependency.setArtifactId( a.getArtifactId() ); - dependency.setGroupId( a.getGroupId() ); - dependency.setVersion( a.getVersion() ); - dependency.setScope( a.getScope() ); - dependency.setType( a.getType() ); - dependency.setClassifier( a.getClassifier() ); + dependency.setArtifactId(a.getArtifactId()); + dependency.setGroupId(a.getGroupId()); + dependency.setVersion(a.getVersion()); + dependency.setScope(a.getScope()); + dependency.setType(a.getType()); + dependency.setClassifier(a.getClassifier()); - list.add( dependency ); + list.add(dependency); } } - return Collections.unmodifiableList( list ); + return Collections.unmodifiableList(list); } @Deprecated - public List getTestArtifacts() - { - List list = new ArrayList<>( getArtifacts().size() ); + public List getTestArtifacts() { + List list = new ArrayList<>(getArtifacts().size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO classpath check doesn't belong here - that's the other method - if ( a.getArtifactHandler().isAddedToClasspath() ) - { - list.add( a ); + if (a.getArtifactHandler().isAddedToClasspath()) { + list.add(a); } } return list; } @Deprecated - public List getTestDependencies() - { + public List getTestDependencies() { Set artifacts = getArtifacts(); - if ( ( artifacts == null ) || artifacts.isEmpty() ) - { + if ((artifacts == null) || artifacts.isEmpty()) { return Collections.emptyList(); } - List list = new ArrayList<>( artifacts.size() ); + List list = new ArrayList<>(artifacts.size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { Dependency dependency = new Dependency(); - dependency.setArtifactId( a.getArtifactId() ); - dependency.setGroupId( a.getGroupId() ); - dependency.setVersion( a.getVersion() ); - dependency.setScope( a.getScope() ); - dependency.setType( a.getType() ); - dependency.setClassifier( a.getClassifier() ); + dependency.setArtifactId(a.getArtifactId()); + dependency.setGroupId(a.getGroupId()); + dependency.setVersion(a.getVersion()); + dependency.setScope(a.getScope()); + dependency.setType(a.getType()); + dependency.setClassifier(a.getClassifier()); - list.add( dependency ); + list.add(dependency); } - return Collections.unmodifiableList( list ); + return Collections.unmodifiableList(list); } @Deprecated // used by the Maven ITs - public List getRuntimeDependencies() - { + public List getRuntimeDependencies() { Set artifacts = getArtifacts(); - if ( ( artifacts == null ) || artifacts.isEmpty() ) - { + if ((artifacts == null) || artifacts.isEmpty()) { return Collections.emptyList(); } - List list = new ArrayList<>( artifacts.size() ); + List list = new ArrayList<>(artifacts.size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_COMPILE.equals( a.getScope() ) || Artifact.SCOPE_RUNTIME.equals( a.getScope() ) ) - { + if (Artifact.SCOPE_COMPILE.equals(a.getScope()) || Artifact.SCOPE_RUNTIME.equals(a.getScope())) { Dependency dependency = new Dependency(); - dependency.setArtifactId( a.getArtifactId() ); - dependency.setGroupId( a.getGroupId() ); - dependency.setVersion( a.getVersion() ); - dependency.setScope( a.getScope() ); - dependency.setType( a.getType() ); - dependency.setClassifier( a.getClassifier() ); + dependency.setArtifactId(a.getArtifactId()); + dependency.setGroupId(a.getGroupId()); + dependency.setVersion(a.getVersion()); + dependency.setScope(a.getScope()); + dependency.setType(a.getType()); + dependency.setClassifier(a.getClassifier()); - list.add( dependency ); + list.add(dependency); } } - return Collections.unmodifiableList( list ); + return Collections.unmodifiableList(list); } @Deprecated - public List getRuntimeArtifacts() - { - List list = new ArrayList<>( getArtifacts().size() ); + public List getRuntimeArtifacts() { + List list = new ArrayList<>(getArtifacts().size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO classpath check doesn't belong here - that's the other method - if ( a.getArtifactHandler().isAddedToClasspath() - // TODO let the scope handler deal with this - && ( Artifact.SCOPE_COMPILE.equals( a.getScope() ) || Artifact.SCOPE_RUNTIME.equals( a.getScope() ) ) ) - { - list.add( a ); + if (a.getArtifactHandler().isAddedToClasspath() + // TODO let the scope handler deal with this + && (Artifact.SCOPE_COMPILE.equals(a.getScope()) || Artifact.SCOPE_RUNTIME.equals(a.getScope()))) { + list.add(a); } } return list; } @Deprecated - public List getSystemClasspathElements() - throws DependencyResolutionRequiredException - { - List list = new ArrayList<>( getArtifacts().size() ); + public List getSystemClasspathElements() throws DependencyResolutionRequiredException { + List list = new ArrayList<>(getArtifacts().size()); String d = getBuild().getOutputDirectory(); - if ( d != null ) - { - list.add( d ); + if (d != null) { + list.add(d); } - for ( Artifact a : getArtifacts() ) - { - if ( a.getArtifactHandler().isAddedToClasspath() ) - { + for (Artifact a : getArtifacts()) { + if (a.getArtifactHandler().isAddedToClasspath()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_SYSTEM.equals( a.getScope() ) ) - { - addArtifactPath( a, list ); + if (Artifact.SCOPE_SYSTEM.equals(a.getScope())) { + addArtifactPath(a, list); } } } @@ -1764,19 +1483,15 @@ public class MavenProject } @Deprecated - public List getSystemArtifacts() - { - List list = new ArrayList<>( getArtifacts().size() ); + public List getSystemArtifacts() { + List list = new ArrayList<>(getArtifacts().size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO classpath check doesn't belong here - that's the other method - if ( a.getArtifactHandler().isAddedToClasspath() ) - { + if (a.getArtifactHandler().isAddedToClasspath()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_SYSTEM.equals( a.getScope() ) ) - { - list.add( a ); + if (Artifact.SCOPE_SYSTEM.equals(a.getScope())) { + list.add(a); } } } @@ -1784,112 +1499,95 @@ public class MavenProject } @Deprecated - public List getSystemDependencies() - { + public List getSystemDependencies() { Set artifacts = getArtifacts(); - if ( ( artifacts == null ) || artifacts.isEmpty() ) - { + if ((artifacts == null) || artifacts.isEmpty()) { return Collections.emptyList(); } - List list = new ArrayList<>( artifacts.size() ); + List list = new ArrayList<>(artifacts.size()); - for ( Artifact a : getArtifacts() ) - { + for (Artifact a : getArtifacts()) { // TODO let the scope handler deal with this - if ( Artifact.SCOPE_SYSTEM.equals( a.getScope() ) ) - { + if (Artifact.SCOPE_SYSTEM.equals(a.getScope())) { Dependency dependency = new Dependency(); - dependency.setArtifactId( a.getArtifactId() ); - dependency.setGroupId( a.getGroupId() ); - dependency.setVersion( a.getVersion() ); - dependency.setScope( a.getScope() ); - dependency.setType( a.getType() ); - dependency.setClassifier( a.getClassifier() ); + dependency.setArtifactId(a.getArtifactId()); + dependency.setGroupId(a.getGroupId()); + dependency.setVersion(a.getVersion()); + dependency.setScope(a.getScope()); + dependency.setType(a.getType()); + dependency.setClassifier(a.getClassifier()); - list.add( dependency ); + list.add(dependency); } } - return Collections.unmodifiableList( list ); + return Collections.unmodifiableList(list); } @Deprecated - public void setReporting( Reporting reporting ) - { - getModel().setReporting( reporting ); + public void setReporting(Reporting reporting) { + getModel().setReporting(reporting); } @Deprecated - public Reporting getReporting() - { + public Reporting getReporting() { return getModel().getReporting(); } @Deprecated - public void setReportArtifacts( Set reportArtifacts ) - { + public void setReportArtifacts(Set reportArtifacts) { this.reportArtifacts = reportArtifacts; reportArtifactMap = null; } @Deprecated - public Set getReportArtifacts() - { + public Set getReportArtifacts() { return reportArtifacts; } @Deprecated - public Map getReportArtifactMap() - { - if ( reportArtifactMap == null ) - { - reportArtifactMap = ArtifactUtils.artifactMapByVersionlessId( getReportArtifacts() ); + public Map getReportArtifactMap() { + if (reportArtifactMap == null) { + reportArtifactMap = ArtifactUtils.artifactMapByVersionlessId(getReportArtifacts()); } return reportArtifactMap; } @Deprecated - public void setExtensionArtifacts( Set extensionArtifacts ) - { + public void setExtensionArtifacts(Set extensionArtifacts) { this.extensionArtifacts = extensionArtifacts; extensionArtifactMap = null; } @Deprecated - public Set getExtensionArtifacts() - { + public Set getExtensionArtifacts() { return extensionArtifacts; } @Deprecated - public Map getExtensionArtifactMap() - { - if ( extensionArtifactMap == null ) - { - extensionArtifactMap = ArtifactUtils.artifactMapByVersionlessId( getExtensionArtifacts() ); + public Map getExtensionArtifactMap() { + if (extensionArtifactMap == null) { + extensionArtifactMap = ArtifactUtils.artifactMapByVersionlessId(getExtensionArtifacts()); } return extensionArtifactMap; } @Deprecated - public List getReportPlugins() - { - if ( getModel().getReporting() == null ) - { + public List getReportPlugins() { + if (getModel().getReporting() == null) { return Collections.emptyList(); } - return Collections.unmodifiableList( getModel().getReporting().getPlugins() ); + return Collections.unmodifiableList(getModel().getReporting().getPlugins()); } @Deprecated - public Xpp3Dom getReportConfiguration( String pluginGroupId, String pluginArtifactId, String reportSetId ) - { + public Xpp3Dom getReportConfiguration(String pluginGroupId, String pluginArtifactId, String reportSetId) { Xpp3Dom dom = null; // ---------------------------------------------------------------------- @@ -1898,24 +1596,18 @@ public class MavenProject // for now I have to iterate through and see what we have. // ---------------------------------------------------------------------- - if ( getReportPlugins() != null ) - { - for ( ReportPlugin plugin : getReportPlugins() ) - { - if ( pluginGroupId.equals( plugin.getGroupId() ) && pluginArtifactId.equals( plugin.getArtifactId() ) ) - { + if (getReportPlugins() != null) { + for (ReportPlugin plugin : getReportPlugins()) { + if (pluginGroupId.equals(plugin.getGroupId()) && pluginArtifactId.equals(plugin.getArtifactId())) { dom = (Xpp3Dom) plugin.getConfiguration(); - if ( reportSetId != null ) - { - ReportSet reportSet = plugin.getReportSetsAsMap().get( reportSetId ); - if ( reportSet != null ) - { + if (reportSetId != null) { + ReportSet reportSet = plugin.getReportSetsAsMap().get(reportSetId); + if (reportSet != null) { Xpp3Dom executionConfiguration = (Xpp3Dom) reportSet.getConfiguration(); - if ( executionConfiguration != null ) - { - Xpp3Dom newDom = new Xpp3Dom( executionConfiguration ); - dom = Xpp3Dom.mergeXpp3Dom( newDom, dom ); + if (executionConfiguration != null) { + Xpp3Dom newDom = new Xpp3Dom(executionConfiguration); + dom = Xpp3Dom.mergeXpp3Dom(newDom, dom); } } } @@ -1924,10 +1616,9 @@ public class MavenProject } } - if ( dom != null ) - { + if (dom != null) { // make a copy so the original in the POM doesn't get messed with - dom = new Xpp3Dom( dom ); + dom = new Xpp3Dom(dom); } return dom; @@ -1937,35 +1628,28 @@ public class MavenProject * @deprecated Use MavenProjectHelper.attachArtifact(..) instead. */ @Deprecated - public void attachArtifact( String type, String classifier, File file ) - { + public void attachArtifact(String type, String classifier, File file) {} + + /** + * @deprecated Use {@link org.apache.maven.model.io.ModelWriter}. + */ + @Deprecated + public void writeModel(Writer writer) throws IOException { + MavenXpp3Writer pomWriter = new MavenXpp3Writer(); + pomWriter.write(writer, getModel()); } /** * @deprecated Use {@link org.apache.maven.model.io.ModelWriter}. */ @Deprecated - public void writeModel( Writer writer ) - throws IOException - { + public void writeOriginalModel(Writer writer) throws IOException { MavenXpp3Writer pomWriter = new MavenXpp3Writer(); - pomWriter.write( writer, getModel() ); - } - - /** - * @deprecated Use {@link org.apache.maven.model.io.ModelWriter}. - */ - @Deprecated - public void writeOriginalModel( Writer writer ) - throws IOException - { - MavenXpp3Writer pomWriter = new MavenXpp3Writer(); - pomWriter.write( writer, getOriginalModel() ); + pomWriter.write(writer, getOriginalModel()); } @Deprecated - public Artifact replaceWithActiveArtifact( Artifact pluginArtifact ) - { + public Artifact replaceWithActiveArtifact(Artifact pluginArtifact) { return pluginArtifact; } @@ -1977,8 +1661,7 @@ public class MavenProject * @since 2.1 */ @Deprecated - public ProjectBuildingRequest getProjectBuildingRequest() - { + public ProjectBuildingRequest getProjectBuildingRequest() { return projectBuilderConfiguration; } @@ -1991,8 +1674,7 @@ public class MavenProject */ // used by maven-dependency-tree @Deprecated - public void setProjectBuildingRequest( ProjectBuildingRequest projectBuildingRequest ) - { + public void setProjectBuildingRequest(ProjectBuildingRequest projectBuildingRequest) { this.projectBuilderConfiguration = projectBuildingRequest; } } diff --git a/maven-core/src/main/java/org/apache/maven/project/MavenProjectHelper.java b/maven-core/src/main/java/org/apache/maven/project/MavenProjectHelper.java index ec5c3907e4..4e75473210 100644 --- a/maven-core/src/main/java/org/apache/maven/project/MavenProjectHelper.java +++ b/maven-core/src/main/java/org/apache/maven/project/MavenProjectHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.List; @@ -25,8 +24,7 @@ import java.util.List; /** * Convenience interface for plugins to add or replace artifacts and resources on projects. */ -public interface MavenProjectHelper -{ +public interface MavenProjectHelper { String ROLE = MavenProjectHelper.class.getName(); /** @@ -35,7 +33,7 @@ public interface MavenProjectHelper * @param artifactFile artifact file. * @param artifactClassifier artifact classifier. */ - void attachArtifact( MavenProject project, File artifactFile, String artifactClassifier ); + void attachArtifact(MavenProject project, File artifactFile, String artifactClassifier); /** * * See {@link #attachArtifact(MavenProject, String, String, java.io.File)}, but with classifier set to null. @@ -43,7 +41,7 @@ public interface MavenProjectHelper * @param artifactType artifact type. * @param artifactFile artifact file. */ - void attachArtifact( MavenProject project, String artifactType, File artifactFile ); + void attachArtifact(MavenProject project, String artifactType, File artifactFile); /** * Add or replace an artifact to the current project. @@ -52,7 +50,7 @@ public interface MavenProjectHelper * @param artifactClassifier the classifier or null. * @param artifactFile the file for the artifact. */ - void attachArtifact( MavenProject project, String artifactType, String artifactClassifier, File artifactFile ); + void attachArtifact(MavenProject project, String artifactType, String artifactClassifier, File artifactFile); /** * Add a resource directory to the project. @@ -61,7 +59,7 @@ public interface MavenProjectHelper * @param includes include patterns. * @param excludes exclude patterns. */ - void addResource( MavenProject project, String resourceDirectory, List includes, List excludes ); + void addResource(MavenProject project, String resourceDirectory, List includes, List excludes); /** * Add a test resource directory to the project. @@ -70,7 +68,5 @@ public interface MavenProjectHelper * @param includes include patterns. * @param excludes exclude patterns. */ - void addTestResource( MavenProject project, String resourceDirectory, List includes, - List excludes ); - + void addTestResource(MavenProject project, String resourceDirectory, List includes, List excludes); } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectBuilder.java b/maven-core/src/main/java/org/apache/maven/project/ProjectBuilder.java index a2db80ed1a..1b1a173718 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,18 +16,17 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.model.building.ModelSource; /** * Builds in-memory descriptions of projects. */ -public interface ProjectBuilder -{ +public interface ProjectBuilder { /** * Builds a project descriptor from the specified POM file. @@ -39,8 +36,7 @@ public interface ProjectBuilder * @return The result of the project building, never {@code null}. * @throws ProjectBuildingException If the project descriptor could not be successfully built. */ - ProjectBuildingResult build( File projectFile, ProjectBuildingRequest request ) - throws ProjectBuildingException; + ProjectBuildingResult build(File projectFile, ProjectBuildingRequest request) throws ProjectBuildingException; /** * Builds a project descriptor for the specified artifact. @@ -50,8 +46,8 @@ public interface ProjectBuilder * @return The result of the project building, never {@code null}. * @throws ProjectBuildingException If the project descriptor could not be successfully built. */ - ProjectBuildingResult build( Artifact projectArtifact, ProjectBuildingRequest request ) - throws ProjectBuildingException; + ProjectBuildingResult build(Artifact projectArtifact, ProjectBuildingRequest request) + throws ProjectBuildingException; /** * Builds a project descriptor for the specified artifact. @@ -64,8 +60,8 @@ public interface ProjectBuilder * @return The result of the project building, never {@code null}. * @throws ProjectBuildingException If the project descriptor could not be successfully built. */ - ProjectBuildingResult build( Artifact projectArtifact, boolean allowStubModel, ProjectBuildingRequest request ) - throws ProjectBuildingException; + ProjectBuildingResult build(Artifact projectArtifact, boolean allowStubModel, ProjectBuildingRequest request) + throws ProjectBuildingException; /** * Builds a project descriptor for the specified model source. @@ -77,8 +73,8 @@ public interface ProjectBuilder * * @see org.apache.maven.model.building.ModelSource2 */ - ProjectBuildingResult build( ModelSource modelSource, ProjectBuildingRequest request ) - throws ProjectBuildingException; + ProjectBuildingResult build(ModelSource modelSource, ProjectBuildingRequest request) + throws ProjectBuildingException; /** * Builds the projects for the specified POM files and optionally their children. @@ -92,7 +88,6 @@ public interface ProjectBuilder * @throws ProjectBuildingException If an error was encountered during building of any project. * {@link ProjectBuildingException#getResults()} provides access to the details of the problems. */ - List build( List pomFiles, boolean recursive, ProjectBuildingRequest request ) - throws ProjectBuildingException; - + List build(List pomFiles, boolean recursive, ProjectBuildingRequest request) + throws ProjectBuildingException; } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java index 148d215862..fad8f77ea9 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.List; @@ -25,18 +24,15 @@ import java.util.List; /** * @author Jason van Zyl */ -public class ProjectBuildingException - extends Exception -{ +public class ProjectBuildingException extends Exception { private final String projectId; private File pomFile; private List results; - public ProjectBuildingException( String projectId, String message, Throwable cause ) - { - super( createMessage( message, projectId, null ), cause ); + public ProjectBuildingException(String projectId, String message, Throwable cause) { + super(createMessage(message, projectId, null), cause); this.projectId = projectId; } @@ -45,9 +41,8 @@ public class ProjectBuildingException * @param message * @param pomFile pom file location */ - public ProjectBuildingException( String projectId, String message, File pomFile ) - { - super( createMessage( message, projectId, pomFile ) ); + public ProjectBuildingException(String projectId, String message, File pomFile) { + super(createMessage(message, projectId, pomFile)); this.projectId = projectId; this.pomFile = pomFile; } @@ -58,60 +53,48 @@ public class ProjectBuildingException * @param pomFile pom file location * @param cause */ - protected ProjectBuildingException( String projectId, String message, File pomFile, Throwable cause ) - { - super( createMessage( message, projectId, pomFile ), cause ); + protected ProjectBuildingException(String projectId, String message, File pomFile, Throwable cause) { + super(createMessage(message, projectId, pomFile), cause); this.projectId = projectId; this.pomFile = pomFile; } - public ProjectBuildingException( List results ) - { - super( "Some problems were encountered while processing the POMs" ); + public ProjectBuildingException(List results) { + super("Some problems were encountered while processing the POMs"); this.projectId = ""; this.results = results; } - public File getPomFile() - { + public File getPomFile() { return pomFile; } /** * @deprecated use {@link #getPomFile()} */ - public String getPomLocation() - { - if ( getPomFile() != null ) - { + public String getPomLocation() { + if (getPomFile() != null) { return getPomFile().getAbsolutePath(); - } - else - { + } else { return "null"; } } - public String getProjectId() - { + public String getProjectId() { return projectId; } - public List getResults() - { + public List getResults() { return results; } - private static String createMessage( String message, String projectId, File pomFile ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( message ); - buffer.append( " for project " ).append( projectId ); - if ( pomFile != null ) - { - buffer.append( " at " ).append( pomFile.getAbsolutePath() ); + private static String createMessage(String message, String projectId, File pomFile) { + StringBuilder buffer = new StringBuilder(256); + buffer.append(message); + buffer.append(" for project ").append(projectId); + if (pomFile != null) { + buffer.append(" at ").append(pomFile.getAbsolutePath()); } return buffer.toString(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingHelper.java b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingHelper.java index 45fff6e638..efbdd3ffe6 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingHelper.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.List; - import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Model; @@ -36,8 +34,7 @@ import org.apache.maven.plugin.version.PluginVersionResolutionException; * * @author Benjamin Bentmann */ -public interface ProjectBuildingHelper -{ +public interface ProjectBuildingHelper { /** * Creates the effective artifact repositories from the specified POM repositories. @@ -50,10 +47,11 @@ public interface ProjectBuildingHelper * @return The effective artifact repositories, never {@code null}. * @throws InvalidRepositoryException */ - List createArtifactRepositories( List pomRepositories, - List externalRepositories, - ProjectBuildingRequest request ) - throws InvalidRepositoryException; + List createArtifactRepositories( + List pomRepositories, + List externalRepositories, + ProjectBuildingRequest request) + throws InvalidRepositoryException; /** * Creates the project realm that hosts the build extensions of the specified model. @@ -65,9 +63,8 @@ public interface ProjectBuildingHelper * @return The record with the project realm and extension artifact filter, never {@code null}. * @throws PluginResolutionException If any build extension could not be resolved. */ - ProjectRealmCache.CacheRecord createProjectRealm( MavenProject project, Model model, - ProjectBuildingRequest request ) - throws PluginResolutionException, PluginVersionResolutionException, PluginManagerException; + ProjectRealmCache.CacheRecord createProjectRealm(MavenProject project, Model model, ProjectBuildingRequest request) + throws PluginResolutionException, PluginVersionResolutionException, PluginManagerException; /** * Updates the context class loader such that the container will search the project realm when the model builder @@ -76,6 +73,5 @@ public interface ProjectBuildingHelper * * @param project The project whose class realm should be selected, must not be {@code null}. */ - void selectProjectRealm( MavenProject project ); - + void selectProjectRealm(MavenProject project); } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingRequest.java b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingRequest.java index 80523ae77f..23f3838a81 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingRequest.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Date; import java.util.List; import java.util.Properties; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Profile; import org.eclipse.aether.RepositorySystemSession; @@ -30,18 +28,17 @@ import org.eclipse.aether.RepositorySystemSession; /** * ProjectBuildingRequest */ -public interface ProjectBuildingRequest -{ +public interface ProjectBuildingRequest { - ProjectBuildingRequest setLocalRepository( ArtifactRepository localRepository ); + ProjectBuildingRequest setLocalRepository(ArtifactRepository localRepository); ArtifactRepository getLocalRepository(); - ProjectBuildingRequest setRemoteRepositories( List remoteRepositories ); + ProjectBuildingRequest setRemoteRepositories(List remoteRepositories); List getRemoteRepositories(); - ProjectBuildingRequest setPluginArtifactRepositories( List pluginArtifactRepositories ); + ProjectBuildingRequest setPluginArtifactRepositories(List pluginArtifactRepositories); List getPluginArtifactRepositories(); @@ -52,7 +49,7 @@ public interface ProjectBuildingRequest * @param systemProperties The system properties, may be {@code null}. * @return This request, never {@code null}. */ - ProjectBuildingRequest setSystemProperties( Properties systemProperties ); + ProjectBuildingRequest setSystemProperties(Properties systemProperties); /** * Gets the system properties to use for interpolation and profile activation. The system properties are collected @@ -70,7 +67,7 @@ public interface ProjectBuildingRequest * @param userProperties The user properties, may be {@code null}. * @return This request, never {@code null}. */ - ProjectBuildingRequest setUserProperties( Properties userProperties ); + ProjectBuildingRequest setUserProperties(Properties userProperties); /** * Gets the user properties to use for interpolation and profile activation. The user properties have been @@ -81,15 +78,15 @@ public interface ProjectBuildingRequest */ Properties getUserProperties(); - void setProject( MavenProject mavenProject ); + void setProject(MavenProject mavenProject); MavenProject getProject(); - ProjectBuildingRequest setProcessPlugins( boolean processPlugins ); + ProjectBuildingRequest setProcessPlugins(boolean processPlugins); boolean isProcessPlugins(); - ProjectBuildingRequest setResolveDependencies( boolean resolveDependencies ); + ProjectBuildingRequest setResolveDependencies(boolean resolveDependencies); boolean isResolveDependencies(); @@ -100,7 +97,7 @@ public interface ProjectBuildingRequest * {@link org.apache.maven.model.building.ModelBuildingRequest#VALIDATION_LEVEL_STRICT}. * @return This configuration, never {@code null}. */ - ProjectBuildingRequest setValidationLevel( int validationLevel ); + ProjectBuildingRequest setValidationLevel(int validationLevel); /** * Gets the level of validation to perform on processed models. @@ -115,11 +112,11 @@ public interface ProjectBuildingRequest * Set any active profiles that the {@link ProjectBuilder} should consider while constructing * a {@link MavenProject}. */ - void setActiveProfileIds( List activeProfileIds ); + void setActiveProfileIds(List activeProfileIds); List getActiveProfileIds(); - void setInactiveProfileIds( List inactiveProfileIds ); + void setInactiveProfileIds(List inactiveProfileIds); List getInactiveProfileIds(); @@ -129,9 +126,9 @@ public interface ProjectBuildingRequest * * @param profile */ - void addProfile( Profile profile ); + void addProfile(Profile profile); - void setProfiles( List profiles ); + void setProfiles(List profiles); List getProfiles(); @@ -147,11 +144,11 @@ public interface ProjectBuildingRequest * * @param buildStartTime The start time of the build, may be {@code null}. */ - void setBuildStartTime( Date buildStartTime ); + void setBuildStartTime(Date buildStartTime); RepositorySystemSession getRepositorySession(); - ProjectBuildingRequest setRepositorySession( RepositorySystemSession repositorySession ); + ProjectBuildingRequest setRepositorySession(RepositorySystemSession repositorySession); /** * Sets the merge mode used to combine repositories declared in the POM with the repositories specified in this @@ -161,7 +158,7 @@ public interface ProjectBuildingRequest * @return This request for chaining, never {@code null}. * @see #setRemoteRepositories(List) */ - ProjectBuildingRequest setRepositoryMerging( RepositoryMerging mode ); + ProjectBuildingRequest setRepositoryMerging(RepositoryMerging mode); /** * Gets the merge mode used to combine repositories declared in the POM with the repositories specified in this @@ -185,13 +182,12 @@ public interface ProjectBuildingRequest * Commit 6cf9320942c34bc68205425ab696b1712ace9ba4 updated the way 'MavenProject' objects are initialized. */ @Deprecated - ProjectBuildingRequest setResolveVersionRanges( boolean value ); + ProjectBuildingRequest setResolveVersionRanges(boolean value); /** * The possible merge modes for combining remote repositories. */ - enum RepositoryMerging - { + enum RepositoryMerging { /** * The repositories declared in the POM have precedence over the repositories specified in the request. @@ -203,5 +199,4 @@ public interface ProjectBuildingRequest */ REQUEST_DOMINANT, } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingResult.java b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingResult.java index 9a43154c0c..77e957ef7b 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingResult.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; import java.util.List; - import org.apache.maven.model.building.ModelProblem; /** @@ -29,8 +27,7 @@ import org.apache.maven.model.building.ModelProblem; * * @author Benjamin Bentmann */ -public interface ProjectBuildingResult -{ +public interface ProjectBuildingResult { /** * Gets the identifier of the project that could not be built. The general format of the identifier is {@code @@ -70,5 +67,4 @@ public interface ProjectBuildingResult * not requested. */ DependencyResolutionResult getDependencyResolutionResult(); - } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/project/ProjectDependenciesResolver.java index 539055ca5f..5269fd0d72 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectDependenciesResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,14 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; /** * Resolves the transitive dependencies of a project. * * @author Benjamin Bentmann */ -public interface ProjectDependenciesResolver -{ +public interface ProjectDependenciesResolver { /** * Resolves the transitive dependencies of a project. @@ -34,7 +32,5 @@ public interface ProjectDependenciesResolver * @return The resolution result, never {@code null}. * @throws DependencyResolutionException If any project dependency could not be resolved. */ - DependencyResolutionResult resolve( DependencyResolutionRequest request ) - throws DependencyResolutionException; - + DependencyResolutionResult resolve(DependencyResolutionRequest request) throws DependencyResolutionException; } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectModelResolver.java b/maven-core/src/main/java/org/apache/maven/project/ProjectModelResolver.java index 5f9529383c..a9e6b25185 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectModelResolver.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectModelResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.Collections; @@ -26,7 +25,6 @@ import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; - import org.apache.maven.api.model.Dependency; import org.apache.maven.api.model.Parent; import org.apache.maven.api.model.Repository; @@ -51,16 +49,13 @@ import org.eclipse.aether.resolution.VersionRangeRequest; import org.eclipse.aether.resolution.VersionRangeResolutionException; import org.eclipse.aether.resolution.VersionRangeResult; - /** * A model resolver to assist building of projects. This resolver gives priority to those repositories that have been * declared in the POM. * * @author Benjamin Bentmann */ -public class ProjectModelResolver - implements ModelResolver -{ +public class ProjectModelResolver implements ModelResolver { private final RepositorySystemSession session; @@ -84,262 +79,227 @@ public class ProjectModelResolver private final ProjectBuildingRequest.RepositoryMerging repositoryMerging; - public ProjectModelResolver( RepositorySystemSession session, RequestTrace trace, RepositorySystem resolver, - RemoteRepositoryManager remoteRepositoryManager, List repositories, - ProjectBuildingRequest.RepositoryMerging repositoryMerging, - ReactorModelPool modelPool ) - { + public ProjectModelResolver( + RepositorySystemSession session, + RequestTrace trace, + RepositorySystem resolver, + RemoteRepositoryManager remoteRepositoryManager, + List repositories, + ProjectBuildingRequest.RepositoryMerging repositoryMerging, + ReactorModelPool modelPool) { this.session = session; this.trace = trace; this.resolver = resolver; this.remoteRepositoryManager = remoteRepositoryManager; this.pomRepositories = new ArrayList<>(); - this.externalRepositories = Collections.unmodifiableList( new ArrayList<>( repositories ) ); + this.externalRepositories = Collections.unmodifiableList(new ArrayList<>(repositories)); this.repositories = new ArrayList<>(); - this.repositories.addAll( externalRepositories ); + this.repositories.addAll(externalRepositories); this.repositoryMerging = repositoryMerging; this.repositoryIds = new HashSet<>(); this.modelPool = modelPool; } - private ProjectModelResolver( ProjectModelResolver original ) - { + private ProjectModelResolver(ProjectModelResolver original) { this.session = original.session; this.trace = original.trace; this.resolver = original.resolver; this.remoteRepositoryManager = original.remoteRepositoryManager; - this.pomRepositories = new ArrayList<>( original.pomRepositories ); + this.pomRepositories = new ArrayList<>(original.pomRepositories); this.externalRepositories = original.externalRepositories; - this.repositories = new ArrayList<>( original.repositories ); + this.repositories = new ArrayList<>(original.repositories); this.repositoryMerging = original.repositoryMerging; - this.repositoryIds = new HashSet<>( original.repositoryIds ); + this.repositoryIds = new HashSet<>(original.repositoryIds); this.modelPool = original.modelPool; } - public void addRepository( Repository repository ) - throws InvalidRepositoryException - { - addRepository( repository, false ); + public void addRepository(Repository repository) throws InvalidRepositoryException { + addRepository(repository, false); } @Override - public void addRepository( final Repository repository, boolean replace ) - throws InvalidRepositoryException - { - if ( !repositoryIds.add( repository.getId() ) ) - { - if ( !replace ) - { + public void addRepository(final Repository repository, boolean replace) throws InvalidRepositoryException { + if (!repositoryIds.add(repository.getId())) { + if (!replace) { return; } // Remove any previous repository with this Id - removeMatchingRepository( repositories, repository.getId() ); - removeMatchingRepository( pomRepositories, repository.getId() ); + removeMatchingRepository(repositories, repository.getId()); + removeMatchingRepository(pomRepositories, repository.getId()); } - List newRepositories = - Collections.singletonList( ArtifactDescriptorUtils.toRemoteRepository( - new org.apache.maven.model.Repository( repository ) ) ); + List newRepositories = Collections.singletonList( + ArtifactDescriptorUtils.toRemoteRepository(new org.apache.maven.model.Repository(repository))); - if ( ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT.equals( repositoryMerging ) ) - { - repositories = remoteRepositoryManager.aggregateRepositories( session, repositories, newRepositories, - true ); - } - else - { + if (ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT.equals(repositoryMerging)) { + repositories = remoteRepositoryManager.aggregateRepositories(session, repositories, newRepositories, true); + } else { pomRepositories = - remoteRepositoryManager.aggregateRepositories( session, pomRepositories, newRepositories, true ); - repositories = - remoteRepositoryManager.aggregateRepositories( session, pomRepositories, externalRepositories, false ); + remoteRepositoryManager.aggregateRepositories(session, pomRepositories, newRepositories, true); + repositories = remoteRepositoryManager.aggregateRepositories( + session, pomRepositories, externalRepositories, false); } } - private static void removeMatchingRepository( Iterable repositories, final String id ) - { - Iterator iterator = repositories.iterator( ); - while ( iterator.hasNext() ) - { + private static void removeMatchingRepository(Iterable repositories, final String id) { + Iterator iterator = repositories.iterator(); + while (iterator.hasNext()) { RemoteRepository next = iterator.next(); - if ( next.getId().equals( id ) ) - { + if (next.getId().equals(id)) { iterator.remove(); } } } - public ModelResolver newCopy() - { - return new ProjectModelResolver( this ); + public ModelResolver newCopy() { + return new ProjectModelResolver(this); } - public ModelSource resolveModel( String groupId, String artifactId, String version ) - throws UnresolvableModelException - { - Artifact pomArtifact = new DefaultArtifact( groupId, artifactId, "", "pom", version ); + public ModelSource resolveModel(String groupId, String artifactId, String version) + throws UnresolvableModelException { + Artifact pomArtifact = new DefaultArtifact(groupId, artifactId, "", "pom", version); - try - { - ArtifactRequest request = new ArtifactRequest( pomArtifact, repositories, context ); - request.setTrace( trace ); - pomArtifact = resolver.resolveArtifact( session, request ).getArtifact(); - } - catch ( ArtifactResolutionException e ) - { - throw new UnresolvableModelException( e.getMessage(), groupId, artifactId, version, e ); + try { + ArtifactRequest request = new ArtifactRequest(pomArtifact, repositories, context); + request.setTrace(trace); + pomArtifact = resolver.resolveArtifact(session, request).getArtifact(); + } catch (ArtifactResolutionException e) { + throw new UnresolvableModelException(e.getMessage(), groupId, artifactId, version, e); } - return new ArtifactModelSource( pomArtifact.getFile(), groupId, artifactId, version ); + return new ArtifactModelSource(pomArtifact.getFile(), groupId, artifactId, version); } @Override - public ModelSource resolveModel( final Parent parent, AtomicReference modified ) - throws UnresolvableModelException - { - try - { - final Artifact artifact = new DefaultArtifact( parent.getGroupId(), parent.getArtifactId(), "", "pom", - parent.getVersion() ); + public ModelSource resolveModel(final Parent parent, AtomicReference modified) + throws UnresolvableModelException { + try { + final Artifact artifact = + new DefaultArtifact(parent.getGroupId(), parent.getArtifactId(), "", "pom", parent.getVersion()); - final VersionRangeRequest versionRangeRequest = new VersionRangeRequest( artifact, repositories, context ); - versionRangeRequest.setTrace( trace ); + final VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact, repositories, context); + versionRangeRequest.setTrace(trace); - final VersionRangeResult versionRangeResult = resolver.resolveVersionRange( session, versionRangeRequest ); + final VersionRangeResult versionRangeResult = resolver.resolveVersionRange(session, versionRangeRequest); - if ( versionRangeResult.getHighestVersion() == null ) - { + if (versionRangeResult.getHighestVersion() == null) { throw new UnresolvableModelException( - String.format( "No versions matched the requested parent version range '%s'", - parent.getVersion() ), - parent.getGroupId(), parent.getArtifactId(), parent.getVersion() ); - + String.format( + "No versions matched the requested parent version range '%s'", parent.getVersion()), + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersion()); } - if ( versionRangeResult.getVersionConstraint() != null - && versionRangeResult.getVersionConstraint().getRange() != null - && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null ) - { + if (versionRangeResult.getVersionConstraint() != null + && versionRangeResult.getVersionConstraint().getRange() != null + && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null) { // Message below is checked for in the MNG-2199 core IT. throw new UnresolvableModelException( - String.format( "The requested parent version range '%s' does not specify an upper bound", - parent.getVersion() ), - parent.getGroupId(), parent.getArtifactId(), parent.getVersion() ); - + String.format( + "The requested parent version range '%s' does not specify an upper bound", + parent.getVersion()), + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersion()); } String newVersion = versionRangeResult.getHighestVersion().toString(); - if ( !parent.getVersion().equals( newVersion ) ) - { - modified.set( parent.withVersion( newVersion ) ); + if (!parent.getVersion().equals(newVersion)) { + modified.set(parent.withVersion(newVersion)); } - return resolveModel( parent.getGroupId(), parent.getArtifactId(), newVersion ); - } - catch ( final VersionRangeResolutionException e ) - { - throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(), - parent.getVersion(), e ); - + return resolveModel(parent.getGroupId(), parent.getArtifactId(), newVersion); + } catch (final VersionRangeResolutionException e) { + throw new UnresolvableModelException( + e.getMessage(), parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), e); } } @Override - public ModelSource resolveModel( final Dependency dependency, AtomicReference modified ) - throws UnresolvableModelException - { - try - { - final Artifact artifact = new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), "", - "pom", dependency.getVersion() ); + public ModelSource resolveModel(final Dependency dependency, AtomicReference modified) + throws UnresolvableModelException { + try { + final Artifact artifact = new DefaultArtifact( + dependency.getGroupId(), dependency.getArtifactId(), "", "pom", dependency.getVersion()); - final VersionRangeRequest versionRangeRequest = new VersionRangeRequest( artifact, repositories, context ); - versionRangeRequest.setTrace( trace ); + final VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact, repositories, context); + versionRangeRequest.setTrace(trace); - final VersionRangeResult versionRangeResult = resolver.resolveVersionRange( session, versionRangeRequest ); + final VersionRangeResult versionRangeResult = resolver.resolveVersionRange(session, versionRangeRequest); - if ( versionRangeResult.getHighestVersion() == null ) - { + if (versionRangeResult.getHighestVersion() == null) { throw new UnresolvableModelException( - String.format( "No versions matched the requested dependency version range '%s'", - dependency.getVersion() ), - dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion() ); - + String.format( + "No versions matched the requested dependency version range '%s'", + dependency.getVersion()), + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion()); } - if ( versionRangeResult.getVersionConstraint() != null - && versionRangeResult.getVersionConstraint().getRange() != null - && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null ) - { + if (versionRangeResult.getVersionConstraint() != null + && versionRangeResult.getVersionConstraint().getRange() != null + && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null) { // Message below is checked for in the MNG-4463 core IT. throw new UnresolvableModelException( - String.format( "The requested dependency version range '%s' does not specify an upper bound", - dependency.getVersion() ), - dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion() ); - + String.format( + "The requested dependency version range '%s' does not specify an upper bound", + dependency.getVersion()), + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion()); } String newVersion = versionRangeResult.getHighestVersion().toString(); - if ( !dependency.getVersion().equals( newVersion ) ) - { - modified.set( dependency.withVersion( newVersion ) ); + if (!dependency.getVersion().equals(newVersion)) { + modified.set(dependency.withVersion(newVersion)); } - if ( modelPool != null ) - { - Model model = - modelPool.get( dependency.getGroupId(), dependency.getArtifactId(), newVersion ); + if (modelPool != null) { + Model model = modelPool.get(dependency.getGroupId(), dependency.getArtifactId(), newVersion); - if ( model != null ) - { - return new FileModelSource( model.getPomFile() ); + if (model != null) { + return new FileModelSource(model.getPomFile()); } } - return resolveModel( dependency.getGroupId(), dependency.getArtifactId(), newVersion ); - } - catch ( VersionRangeResolutionException e ) - { - throw new UnresolvableModelException( e.getMessage(), dependency.getGroupId(), dependency.getArtifactId(), - dependency.getVersion(), e ); - + return resolveModel(dependency.getGroupId(), dependency.getArtifactId(), newVersion); + } catch (VersionRangeResolutionException e) { + throw new UnresolvableModelException( + e.getMessage(), dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), e); } } @Override - public ModelSource resolveModel( org.apache.maven.model.Parent parent ) throws UnresolvableModelException - { + public ModelSource resolveModel(org.apache.maven.model.Parent parent) throws UnresolvableModelException { AtomicReference resolvedParent = new AtomicReference<>(); - ModelSource result = resolveModel( parent.getDelegate(), resolvedParent ); - if ( resolvedParent.get() != null ) - { - parent.setVersion( resolvedParent.get().getVersion() ); + ModelSource result = resolveModel(parent.getDelegate(), resolvedParent); + if (resolvedParent.get() != null) { + parent.setVersion(resolvedParent.get().getVersion()); } return result; } @Override - public ModelSource resolveModel( org.apache.maven.model.Dependency dependency ) throws UnresolvableModelException - { + public ModelSource resolveModel(org.apache.maven.model.Dependency dependency) throws UnresolvableModelException { AtomicReference resolvedDependency = new AtomicReference<>(); - ModelSource result = resolveModel( dependency.getDelegate(), resolvedDependency ); - if ( resolvedDependency.get() != null ) - { - dependency.setVersion( resolvedDependency.get().getVersion() ); + ModelSource result = resolveModel(dependency.getDelegate(), resolvedDependency); + if (resolvedDependency.get() != null) { + dependency.setVersion(resolvedDependency.get().getVersion()); } return result; } @Override - public void addRepository( org.apache.maven.model.Repository repository ) throws InvalidRepositoryException - { - addRepository( repository.getDelegate() ); + public void addRepository(org.apache.maven.model.Repository repository) throws InvalidRepositoryException { + addRepository(repository.getDelegate()); } @Override - public void addRepository( org.apache.maven.model.Repository repository, boolean replace ) - throws InvalidRepositoryException - { - addRepository( repository.getDelegate(), replace ); + public void addRepository(org.apache.maven.model.Repository repository, boolean replace) + throws InvalidRepositoryException { + addRepository(repository.getDelegate(), replace); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectRealmCache.java b/maven-core/src/main/java/org/apache/maven/project/ProjectRealmCache.java index 28ac0d6200..99a10aa034 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectRealmCache.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectRealmCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.List; - import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.eclipse.aether.graph.DependencyFilter; @@ -32,30 +30,25 @@ import org.eclipse.aether.graph.DependencyFilter; * @author Igor Fedorenko * @author Benjamin Bentmann */ -public interface ProjectRealmCache -{ +public interface ProjectRealmCache { /** * A cache key. */ - interface Key - { + interface Key { // marker interface for cache keys } /** * CacheRecord */ - class CacheRecord - { + class CacheRecord { - public ClassRealm getRealm() - { + public ClassRealm getRealm() { return realm; } - public DependencyFilter getExtensionArtifactFilter() - { + public DependencyFilter getExtensionArtifactFilter() { return extensionArtifactFilter; } @@ -63,19 +56,17 @@ public interface ProjectRealmCache private final DependencyFilter extensionArtifactFilter; - CacheRecord( ClassRealm realm, DependencyFilter extensionArtifactFilter ) - { + CacheRecord(ClassRealm realm, DependencyFilter extensionArtifactFilter) { this.realm = realm; this.extensionArtifactFilter = extensionArtifactFilter; } - } - Key createKey( List extensionRealms ); + Key createKey(List extensionRealms); - CacheRecord get( Key key ); + CacheRecord get(Key key); - CacheRecord put( Key key, ClassRealm projectRealm, DependencyFilter extensionArtifactFilter ); + CacheRecord put(Key key, ClassRealm projectRealm, DependencyFilter extensionArtifactFilter); void flush(); @@ -87,6 +78,5 @@ public interface ProjectRealmCache * @param project The project that employs the plugin realm, must not be {@code null}. * @param record The cache record being used for the project, must not be {@code null}. */ - void register( MavenProject project, Key key, CacheRecord record ); - + void register(MavenProject project, Key key, CacheRecord record); } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectSorter.java b/maven-core/src/main/java/org/apache/maven/project/ProjectSorter.java index eaa4ce7629..9b69339586 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectSorter.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectSorter.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Collection; import java.util.Collections; @@ -25,13 +24,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import org.apache.maven.api.model.Build; -import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.api.model.Dependency; import org.apache.maven.api.model.Extension; import org.apache.maven.api.model.Parent; import org.apache.maven.api.model.Plugin; +import org.apache.maven.artifact.ArtifactUtils; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.dag.CycleDetectedException; import org.codehaus.plexus.util.dag.DAG; @@ -41,8 +39,7 @@ import org.codehaus.plexus.util.dag.Vertex; /** * ProjectSorter */ -public class ProjectSorter -{ +public class ProjectSorter { private DAG dag; private List sortedProjects; @@ -72,194 +69,218 @@ public class ProjectSorter // In this case, both the verify and the report goals are called // in a different lifecycle. Though the compiler-plugin has a valid use case, although // that seems to work fine. We need to take versions and lifecycle into account. - public ProjectSorter( Collection projects ) - throws CycleDetectedException, DuplicateProjectException - { + public ProjectSorter(Collection projects) throws CycleDetectedException, DuplicateProjectException { dag = new DAG(); // groupId:artifactId:version -> project - projectMap = new HashMap<>( projects.size() * 2 ); + projectMap = new HashMap<>(projects.size() * 2); // groupId:artifactId -> (version -> vertex) - Map> vertexMap = new HashMap<>( projects.size() * 2 ); + Map> vertexMap = new HashMap<>(projects.size() * 2); - for ( MavenProject project : projects ) - { - String projectId = getId( project ); + for (MavenProject project : projects) { + String projectId = getId(project); - MavenProject conflictingProject = projectMap.put( projectId, project ); + MavenProject conflictingProject = projectMap.put(projectId, project); - if ( conflictingProject != null ) - { - throw new DuplicateProjectException( projectId, conflictingProject.getFile(), project.getFile(), - "Project '" + projectId + "' is duplicated in the reactor" ); + if (conflictingProject != null) { + throw new DuplicateProjectException( + projectId, + conflictingProject.getFile(), + project.getFile(), + "Project '" + projectId + "' is duplicated in the reactor"); } - String projectKey = ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() ); + String projectKey = ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()); - Map vertices = vertexMap.computeIfAbsent( projectKey, k -> new HashMap<>( 2, 1 ) ); + Map vertices = vertexMap.computeIfAbsent(projectKey, k -> new HashMap<>(2, 1)); - vertices.put( project.getVersion(), dag.addVertex( projectId ) ); + vertices.put(project.getVersion(), dag.addVertex(projectId)); } - for ( Vertex projectVertex : dag.getVertices() ) - { + for (Vertex projectVertex : dag.getVertices()) { String projectId = projectVertex.getLabel(); - MavenProject project = projectMap.get( projectId ); + MavenProject project = projectMap.get(projectId); - for ( Dependency dependency : project.getModel().getDelegate().getDependencies() ) - { - addEdge( projectMap, vertexMap, project, projectVertex, dependency.getGroupId(), - dependency.getArtifactId(), dependency.getVersion(), false, false ); + for (Dependency dependency : project.getModel().getDelegate().getDependencies()) { + addEdge( + projectMap, + vertexMap, + project, + projectVertex, + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + false, + false); } Parent parent = project.getModel().getDelegate().getParent(); - if ( parent != null ) - { + if (parent != null) { // Parent is added as an edge, but must not cause a cycle - so we remove any other edges it has // in conflict - addEdge( projectMap, vertexMap, null, projectVertex, parent.getGroupId(), parent.getArtifactId(), - parent.getVersion(), true, false ); + addEdge( + projectMap, + vertexMap, + null, + projectVertex, + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersion(), + true, + false); } Build build = project.getModel().getDelegate().getBuild(); - if ( build != null ) - { - for ( Plugin plugin : build.getPlugins() ) - { - addEdge( projectMap, vertexMap, project, projectVertex, plugin.getGroupId(), - plugin.getArtifactId(), plugin.getVersion(), false, true ); + if (build != null) { + for (Plugin plugin : build.getPlugins()) { + addEdge( + projectMap, + vertexMap, + project, + projectVertex, + plugin.getGroupId(), + plugin.getArtifactId(), + plugin.getVersion(), + false, + true); - for ( Dependency dependency : plugin.getDependencies() ) - { - addEdge( projectMap, vertexMap, project, projectVertex, dependency.getGroupId(), - dependency.getArtifactId(), dependency.getVersion(), false, true ); + for (Dependency dependency : plugin.getDependencies()) { + addEdge( + projectMap, + vertexMap, + project, + projectVertex, + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + false, + true); } } - for ( Extension extension : build.getExtensions() ) - { - addEdge( projectMap, vertexMap, project, projectVertex, extension.getGroupId(), - extension.getArtifactId(), extension.getVersion(), false, true ); + for (Extension extension : build.getExtensions()) { + addEdge( + projectMap, + vertexMap, + project, + projectVertex, + extension.getGroupId(), + extension.getArtifactId(), + extension.getVersion(), + false, + true); } } } - List sortedProjectLabels = TopologicalSorter.sort( dag ); + List sortedProjectLabels = TopologicalSorter.sort(dag); - this.sortedProjects = sortedProjectLabels.stream().map( id -> projectMap.get( id ) ) - .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); + this.sortedProjects = sortedProjectLabels.stream() + .map(id -> projectMap.get(id)) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void addEdge( Map projectMap, Map> vertexMap, - MavenProject project, Vertex projectVertex, String groupId, String artifactId, - String version, boolean force, boolean safe ) - throws CycleDetectedException - { - String projectKey = ArtifactUtils.versionlessKey( groupId, artifactId ); - Map vertices = vertexMap.get( projectKey ); + @SuppressWarnings("checkstyle:parameternumber") + private void addEdge( + Map projectMap, + Map> vertexMap, + MavenProject project, + Vertex projectVertex, + String groupId, + String artifactId, + String version, + boolean force, + boolean safe) + throws CycleDetectedException { + String projectKey = ArtifactUtils.versionlessKey(groupId, artifactId); - if ( vertices != null ) - { - if ( isSpecificVersion( version ) ) - { - Vertex vertex = vertices.get( version ); - if ( vertex != null ) - { - addEdge( projectVertex, vertex, project, projectMap, force, safe ); + Map vertices = vertexMap.get(projectKey); + + if (vertices != null) { + if (isSpecificVersion(version)) { + Vertex vertex = vertices.get(version); + if (vertex != null) { + addEdge(projectVertex, vertex, project, projectMap, force, safe); } - } - else - { - for ( Vertex vertex : vertices.values() ) - { - addEdge( projectVertex, vertex, project, projectMap, force, safe ); + } else { + for (Vertex vertex : vertices.values()) { + addEdge(projectVertex, vertex, project, projectMap, force, safe); } } } } - private void addEdge( Vertex fromVertex, Vertex toVertex, MavenProject fromProject, - Map projectMap, boolean force, boolean safe ) - throws CycleDetectedException - { - if ( fromVertex.equals( toVertex ) ) - { + private void addEdge( + Vertex fromVertex, + Vertex toVertex, + MavenProject fromProject, + Map projectMap, + boolean force, + boolean safe) + throws CycleDetectedException { + if (fromVertex.equals(toVertex)) { return; } - if ( fromProject != null ) - { - MavenProject toProject = projectMap.get( toVertex.getLabel() ); - fromProject.addProjectReference( toProject ); + if (fromProject != null) { + MavenProject toProject = projectMap.get(toVertex.getLabel()); + fromProject.addProjectReference(toProject); } - if ( force && toVertex.getChildren().contains( fromVertex ) ) - { - dag.removeEdge( toVertex, fromVertex ); + if (force && toVertex.getChildren().contains(fromVertex)) { + dag.removeEdge(toVertex, fromVertex); } - try - { - dag.addEdge( fromVertex, toVertex ); - } - catch ( CycleDetectedException e ) - { - if ( !safe ) - { + try { + dag.addEdge(fromVertex, toVertex); + } catch (CycleDetectedException e) { + if (!safe) { throw e; } } } - private boolean isSpecificVersion( String version ) - { - return !( StringUtils.isEmpty( version ) || version.startsWith( "[" ) || version.startsWith( "(" ) ); + private boolean isSpecificVersion(String version) { + return !(StringUtils.isEmpty(version) || version.startsWith("[") || version.startsWith("(")); } - // TODO !![jc; 28-jul-2005] check this; if we're using '-r' and there are aggregator tasks, this will result in weirdness. - public MavenProject getTopLevelProject() - { - return sortedProjects.stream().filter( MavenProject::isExecutionRoot ).findFirst() - .orElse( null ); + // TODO !![jc; 28-jul-2005] check this; if we're using '-r' and there are aggregator tasks, this will result in + // weirdness. + public MavenProject getTopLevelProject() { + return sortedProjects.stream() + .filter(MavenProject::isExecutionRoot) + .findFirst() + .orElse(null); } - public List getSortedProjects() - { + public List getSortedProjects() { return sortedProjects; } - public boolean hasMultipleProjects() - { + public boolean hasMultipleProjects() { return sortedProjects.size() > 1; } - public List getDependents( String id ) - { - return dag.getParentLabels( id ); + public List getDependents(String id) { + return dag.getParentLabels(id); } - public List getDependencies( String id ) - { - return dag.getChildLabels( id ); + public List getDependencies(String id) { + return dag.getChildLabels(id); } - public static String getId( MavenProject project ) - { - return ArtifactUtils.key( project.getGroupId(), project.getArtifactId(), project.getVersion() ); + public static String getId(MavenProject project) { + return ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion()); } - public DAG getDAG() - { + public DAG getDAG() { return dag; } - public Map getProjectMap() - { + public Map getProjectMap() { return projectMap; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/ReactorModelPool.java b/maven-core/src/main/java/org/apache/maven/project/ReactorModelPool.java index de8af7e5e6..476132df44 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ReactorModelPool.java +++ b/maven-core/src/main/java/org/apache/maven/project/ReactorModelPool.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.nio.file.Files; import java.nio.file.Path; @@ -27,7 +26,6 @@ import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; - import org.apache.maven.model.Model; /** @@ -37,8 +35,7 @@ import org.apache.maven.model.Model; * @author Benjamin Bentmann * @author Robert Scholte */ -class ReactorModelPool -{ +class ReactorModelPool { private final Map> modelsByGa = new HashMap<>(); private final Map modelsByPath = new HashMap<>(); @@ -52,15 +49,14 @@ class ReactorModelPool * @return the matching model or {@code null} * @throws IllegalStateException if version was null and multiple modules share the same groupId + artifactId */ - public Model get( String groupId, String artifactId, String version ) - { - return modelsByGa.getOrDefault( new GAKey( groupId, artifactId ), Collections.emptySet() ).stream() - .filter( m -> version == null || version.equals( getVersion( m ) ) ) - .reduce( ( a, b ) -> - { - throw new IllegalStateException( "Multiple modules with key " - + a.getGroupId() + ':' + a.getArtifactId() ); - } ).orElse( null ); + public Model get(String groupId, String artifactId, String version) { + return modelsByGa.getOrDefault(new GAKey(groupId, artifactId), Collections.emptySet()).stream() + .filter(m -> version == null || version.equals(getVersion(m))) + .reduce((a, b) -> { + throw new IllegalStateException( + "Multiple modules with key " + a.getGroupId() + ':' + a.getArtifactId()); + }) + .orElse(null); } /** @@ -70,60 +66,49 @@ class ReactorModelPool * @return the matching model or {@code null} * @since 4.0.0 */ - public Model get( Path path ) - { + public Model get(Path path) { final Path pomFile; - if ( Files.isDirectory( path ) ) - { - pomFile = path.resolve( "pom.xml" ); - } - else - { + if (Files.isDirectory(path)) { + pomFile = path.resolve("pom.xml"); + } else { pomFile = path; } - return modelsByPath.get( pomFile ); + return modelsByPath.get(pomFile); } - private String getVersion( Model model ) - { + private String getVersion(Model model) { String version = model.getVersion(); - if ( version == null && model.getParent() != null ) - { + if (version == null && model.getParent() != null) { version = model.getParent().getVersion(); } return version; } - static class Builder - { + static class Builder { private ReactorModelPool pool = new ReactorModelPool(); - Builder put( Path pomFile, Model model ) - { - pool.modelsByPath.put( pomFile, model ); - pool.modelsByGa.computeIfAbsent( new GAKey( getGroupId( model ), model.getArtifactId() ), - k -> new HashSet() ).add( model ); + Builder put(Path pomFile, Model model) { + pool.modelsByPath.put(pomFile, model); + pool.modelsByGa + .computeIfAbsent(new GAKey(getGroupId(model), model.getArtifactId()), k -> new HashSet()) + .add(model); return this; } - ReactorModelPool build() - { + ReactorModelPool build() { return pool; } - private static String getGroupId( Model model ) - { + private static String getGroupId(Model model) { String groupId = model.getGroupId(); - if ( groupId == null && model.getParent() != null ) - { + if (groupId == null && model.getParent() != null) { groupId = model.getParent().getGroupId(); } return groupId; } } - private static final class GAKey - { + private static final class GAKey { private final String groupId; @@ -131,40 +116,34 @@ class ReactorModelPool private final int hashCode; - GAKey( String groupId, String artifactId ) - { - this.groupId = ( groupId != null ) ? groupId : ""; - this.artifactId = ( artifactId != null ) ? artifactId : ""; + GAKey(String groupId, String artifactId) { + this.groupId = (groupId != null) ? groupId : ""; + this.artifactId = (artifactId != null) ? artifactId : ""; - hashCode = Objects.hash( this.groupId, this.artifactId ); + hashCode = Objects.hash(this.groupId, this.artifactId); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } GAKey that = (GAKey) obj; - return artifactId.equals( that.artifactId ) && groupId.equals( that.groupId ); + return artifactId.equals(that.artifactId) && groupId.equals(that.groupId); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 128 ); - buffer.append( groupId ).append( ':' ).append( artifactId ); + public String toString() { + StringBuilder buffer = new StringBuilder(128); + buffer.append(groupId).append(':').append(artifactId); return buffer.toString(); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/RepositorySessionDecorator.java b/maven-core/src/main/java/org/apache/maven/project/RepositorySessionDecorator.java index d739c75be2..e8c1daf4d8 100644 --- a/maven-core/src/main/java/org/apache/maven/project/RepositorySessionDecorator.java +++ b/maven-core/src/main/java/org/apache/maven/project/RepositorySessionDecorator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import org.eclipse.aether.RepositorySystemSession; @@ -27,10 +26,9 @@ import org.eclipse.aether.RepositorySystemSession; * Note: This interface is part of work in progress and can be changed or removed without notice. * @since 3.2.4 */ -public interface RepositorySessionDecorator -{ +public interface RepositorySessionDecorator { /** * Returns possibly {@code null} Aether repository system session to be used to resolve project dependencies. */ - RepositorySystemSession decorate( MavenProject project, RepositorySystemSession session ); + RepositorySystemSession decorate(MavenProject project, RepositorySystemSession session); } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/ActiveProjectArtifact.java b/maven-core/src/main/java/org/apache/maven/project/artifact/ActiveProjectArtifact.java index 5a96efd62b..be93dee2f7 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/ActiveProjectArtifact.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/ActiveProjectArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,7 +16,11 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; +import java.io.File; +import java.util.Collection; +import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -29,10 +31,6 @@ import org.apache.maven.artifact.versioning.OverConstrainedVersionException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.project.MavenProject; -import java.io.File; -import java.util.Collection; -import java.util.List; - /** * Wraps an active project instance to be able to receive updates from its artifact without affecting the original * attributes of this artifact. @@ -42,360 +40,295 @@ import java.util.List; * should be split. ie scope, file, etc depend on the context of use, whereas everything else is immutable. */ @Deprecated -public class ActiveProjectArtifact - implements Artifact -{ +public class ActiveProjectArtifact implements Artifact { private final Artifact artifact; private final MavenProject project; - public ActiveProjectArtifact( MavenProject project, Artifact artifact ) - { + public ActiveProjectArtifact(MavenProject project, Artifact artifact) { this.artifact = artifact; this.project = project; - artifact.setFile( project.getArtifact().getFile() ); - artifact.setResolved( true ); + artifact.setFile(project.getArtifact().getFile()); + artifact.setResolved(true); } /** {@inheritDoc} */ - public File getFile() - { + public File getFile() { // we need to get the latest file for the project, not the artifact that was created at one point in time return project.getArtifact().getFile(); } /** {@inheritDoc} */ - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } /** {@inheritDoc} */ - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } /** {@inheritDoc} */ - public String getVersion() - { + public String getVersion() { return artifact.getVersion(); } /** {@inheritDoc} */ - public void setVersion( String version ) - { - artifact.setVersion( version ); + public void setVersion(String version) { + artifact.setVersion(version); } /** {@inheritDoc} */ - public String getScope() - { + public String getScope() { return artifact.getScope(); } /** {@inheritDoc} */ - public String getType() - { + public String getType() { return artifact.getType(); } /** {@inheritDoc} */ - public String getClassifier() - { + public String getClassifier() { return artifact.getClassifier(); } /** {@inheritDoc} */ - public boolean hasClassifier() - { + public boolean hasClassifier() { return artifact.hasClassifier(); } /** {@inheritDoc} */ - public void setFile( File destination ) - { - artifact.setFile( destination ); - project.getArtifact().setFile( destination ); + public void setFile(File destination) { + artifact.setFile(destination); + project.getArtifact().setFile(destination); } /** {@inheritDoc} */ - public String getBaseVersion() - { + public String getBaseVersion() { return artifact.getBaseVersion(); } /** {@inheritDoc} */ - public void setBaseVersion( String baseVersion ) - { - artifact.setBaseVersion( baseVersion ); + public void setBaseVersion(String baseVersion) { + artifact.setBaseVersion(baseVersion); } /** {@inheritDoc} */ - public String getId() - { + public String getId() { return artifact.getId(); } /** {@inheritDoc} */ - public String getDependencyConflictId() - { + public String getDependencyConflictId() { return artifact.getDependencyConflictId(); } /** {@inheritDoc} */ - public void addMetadata( ArtifactMetadata metadata ) - { - artifact.addMetadata( metadata ); + public void addMetadata(ArtifactMetadata metadata) { + artifact.addMetadata(metadata); } /** {@inheritDoc} */ - public Collection getMetadataList() - { + public Collection getMetadataList() { return artifact.getMetadataList(); } /** {@inheritDoc} */ - public void setRepository( ArtifactRepository remoteRepository ) - { - artifact.setRepository( remoteRepository ); + public void setRepository(ArtifactRepository remoteRepository) { + artifact.setRepository(remoteRepository); } /** {@inheritDoc} */ - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return artifact.getRepository(); } /** {@inheritDoc} */ - public void updateVersion( String version, ArtifactRepository localRepository ) - { - artifact.updateVersion( version, localRepository ); + public void updateVersion(String version, ArtifactRepository localRepository) { + artifact.updateVersion(version, localRepository); } /** {@inheritDoc} */ - public String getDownloadUrl() - { + public String getDownloadUrl() { return artifact.getDownloadUrl(); } /** {@inheritDoc} */ - public void setDownloadUrl( String downloadUrl ) - { - artifact.setDownloadUrl( downloadUrl ); + public void setDownloadUrl(String downloadUrl) { + artifact.setDownloadUrl(downloadUrl); } /** {@inheritDoc} */ - public ArtifactFilter getDependencyFilter() - { + public ArtifactFilter getDependencyFilter() { return artifact.getDependencyFilter(); } /** {@inheritDoc} */ - public void setDependencyFilter( ArtifactFilter artifactFilter ) - { - artifact.setDependencyFilter( artifactFilter ); + public void setDependencyFilter(ArtifactFilter artifactFilter) { + artifact.setDependencyFilter(artifactFilter); } /** {@inheritDoc} */ - public ArtifactHandler getArtifactHandler() - { + public ArtifactHandler getArtifactHandler() { return artifact.getArtifactHandler(); } /** {@inheritDoc} */ - public List getDependencyTrail() - { + public List getDependencyTrail() { return artifact.getDependencyTrail(); } /** {@inheritDoc} */ - public void setDependencyTrail( List dependencyTrail ) - { - artifact.setDependencyTrail( dependencyTrail ); + public void setDependencyTrail(List dependencyTrail) { + artifact.setDependencyTrail(dependencyTrail); } /** {@inheritDoc} */ - public void setScope( String scope ) - { - artifact.setScope( scope ); + public void setScope(String scope) { + artifact.setScope(scope); } /** {@inheritDoc} */ - public VersionRange getVersionRange() - { + public VersionRange getVersionRange() { return artifact.getVersionRange(); } /** {@inheritDoc} */ - public void setVersionRange( VersionRange newRange ) - { - artifact.setVersionRange( newRange ); + public void setVersionRange(VersionRange newRange) { + artifact.setVersionRange(newRange); } /** {@inheritDoc} */ - public void selectVersion( String version ) - { - artifact.selectVersion( version ); + public void selectVersion(String version) { + artifact.selectVersion(version); } /** {@inheritDoc} */ - public void setGroupId( String groupId ) - { - artifact.setGroupId( groupId ); + public void setGroupId(String groupId) { + artifact.setGroupId(groupId); } /** {@inheritDoc} */ - public void setArtifactId( String artifactId ) - { - artifact.setArtifactId( artifactId ); + public void setArtifactId(String artifactId) { + artifact.setArtifactId(artifactId); } /** {@inheritDoc} */ - public boolean isSnapshot() - { + public boolean isSnapshot() { return artifact.isSnapshot(); } /** {@inheritDoc} */ - public int compareTo( Artifact a ) - { - return artifact.compareTo( a ); + public int compareTo(Artifact a) { + return artifact.compareTo(a); } /** {@inheritDoc} */ - public void setResolved( boolean resolved ) - { - artifact.setResolved( resolved ); + public void setResolved(boolean resolved) { + artifact.setResolved(resolved); } /** {@inheritDoc} */ - public boolean isResolved() - { + public boolean isResolved() { return artifact.isResolved(); } /** {@inheritDoc} */ - public void setResolvedVersion( String version ) - { - artifact.setResolvedVersion( version ); + public void setResolvedVersion(String version) { + artifact.setResolvedVersion(version); } /** {@inheritDoc} */ - public void setArtifactHandler( ArtifactHandler handler ) - { - artifact.setArtifactHandler( handler ); + public void setArtifactHandler(ArtifactHandler handler) { + artifact.setArtifactHandler(handler); } /** {@inheritDoc} */ - public String toString() - { + public String toString() { return "active project artifact[artifact: " + artifact + ", project: " + project + "]"; } /** {@inheritDoc} */ - public boolean isRelease() - { + public boolean isRelease() { return artifact.isRelease(); } /** {@inheritDoc} */ - public void setRelease( boolean release ) - { - artifact.setRelease( release ); + public void setRelease(boolean release) { + artifact.setRelease(release); } /** {@inheritDoc} */ - public List getAvailableVersions() - { + public List getAvailableVersions() { return artifact.getAvailableVersions(); } /** {@inheritDoc} */ - public void setAvailableVersions( List versions ) - { - artifact.setAvailableVersions( versions ); + public void setAvailableVersions(List versions) { + artifact.setAvailableVersions(versions); } /** {@inheritDoc} */ - public boolean isOptional() - { + public boolean isOptional() { return artifact.isOptional(); } /** {@inheritDoc} */ - public ArtifactVersion getSelectedVersion() - throws OverConstrainedVersionException - { + public ArtifactVersion getSelectedVersion() throws OverConstrainedVersionException { return artifact.getSelectedVersion(); } /** {@inheritDoc} */ - public boolean isSelectedVersionKnown() - throws OverConstrainedVersionException - { + public boolean isSelectedVersionKnown() throws OverConstrainedVersionException { return artifact.isSelectedVersionKnown(); } /** {@inheritDoc} */ - public void setOptional( boolean optional ) - { - artifact.setOptional( optional ); + public void setOptional(boolean optional) { + artifact.setOptional(optional); } /** {@inheritDoc} */ - public int hashCode() - { + public int hashCode() { int result = 17; result = 37 * result + getGroupId().hashCode(); result = 37 * result + getArtifactId().hashCode(); result = 37 * result + getType().hashCode(); - if ( getVersion() != null ) - { + if (getVersion() != null) { result = 37 * result + getVersion().hashCode(); } - result = 37 * result + ( getClassifier() != null ? getClassifier().hashCode() : 0 ); + result = 37 * result + (getClassifier() != null ? getClassifier().hashCode() : 0); return result; } /** {@inheritDoc} */ - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof Artifact ) ) - { + if (!(o instanceof Artifact)) { return false; } Artifact a = (Artifact) o; - if ( !a.getGroupId().equals( getGroupId() ) ) - { + if (!a.getGroupId().equals(getGroupId())) { return false; - } - else if ( !a.getArtifactId().equals( getArtifactId() ) ) - { + } else if (!a.getArtifactId().equals(getArtifactId())) { return false; - } - else if ( !a.getVersion().equals( getVersion() ) ) - { + } else if (!a.getVersion().equals(getVersion())) { return false; - } - else if ( !a.getType().equals( getType() ) ) - { + } else if (!a.getType().equals(getType())) { return false; - } - else - { - return a.getClassifier() == null ? getClassifier() == null : a.getClassifier().equals( getClassifier() ); + } else { + return a.getClassifier() == null + ? getClassifier() == null + : a.getClassifier().equals(getClassifier()); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/ArtifactWithDependencies.java b/maven-core/src/main/java/org/apache/maven/project/artifact/ArtifactWithDependencies.java index a83cae6683..92543e42cc 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/ArtifactWithDependencies.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/ArtifactWithDependencies.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,19 +16,17 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.util.List; - import org.apache.maven.model.Dependency; /** * ArtifactWithDependencies */ -public interface ArtifactWithDependencies -{ +public interface ArtifactWithDependencies { List getDependencies(); List getManagedDependencies(); - } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/AttachedArtifact.java b/maven-core/src/main/java/org/apache/maven/project/artifact/AttachedArtifact.java index fd2b956c24..10a7d92920 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/AttachedArtifact.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/AttachedArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,7 +16,11 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.InvalidArtifactRTException; @@ -28,158 +30,137 @@ import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.VersionRange; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - /** *Warning: This is an internal utility class that is only public for technical reasons, it is not part * of the public API. In particular, this class can be changed or deleted without prior notice. Use * {@link org.apache.maven.project.MavenProjectHelper#attachArtifact} instead. */ @Deprecated -public class AttachedArtifact - extends DefaultArtifact -{ +public class AttachedArtifact extends DefaultArtifact { private final Artifact parent; - public AttachedArtifact( Artifact parent, String type, String classifier, ArtifactHandler artifactHandler ) - { - super( parent.getGroupId(), parent.getArtifactId(), parent.getVersionRange(), parent.getScope(), type, - classifier, artifactHandler, parent.isOptional() ); + public AttachedArtifact(Artifact parent, String type, String classifier, ArtifactHandler artifactHandler) { + super( + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersionRange(), + parent.getScope(), + type, + classifier, + artifactHandler, + parent.isOptional()); - setDependencyTrail( Collections.singletonList( parent.getId() ) ); + setDependencyTrail(Collections.singletonList(parent.getId())); this.parent = parent; - if ( getId().equals( parent.getId() ) ) - { - throw new InvalidArtifactRTException( parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), - parent.getType(), "An attached artifact must have a different ID" - + " than its corresponding main artifact." ); + if (getId().equals(parent.getId())) { + throw new InvalidArtifactRTException( + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersion(), + parent.getType(), + "An attached artifact must have a different ID" + " than its corresponding main artifact."); } } - public AttachedArtifact( Artifact parent, String type, ArtifactHandler artifactHandler ) - { - this( parent, type, null, artifactHandler ); + public AttachedArtifact(Artifact parent, String type, ArtifactHandler artifactHandler) { + this(parent, type, null, artifactHandler); } - public void setArtifactId( String artifactId ) - { - throw new UnsupportedOperationException( "Cannot change the artifactId for an attached artifact." - + " It is derived from the main artifact." ); + public void setArtifactId(String artifactId) { + throw new UnsupportedOperationException( + "Cannot change the artifactId for an attached artifact." + " It is derived from the main artifact."); } - public List getAvailableVersions() - { + public List getAvailableVersions() { return parent.getAvailableVersions(); } - public void setAvailableVersions( List availableVersions ) - { - throw new UnsupportedOperationException( "Cannot change the version information for an attached artifact." - + " It is derived from the main artifact." ); + public void setAvailableVersions(List availableVersions) { + throw new UnsupportedOperationException("Cannot change the version information for an attached artifact." + + " It is derived from the main artifact."); } - public String getBaseVersion() - { + public String getBaseVersion() { return parent.getBaseVersion(); } - public void setBaseVersion( String baseVersion ) - { - throw new UnsupportedOperationException( "Cannot change the version information for an attached artifact." - + " It is derived from the main artifact." ); + public void setBaseVersion(String baseVersion) { + throw new UnsupportedOperationException("Cannot change the version information for an attached artifact." + + " It is derived from the main artifact."); } - public String getDownloadUrl() - { + public String getDownloadUrl() { return parent.getDownloadUrl(); } - public void setDownloadUrl( String downloadUrl ) - { - throw new UnsupportedOperationException( "Cannot change the download information for an attached artifact." - + " It is derived from the main artifact." ); + public void setDownloadUrl(String downloadUrl) { + throw new UnsupportedOperationException("Cannot change the download information for an attached artifact." + + " It is derived from the main artifact."); } - public void setGroupId( String groupId ) - { - throw new UnsupportedOperationException( "Cannot change the groupId for an attached artifact." - + " It is derived from the main artifact." ); + public void setGroupId(String groupId) { + throw new UnsupportedOperationException( + "Cannot change the groupId for an attached artifact." + " It is derived from the main artifact."); } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return parent.getRepository(); } - public void setRepository( ArtifactRepository repository ) - { - throw new UnsupportedOperationException( "Cannot change the repository information for an attached artifact." - + " It is derived from the main artifact." ); + public void setRepository(ArtifactRepository repository) { + throw new UnsupportedOperationException("Cannot change the repository information for an attached artifact." + + " It is derived from the main artifact."); } - public String getScope() - { + public String getScope() { return parent.getScope(); } - public void setScope( String scope ) - { - throw new UnsupportedOperationException( "Cannot change the scoping information for an attached artifact." - + " It is derived from the main artifact." ); + public void setScope(String scope) { + throw new UnsupportedOperationException("Cannot change the scoping information for an attached artifact." + + " It is derived from the main artifact."); } - public String getVersion() - { + public String getVersion() { return parent.getVersion(); } - public void setVersion( String version ) - { - throw new UnsupportedOperationException( "Cannot change the version information for an attached artifact." - + " It is derived from the main artifact." ); + public void setVersion(String version) { + throw new UnsupportedOperationException("Cannot change the version information for an attached artifact." + + " It is derived from the main artifact."); } - public VersionRange getVersionRange() - { + public VersionRange getVersionRange() { return parent.getVersionRange(); } - public void setVersionRange( VersionRange range ) - { - throw new UnsupportedOperationException( "Cannot change the version information for an attached artifact." - + " It is derived from the main artifact." ); + public void setVersionRange(VersionRange range) { + throw new UnsupportedOperationException("Cannot change the version information for an attached artifact." + + " It is derived from the main artifact."); } - public boolean isRelease() - { + public boolean isRelease() { return parent.isRelease(); } - public void setRelease( boolean release ) - { - throw new UnsupportedOperationException( "Cannot change the version information for an attached artifact." - + " It is derived from the main artifact." ); + public void setRelease(boolean release) { + throw new UnsupportedOperationException("Cannot change the version information for an attached artifact." + + " It is derived from the main artifact."); } - public boolean isSnapshot() - { + public boolean isSnapshot() { return parent.isSnapshot(); } - public void addMetadata( ArtifactMetadata metadata ) - { + public void addMetadata(ArtifactMetadata metadata) { // ignore. The parent artifact will handle metadata. // we must fail silently here to avoid problems with the artifact transformers. } - public Collection getMetadataList() - { + public Collection getMetadataList() { return Collections.emptyList(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMavenMetadataCache.java b/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMavenMetadataCache.java index 576870972f..61913ac7f9 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMavenMetadataCache.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMavenMetadataCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.io.File; import java.util.ArrayList; @@ -26,13 +25,11 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.metadata.ResolutionGroup; @@ -44,159 +41,138 @@ import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; */ @Named @Singleton -public class DefaultMavenMetadataCache - implements MavenMetadataCache -{ +public class DefaultMavenMetadataCache implements MavenMetadataCache { protected final Map cache = new ConcurrentHashMap<>(); /** * CacheKey */ - public static class CacheKey - { + public static class CacheKey { private final Artifact artifact; private final long pomHash; private final boolean resolveManagedVersions; private final List repositories = new ArrayList<>(); private final int hashCode; - public CacheKey( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, - List remoteRepositories ) - { + public CacheKey( + Artifact artifact, + boolean resolveManagedVersions, + ArtifactRepository localRepository, + List remoteRepositories) { File file = artifact.getFile(); - this.artifact = ArtifactUtils.copyArtifact( artifact ); - if ( "pom".equals( artifact.getType() ) && file != null ) - { + this.artifact = ArtifactUtils.copyArtifact(artifact); + if ("pom".equals(artifact.getType()) && file != null) { pomHash = file.getPath().hashCode() + file.lastModified(); - } - else - { + } else { pomHash = 0; } this.resolveManagedVersions = resolveManagedVersions; - this.repositories.add( localRepository ); - this.repositories.addAll( remoteRepositories ); + this.repositories.add(localRepository); + this.repositories.addAll(remoteRepositories); int hash = 17; - hash = hash * 31 + artifactHashCode( artifact ); - hash = hash * 31 + ( resolveManagedVersions ? 1 : 2 ); - hash = hash * 31 + repositoriesHashCode( repositories ); + hash = hash * 31 + artifactHashCode(artifact); + hash = hash * 31 + (resolveManagedVersions ? 1 : 2); + hash = hash * 31 + repositoriesHashCode(repositories); this.hashCode = hash; } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof CacheKey ) ) - { + if (!(o instanceof CacheKey)) { return false; } CacheKey other = (CacheKey) o; - return pomHash == other.pomHash && artifactEquals( artifact, other.artifact ) - && resolveManagedVersions == other.resolveManagedVersions - && repositoriesEquals( repositories, other.repositories ); + return pomHash == other.pomHash + && artifactEquals(artifact, other.artifact) + && resolveManagedVersions == other.resolveManagedVersions + && repositoriesEquals(repositories, other.repositories); } } - private static int artifactHashCode( Artifact a ) - { + private static int artifactHashCode(Artifact a) { int result = 17; result = 31 * result + a.getGroupId().hashCode(); result = 31 * result + a.getArtifactId().hashCode(); result = 31 * result + a.getType().hashCode(); - if ( a.getVersion() != null ) - { + if (a.getVersion() != null) { result = 31 * result + a.getVersion().hashCode(); } - result = 31 * result + ( a.getClassifier() != null ? a.getClassifier().hashCode() : 0 ); - result = 31 * result + ( a.getScope() != null ? a.getScope().hashCode() : 0 ); - result = 31 * result + ( a.getDependencyFilter() != null ? a.getDependencyFilter().hashCode() : 0 ); - result = 31 * result + ( a.isOptional() ? 1 : 0 ); + result = 31 * result + (a.getClassifier() != null ? a.getClassifier().hashCode() : 0); + result = 31 * result + (a.getScope() != null ? a.getScope().hashCode() : 0); + result = 31 * result + + (a.getDependencyFilter() != null ? a.getDependencyFilter().hashCode() : 0); + result = 31 * result + (a.isOptional() ? 1 : 0); return result; } - private static boolean artifactEquals( Artifact a1, Artifact a2 ) - { - if ( a1 == a2 ) - { + private static boolean artifactEquals(Artifact a1, Artifact a2) { + if (a1 == a2) { return true; } - return Objects.equals( a1.getGroupId(), a2.getGroupId() ) - && Objects.equals( a1.getArtifactId(), a2.getArtifactId() ) - && Objects.equals( a1.getType(), a2.getType() ) - && Objects.equals( a1.getVersion(), a2.getVersion() ) - && Objects.equals( a1.getClassifier(), a2.getClassifier() ) - && Objects.equals( a1.getScope(), a2.getScope() ) - && Objects.equals( a1.getDependencyFilter(), a2.getDependencyFilter() ) - && a1.isOptional() == a2.isOptional(); + return Objects.equals(a1.getGroupId(), a2.getGroupId()) + && Objects.equals(a1.getArtifactId(), a2.getArtifactId()) + && Objects.equals(a1.getType(), a2.getType()) + && Objects.equals(a1.getVersion(), a2.getVersion()) + && Objects.equals(a1.getClassifier(), a2.getClassifier()) + && Objects.equals(a1.getScope(), a2.getScope()) + && Objects.equals(a1.getDependencyFilter(), a2.getDependencyFilter()) + && a1.isOptional() == a2.isOptional(); } - private static int repositoryHashCode( ArtifactRepository repository ) - { + private static int repositoryHashCode(ArtifactRepository repository) { int result = 17; - result = 31 * result + ( repository.getId() != null ? repository.getId().hashCode() : 0 ); + result = 31 * result + (repository.getId() != null ? repository.getId().hashCode() : 0); return result; } - private static int repositoriesHashCode( List repositories ) - { + private static int repositoriesHashCode(List repositories) { int result = 17; - for ( ArtifactRepository repository : repositories ) - { - result = 31 * result + repositoryHashCode( repository ); + for (ArtifactRepository repository : repositories) { + result = 31 * result + repositoryHashCode(repository); } return result; } - private static boolean repositoryEquals( ArtifactRepository r1, ArtifactRepository r2 ) - { - if ( r1 == r2 ) - { + private static boolean repositoryEquals(ArtifactRepository r1, ArtifactRepository r2) { + if (r1 == r2) { return true; } - return Objects.equals( r1.getId(), r2.getId() ) - && Objects.equals( r1.getUrl(), r2.getUrl() ) - && repositoryPolicyEquals( r1.getReleases(), r2.getReleases() ) - && repositoryPolicyEquals( r1.getSnapshots(), r2.getSnapshots() ); + return Objects.equals(r1.getId(), r2.getId()) + && Objects.equals(r1.getUrl(), r2.getUrl()) + && repositoryPolicyEquals(r1.getReleases(), r2.getReleases()) + && repositoryPolicyEquals(r1.getSnapshots(), r2.getSnapshots()); } - private static boolean repositoryPolicyEquals( ArtifactRepositoryPolicy p1, ArtifactRepositoryPolicy p2 ) - { - if ( p1 == p2 ) - { + private static boolean repositoryPolicyEquals(ArtifactRepositoryPolicy p1, ArtifactRepositoryPolicy p2) { + if (p1 == p2) { return true; } - return p1.isEnabled() == p2.isEnabled() && Objects.equals( p1.getUpdatePolicy(), p2.getUpdatePolicy() ); + return p1.isEnabled() == p2.isEnabled() && Objects.equals(p1.getUpdatePolicy(), p2.getUpdatePolicy()); } - private static boolean repositoriesEquals( List r1, List r2 ) - { - if ( r1.size() != r2.size() ) - { + private static boolean repositoriesEquals(List r1, List r2) { + if (r1.size() != r2.size()) { return false; } - for ( Iterator it1 = r1.iterator(), it2 = r2.iterator(); it1.hasNext(); ) - { - if ( !repositoryEquals( it1.next(), it2.next() ) ) - { + for (Iterator it1 = r1.iterator(), it2 = r2.iterator(); it1.hasNext(); ) { + if (!repositoryEquals(it1.next(), it2.next())) { return false; } } @@ -207,8 +183,7 @@ public class DefaultMavenMetadataCache /** * CacheRecord */ - public class CacheRecord - { + public class CacheRecord { private Artifact pomArtifact; private Artifact relocatedArtifact; private List artifacts; @@ -218,78 +193,64 @@ public class DefaultMavenMetadataCache private long length; private long timestamp; - CacheRecord( Artifact pomArtifact, Artifact relocatedArtifact, Set artifacts, - Map managedVersions, List remoteRepositories ) - { - this.pomArtifact = ArtifactUtils.copyArtifact( pomArtifact ); - this.relocatedArtifact = ArtifactUtils.copyArtifactSafe( relocatedArtifact ); - this.artifacts = ArtifactUtils.copyArtifacts( artifacts, new ArrayList<>() ); - this.remoteRepositories = new ArrayList<>( remoteRepositories ); + CacheRecord( + Artifact pomArtifact, + Artifact relocatedArtifact, + Set artifacts, + Map managedVersions, + List remoteRepositories) { + this.pomArtifact = ArtifactUtils.copyArtifact(pomArtifact); + this.relocatedArtifact = ArtifactUtils.copyArtifactSafe(relocatedArtifact); + this.artifacts = ArtifactUtils.copyArtifacts(artifacts, new ArrayList<>()); + this.remoteRepositories = new ArrayList<>(remoteRepositories); this.managedVersions = managedVersions; - if ( managedVersions != null ) - { - this.managedVersions = - ArtifactUtils.copyArtifacts( managedVersions, new LinkedHashMap<>() ); + if (managedVersions != null) { + this.managedVersions = ArtifactUtils.copyArtifacts(managedVersions, new LinkedHashMap<>()); } File pomFile = pomArtifact.getFile(); - if ( pomFile != null && pomFile.canRead() ) - { + if (pomFile != null && pomFile.canRead()) { this.length = pomFile.length(); this.timestamp = pomFile.lastModified(); - } - else - { + } else { this.length = -1; this.timestamp = -1; } } - public Artifact getArtifact() - { + public Artifact getArtifact() { return pomArtifact; } - public Artifact getRelocatedArtifact() - { + public Artifact getRelocatedArtifact() { return relocatedArtifact; } - public List getArtifacts() - { + public List getArtifacts() { return artifacts; } - public Map getManagedVersions() - { + public Map getManagedVersions() { return managedVersions; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - public boolean isStale() - { + public boolean isStale() { File pomFile = pomArtifact.getFile(); - if ( pomFile != null ) - { - if ( pomFile.canRead() ) - { + if (pomFile != null) { + if (pomFile.canRead()) { return length != pomFile.length() || timestamp != pomFile.lastModified(); - } - else - { + } else { // if the POM didn't exist, retry if any repo is configured to always update boolean snapshot = pomArtifact.isSnapshot(); - for ( ArtifactRepository repository : remoteRepositories ) - { + for (ArtifactRepository repository : remoteRepositories) { ArtifactRepositoryPolicy policy = - snapshot ? repository.getSnapshots() : repository.getReleases(); - if ( ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy.getUpdatePolicy() ) ) - { + snapshot ? repository.getSnapshots() : repository.getReleases(); + if (ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(policy.getUpdatePolicy())) { return true; } } @@ -300,57 +261,61 @@ public class DefaultMavenMetadataCache } } + public ResolutionGroup get( + Artifact artifact, + boolean resolveManagedVersions, + ArtifactRepository localRepository, + List remoteRepositories) { + CacheKey cacheKey = newCacheKey(artifact, resolveManagedVersions, localRepository, remoteRepositories); - public ResolutionGroup get( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, - List remoteRepositories ) - { - CacheKey cacheKey = newCacheKey( artifact, resolveManagedVersions, localRepository, remoteRepositories ); + CacheRecord cacheRecord = cache.get(cacheKey); - CacheRecord cacheRecord = cache.get( cacheKey ); - - if ( cacheRecord != null && !cacheRecord.isStale() ) - { - Artifact pomArtifact = ArtifactUtils.copyArtifact( cacheRecord.getArtifact() ); - Artifact relocatedArtifact = ArtifactUtils.copyArtifactSafe( cacheRecord.getRelocatedArtifact() ); - Set artifacts = - ArtifactUtils.copyArtifacts( cacheRecord.getArtifacts(), new LinkedHashSet<>() ); + if (cacheRecord != null && !cacheRecord.isStale()) { + Artifact pomArtifact = ArtifactUtils.copyArtifact(cacheRecord.getArtifact()); + Artifact relocatedArtifact = ArtifactUtils.copyArtifactSafe(cacheRecord.getRelocatedArtifact()); + Set artifacts = ArtifactUtils.copyArtifacts(cacheRecord.getArtifacts(), new LinkedHashSet<>()); Map managedVersions = cacheRecord.getManagedVersions(); - if ( managedVersions != null ) - { - managedVersions = ArtifactUtils.copyArtifacts( managedVersions, new LinkedHashMap<>() ); + if (managedVersions != null) { + managedVersions = ArtifactUtils.copyArtifacts(managedVersions, new LinkedHashMap<>()); } - return new ResolutionGroup( pomArtifact, relocatedArtifact, artifacts, managedVersions, - cacheRecord.getRemoteRepositories() ); + return new ResolutionGroup( + pomArtifact, relocatedArtifact, artifacts, managedVersions, cacheRecord.getRemoteRepositories()); } - cache.remove( cacheKey ); + cache.remove(cacheKey); return null; } - public void put( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, - List remoteRepositories, ResolutionGroup result ) - { - put( newCacheKey( artifact, resolveManagedVersions, localRepository, remoteRepositories ), result ); + public void put( + Artifact artifact, + boolean resolveManagedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ResolutionGroup result) { + put(newCacheKey(artifact, resolveManagedVersions, localRepository, remoteRepositories), result); } - protected CacheKey newCacheKey( Artifact artifact, boolean resolveManagedVersions, - ArtifactRepository localRepository, List remoteRepositories ) - { - return new CacheKey( artifact, resolveManagedVersions, localRepository, remoteRepositories ); + protected CacheKey newCacheKey( + Artifact artifact, + boolean resolveManagedVersions, + ArtifactRepository localRepository, + List remoteRepositories) { + return new CacheKey(artifact, resolveManagedVersions, localRepository, remoteRepositories); } - protected void put( CacheKey cacheKey, ResolutionGroup result ) - { - CacheRecord cacheRecord = - new CacheRecord( result.getPomArtifact(), result.getRelocatedArtifact(), result.getArtifacts(), - result.getManagedVersions(), result.getResolutionRepositories() ); + protected void put(CacheKey cacheKey, ResolutionGroup result) { + CacheRecord cacheRecord = new CacheRecord( + result.getPomArtifact(), + result.getRelocatedArtifact(), + result.getArtifacts(), + result.getManagedVersions(), + result.getResolutionRepositories()); - cache.put( cacheKey, cacheRecord ); + cache.put(cacheKey, cacheRecord); } - public void flush() - { + public void flush() { cache.clear(); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMetadataSource.java b/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMetadataSource.java index 8a8eb6f0cb..57d3c9d307 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMetadataSource.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager; import org.apache.maven.plugin.LegacySupport; @@ -37,14 +35,14 @@ import org.apache.maven.project.ProjectBuilder; */ @Named @Singleton -public class DefaultMetadataSource - extends MavenMetadataSource -{ +public class DefaultMetadataSource extends MavenMetadataSource { @Inject public DefaultMetadataSource( - RepositoryMetadataManager repositoryMetadataManager, ArtifactFactory repositorySystem, - ProjectBuilder projectBuilder, MavenMetadataCache cache, LegacySupport legacySupport ) - { - super( repositoryMetadataManager, repositorySystem, projectBuilder, cache, legacySupport ); + RepositoryMetadataManager repositoryMetadataManager, + ArtifactFactory repositorySystem, + ProjectBuilder projectBuilder, + MavenMetadataCache cache, + LegacySupport legacySupport) { + super(repositoryMetadataManager, repositorySystem, projectBuilder, cache, legacySupport); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCache.java b/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCache.java index b4ec77d9ad..a13c057d84 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCache.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.util.ArrayList; import java.util.Collection; @@ -29,10 +28,8 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.lifecycle.LifecycleExecutionException; @@ -49,15 +46,11 @@ import org.eclipse.aether.repository.WorkspaceRepository; */ @Named @Singleton -public class DefaultProjectArtifactsCache - implements ProjectArtifactsCache -{ +public class DefaultProjectArtifactsCache implements ProjectArtifactsCache { /** * CacheKey */ - protected static class CacheKey - implements Key - { + protected static class CacheKey implements Key { private final String groupId; @@ -81,118 +74,116 @@ public class DefaultProjectArtifactsCache private final int hashCode; - public CacheKey( MavenProject project, List repositories, - Collection scopesToCollect, Collection scopesToResolve, boolean aggregating, - RepositorySystemSession session ) - { + public CacheKey( + MavenProject project, + List repositories, + Collection scopesToCollect, + Collection scopesToResolve, + boolean aggregating, + RepositorySystemSession session) { groupId = project.getGroupId(); artifactId = project.getArtifactId(); version = project.getVersion(); Set deps = new LinkedHashSet<>(); - if ( project.getDependencyArtifacts() != null ) - { - for ( Artifact dep: project.getDependencyArtifacts() ) - { - deps.add( dep.toString() ); - } - } - dependencyArtifacts = Collections.unmodifiableSet( deps ); - - workspace = RepositoryUtils.getWorkspace( session ); - this.localRepo = session.getLocalRepository(); - this.repositories = new ArrayList<>( repositories.size() ); - for ( RemoteRepository repository : repositories ) - { - if ( repository.isRepositoryManager() ) - { - this.repositories.addAll( repository.getMirroredRepositories() ); + if (project.getDependencyArtifacts() != null) { + for (Artifact dep : project.getDependencyArtifacts()) { + deps.add(dep.toString()); } - else - { - this.repositories.add( repository ); + } + dependencyArtifacts = Collections.unmodifiableSet(deps); + + workspace = RepositoryUtils.getWorkspace(session); + this.localRepo = session.getLocalRepository(); + this.repositories = new ArrayList<>(repositories.size()); + for (RemoteRepository repository : repositories) { + if (repository.isRepositoryManager()) { + this.repositories.addAll(repository.getMirroredRepositories()); + } else { + this.repositories.add(repository); } } collect = scopesToCollect == null - ? Collections.emptySet() - : Collections.unmodifiableSet( new HashSet<>( scopesToCollect ) ); + ? Collections.emptySet() + : Collections.unmodifiableSet(new HashSet<>(scopesToCollect)); resolve = scopesToResolve == null - ? Collections.emptySet() - : Collections.unmodifiableSet( new HashSet<>( scopesToResolve ) ); + ? Collections.emptySet() + : Collections.unmodifiableSet(new HashSet<>(scopesToResolve)); this.aggregating = aggregating; int hash = 17; - hash = hash * 31 + Objects.hashCode( groupId ); - hash = hash * 31 + Objects.hashCode( artifactId ); - hash = hash * 31 + Objects.hashCode( version ); - hash = hash * 31 + Objects.hashCode( dependencyArtifacts ); - hash = hash * 31 + Objects.hashCode( workspace ); - hash = hash * 31 + Objects.hashCode( localRepo ); - hash = hash * 31 + RepositoryUtils.repositoriesHashCode( repositories ); - hash = hash * 31 + Objects.hashCode( collect ); - hash = hash * 31 + Objects.hashCode( resolve ); - hash = hash * 31 + Objects.hashCode( aggregating ); + hash = hash * 31 + Objects.hashCode(groupId); + hash = hash * 31 + Objects.hashCode(artifactId); + hash = hash * 31 + Objects.hashCode(version); + hash = hash * 31 + Objects.hashCode(dependencyArtifacts); + hash = hash * 31 + Objects.hashCode(workspace); + hash = hash * 31 + Objects.hashCode(localRepo); + hash = hash * 31 + RepositoryUtils.repositoriesHashCode(repositories); + hash = hash * 31 + Objects.hashCode(collect); + hash = hash * 31 + Objects.hashCode(resolve); + hash = hash * 31 + Objects.hashCode(aggregating); this.hashCode = hash; } @Override - public String toString() - { + public String toString() { return groupId + ":" + artifactId + ":" + version; } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object o ) - { - if ( o == this ) - { + public boolean equals(Object o) { + if (o == this) { return true; } - if ( !( o instanceof CacheKey ) ) - { + if (!(o instanceof CacheKey)) { return false; } CacheKey that = (CacheKey) o; - return Objects.equals( groupId, that.groupId ) && Objects.equals( artifactId, that.artifactId ) - && Objects.equals( version, that.version ) - && Objects.equals( dependencyArtifacts, that.dependencyArtifacts ) - && Objects.equals( workspace, that.workspace ) - && Objects.equals( localRepo, that.localRepo ) - && RepositoryUtils.repositoriesEquals( repositories, that.repositories ) - && Objects.equals( collect, that.collect ) - && Objects.equals( resolve, that.resolve ) - && aggregating == that.aggregating; + return Objects.equals(groupId, that.groupId) + && Objects.equals(artifactId, that.artifactId) + && Objects.equals(version, that.version) + && Objects.equals(dependencyArtifacts, that.dependencyArtifacts) + && Objects.equals(workspace, that.workspace) + && Objects.equals(localRepo, that.localRepo) + && RepositoryUtils.repositoriesEquals(repositories, that.repositories) + && Objects.equals(collect, that.collect) + && Objects.equals(resolve, that.resolve) + && aggregating == that.aggregating; } } protected final Map cache = new ConcurrentHashMap<>(); @Override - public Key createKey( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, boolean aggregating, RepositorySystemSession session ) - { - return new CacheKey( project, project.getRemoteProjectRepositories(), scopesToCollect, scopesToResolve, - aggregating, session ); + public Key createKey( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + boolean aggregating, + RepositorySystemSession session) { + return new CacheKey( + project, + project.getRemoteProjectRepositories(), + scopesToCollect, + scopesToResolve, + aggregating, + session); } @Override - public CacheRecord get( Key key ) - throws LifecycleExecutionException - { - CacheRecord cacheRecord = cache.get( key ); + public CacheRecord get(Key key) throws LifecycleExecutionException { + CacheRecord cacheRecord = cache.get(key); - if ( cacheRecord != null && cacheRecord.getException() != null ) - { + if (cacheRecord != null && cacheRecord.getException() != null) { throw cacheRecord.getException(); } @@ -200,52 +191,44 @@ public class DefaultProjectArtifactsCache } @Override - public CacheRecord put( Key key, Set projectArtifacts ) - { - Objects.requireNonNull( projectArtifacts, "projectArtifacts cannot be null" ); + public CacheRecord put(Key key, Set projectArtifacts) { + Objects.requireNonNull(projectArtifacts, "projectArtifacts cannot be null"); - assertUniqueKey( key ); + assertUniqueKey(key); - CacheRecord record = - new CacheRecord( Collections.unmodifiableSet( new LinkedHashSet<>( projectArtifacts ) ) ); + CacheRecord record = new CacheRecord(Collections.unmodifiableSet(new LinkedHashSet<>(projectArtifacts))); - cache.put( key, record ); + cache.put(key, record); return record; } - protected void assertUniqueKey( Key key ) - { - if ( cache.containsKey( key ) ) - { - throw new IllegalStateException( "Duplicate artifact resolution result for project " + key ); + protected void assertUniqueKey(Key key) { + if (cache.containsKey(key)) { + throw new IllegalStateException("Duplicate artifact resolution result for project " + key); } } @Override - public CacheRecord put( Key key, LifecycleExecutionException exception ) - { - Objects.requireNonNull( exception, "exception cannot be null" ); + public CacheRecord put(Key key, LifecycleExecutionException exception) { + Objects.requireNonNull(exception, "exception cannot be null"); - assertUniqueKey( key ); + assertUniqueKey(key); - CacheRecord record = new CacheRecord( exception ); + CacheRecord record = new CacheRecord(exception); - cache.put( key, record ); + cache.put(key, record); return record; } @Override - public void flush() - { + public void flush() { cache.clear(); } @Override - public void register( MavenProject project, Key cacheKey, CacheRecord record ) - { + public void register(MavenProject project, Key cacheKey, CacheRecord record) { // default cache does not track record usage } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/InvalidDependencyVersionException.java b/maven-core/src/main/java/org/apache/maven/project/artifact/InvalidDependencyVersionException.java index 8a1de685a8..a214e2631d 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/InvalidDependencyVersionException.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/InvalidDependencyVersionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.io.File; - import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.model.Dependency; @@ -31,25 +29,20 @@ import org.apache.maven.project.InvalidProjectVersionException; * * @author Brett Porter */ -public class InvalidDependencyVersionException - extends InvalidProjectVersionException -{ +public class InvalidDependencyVersionException extends InvalidProjectVersionException { private Dependency dependency; - public InvalidDependencyVersionException( String projectId, Dependency dependency, File pomFile, - InvalidVersionSpecificationException cause ) - { - super( projectId, formatLocationInPom( dependency ), dependency.getVersion(), pomFile, cause ); + public InvalidDependencyVersionException( + String projectId, Dependency dependency, File pomFile, InvalidVersionSpecificationException cause) { + super(projectId, formatLocationInPom(dependency), dependency.getVersion(), pomFile, cause); this.dependency = dependency; } - private static String formatLocationInPom( Dependency dependency ) - { - return "Dependency: " + ArtifactUtils.versionlessKey( dependency.getGroupId(), dependency.getArtifactId() ); + private static String formatLocationInPom(Dependency dependency) { + return "Dependency: " + ArtifactUtils.versionlessKey(dependency.getGroupId(), dependency.getArtifactId()); } - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataCache.java b/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataCache.java index 033e42ac1a..1b98b0749b 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataCache.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,24 +16,30 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.util.List; - import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.metadata.ResolutionGroup; +import org.apache.maven.artifact.repository.ArtifactRepository; /** * MavenMetadataCache */ -public interface MavenMetadataCache -{ +public interface MavenMetadataCache { - ResolutionGroup get( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, - List remoteRepositories ); + ResolutionGroup get( + Artifact artifact, + boolean resolveManagedVersions, + ArtifactRepository localRepository, + List remoteRepositories); - void put( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, - List remoteRepositories, ResolutionGroup result ); + void put( + Artifact artifact, + boolean resolveManagedVersions, + ArtifactRepository localRepository, + List remoteRepositories, + ResolutionGroup result); void flush(); } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java b/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java index c3cec7348c..aa86eaede7 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.io.File; import java.util.ArrayList; @@ -31,11 +30,9 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; @@ -88,12 +85,10 @@ import org.slf4j.LoggerFactory; /** * @author Jason van Zyl */ -@Named( "maven" ) +@Named("maven") @Singleton -public class MavenMetadataSource - implements ArtifactMetadataSource -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class MavenMetadataSource implements ArtifactMetadataSource { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final RepositoryMetadataManager repositoryMetadataManager; private final ArtifactFactory repositorySystem; private final ProjectBuilder projectBuilder; @@ -106,8 +101,7 @@ public class MavenMetadataSource ArtifactFactory repositorySystem, ProjectBuilder projectBuilder, MavenMetadataCache cache, - LegacySupport legacySupport ) - { + LegacySupport legacySupport) { this.repositoryMetadataManager = repositoryMetadataManager; this.repositorySystem = repositorySystem; this.projectBuilder = projectBuilder; @@ -115,59 +109,56 @@ public class MavenMetadataSource this.legacySupport = legacySupport; } - private void injectSession( MetadataResolutionRequest request ) - { + private void injectSession(MetadataResolutionRequest request) { RepositorySystemSession session = legacySupport.getRepositorySession(); - if ( session != null ) - { - request.setOffline( session.isOffline() ); - request.setForceUpdate( RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( session.getUpdatePolicy() ) ); + if (session != null) { + request.setOffline(session.isOffline()); + request.setForceUpdate(RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(session.getUpdatePolicy())); } } - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { - return retrieve( artifact, localRepository, remoteRepositories, false ); + public ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { + return retrieve(artifact, localRepository, remoteRepositories, false); } - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories, boolean resolveManagedVersions ) - throws ArtifactMetadataRetrievalException - { + public ResolutionGroup retrieve( + Artifact artifact, + ArtifactRepository localRepository, + List remoteRepositories, + boolean resolveManagedVersions) + throws ArtifactMetadataRetrievalException { MetadataResolutionRequest request = new DefaultMetadataResolutionRequest(); - injectSession( request ); - request.setArtifact( artifact ); - request.setLocalRepository( localRepository ); - request.setRemoteRepositories( remoteRepositories ); - request.setResolveManagedVersions( resolveManagedVersions ); - return retrieve( request ); + injectSession(request); + request.setArtifact(artifact); + request.setLocalRepository(localRepository); + request.setRemoteRepositories(remoteRepositories); + request.setResolveManagedVersions(resolveManagedVersions); + return retrieve(request); } - public ResolutionGroup retrieve( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { + public ResolutionGroup retrieve(MetadataResolutionRequest request) throws ArtifactMetadataRetrievalException { Artifact artifact = request.getArtifact(); // // If we have a system scoped artifact then we do not want any searching in local or remote repositories // and we want artifact resolution to only return the system scoped artifact itself. // - if ( artifact.getScope() != null && artifact.getScope().equals( Artifact.SCOPE_SYSTEM ) ) - { - return new ResolutionGroup( null, null, null ); + if (artifact.getScope() != null && artifact.getScope().equals(Artifact.SCOPE_SYSTEM)) { + return new ResolutionGroup(null, null, null); } - ResolutionGroup cached = - cache.get( artifact, request.isResolveManagedVersions(), request.getLocalRepository(), - request.getRemoteRepositories() ); + ResolutionGroup cached = cache.get( + artifact, + request.isResolveManagedVersions(), + request.getLocalRepository(), + request.getRemoteRepositories()); - if ( cached != null - // if the POM has no file, we cached a missing artifact, only return the cached data if no update forced - && ( !request.isForceUpdate() || hasFile( cached.getPomArtifact() ) ) ) - { + if (cached != null + // if the POM has no file, we cached a missing artifact, only return the cached data if no update forced + && (!request.isForceUpdate() || hasFile(cached.getPomArtifact()))) { return cached; } @@ -184,45 +175,35 @@ public class MavenMetadataSource // TODO hack: don't rebuild model if it was already loaded during reactor resolution final WorkspaceReader workspace = legacySupport.getRepositorySession().getWorkspaceReader(); Model model = null; - if ( workspace instanceof MavenWorkspaceReader ) - { - model = ( (MavenWorkspaceReader) workspace ).findModel( RepositoryUtils.toArtifact( artifact ) ); + if (workspace instanceof MavenWorkspaceReader) { + model = ((MavenWorkspaceReader) workspace).findModel(RepositoryUtils.toArtifact(artifact)); } - if ( model != null ) - { + if (model != null) { pomArtifact = artifact; dependencies = model.getDependencies(); DependencyManagement dependencyManagement = model.getDependencyManagement(); managedDependencies = dependencyManagement == null ? null : dependencyManagement.getDependencies(); MavenSession session = legacySupport.getSession(); - if ( session != null ) - { + if (session != null) { pomRepositories = session.getProjects().stream() - .filter( p -> artifact.equals( p.getArtifact() ) ) - .map( MavenProject::getRemoteArtifactRepositories ) + .filter(p -> artifact.equals(p.getArtifact())) + .map(MavenProject::getRemoteArtifactRepositories) .findFirst() - .orElseGet( ArrayList::new ); - } - else - { + .orElseGet(ArrayList::new); + } else { pomRepositories = new ArrayList<>(); } - } - else if ( artifact instanceof ArtifactWithDependencies ) - { + } else if (artifact instanceof ArtifactWithDependencies) { pomArtifact = artifact; - dependencies = ( (ArtifactWithDependencies) artifact ).getDependencies(); + dependencies = ((ArtifactWithDependencies) artifact).getDependencies(); - managedDependencies = ( (ArtifactWithDependencies) artifact ).getManagedDependencies(); - } - else - { - ProjectRelocation rel = retrieveRelocatedProject( artifact, request ); + managedDependencies = ((ArtifactWithDependencies) artifact).getManagedDependencies(); + } else { + ProjectRelocation rel = retrieveRelocatedProject(artifact, request); - if ( rel == null ) - { + if (rel == null) { return null; } @@ -230,18 +211,15 @@ public class MavenMetadataSource relocatedArtifact = rel.relocatedArtifact; - if ( rel.project == null ) - { + if (rel.project == null) { // When this happens we have a Maven 1.x POM, or some invalid POM. // It should have never found its way into Maven 2.x repository but it did. dependencies = Collections.emptyList(); - } - else - { + } else { dependencies = rel.project.getModel().getDependencies(); DependencyManagement depMgmt = rel.project.getModel().getDependencyManagement(); - managedDependencies = ( depMgmt != null ) ? depMgmt.getDependencies() : null; + managedDependencies = (depMgmt != null) ? depMgmt.getDependencies() : null; pomRepositories = rel.project.getRemoteArtifactRepositories(); } @@ -249,261 +227,222 @@ public class MavenMetadataSource Set artifacts = Collections.emptySet(); - if ( !artifact.getArtifactHandler().isIncludesDependencies() ) - { + if (!artifact.getArtifactHandler().isIncludesDependencies()) { artifacts = new LinkedHashSet<>(); - for ( Dependency dependency : dependencies ) - { - Artifact dependencyArtifact = createDependencyArtifact( dependency, artifact, pomArtifact ); + for (Dependency dependency : dependencies) { + Artifact dependencyArtifact = createDependencyArtifact(dependency, artifact, pomArtifact); - if ( dependencyArtifact != null ) - { - artifacts.add( dependencyArtifact ); + if (dependencyArtifact != null) { + artifacts.add(dependencyArtifact); } } } Map managedVersions = null; - if ( managedDependencies != null && request.isResolveManagedVersions() ) - { + if (managedDependencies != null && request.isResolveManagedVersions()) { managedVersions = new HashMap<>(); - for ( Dependency managedDependency : managedDependencies ) - { - Artifact managedArtifact = createDependencyArtifact( managedDependency, null, pomArtifact ); + for (Dependency managedDependency : managedDependencies) { + Artifact managedArtifact = createDependencyArtifact(managedDependency, null, pomArtifact); - managedVersions.put( managedDependency.getManagementKey(), managedArtifact ); + managedVersions.put(managedDependency.getManagementKey(), managedArtifact); } } List aggregatedRepositories = - aggregateRepositories( request.getRemoteRepositories(), pomRepositories ); + aggregateRepositories(request.getRemoteRepositories(), pomRepositories); ResolutionGroup result = - new ResolutionGroup( pomArtifact, relocatedArtifact, artifacts, managedVersions, aggregatedRepositories ); + new ResolutionGroup(pomArtifact, relocatedArtifact, artifacts, managedVersions, aggregatedRepositories); - cache.put( artifact, request.isResolveManagedVersions(), request.getLocalRepository(), - request.getRemoteRepositories(), result ); + cache.put( + artifact, + request.isResolveManagedVersions(), + request.getLocalRepository(), + request.getRemoteRepositories(), + result); return result; } - private boolean hasFile( Artifact artifact ) - { - return artifact != null && artifact.getFile() != null && artifact.getFile().exists(); + private boolean hasFile(Artifact artifact) { + return artifact != null + && artifact.getFile() != null + && artifact.getFile().exists(); } - private List aggregateRepositories( List requestRepositories, - List pomRepositories ) - { + private List aggregateRepositories( + List requestRepositories, List pomRepositories) { List repositories = requestRepositories; - if ( pomRepositories != null && !pomRepositories.isEmpty() ) - { + if (pomRepositories != null && !pomRepositories.isEmpty()) { Map repos = new LinkedHashMap<>(); - for ( ArtifactRepository repo : requestRepositories ) - { - if ( !repos.containsKey( repo.getId() ) ) - { - repos.put( repo.getId(), repo ); + for (ArtifactRepository repo : requestRepositories) { + if (!repos.containsKey(repo.getId())) { + repos.put(repo.getId(), repo); } } - for ( ArtifactRepository repo : pomRepositories ) - { - if ( !repos.containsKey( repo.getId() ) ) - { - repos.put( repo.getId(), repo ); + for (ArtifactRepository repo : pomRepositories) { + if (!repos.containsKey(repo.getId())) { + repos.put(repo.getId(), repo); } } - repositories = new ArrayList<>( repos.values() ); + repositories = new ArrayList<>(repos.values()); } return repositories; } - private Artifact createDependencyArtifact( Dependency dependency, Artifact owner, Artifact pom ) - throws ArtifactMetadataRetrievalException - { - try - { - String inheritedScope = ( owner != null ) ? owner.getScope() : null; + private Artifact createDependencyArtifact(Dependency dependency, Artifact owner, Artifact pom) + throws ArtifactMetadataRetrievalException { + try { + String inheritedScope = (owner != null) ? owner.getScope() : null; - ArtifactFilter inheritedFilter = ( owner != null ) ? owner.getDependencyFilter() : null; + ArtifactFilter inheritedFilter = (owner != null) ? owner.getDependencyFilter() : null; - return createDependencyArtifact( repositorySystem, dependency, inheritedScope, inheritedFilter ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new ArtifactMetadataRetrievalException( "Invalid version for dependency " - + dependency.getManagementKey() + ": " + e.getMessage(), e, pom ); + return createDependencyArtifact(repositorySystem, dependency, inheritedScope, inheritedFilter); + } catch (InvalidVersionSpecificationException e) { + throw new ArtifactMetadataRetrievalException( + "Invalid version for dependency " + dependency.getManagementKey() + ": " + e.getMessage(), e, pom); } } - private static Artifact createDependencyArtifact( ArtifactFactory factory, Dependency dependency, - String inheritedScope, ArtifactFilter inheritedFilter ) - throws InvalidVersionSpecificationException - { - String effectiveScope = getEffectiveScope( dependency.getScope(), inheritedScope ); + private static Artifact createDependencyArtifact( + ArtifactFactory factory, Dependency dependency, String inheritedScope, ArtifactFilter inheritedFilter) + throws InvalidVersionSpecificationException { + String effectiveScope = getEffectiveScope(dependency.getScope(), inheritedScope); - if ( effectiveScope == null ) - { + if (effectiveScope == null) { return null; } - VersionRange versionRange = VersionRange.createFromVersionSpec( dependency.getVersion() ); + VersionRange versionRange = VersionRange.createFromVersionSpec(dependency.getVersion()); - Artifact dependencyArtifact = - factory.createDependencyArtifact( dependency.getGroupId(), dependency.getArtifactId(), versionRange, - dependency.getType(), dependency.getClassifier(), effectiveScope, - dependency.isOptional() ); + Artifact dependencyArtifact = factory.createDependencyArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + versionRange, + dependency.getType(), + dependency.getClassifier(), + effectiveScope, + dependency.isOptional()); - if ( inheritedFilter != null && !inheritedFilter.include( dependencyArtifact ) ) - { + if (inheritedFilter != null && !inheritedFilter.include(dependencyArtifact)) { return null; } - if ( Artifact.SCOPE_SYSTEM.equals( effectiveScope ) ) - { - dependencyArtifact.setFile( new File( dependency.getSystemPath() ) ); + if (Artifact.SCOPE_SYSTEM.equals(effectiveScope)) { + dependencyArtifact.setFile(new File(dependency.getSystemPath())); } - dependencyArtifact.setDependencyFilter( createDependencyFilter( dependency, inheritedFilter ) ); + dependencyArtifact.setDependencyFilter(createDependencyFilter(dependency, inheritedFilter)); return dependencyArtifact; } - private static String getEffectiveScope( String originalScope, String inheritedScope ) - { + private static String getEffectiveScope(String originalScope, String inheritedScope) { String effectiveScope = Artifact.SCOPE_RUNTIME; - if ( originalScope == null ) - { + if (originalScope == null) { originalScope = Artifact.SCOPE_COMPILE; } - if ( inheritedScope == null ) - { + if (inheritedScope == null) { // direct dependency retains its scope effectiveScope = originalScope; - } - else if ( Artifact.SCOPE_TEST.equals( originalScope ) || Artifact.SCOPE_PROVIDED.equals( originalScope ) ) - { + } else if (Artifact.SCOPE_TEST.equals(originalScope) || Artifact.SCOPE_PROVIDED.equals(originalScope)) { // test and provided are not transitive, so exclude them effectiveScope = null; - } - else if ( Artifact.SCOPE_SYSTEM.equals( originalScope ) ) - { + } else if (Artifact.SCOPE_SYSTEM.equals(originalScope)) { // system scope come through unchanged... effectiveScope = Artifact.SCOPE_SYSTEM; - } - else if ( Artifact.SCOPE_COMPILE.equals( originalScope ) && Artifact.SCOPE_COMPILE.equals( inheritedScope ) ) - { + } else if (Artifact.SCOPE_COMPILE.equals(originalScope) && Artifact.SCOPE_COMPILE.equals(inheritedScope)) { // added to retain compile scope. Remove if you want compile inherited as runtime effectiveScope = Artifact.SCOPE_COMPILE; - } - else if ( Artifact.SCOPE_TEST.equals( inheritedScope ) ) - { + } else if (Artifact.SCOPE_TEST.equals(inheritedScope)) { effectiveScope = Artifact.SCOPE_TEST; - } - else if ( Artifact.SCOPE_PROVIDED.equals( inheritedScope ) ) - { + } else if (Artifact.SCOPE_PROVIDED.equals(inheritedScope)) { effectiveScope = Artifact.SCOPE_PROVIDED; } return effectiveScope; } - private static ArtifactFilter createDependencyFilter( Dependency dependency, ArtifactFilter inheritedFilter ) - { + private static ArtifactFilter createDependencyFilter(Dependency dependency, ArtifactFilter inheritedFilter) { ArtifactFilter effectiveFilter = inheritedFilter; - if ( !dependency.getExclusions().isEmpty() ) - { - effectiveFilter = new ExclusionArtifactFilter( dependency.getExclusions() ); + if (!dependency.getExclusions().isEmpty()) { + effectiveFilter = new ExclusionArtifactFilter(dependency.getExclusions()); - if ( inheritedFilter != null ) - { - effectiveFilter = new AndArtifactFilter( Arrays.asList( inheritedFilter, effectiveFilter ) ); + if (inheritedFilter != null) { + effectiveFilter = new AndArtifactFilter(Arrays.asList(inheritedFilter, effectiveFilter)); } } return effectiveFilter; } - public List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { + public List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { MetadataResolutionRequest request = new DefaultMetadataResolutionRequest(); - injectSession( request ); - request.setArtifact( artifact ); - request.setLocalRepository( localRepository ); - request.setRemoteRepositories( remoteRepositories ); - return retrieveAvailableVersions( request ); + injectSession(request); + request.setArtifact(artifact); + request.setLocalRepository(localRepository); + request.setRemoteRepositories(remoteRepositories); + return retrieveAvailableVersions(request); } - public List retrieveAvailableVersions( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException - { - RepositoryMetadata metadata = new ArtifactRepositoryMetadata( request.getArtifact() ); + public List retrieveAvailableVersions(MetadataResolutionRequest request) + throws ArtifactMetadataRetrievalException { + RepositoryMetadata metadata = new ArtifactRepositoryMetadata(request.getArtifact()); - try - { - repositoryMetadataManager.resolve( metadata, request ); - } - catch ( RepositoryMetadataResolutionException e ) - { - throw new ArtifactMetadataRetrievalException( e.getMessage(), e, request.getArtifact() ); + try { + repositoryMetadataManager.resolve(metadata, request); + } catch (RepositoryMetadataResolutionException e) { + throw new ArtifactMetadataRetrievalException(e.getMessage(), e, request.getArtifact()); } - List availableVersions = request.getLocalRepository().findVersions( request.getArtifact() ); + List availableVersions = request.getLocalRepository().findVersions(request.getArtifact()); - return retrieveAvailableVersionsFromMetadata( metadata.getMetadata(), availableVersions ); + return retrieveAvailableVersionsFromMetadata(metadata.getMetadata(), availableVersions); } - public List retrieveAvailableVersionsFromDeploymentRepository( Artifact artifact, - ArtifactRepository localRepository, - ArtifactRepository deploymentRepository ) - throws ArtifactMetadataRetrievalException - { - RepositoryMetadata metadata = new ArtifactRepositoryMetadata( artifact ); + public List retrieveAvailableVersionsFromDeploymentRepository( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository deploymentRepository) + throws ArtifactMetadataRetrievalException { + RepositoryMetadata metadata = new ArtifactRepositoryMetadata(artifact); - try - { - repositoryMetadataManager.resolveAlways( metadata, localRepository, deploymentRepository ); - } - catch ( RepositoryMetadataResolutionException e ) - { - throw new ArtifactMetadataRetrievalException( e.getMessage(), e, artifact ); + try { + repositoryMetadataManager.resolveAlways(metadata, localRepository, deploymentRepository); + } catch (RepositoryMetadataResolutionException e) { + throw new ArtifactMetadataRetrievalException(e.getMessage(), e, artifact); } - List availableVersions = localRepository.findVersions( artifact ); + List availableVersions = localRepository.findVersions(artifact); - return retrieveAvailableVersionsFromMetadata( metadata.getMetadata(), availableVersions ); + return retrieveAvailableVersionsFromMetadata(metadata.getMetadata(), availableVersions); } - private List retrieveAvailableVersionsFromMetadata( Metadata repoMetadata, - List availableVersions ) - { + private List retrieveAvailableVersionsFromMetadata( + Metadata repoMetadata, List availableVersions) { Collection versions = new LinkedHashSet<>(); - if ( ( repoMetadata != null ) && ( repoMetadata.getVersioning() != null ) ) - { - versions.addAll( repoMetadata.getVersioning().getVersions() ); + if ((repoMetadata != null) && (repoMetadata.getVersioning() != null)) { + versions.addAll(repoMetadata.getVersioning().getVersions()); } - versions.addAll( availableVersions ); + versions.addAll(availableVersions); - List artifactVersions = new ArrayList<>( versions.size() ); + List artifactVersions = new ArrayList<>(versions.size()); - for ( String version : versions ) - { - artifactVersions.add( new DefaultArtifactVersion( version ) ); + for (String version : versions) { + artifactVersions.add(new DefaultArtifactVersion(version)); } return artifactVersions; @@ -511,163 +450,133 @@ public class MavenMetadataSource // USED BY MAVEN ASSEMBLY PLUGIN @Deprecated - public static Set createArtifacts( ArtifactFactory artifactFactory, List dependencies, - String inheritedScope, ArtifactFilter dependencyFilter, - MavenProject project ) - throws InvalidDependencyVersionException - { + public static Set createArtifacts( + ArtifactFactory artifactFactory, + List dependencies, + String inheritedScope, + ArtifactFilter dependencyFilter, + MavenProject project) + throws InvalidDependencyVersionException { Set artifacts = new LinkedHashSet<>(); - for ( Dependency d : dependencies ) - { + for (Dependency d : dependencies) { Artifact dependencyArtifact; - try - { - dependencyArtifact = createDependencyArtifact( artifactFactory, d, inheritedScope, dependencyFilter ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new InvalidDependencyVersionException( project.getId(), d, project.getFile(), e ); + try { + dependencyArtifact = createDependencyArtifact(artifactFactory, d, inheritedScope, dependencyFilter); + } catch (InvalidVersionSpecificationException e) { + throw new InvalidDependencyVersionException(project.getId(), d, project.getFile(), e); } - if ( dependencyArtifact != null ) - { - artifacts.add( dependencyArtifact ); + if (dependencyArtifact != null) { + artifacts.add(dependencyArtifact); } } return artifacts; } - @SuppressWarnings( "checkstyle:methodlength" ) - private ProjectRelocation retrieveRelocatedProject( Artifact artifact, MetadataResolutionRequest repositoryRequest ) - throws ArtifactMetadataRetrievalException - { + @SuppressWarnings("checkstyle:methodlength") + private ProjectRelocation retrieveRelocatedProject(Artifact artifact, MetadataResolutionRequest repositoryRequest) + throws ArtifactMetadataRetrievalException { MavenProject project; Artifact pomArtifact; Artifact relocatedArtifact = null; boolean done = false; - do - { + do { project = null; - pomArtifact = - repositorySystem.createProjectArtifact( artifact.getGroupId(), - artifact.getArtifactId(), - artifact.getVersion(), artifact.getScope() ); + pomArtifact = repositorySystem.createProjectArtifact( + artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope()); - if ( "pom".equals( artifact.getType() ) ) - { - pomArtifact.setFile( artifact.getFile() ); + if ("pom".equals(artifact.getType())) { + pomArtifact.setFile(artifact.getFile()); } - if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) - { + if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { done = true; - } - else - { - try - { + } else { + try { ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setLocalRepository( repositoryRequest.getLocalRepository() ); - configuration.setRemoteRepositories( repositoryRequest.getRemoteRepositories() ); - configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); - configuration.setProcessPlugins( false ); - configuration.setRepositoryMerging( ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT ); + configuration.setLocalRepository(repositoryRequest.getLocalRepository()); + configuration.setRemoteRepositories(repositoryRequest.getRemoteRepositories()); + configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); + configuration.setProcessPlugins(false); + configuration.setRepositoryMerging(ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT); MavenSession session = legacySupport.getSession(); - if ( session != null ) - { - configuration.setSystemProperties( session.getSystemProperties() ); - configuration.setUserProperties( session.getUserProperties() ); + if (session != null) { + configuration.setSystemProperties(session.getSystemProperties()); + configuration.setUserProperties(session.getUserProperties()); + } else { + configuration.setSystemProperties(getSystemProperties()); + configuration.setUserProperties(new Properties()); } - else - { - configuration.setSystemProperties( getSystemProperties() ); - configuration.setUserProperties( new Properties() ); - } - configuration.setRepositorySession( legacySupport.getRepositorySession() ); + configuration.setRepositorySession(legacySupport.getRepositorySession()); - project = projectBuilder.build( pomArtifact, configuration ).getProject(); - } - catch ( ProjectBuildingException e ) - { - ModelProblem missingParentPom = hasMissingParentPom( e ); - if ( missingParentPom != null ) - { - throw new ArtifactMetadataRetrievalException( "Failed to process POM for " - + artifact.getId() + ": " + missingParentPom.getMessage(), - missingParentPom.getException(), - artifact ); + project = projectBuilder.build(pomArtifact, configuration).getProject(); + } catch (ProjectBuildingException e) { + ModelProblem missingParentPom = hasMissingParentPom(e); + if (missingParentPom != null) { + throw new ArtifactMetadataRetrievalException( + "Failed to process POM for " + artifact.getId() + ": " + missingParentPom.getMessage(), + missingParentPom.getException(), + artifact); } String message; - if ( isMissingPom( e ) ) - { + if (isMissingPom(e)) { message = "Missing POM for " + artifact.getId(); - } - else if ( isNonTransferablePom( e ) ) - { - throw new ArtifactMetadataRetrievalException( "Failed to retrieve POM for " - + artifact.getId() + ": " + e.getCause().getMessage(), e.getCause(), - artifact ); - } - else - { - message = - "Invalid POM for " + artifact.getId() + } else if (isNonTransferablePom(e)) { + throw new ArtifactMetadataRetrievalException( + "Failed to retrieve POM for " + artifact.getId() + ": " + + e.getCause().getMessage(), + e.getCause(), + artifact); + } else { + message = "Invalid POM for " + artifact.getId() + ", transitive dependencies (if any) will not be available" + ", enable verbose output (-X) for more details"; } - if ( logger.isDebugEnabled() ) - { + if (logger.isDebugEnabled()) { message += ": " + e.getMessage(); } - logger.warn( message ); + logger.warn(message); } - if ( project != null ) - { + if (project != null) { Relocation relocation = null; DistributionManagement distMgmt = project.getModel().getDistributionManagement(); - if ( distMgmt != null ) - { + if (distMgmt != null) { relocation = distMgmt.getRelocation(); - artifact.setDownloadUrl( distMgmt.getDownloadUrl() ); - pomArtifact.setDownloadUrl( distMgmt.getDownloadUrl() ); + artifact.setDownloadUrl(distMgmt.getDownloadUrl()); + pomArtifact.setDownloadUrl(distMgmt.getDownloadUrl()); } - if ( relocation != null ) - { - if ( relocation.getGroupId() != null ) - { - artifact.setGroupId( relocation.getGroupId() ); + if (relocation != null) { + if (relocation.getGroupId() != null) { + artifact.setGroupId(relocation.getGroupId()); relocatedArtifact = artifact; - project.setGroupId( relocation.getGroupId() ); + project.setGroupId(relocation.getGroupId()); } - if ( relocation.getArtifactId() != null ) - { - artifact.setArtifactId( relocation.getArtifactId() ); + if (relocation.getArtifactId() != null) { + artifact.setArtifactId(relocation.getArtifactId()); relocatedArtifact = artifact; - project.setArtifactId( relocation.getArtifactId() ); + project.setArtifactId(relocation.getArtifactId()); } - if ( relocation.getVersion() != null ) - { + if (relocation.getVersion() != null) { // note: see MNG-3454. This causes a problem, but fixing it may break more. - artifact.setVersionRange( VersionRange.createFromVersion( relocation.getVersion() ) ); + artifact.setVersionRange(VersionRange.createFromVersion(relocation.getVersion())); relocatedArtifact = artifact; - project.setVersion( relocation.getVersion() ); + project.setVersion(relocation.getVersion()); } - if ( artifact.getDependencyFilter() != null - && !artifact.getDependencyFilter().include( artifact ) ) - { + if (artifact.getDependencyFilter() != null + && !artifact.getDependencyFilter().include(artifact)) { return null; } @@ -675,47 +584,37 @@ public class MavenMetadataSource // retrieved, we need to update it. // TODO shouldn't the versions be merged across relocations? List available = artifact.getAvailableVersions(); - if ( available != null && !available.isEmpty() ) - { + if (available != null && !available.isEmpty()) { MetadataResolutionRequest metadataRequest = - new DefaultMetadataResolutionRequest( repositoryRequest ); - metadataRequest.setArtifact( artifact ); - available = retrieveAvailableVersions( metadataRequest ); - artifact.setAvailableVersions( available ); + new DefaultMetadataResolutionRequest(repositoryRequest); + metadataRequest.setArtifact(artifact); + available = retrieveAvailableVersions(metadataRequest); + artifact.setAvailableVersions(available); } - String message = - " this artifact has been relocated to " + artifact.getGroupId() + ":" + String message = " this artifact has been relocated to " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + "."; - if ( relocation.getMessage() != null ) - { + if (relocation.getMessage() != null) { message += " " + relocation.getMessage(); } - if ( artifact.getDependencyTrail() != null && artifact.getDependencyTrail().size() == 1 ) - { - logger.warn( "While downloading " + pomArtifact.getGroupId() + ":" - + pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion() + message ); + if (artifact.getDependencyTrail() != null + && artifact.getDependencyTrail().size() == 1) { + logger.warn("While downloading " + pomArtifact.getGroupId() + ":" + + pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion() + message); + } else { + logger.debug("While downloading " + pomArtifact.getGroupId() + ":" + + pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion() + message); } - else - { - logger.debug( "While downloading " + pomArtifact.getGroupId() + ":" - + pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion() + message ); - } - } - else - { + } else { done = true; } - } - else - { + } else { done = true; } } - } - while ( !done ); + } while (!done); ProjectRelocation rel = new ProjectRelocation(); rel.project = project; @@ -725,61 +624,49 @@ public class MavenMetadataSource return rel; } - private ModelProblem hasMissingParentPom( ProjectBuildingException e ) - { - if ( e.getCause() instanceof ModelBuildingException ) - { + private ModelProblem hasMissingParentPom(ProjectBuildingException e) { + if (e.getCause() instanceof ModelBuildingException) { ModelBuildingException mbe = (ModelBuildingException) e.getCause(); - for ( ModelProblem problem : mbe.getProblems() ) - { - if ( problem.getException() instanceof UnresolvableModelException ) - { + for (ModelProblem problem : mbe.getProblems()) { + if (problem.getException() instanceof UnresolvableModelException) { return problem; } } - } return null; } - private boolean isMissingPom( Exception e ) - { - if ( e.getCause() instanceof MultipleArtifactsNotFoundException ) - { + private boolean isMissingPom(Exception e) { + if (e.getCause() instanceof MultipleArtifactsNotFoundException) { return true; } return e.getCause() instanceof org.eclipse.aether.resolution.ArtifactResolutionException - && e.getCause().getCause() instanceof ArtifactNotFoundException; + && e.getCause().getCause() instanceof ArtifactNotFoundException; } - private boolean isNonTransferablePom( Exception e ) - { - if ( e.getCause() instanceof ArtifactResolutionException ) - { + private boolean isNonTransferablePom(Exception e) { + if (e.getCause() instanceof ArtifactResolutionException) { return true; } return e.getCause() instanceof org.eclipse.aether.resolution.ArtifactResolutionException - && !( e.getCause().getCause() instanceof ArtifactNotFoundException ); + && !(e.getCause().getCause() instanceof ArtifactNotFoundException); } - private Properties getSystemProperties() - { + private Properties getSystemProperties() { Properties props = new Properties(); - EnvironmentUtils.addEnvVars( props ); + EnvironmentUtils.addEnvVars(props); - SystemProperties.addSystemProperties( props ); + SystemProperties.addSystemProperties(props); return props; } - private static final class ProjectRelocation - { + private static final class ProjectRelocation { private MavenProject project; private Artifact pomArtifact; private Artifact relocatedArtifact; } - } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/PluginArtifact.java b/maven-core/src/main/java/org/apache/maven/project/artifact/PluginArtifact.java index c6bf9b8bb7..64deee8e23 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/PluginArtifact.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/PluginArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.util.Collections; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; @@ -31,67 +29,58 @@ import org.apache.maven.model.Plugin; /** * PluginArtifact */ -public class PluginArtifact - extends DefaultArtifact - implements ArtifactWithDependencies -{ +public class PluginArtifact extends DefaultArtifact implements ArtifactWithDependencies { private Plugin plugin; - public PluginArtifact( Plugin plugin, Artifact pluginArtifact ) - { - super( plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion(), null, "maven-plugin", null, - new PluginArtifactHandler() ); + public PluginArtifact(Plugin plugin, Artifact pluginArtifact) { + super( + plugin.getGroupId(), + plugin.getArtifactId(), + plugin.getVersion(), + null, + "maven-plugin", + null, + new PluginArtifactHandler()); this.plugin = plugin; - setFile( pluginArtifact.getFile() ); - setResolved( true ); + setFile(pluginArtifact.getFile()); + setResolved(true); } - public List getDependencies() - { + public List getDependencies() { return plugin.getDependencies(); } - public List getManagedDependencies() - { + public List getManagedDependencies() { return Collections.emptyList(); } // TODO: this is duplicate of MavenPluginArtifactHandlerProvider provided one - static class PluginArtifactHandler - implements ArtifactHandler - { - public String getClassifier() - { + static class PluginArtifactHandler implements ArtifactHandler { + public String getClassifier() { return null; } - public String getDirectory() - { + public String getDirectory() { return null; } - public String getExtension() - { + public String getExtension() { return "jar"; } - public String getLanguage() - { + public String getLanguage() { return "none"; } - public String getPackaging() - { + public String getPackaging() { return "maven-plugin"; } - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return true; } - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return false; } } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifact.java b/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifact.java index 8ef4444822..8225e6b7fc 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifact.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.util.Collections; import java.util.List; - import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.model.Dependency; @@ -31,76 +29,63 @@ import org.apache.maven.project.MavenProject; /** * ProjectArtifact */ -public class ProjectArtifact - extends DefaultArtifact - implements ArtifactWithDependencies -{ +public class ProjectArtifact extends DefaultArtifact implements ArtifactWithDependencies { private MavenProject project; - public ProjectArtifact( MavenProject project ) - { - super( project.getGroupId(), project.getArtifactId(), project.getVersion(), null, "pom", null, - new PomArtifactHandler() ); + public ProjectArtifact(MavenProject project) { + super( + project.getGroupId(), + project.getArtifactId(), + project.getVersion(), + null, + "pom", + null, + new PomArtifactHandler()); this.project = project; - setFile( project.getFile() ); - setResolved( true ); + setFile(project.getFile()); + setResolved(true); } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public List getDependencies() - { + public List getDependencies() { return project.getModel().getDependencies(); } - public List getManagedDependencies() - { + public List getManagedDependencies() { DependencyManagement depMngt = project.getModel().getDependencyManagement(); - return ( depMngt != null ) - ? Collections.unmodifiableList( depMngt.getDependencies() ) - : Collections.emptyList(); - + return (depMngt != null) ? Collections.unmodifiableList(depMngt.getDependencies()) : Collections.emptyList(); } // TODO: this is duplicate of PomArtifactHandlerProvider provided one - static class PomArtifactHandler - implements ArtifactHandler - { - public String getClassifier() - { + static class PomArtifactHandler implements ArtifactHandler { + public String getClassifier() { return null; } - public String getDirectory() - { + public String getDirectory() { return null; } - public String getExtension() - { + public String getExtension() { return "pom"; } - public String getLanguage() - { + public String getLanguage() { return "none"; } - public String getPackaging() - { + public String getPackaging() { return "pom"; } - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return false; } - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return false; } } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactMetadata.java b/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactMetadata.java index 7ea99bf0f6..ec508224d1 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.io.File; import java.io.IOException; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.AbstractArtifactMetadata; import org.apache.maven.artifact.metadata.ArtifactMetadata; @@ -34,48 +32,38 @@ import org.codehaus.plexus.util.FileUtils; * * @author Brett Porter */ -public class ProjectArtifactMetadata - extends AbstractArtifactMetadata -{ +public class ProjectArtifactMetadata extends AbstractArtifactMetadata { private final File file; - public ProjectArtifactMetadata( Artifact artifact ) - { - this( artifact, null ); + public ProjectArtifactMetadata(Artifact artifact) { + this(artifact, null); } - public ProjectArtifactMetadata( Artifact artifact, File file ) - { - super( artifact ); + public ProjectArtifactMetadata(Artifact artifact, File file) { + super(artifact); this.file = file; } - public File getFile() - { + public File getFile() { return file; } - public String getRemoteFilename() - { + public String getRemoteFilename() { return getFilename(); } - public String getLocalFilename( ArtifactRepository repository ) - { + public String getLocalFilename(ArtifactRepository repository) { return getFilename(); } - private String getFilename() - { + private String getFilename() { return getArtifactId() + "-" + artifact.getVersion() + ".pom"; } - public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws RepositoryMetadataStoreException - { - File destination = - new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( this, - remoteRepository ) ); + public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataStoreException { + File destination = new File( + localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(this, remoteRepository)); // ---------------------------------------------------------------------------- // I'm fully aware that the file could just be moved using File.rename but @@ -84,47 +72,37 @@ public class ProjectArtifactMetadata // here and be safe. jvz. // ---------------------------------------------------------------------------- - try - { - FileUtils.copyFile( file, destination ); - } - catch ( IOException e ) - { - throw new RepositoryMetadataStoreException( "Error copying POM to the local repository.", e ); + try { + FileUtils.copyFile(file, destination); + } catch (IOException e) { + throw new RepositoryMetadataStoreException("Error copying POM to the local repository.", e); } } - public String toString() - { + public String toString() { return "project information for " + artifact.getArtifactId() + " " + artifact.getVersion(); } - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return true; } - public String getBaseVersion() - { + public String getBaseVersion() { return artifact.getBaseVersion(); } - public Object getKey() - { + public Object getKey() { return "project " + artifact.getGroupId() + ":" + artifact.getArtifactId(); } - public void merge( ArtifactMetadata metadata ) - { + public void merge(ArtifactMetadata metadata) { ProjectArtifactMetadata m = (ProjectArtifactMetadata) metadata; - if ( !m.file.equals( file ) ) - { - throw new IllegalStateException( "Cannot add two different pieces of metadata for: " + getKey() ); + if (!m.file.equals(file)) { + throw new IllegalStateException("Cannot add two different pieces of metadata for: " + getKey()); } } - public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata ) - { - this.merge( (ArtifactMetadata) metadata ); + public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) { + this.merge((ArtifactMetadata) metadata); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactsCache.java b/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactsCache.java index fa0f3c5bc9..1b49e806ef 100644 --- a/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactsCache.java +++ b/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactsCache.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,15 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import java.util.Collection; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.project.MavenProject; import org.eclipse.aether.RepositorySystemSession; + /** * Caches project artifacts. Warning: This is an internal utility interface that is only public for * technical reasons, it is not part of the public API. In particular, this interface can be changed or deleted without @@ -35,58 +34,55 @@ import org.eclipse.aether.RepositorySystemSession; * @author Benjamin Bentmann * @author Anton Tanasenko */ -public interface ProjectArtifactsCache -{ +public interface ProjectArtifactsCache { /** * A cache key. */ - interface Key - { + interface Key { // marker interface for cache keys } /** * CacheRecord */ - class CacheRecord - { + class CacheRecord { - public Set getArtifacts() - { + public Set getArtifacts() { return artifacts; } private final Set artifacts; - public LifecycleExecutionException getException() - { + public LifecycleExecutionException getException() { return exception; } private final LifecycleExecutionException exception; - CacheRecord( Set artifacts ) - { + CacheRecord(Set artifacts) { this.artifacts = artifacts; this.exception = null; } - CacheRecord( LifecycleExecutionException exception ) - { + CacheRecord(LifecycleExecutionException exception) { this.artifacts = null; this.exception = exception; } } - Key createKey( MavenProject project, Collection scopesToCollect, Collection scopesToResolve, - boolean aggregating, RepositorySystemSession session ); + Key createKey( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + boolean aggregating, + RepositorySystemSession session); - CacheRecord get( Key key ) throws LifecycleExecutionException; + CacheRecord get(Key key) throws LifecycleExecutionException; - CacheRecord put( Key key, Set pluginArtifacts ); + CacheRecord put(Key key, Set pluginArtifacts); - CacheRecord put( Key key, LifecycleExecutionException e ); + CacheRecord put(Key key, LifecycleExecutionException e); void flush(); @@ -98,6 +94,5 @@ public interface ProjectArtifactsCache * @param project The project that employs the plugin realm, must not be {@code null}. * @param record The cache record being used for the project, must not be {@code null}. */ - void register( MavenProject project, Key cacheKey, CacheRecord record ); - + void register(MavenProject project, Key cacheKey, CacheRecord record); } diff --git a/maven-core/src/main/java/org/apache/maven/project/collector/DefaultProjectsSelector.java b/maven-core/src/main/java/org/apache/maven/project/collector/DefaultProjectsSelector.java index 74be84ad12..a6b6fa81e8 100644 --- a/maven-core/src/main/java/org/apache/maven/project/collector/DefaultProjectsSelector.java +++ b/maven-core/src/main/java/org/apache/maven/project/collector/DefaultProjectsSelector.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.collector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,14 @@ package org.apache.maven.project.collector; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.collector; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.model.building.ModelProblemUtils; @@ -31,72 +36,59 @@ import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - /** * Utility to select projects for a given set of pom.xml files. */ @Named @Singleton -public class DefaultProjectsSelector implements ProjectsSelector -{ - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultProjectsSelector.class ); +public class DefaultProjectsSelector implements ProjectsSelector { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultProjectsSelector.class); private final ProjectBuilder projectBuilder; @Inject - public DefaultProjectsSelector( ProjectBuilder projectBuilder ) - { + public DefaultProjectsSelector(ProjectBuilder projectBuilder) { this.projectBuilder = projectBuilder; } @Override - public List selectProjects( List files, MavenExecutionRequest request ) - throws ProjectBuildingException - { + public List selectProjects(List files, MavenExecutionRequest request) + throws ProjectBuildingException { ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest(); boolean hasProjectSelection = !request.getProjectActivation().isEmpty(); boolean isRecursive = hasProjectSelection || request.isRecursive(); - List results = projectBuilder.build( files, isRecursive, projectBuildingRequest ); + List results = projectBuilder.build(files, isRecursive, projectBuildingRequest); - List projects = new ArrayList<>( results.size() ); + List projects = new ArrayList<>(results.size()); boolean problems = false; - for ( ProjectBuildingResult result : results ) - { - projects.add( result.getProject() ); + for (ProjectBuildingResult result : results) { + projects.add(result.getProject()); - if ( !result.getProblems().isEmpty() && LOGGER.isWarnEnabled() ) - { - LOGGER.warn( "" ); - LOGGER.warn( "Some problems were encountered while building the effective model for '{}'", - result.getProject().getId() ); + if (!result.getProblems().isEmpty() && LOGGER.isWarnEnabled()) { + LOGGER.warn(""); + LOGGER.warn( + "Some problems were encountered while building the effective model for '{}'", + result.getProject().getId()); - for ( ModelProblem problem : result.getProblems() ) - { - String loc = ModelProblemUtils.formatLocation( problem, result.getProjectId() ); - LOGGER.warn( "{}{}", problem.getMessage(), ( StringUtils.isNotEmpty( loc ) ? " @ " + loc : "" ) ); + for (ModelProblem problem : result.getProblems()) { + String loc = ModelProblemUtils.formatLocation(problem, result.getProjectId()); + LOGGER.warn("{}{}", problem.getMessage(), (StringUtils.isNotEmpty(loc) ? " @ " + loc : "")); } problems = true; } } - if ( problems ) - { - LOGGER.warn( "" ); - LOGGER.warn( "It is highly recommended to fix these problems" - + " because they threaten the stability of your build." ); - LOGGER.warn( "" ); - LOGGER.warn( "For this reason, future Maven versions might no" - + " longer support building such malformed projects." ); - LOGGER.warn( "" ); + if (problems) { + LOGGER.warn(""); + LOGGER.warn("It is highly recommended to fix these problems" + + " because they threaten the stability of your build."); + LOGGER.warn(""); + LOGGER.warn("For this reason, future Maven versions might no" + + " longer support building such malformed projects."); + LOGGER.warn(""); } return projects; diff --git a/maven-core/src/main/java/org/apache/maven/project/collector/MultiModuleCollectionStrategy.java b/maven-core/src/main/java/org/apache/maven/project/collector/MultiModuleCollectionStrategy.java index d6c4cd7027..23dc3e2895 100644 --- a/maven-core/src/main/java/org/apache/maven/project/collector/MultiModuleCollectionStrategy.java +++ b/maven-core/src/main/java/org/apache/maven/project/collector/MultiModuleCollectionStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.collector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,17 @@ package org.apache.maven.project.collector; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.collector; +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.model.Plugin; import org.apache.maven.model.building.ModelProblem; @@ -33,69 +41,52 @@ import org.eclipse.aether.transfer.ArtifactNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; - /** * Strategy for collecting Maven projects from the multi-module project root, even when executed in a submodule. */ -@Named( "MultiModuleCollectionStrategy" ) +@Named("MultiModuleCollectionStrategy") @Singleton -public class MultiModuleCollectionStrategy implements ProjectCollectionStrategy -{ - private static final Logger LOGGER = LoggerFactory.getLogger( MultiModuleCollectionStrategy.class ); +public class MultiModuleCollectionStrategy implements ProjectCollectionStrategy { + private static final Logger LOGGER = LoggerFactory.getLogger(MultiModuleCollectionStrategy.class); private final ModelLocator modelLocator; private final ProjectsSelector projectsSelector; @Inject - public MultiModuleCollectionStrategy( ModelLocator modelLocator, ProjectsSelector projectsSelector ) - { + public MultiModuleCollectionStrategy(ModelLocator modelLocator, ProjectsSelector projectsSelector) { this.modelLocator = modelLocator; this.projectsSelector = projectsSelector; } @Override - public List collectProjects( MavenExecutionRequest request ) throws ProjectBuildingException - { - File moduleProjectPomFile = getMultiModuleProjectPomFile( request ); - List files = Collections.singletonList( moduleProjectPomFile.getAbsoluteFile() ); - try - { - List projects = projectsSelector.selectProjects( files, request ); - boolean isRequestedProjectCollected = isRequestedProjectCollected( request, projects ); - if ( isRequestedProjectCollected ) - { + public List collectProjects(MavenExecutionRequest request) throws ProjectBuildingException { + File moduleProjectPomFile = getMultiModuleProjectPomFile(request); + List files = Collections.singletonList(moduleProjectPomFile.getAbsoluteFile()); + try { + List projects = projectsSelector.selectProjects(files, request); + boolean isRequestedProjectCollected = isRequestedProjectCollected(request, projects); + if (isRequestedProjectCollected) { return projects; - } - else - { - LOGGER.debug( "Multi module project collection failed:{}" - + "Detected a POM file next to a .mvn directory in a parent directory ({}). " - + "Maven assumed that POM file to be the parent of the requested project ({}), but it turned " - + "out that it was not. Another project collection strategy will be executed as result.", - System.lineSeparator(), moduleProjectPomFile.getAbsolutePath(), - request.getPom().getAbsolutePath() ); + } else { + LOGGER.debug( + "Multi module project collection failed:{}" + + "Detected a POM file next to a .mvn directory in a parent directory ({}). " + + "Maven assumed that POM file to be the parent of the requested project ({}), but it turned " + + "out that it was not. Another project collection strategy will be executed as result.", + System.lineSeparator(), + moduleProjectPomFile.getAbsolutePath(), + request.getPom().getAbsolutePath()); return Collections.emptyList(); } - } - catch ( ProjectBuildingException e ) - { - boolean fallThrough = isModuleOutsideRequestScopeDependingOnPluginModule( request, e ); + } catch (ProjectBuildingException e) { + boolean fallThrough = isModuleOutsideRequestScopeDependingOnPluginModule(request, e); - if ( fallThrough ) - { - LOGGER.debug( "Multi module project collection failed:{}" - + "Detected that one of the modules of this multi-module project uses another module as " - + "plugin extension which still needed to be built. This is not possible within the same " - + "reactor build. Another project collection strategy will be executed as result.", - System.lineSeparator() ); + if (fallThrough) { + LOGGER.debug( + "Multi module project collection failed:{}" + + "Detected that one of the modules of this multi-module project uses another module as " + + "plugin extension which still needed to be built. This is not possible within the same " + + "reactor build. Another project collection strategy will be executed as result.", + System.lineSeparator()); return Collections.emptyList(); } @@ -103,21 +94,18 @@ public class MultiModuleCollectionStrategy implements ProjectCollectionStrategy } } - private File getMultiModuleProjectPomFile( MavenExecutionRequest request ) - { - if ( request.getPom().getParentFile().equals( request.getMultiModuleProjectDirectory() ) ) - { + private File getMultiModuleProjectPomFile(MavenExecutionRequest request) { + if (request.getPom().getParentFile().equals(request.getMultiModuleProjectDirectory())) { return request.getPom(); - } - else - { - File multiModuleProjectPom = modelLocator.locatePom( request.getMultiModuleProjectDirectory() ); - if ( !multiModuleProjectPom.exists() ) - { - LOGGER.info( "Maven detected that the requested POM file is part of a multi-module project, " - + "but could not find a pom.xml file in the multi-module root directory '{}'.", - request.getMultiModuleProjectDirectory() ); - LOGGER.info( "The reactor is limited to all projects under: " + request.getPom().getParent() ); + } else { + File multiModuleProjectPom = modelLocator.locatePom(request.getMultiModuleProjectDirectory()); + if (!multiModuleProjectPom.exists()) { + LOGGER.info( + "Maven detected that the requested POM file is part of a multi-module project, " + + "but could not find a pom.xml file in the multi-module root directory '{}'.", + request.getMultiModuleProjectDirectory()); + LOGGER.info("The reactor is limited to all projects under: " + + request.getPom().getParent()); return request.getPom(); } @@ -132,11 +120,8 @@ public class MultiModuleCollectionStrategy implements ProjectCollectionStrategy * * @return true if the collected projects contain the requested project (for example with -f) */ - private boolean isRequestedProjectCollected( MavenExecutionRequest request, List projects ) - { - return projects.stream() - .map( MavenProject::getFile ) - .anyMatch( request.getPom()::equals ); + private boolean isRequestedProjectCollected(MavenExecutionRequest request, List projects) { + return projects.stream().map(MavenProject::getFile).anyMatch(request.getPom()::equals); } /** @@ -153,42 +138,41 @@ public class MultiModuleCollectionStrategy implements ProjectCollectionStrategy * * @return true if the module which fails to collect the inter-module plugin is not part of the build. */ - private boolean isModuleOutsideRequestScopeDependingOnPluginModule( MavenExecutionRequest request, - ProjectBuildingException exception ) - { + private boolean isModuleOutsideRequestScopeDependingOnPluginModule( + MavenExecutionRequest request, ProjectBuildingException exception) { return exception.getResults().stream() - .map( ProjectBuildingResult::getProject ) - .filter( Objects::nonNull ) - .filter( project -> request.getPom().equals( project.getFile() ) ) + .map(ProjectBuildingResult::getProject) + .filter(Objects::nonNull) + .filter(project -> request.getPom().equals(project.getFile())) .findFirst() - .map( requestPomProject -> - { + .map(requestPomProject -> { List modules = requestPomProject.getCollectedProjects() != null - ? requestPomProject.getCollectedProjects() : Collections.emptyList(); - List projectsInRequestScope = new ArrayList<>( modules ); - projectsInRequestScope.add( requestPomProject ); + ? requestPomProject.getCollectedProjects() + : Collections.emptyList(); + List projectsInRequestScope = new ArrayList<>(modules); + projectsInRequestScope.add(requestPomProject); Predicate projectsOutsideOfRequestScope = - pr -> !projectsInRequestScope.contains( pr.getProject() ); + pr -> !projectsInRequestScope.contains(pr.getProject()); - Predicate pluginArtifactNotFoundException = - exc -> exc instanceof PluginManagerException - && exc.getCause() instanceof PluginResolutionException - && exc.getCause().getCause() instanceof ArtifactResolutionException - && exc.getCause().getCause().getCause() instanceof ArtifactNotFoundException; + Predicate pluginArtifactNotFoundException = exc -> exc instanceof PluginManagerException + && exc.getCause() instanceof PluginResolutionException + && exc.getCause().getCause() instanceof ArtifactResolutionException + && exc.getCause().getCause().getCause() instanceof ArtifactNotFoundException; Predicate isPluginPartOfRequestScope = plugin -> projectsInRequestScope.stream() - .anyMatch( project -> project.getGroupId().equals( plugin.getGroupId() ) - && project.getArtifactId().equals( plugin.getArtifactId() ) - && project.getVersion().equals( plugin.getVersion() ) ); + .anyMatch(project -> project.getGroupId().equals(plugin.getGroupId()) + && project.getArtifactId().equals(plugin.getArtifactId()) + && project.getVersion().equals(plugin.getVersion())); return exception.getResults().stream() - .filter( projectsOutsideOfRequestScope ) - .flatMap( projectBuildingResult -> projectBuildingResult.getProblems().stream() ) - .map( ModelProblem::getException ) - .filter( pluginArtifactNotFoundException ) - .map( exc -> ( ( PluginResolutionException ) exc.getCause() ).getPlugin() ) - .anyMatch( isPluginPartOfRequestScope ); - } ).orElse( false ); + .filter(projectsOutsideOfRequestScope) + .flatMap(projectBuildingResult -> projectBuildingResult.getProblems().stream()) + .map(ModelProblem::getException) + .filter(pluginArtifactNotFoundException) + .map(exc -> ((PluginResolutionException) exc.getCause()).getPlugin()) + .anyMatch(isPluginPartOfRequestScope); + }) + .orElse(false); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/collector/PomlessCollectionStrategy.java b/maven-core/src/main/java/org/apache/maven/project/collector/PomlessCollectionStrategy.java index 828485a995..44a8e9c149 100644 --- a/maven-core/src/main/java/org/apache/maven/project/collector/PomlessCollectionStrategy.java +++ b/maven-core/src/main/java/org/apache/maven/project/collector/PomlessCollectionStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.collector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,13 @@ package org.apache.maven.project.collector; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.collector; +import java.util.Arrays; +import java.util.List; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.DefaultMaven; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.model.building.ModelSource; @@ -28,38 +32,28 @@ import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectBuildingRequest; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.util.Arrays; -import java.util.List; - /** * Strategy to collect projects for building when the Maven invocation is not in a directory that contains a pom.xml. */ -@Named( "PomlessCollectionStrategy" ) +@Named("PomlessCollectionStrategy") @Singleton -public class PomlessCollectionStrategy - implements ProjectCollectionStrategy -{ +public class PomlessCollectionStrategy implements ProjectCollectionStrategy { private final ProjectBuilder projectBuilder; @Inject - public PomlessCollectionStrategy( ProjectBuilder projectBuilder ) - { + public PomlessCollectionStrategy(ProjectBuilder projectBuilder) { this.projectBuilder = projectBuilder; } @Override - public List collectProjects( final MavenExecutionRequest request ) - throws ProjectBuildingException - { + public List collectProjects(final MavenExecutionRequest request) throws ProjectBuildingException { ProjectBuildingRequest buildingRequest = request.getProjectBuildingRequest(); - ModelSource modelSource = new UrlModelSource( DefaultMaven.class.getResource( "project/standalone.xml" ) ); - MavenProject project = projectBuilder.build( modelSource, buildingRequest ).getProject(); - project.setExecutionRoot( true ); - request.setProjectPresent( false ); + ModelSource modelSource = new UrlModelSource(DefaultMaven.class.getResource("project/standalone.xml")); + MavenProject project = + projectBuilder.build(modelSource, buildingRequest).getProject(); + project.setExecutionRoot(true); + request.setProjectPresent(false); - return Arrays.asList( project ); + return Arrays.asList(project); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/collector/ProjectCollectionStrategy.java b/maven-core/src/main/java/org/apache/maven/project/collector/ProjectCollectionStrategy.java index 53521f09d9..c377eeb04e 100644 --- a/maven-core/src/main/java/org/apache/maven/project/collector/ProjectCollectionStrategy.java +++ b/maven-core/src/main/java/org/apache/maven/project/collector/ProjectCollectionStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.collector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,22 @@ package org.apache.maven.project.collector; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.collector; +import java.util.List; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; -import java.util.List; - /** * Describes strategies for finding projects that Maven could build. */ -public interface ProjectCollectionStrategy -{ +public interface ProjectCollectionStrategy { /** * * @param request * @return * @throws ProjectBuildingException */ - List collectProjects( MavenExecutionRequest request ) - throws ProjectBuildingException; + List collectProjects(MavenExecutionRequest request) throws ProjectBuildingException; } diff --git a/maven-core/src/main/java/org/apache/maven/project/collector/ProjectsSelector.java b/maven-core/src/main/java/org/apache/maven/project/collector/ProjectsSelector.java index 1731021d91..2cc7b846bf 100644 --- a/maven-core/src/main/java/org/apache/maven/project/collector/ProjectsSelector.java +++ b/maven-core/src/main/java/org/apache/maven/project/collector/ProjectsSelector.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.collector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,19 +16,18 @@ package org.apache.maven.project.collector; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.collector; +import java.io.File; +import java.util.List; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; -import java.io.File; -import java.util.List; - /** * Facade to select projects for a given set of pom.xml files. */ -public interface ProjectsSelector -{ +public interface ProjectsSelector { /** * Select Maven projects from a list of POM files. * @param files List of POM files. @@ -38,6 +35,5 @@ public interface ProjectsSelector * @return A list of projects that have been found in the specified POM files. * @throws ProjectBuildingException In case the POMs are not used. */ - List selectProjects( List files, MavenExecutionRequest request ) - throws ProjectBuildingException; + List selectProjects(List files, MavenExecutionRequest request) throws ProjectBuildingException; } diff --git a/maven-core/src/main/java/org/apache/maven/project/collector/RequestPomCollectionStrategy.java b/maven-core/src/main/java/org/apache/maven/project/collector/RequestPomCollectionStrategy.java index bf50856950..c3436f02a0 100644 --- a/maven-core/src/main/java/org/apache/maven/project/collector/RequestPomCollectionStrategy.java +++ b/maven-core/src/main/java/org/apache/maven/project/collector/RequestPomCollectionStrategy.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.collector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,37 +16,34 @@ package org.apache.maven.project.collector; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.collector; +import java.io.File; +import java.util.Collections; +import java.util.List; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.io.File; -import java.util.Collections; -import java.util.List; - /** * Strategy to collect projects based on the -f CLI parameter or the pom.xml in the working directory. */ -@Named( "RequestPomCollectionStrategy" ) +@Named("RequestPomCollectionStrategy") @Singleton -public class RequestPomCollectionStrategy implements ProjectCollectionStrategy -{ +public class RequestPomCollectionStrategy implements ProjectCollectionStrategy { private final ProjectsSelector projectsSelector; @Inject - public RequestPomCollectionStrategy( ProjectsSelector projectsSelector ) - { + public RequestPomCollectionStrategy(ProjectsSelector projectsSelector) { this.projectsSelector = projectsSelector; } @Override - public List collectProjects( MavenExecutionRequest request ) throws ProjectBuildingException - { - List files = Collections.singletonList( request.getPom().getAbsoluteFile() ); - return projectsSelector.selectProjects( files, request ); + public List collectProjects(MavenExecutionRequest request) throws ProjectBuildingException { + List files = Collections.singletonList(request.getPom().getAbsoluteFile()); + return projectsSelector.selectProjects(files, request); } } diff --git a/maven-core/src/main/java/org/apache/maven/project/path/PathTranslator.java b/maven-core/src/main/java/org/apache/maven/project/path/PathTranslator.java index 18e349ac18..8afcb93710 100644 --- a/maven-core/src/main/java/org/apache/maven/project/path/PathTranslator.java +++ b/maven-core/src/main/java/org/apache/maven/project/path/PathTranslator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.path; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.path; * "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 + * 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 @@ -18,24 +16,23 @@ package org.apache.maven.project.path; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.path; import java.io.File; - import org.apache.maven.model.Model; /** * @author Jason van Zyl */ @Deprecated -public interface PathTranslator -{ +public interface PathTranslator { String ROLE = PathTranslator.class.getName(); - void alignToBaseDirectory( Model model, File basedir ); + void alignToBaseDirectory(Model model, File basedir); - String alignToBaseDirectory( String path, File basedir ); + String alignToBaseDirectory(String path, File basedir); - void unalignFromBaseDirectory( Model model, File basedir ); + void unalignFromBaseDirectory(Model model, File basedir); - String unalignFromBaseDirectory( String directory, File basedir ); + String unalignFromBaseDirectory(String directory, File basedir); } diff --git a/maven-core/src/main/java/org/apache/maven/properties/internal/EnvironmentUtils.java b/maven-core/src/main/java/org/apache/maven/properties/internal/EnvironmentUtils.java index 2c3196fb69..ddbd366241 100644 --- a/maven-core/src/main/java/org/apache/maven/properties/internal/EnvironmentUtils.java +++ b/maven-core/src/main/java/org/apache/maven/properties/internal/EnvironmentUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.properties.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.properties.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.properties.internal; import java.util.Locale; import java.util.Map; import java.util.Properties; - import org.codehaus.plexus.util.Os; /** @@ -33,8 +31,7 @@ import org.codehaus.plexus.util.Os; * @since 3.0 * @author Benjamin Bentmann */ -public class EnvironmentUtils -{ +public class EnvironmentUtils { private static Properties envVars; @@ -46,25 +43,20 @@ public class EnvironmentUtils * * @param props The properties to add the environment variables to, may be {@code null}. */ - public static void addEnvVars( Properties props ) - { - if ( props != null ) - { - if ( envVars == null ) - { + public static void addEnvVars(Properties props) { + if (props != null) { + if (envVars == null) { Properties tmp = new Properties(); - boolean caseSensitive = !Os.isFamily( Os.FAMILY_WINDOWS ); - for ( Map.Entry entry : System.getenv().entrySet() ) - { - String key = - "env." + ( caseSensitive ? entry.getKey() : entry.getKey().toUpperCase( Locale.ENGLISH ) ); - tmp.setProperty( key, entry.getValue() ); + boolean caseSensitive = !Os.isFamily(Os.FAMILY_WINDOWS); + for (Map.Entry entry : System.getenv().entrySet()) { + String key = "env." + + (caseSensitive ? entry.getKey() : entry.getKey().toUpperCase(Locale.ENGLISH)); + tmp.setProperty(key, entry.getValue()); } envVars = tmp; } - props.putAll( envVars ); + props.putAll(envVars); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/properties/internal/SystemProperties.java b/maven-core/src/main/java/org/apache/maven/properties/internal/SystemProperties.java index c7ab086112..84b68a4623 100644 --- a/maven-core/src/main/java/org/apache/maven/properties/internal/SystemProperties.java +++ b/maven-core/src/main/java/org/apache/maven/properties/internal/SystemProperties.java @@ -1,5 +1,3 @@ -package org.apache.maven.properties.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,20 +16,19 @@ package org.apache.maven.properties.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.properties.internal; import java.util.Properties; /** * @since 3.2.3 */ -public class SystemProperties -{ +public class SystemProperties { /** * Thread-safe System.properties copy implementation. */ - public static void addSystemProperties( Properties props ) - { - props.putAll( getSystemProperties() ); + public static void addSystemProperties(Properties props) { + props.putAll(getSystemProperties()); } /** @@ -39,9 +36,8 @@ public class SystemProperties * * @return {@link System#getProperties()} obtained in a thread-safe manner. */ - public static Properties getSystemProperties() - { - return copyProperties( System.getProperties() ); + public static Properties getSystemProperties() { + return copyProperties(System.getProperties()); } /** @@ -49,15 +45,12 @@ public class SystemProperties * @param properties Properties to copy. * @return Copy of the given properties. */ - public static Properties copyProperties( Properties properties ) - { + public static Properties copyProperties(Properties properties) { final Properties copyProperties = new Properties(); // guard against modification/removal of keys in the given properties (MNG-5670, MNG-6053, MNG-6105) - synchronized ( properties ) - { - copyProperties.putAll( properties ); + synchronized (properties) { + copyProperties.putAll(properties); } return copyProperties; } - } diff --git a/maven-core/src/main/java/org/apache/maven/repository/ArtifactDoesNotExistException.java b/maven-core/src/main/java/org/apache/maven/repository/ArtifactDoesNotExistException.java index 3e72387702..98918468c7 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/ArtifactDoesNotExistException.java +++ b/maven-core/src/main/java/org/apache/maven/repository/ArtifactDoesNotExistException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,20 +16,17 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; /** * ArtifactDoesNotExistException */ -public class ArtifactDoesNotExistException - extends Exception -{ - public ArtifactDoesNotExistException( final String message ) - { - super( message ); +public class ArtifactDoesNotExistException extends Exception { + public ArtifactDoesNotExistException(final String message) { + super(message); } - public ArtifactDoesNotExistException( final String message, final Throwable cause ) - { - super( message, cause ); + public ArtifactDoesNotExistException(final String message, final Throwable cause) { + super(message, cause); } } diff --git a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferEvent.java b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferEvent.java index f560c54ba6..55720cea9c 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferEvent.java +++ b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.repository; import java.io.File; import java.util.EventObject; @@ -29,9 +27,7 @@ import java.util.EventObject; * * @author Michal Maczka */ -public class ArtifactTransferEvent - extends EventObject -{ +public class ArtifactTransferEvent extends EventObject { /** * A transfer was attempted, but has not yet commenced. */ @@ -85,36 +81,32 @@ public class ArtifactTransferEvent private int dataLength; - public ArtifactTransferEvent( String wagon, final int eventType, final int requestType, - ArtifactTransferResource artifact ) - { - super( wagon ); + public ArtifactTransferEvent( + String wagon, final int eventType, final int requestType, ArtifactTransferResource artifact) { + super(wagon); - setEventType( eventType ); + setEventType(eventType); - setRequestType( requestType ); + setRequestType(requestType); this.artifact = artifact; } - public ArtifactTransferEvent( String wagon, final Exception exception, final int requestType, - ArtifactTransferResource artifact ) - { - this( wagon, TRANSFER_ERROR, requestType, artifact ); + public ArtifactTransferEvent( + String wagon, final Exception exception, final int requestType, ArtifactTransferResource artifact) { + this(wagon, TRANSFER_ERROR, requestType, artifact); this.exception = exception; } - public ArtifactTransferResource getResource() - { + public ArtifactTransferResource getResource() { return artifact; } /** * @return Returns the exception. */ - public Exception getException() - { + public Exception getException() { return exception; } @@ -124,8 +116,7 @@ public class ArtifactTransferEvent * @return Returns the request type. The Request type is one of * TransferEvent.REQUEST_GET or TransferEvent.REQUEST_PUT */ - public int getRequestType() - { + public int getRequestType() { return requestType; } @@ -137,16 +128,14 @@ public class ArtifactTransferEvent * TransferEvent.REQUEST_GET or TransferEvent.REQUEST_PUT. * @throws IllegalArgumentException when */ - public void setRequestType( final int requestType ) - { - switch ( requestType ) - { + public void setRequestType(final int requestType) { + switch (requestType) { case REQUEST_PUT: break; case REQUEST_GET: break; - default : - throw new IllegalArgumentException( "Illegal request type: " + requestType ); + default: + throw new IllegalArgumentException("Illegal request type: " + requestType); } this.requestType = requestType; @@ -155,18 +144,15 @@ public class ArtifactTransferEvent /** * @return Returns the eventType. */ - public int getEventType() - { + public int getEventType() { return eventType; } /** * @param eventType The eventType to set. */ - public void setEventType( final int eventType ) - { - switch ( eventType ) - { + public void setEventType(final int eventType) { + switch (eventType) { case TRANSFER_INITIATED: break; case TRANSFER_STARTED: @@ -177,8 +163,8 @@ public class ArtifactTransferEvent break; case TRANSFER_ERROR: break; - default : - throw new IllegalArgumentException( "Illegal event type: " + eventType ); + default: + throw new IllegalArgumentException("Illegal event type: " + eventType); } this.eventType = eventType; @@ -187,153 +173,127 @@ public class ArtifactTransferEvent /** * @return Returns the local file. */ - public File getLocalFile() - { + public File getLocalFile() { return localFile; } /** * @param localFile The local file to set. */ - public void setLocalFile( File localFile ) - { + public void setLocalFile(File localFile) { this.localFile = localFile; } - public long getTransferredBytes() - { + public long getTransferredBytes() { return transferredBytes; } - public void setTransferredBytes( long transferredBytes ) - { + public void setTransferredBytes(long transferredBytes) { this.transferredBytes = transferredBytes; } - public byte[] getDataBuffer() - { + public byte[] getDataBuffer() { return dataBuffer; } - public void setDataBuffer( byte[] dataBuffer ) - { + public void setDataBuffer(byte[] dataBuffer) { this.dataBuffer = dataBuffer; } - public int getDataOffset() - { + public int getDataOffset() { return dataOffset; } - public void setDataOffset( int dataOffset ) - { + public void setDataOffset(int dataOffset) { this.dataOffset = dataOffset; } - public int getDataLength() - { + public int getDataLength() { return dataLength; } - public void setDataLength( int dataLength ) - { + public void setDataLength(int dataLength) { this.dataLength = dataLength; } - public String toString() - { - StringBuilder sb = new StringBuilder( 64 ); + public String toString() { + StringBuilder sb = new StringBuilder(64); - sb.append( "TransferEvent[" ); + sb.append("TransferEvent["); - switch ( this.getRequestType() ) - { + switch (this.getRequestType()) { case REQUEST_GET: - sb.append( "GET" ); + sb.append("GET"); break; case REQUEST_PUT: - sb.append( "PUT" ); + sb.append("PUT"); break; default: - sb.append( this.getRequestType() ); + sb.append(this.getRequestType()); break; } - sb.append( '|' ); - switch ( this.getEventType() ) - { + sb.append('|'); + switch (this.getEventType()) { case TRANSFER_COMPLETED: - sb.append( "COMPLETED" ); + sb.append("COMPLETED"); break; case TRANSFER_ERROR: - sb.append( "ERROR" ); + sb.append("ERROR"); break; case TRANSFER_INITIATED: - sb.append( "INITIATED" ); + sb.append("INITIATED"); break; case TRANSFER_PROGRESS: - sb.append( "PROGRESS" ); + sb.append("PROGRESS"); break; case TRANSFER_STARTED: - sb.append( "STARTED" ); + sb.append("STARTED"); break; default: - sb.append( this.getEventType() ); + sb.append(this.getEventType()); break; } - sb.append( '|' ); - sb.append( this.getLocalFile() ).append( '|' ); - sb.append( ']' ); + sb.append('|'); + sb.append(this.getLocalFile()).append('|'); + sb.append(']'); return sb.toString(); } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + eventType; - result = prime * result + ( ( exception == null ) ? 0 : exception.hashCode() ); - result = prime * result + ( ( localFile == null ) ? 0 : localFile.hashCode() ); + result = prime * result + ((exception == null) ? 0 : exception.hashCode()); + result = prime * result + ((localFile == null) ? 0 : localFile.hashCode()); result = prime * result + requestType; return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( ( obj == null ) || ( getClass() != obj.getClass() ) ) - { + if ((obj == null) || (getClass() != obj.getClass())) { return false; } final ArtifactTransferEvent other = (ArtifactTransferEvent) obj; - if ( eventType != other.eventType ) - { + if (eventType != other.eventType) { return false; } - if ( exception == null ) - { - if ( other.exception != null ) - { + if (exception == null) { + if (other.exception != null) { return false; } - } - else if ( !exception.getClass().equals( other.exception.getClass() ) ) - { + } else if (!exception.getClass().equals(other.exception.getClass())) { return false; } - if ( requestType != other.requestType ) - { + if (requestType != other.requestType) { return false; - } - else - { - return source.equals( other.source ); + } else { + return source.equals(other.source); } } - } diff --git a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferFailedException.java b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferFailedException.java index f35de659b7..e041f7c472 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferFailedException.java +++ b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferFailedException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,21 +16,17 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; /** * ArtifactTransferFailedException */ -public class ArtifactTransferFailedException - extends Exception -{ - public ArtifactTransferFailedException( final String message ) - { - super( message ); +public class ArtifactTransferFailedException extends Exception { + public ArtifactTransferFailedException(final String message) { + super(message); } - public ArtifactTransferFailedException( final String message, final Throwable cause ) - { - super( message, cause ); + public ArtifactTransferFailedException(final String message, final Throwable cause) { + super(message, cause); } - } diff --git a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferListener.java b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferListener.java index c6d2446e37..77525cf618 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferListener.java +++ b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository; * "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 + * 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 @@ -18,22 +16,21 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; /** * ArtifactTransferListener */ -public interface ArtifactTransferListener -{ +public interface ArtifactTransferListener { boolean isShowChecksumEvents(); - void setShowChecksumEvents( boolean showChecksumEvents ); + void setShowChecksumEvents(boolean showChecksumEvents); - void transferInitiated( ArtifactTransferEvent transferEvent ); + void transferInitiated(ArtifactTransferEvent transferEvent); - void transferStarted( ArtifactTransferEvent transferEvent ); + void transferStarted(ArtifactTransferEvent transferEvent); - void transferProgress( ArtifactTransferEvent transferEvent ); - - void transferCompleted( ArtifactTransferEvent transferEvent ); + void transferProgress(ArtifactTransferEvent transferEvent); + void transferCompleted(ArtifactTransferEvent transferEvent); } diff --git a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferResource.java b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferResource.java index 8ed081ffc0..90f678afa7 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferResource.java +++ b/maven-core/src/main/java/org/apache/maven/repository/ArtifactTransferResource.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,14 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; /** * Describes a resource being uploaded or downloaded by the repository system. * * @author Benjamin Bentmann */ -public interface ArtifactTransferResource -{ +public interface ArtifactTransferResource { /** * The base URL of the repository, e.g. "http://repo1.maven.org/maven2/". Unless the URL is unknown, it will be @@ -62,5 +60,4 @@ public interface ArtifactTransferResource * @return The timestamp when the transfer of this artifact was started. */ long getTransferStartTime(); - } diff --git a/maven-core/src/main/java/org/apache/maven/repository/DelegatingLocalArtifactRepository.java b/maven-core/src/main/java/org/apache/maven/repository/DelegatingLocalArtifactRepository.java index eb8f5eae54..e30b5a3756 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/DelegatingLocalArtifactRepository.java +++ b/maven-core/src/main/java/org/apache/maven/repository/DelegatingLocalArtifactRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -37,27 +35,22 @@ import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; * and user local repository. */ @Deprecated -public class DelegatingLocalArtifactRepository - extends MavenArtifactRepository -{ +public class DelegatingLocalArtifactRepository extends MavenArtifactRepository { private LocalArtifactRepository buildReactor; private LocalArtifactRepository ideWorkspace; private ArtifactRepository userLocalArtifactRepository; - public DelegatingLocalArtifactRepository( ArtifactRepository artifactRepository ) - { + public DelegatingLocalArtifactRepository(ArtifactRepository artifactRepository) { this.userLocalArtifactRepository = artifactRepository; } - public void setBuildReactor( LocalArtifactRepository localRepository ) - { + public void setBuildReactor(LocalArtifactRepository localRepository) { this.buildReactor = localRepository; } - public void setIdeWorkspace( LocalArtifactRepository localRepository ) - { + public void setIdeWorkspace(LocalArtifactRepository localRepository) { this.ideWorkspace = localRepository; } @@ -65,140 +58,117 @@ public class DelegatingLocalArtifactRepository * @deprecated instead use {@link #getIdeWorkspace()} */ @Deprecated - public LocalArtifactRepository getIdeWorspace() - { + public LocalArtifactRepository getIdeWorspace() { return ideWorkspace; } - public LocalArtifactRepository getIdeWorkspace() - { + public LocalArtifactRepository getIdeWorkspace() { return getIdeWorspace(); } @Override - public Artifact find( Artifact artifact ) - { - if ( !artifact.isRelease() && buildReactor != null ) - { - artifact = buildReactor.find( artifact ); + public Artifact find(Artifact artifact) { + if (!artifact.isRelease() && buildReactor != null) { + artifact = buildReactor.find(artifact); } - if ( !artifact.isResolved() && ideWorkspace != null ) - { - artifact = ideWorkspace.find( artifact ); + if (!artifact.isResolved() && ideWorkspace != null) { + artifact = ideWorkspace.find(artifact); } - if ( !artifact.isResolved() ) - { - artifact = userLocalArtifactRepository.find( artifact ); + if (!artifact.isResolved()) { + artifact = userLocalArtifactRepository.find(artifact); } return artifact; } @Override - public List findVersions( Artifact artifact ) - { + public List findVersions(Artifact artifact) { Collection versions = new LinkedHashSet<>(); - if ( buildReactor != null ) - { - versions.addAll( buildReactor.findVersions( artifact ) ); + if (buildReactor != null) { + versions.addAll(buildReactor.findVersions(artifact)); } - if ( ideWorkspace != null ) - { - versions.addAll( ideWorkspace.findVersions( artifact ) ); + if (ideWorkspace != null) { + versions.addAll(ideWorkspace.findVersions(artifact)); } - versions.addAll( userLocalArtifactRepository.findVersions( artifact ) ); + versions.addAll(userLocalArtifactRepository.findVersions(artifact)); - return Collections.unmodifiableList( new ArrayList<>( versions ) ); + return Collections.unmodifiableList(new ArrayList<>(versions)); } - public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository ) - { - return userLocalArtifactRepository.pathOfLocalRepositoryMetadata( metadata, repository ); + public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { + return userLocalArtifactRepository.pathOfLocalRepositoryMetadata(metadata, repository); } - public String getId() - { + public String getId() { return userLocalArtifactRepository.getId(); } @Override - public String pathOf( Artifact artifact ) - { - return userLocalArtifactRepository.pathOf( artifact ); + public String pathOf(Artifact artifact) { + return userLocalArtifactRepository.pathOf(artifact); } @Override - public String getBasedir() - { - return ( userLocalArtifactRepository != null ) ? userLocalArtifactRepository.getBasedir() : null; + public String getBasedir() { + return (userLocalArtifactRepository != null) ? userLocalArtifactRepository.getBasedir() : null; } @Override - public ArtifactRepositoryLayout getLayout() - { + public ArtifactRepositoryLayout getLayout() { return userLocalArtifactRepository.getLayout(); } @Override - public ArtifactRepositoryPolicy getReleases() - { + public ArtifactRepositoryPolicy getReleases() { return userLocalArtifactRepository.getReleases(); } @Override - public ArtifactRepositoryPolicy getSnapshots() - { + public ArtifactRepositoryPolicy getSnapshots() { return userLocalArtifactRepository.getSnapshots(); } @Override - public String getKey() - { + public String getKey() { return userLocalArtifactRepository.getKey(); } @Override - public String getUrl() - { + public String getUrl() { return userLocalArtifactRepository.getUrl(); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + ( buildReactor == null ? 0 : buildReactor.hashCode() ); - hash = hash * 31 + ( ideWorkspace == null ? 0 : ideWorkspace.hashCode() ); - hash = hash * 31 + ( userLocalArtifactRepository == null ? 0 : userLocalArtifactRepository.hashCode() ); + hash = hash * 31 + (buildReactor == null ? 0 : buildReactor.hashCode()); + hash = hash * 31 + (ideWorkspace == null ? 0 : ideWorkspace.hashCode()); + hash = hash * 31 + (userLocalArtifactRepository == null ? 0 : userLocalArtifactRepository.hashCode()); return hash; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } DelegatingLocalArtifactRepository other = (DelegatingLocalArtifactRepository) obj; - return eq( buildReactor, other.buildReactor ) - && eq( ideWorkspace, other.ideWorkspace ) - && eq( userLocalArtifactRepository, other.userLocalArtifactRepository ); + return eq(buildReactor, other.buildReactor) + && eq(ideWorkspace, other.ideWorkspace) + && eq(userLocalArtifactRepository, other.userLocalArtifactRepository); } } diff --git a/maven-core/src/main/java/org/apache/maven/repository/LocalArtifactRepository.java b/maven-core/src/main/java/org/apache/maven/repository/LocalArtifactRepository.java index 6f1c93478b..ce66c112fd 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/LocalArtifactRepository.java +++ b/maven-core/src/main/java/org/apache/maven/repository/LocalArtifactRepository.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.MavenArtifactRepository; @@ -25,12 +24,10 @@ import org.apache.maven.artifact.repository.MavenArtifactRepository; /** * LocalArtifactRepository */ -public abstract class LocalArtifactRepository - extends MavenArtifactRepository -{ +public abstract class LocalArtifactRepository extends MavenArtifactRepository { public static final String IDE_WORKSPACE = "ide-workspace"; - public abstract Artifact find( Artifact artifact ); + public abstract Artifact find(Artifact artifact); public abstract boolean hasLocalMetadata(); } diff --git a/maven-core/src/main/java/org/apache/maven/repository/LocalRepositoryNotAccessibleException.java b/maven-core/src/main/java/org/apache/maven/repository/LocalRepositoryNotAccessibleException.java index 54e4ef4b0f..4058db5151 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/LocalRepositoryNotAccessibleException.java +++ b/maven-core/src/main/java/org/apache/maven/repository/LocalRepositoryNotAccessibleException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.io.IOException; @@ -26,19 +25,14 @@ import java.io.IOException; * * @author Benjamin Bentmann */ -public class LocalRepositoryNotAccessibleException - extends IOException -{ +public class LocalRepositoryNotAccessibleException extends IOException { - public LocalRepositoryNotAccessibleException( String message, Throwable cause ) - { - super( message ); - initCause( cause ); + public LocalRepositoryNotAccessibleException(String message, Throwable cause) { + super(message); + initCause(cause); } - public LocalRepositoryNotAccessibleException( String message ) - { - super( message ); + public LocalRepositoryNotAccessibleException(String message) { + super(message); } - } diff --git a/maven-core/src/main/java/org/apache/maven/repository/RepositorySystem.java b/maven-core/src/main/java/org/apache/maven/repository/RepositorySystem.java index 30b49256fa..5c0f89a8e9 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/RepositorySystem.java +++ b/maven-core/src/main/java/org/apache/maven/repository/RepositorySystem.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.io.File; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -40,51 +38,49 @@ import org.eclipse.aether.RepositorySystemSession; * @author Jason van Zyl * @since 3.0-alpha */ -public interface RepositorySystem -{ +public interface RepositorySystem { String DEFAULT_LOCAL_REPO_ID = "local"; - @SuppressWarnings( "checkstyle:constantname" ) - String userHome = System.getProperty( "user.home" ); + @SuppressWarnings("checkstyle:constantname") + String userHome = System.getProperty("user.home"); - @SuppressWarnings( "checkstyle:constantname" ) - File userMavenConfigurationHome = new File( userHome, ".m2" ); + @SuppressWarnings("checkstyle:constantname") + File userMavenConfigurationHome = new File(userHome, ".m2"); - @SuppressWarnings( "checkstyle:constantname" ) - File defaultUserLocalRepository = new File( userMavenConfigurationHome, "repository" ); + @SuppressWarnings("checkstyle:constantname") + File defaultUserLocalRepository = new File(userMavenConfigurationHome, "repository"); String DEFAULT_REMOTE_REPO_ID = "central"; String DEFAULT_REMOTE_REPO_URL = "https://repo.maven.apache.org/maven2"; - Artifact createArtifact( String groupId, String artifactId, String version, String packaging ); + Artifact createArtifact(String groupId, String artifactId, String version, String packaging); - Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ); + Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type); - Artifact createProjectArtifact( String groupId, String artifactId, String version ); + Artifact createProjectArtifact(String groupId, String artifactId, String version); - Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, - String classifier ); + Artifact createArtifactWithClassifier( + String groupId, String artifactId, String version, String type, String classifier); - Artifact createPluginArtifact( Plugin plugin ); + Artifact createPluginArtifact(Plugin plugin); - Artifact createDependencyArtifact( Dependency dependency ); + Artifact createDependencyArtifact(Dependency dependency); - ArtifactRepository buildArtifactRepository( Repository repository ) - throws InvalidRepositoryException; + ArtifactRepository buildArtifactRepository(Repository repository) throws InvalidRepositoryException; - ArtifactRepository createDefaultRemoteRepository() - throws InvalidRepositoryException; + ArtifactRepository createDefaultRemoteRepository() throws InvalidRepositoryException; - ArtifactRepository createDefaultLocalRepository() - throws InvalidRepositoryException; + ArtifactRepository createDefaultLocalRepository() throws InvalidRepositoryException; - ArtifactRepository createLocalRepository( File localRepository ) - throws InvalidRepositoryException; + ArtifactRepository createLocalRepository(File localRepository) throws InvalidRepositoryException; - ArtifactRepository createArtifactRepository( String id, String url, ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ); + ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases); /** * Calculates the effective repositories for the given input repositories which are assumed to be already mirrored @@ -95,7 +91,7 @@ public interface RepositorySystem * @param repositories The original repositories, may be {@code null}. * @return The effective repositories or {@code null} if the input was {@code null}. */ - List getEffectiveRepositories( List repositories ); + List getEffectiveRepositories(List repositories); /** * Determines the mirror for the specified repository. @@ -104,7 +100,7 @@ public interface RepositorySystem * @param mirrors The available mirrors, may be {@code null}. * @return The mirror specification for the repository or {@code null} if no mirror matched. */ - Mirror getMirror( ArtifactRepository repository, List mirrors ); + Mirror getMirror(ArtifactRepository repository, List mirrors); /** * Injects the mirroring information into the specified repositories. For each repository that is matched by a @@ -115,7 +111,7 @@ public interface RepositorySystem * @param repositories The repositories into which to inject the mirror information, may be {@code null}. * @param mirrors The available mirrors, may be {@code null}. */ - void injectMirror( List repositories, List mirrors ); + void injectMirror(List repositories, List mirrors); /** * Injects the proxy information into the specified repositories. For each repository that is matched by a proxy, @@ -126,7 +122,7 @@ public interface RepositorySystem * @param repositories The repositories into which to inject the proxy information, may be {@code null}. * @param proxies The available proxies, may be {@code null}. */ - void injectProxy( List repositories, List proxies ); + void injectProxy(List repositories, List proxies); /** * Injects the authentication information into the specified repositories. For each repository that is matched by a @@ -137,15 +133,15 @@ public interface RepositorySystem * @param repositories The repositories into which to inject the authentication information, may be {@code null}. * @param servers The available servers, may be {@code null}. */ - void injectAuthentication( List repositories, List servers ); + void injectAuthentication(List repositories, List servers); - void injectMirror( RepositorySystemSession session, List repositories ); + void injectMirror(RepositorySystemSession session, List repositories); - void injectProxy( RepositorySystemSession session, List repositories ); + void injectProxy(RepositorySystemSession session, List repositories); - void injectAuthentication( RepositorySystemSession session, List repositories ); + void injectAuthentication(RepositorySystemSession session, List repositories); - ArtifactResolutionResult resolve( ArtifactResolutionRequest request ); + ArtifactResolutionResult resolve(ArtifactResolutionRequest request); // Install @@ -156,12 +152,14 @@ public interface RepositorySystem // // Raw file transfers // - void publish( ArtifactRepository repository, File source, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException; - - void retrieve( ArtifactRepository repository, File destination, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException, ArtifactDoesNotExistException; + void publish( + ArtifactRepository repository, File source, String remotePath, ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException; + void retrieve( + ArtifactRepository repository, + File destination, + String remotePath, + ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException, ArtifactDoesNotExistException; } diff --git a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/AbstractArtifactMetadata.java b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/AbstractArtifactMetadata.java index 36bde148f5..65a2e98533 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/AbstractArtifactMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/AbstractArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import org.apache.maven.artifact.Artifact; @@ -26,41 +25,34 @@ import org.apache.maven.artifact.Artifact; * * @author Brett Porter */ -public abstract class AbstractArtifactMetadata - implements ArtifactMetadata -{ +public abstract class AbstractArtifactMetadata implements ArtifactMetadata { private static final String LS = System.lineSeparator(); protected Artifact artifact; - protected AbstractArtifactMetadata( Artifact artifact ) - { + protected AbstractArtifactMetadata(Artifact artifact) { this.artifact = artifact; } - public boolean storedInGroupDirectory() - { + public boolean storedInGroupDirectory() { return false; } - public String getGroupId() - { + public String getGroupId() { return artifact.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return artifact.getArtifactId(); } - public String extendedToString() - { - StringBuilder buffer = new StringBuilder( 256 ); + public String extendedToString() { + StringBuilder buffer = new StringBuilder(256); - buffer.append( LS ).append( "Artifact Metadata" ).append( LS ).append( "--------------------------" ); - buffer.append( LS ).append( "GroupId: " ).append( getGroupId() ); - buffer.append( LS ).append( "ArtifactId: " ).append( getArtifactId() ); - buffer.append( LS ).append( "Metadata Type: " ).append( getClass().getName() ); + buffer.append(LS).append("Artifact Metadata").append(LS).append("--------------------------"); + buffer.append(LS).append("GroupId: ").append(getGroupId()); + buffer.append(LS).append("ArtifactId: ").append(getArtifactId()); + buffer.append(LS).append("Metadata Type: ").append(getClass().getName()); return buffer.toString(); } diff --git a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataRetrievalException.java b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataRetrievalException.java index bc8ceacdc5..616a6e5464 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataRetrievalException.java +++ b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataRetrievalException.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.metadata; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import org.apache.maven.artifact.Artifact; @@ -26,9 +25,7 @@ import org.apache.maven.artifact.Artifact; * * @author Jason van Zyl */ -public class ArtifactMetadataRetrievalException - extends Exception -{ +public class ArtifactMetadataRetrievalException extends Exception { private Artifact artifact; /** @@ -36,9 +33,8 @@ public class ArtifactMetadataRetrievalException * @deprecated use {@link #ArtifactMetadataRetrievalException(String, Throwable, Artifact)} */ @Deprecated - public ArtifactMetadataRetrievalException( String message ) - { - this( message, null, null ); + public ArtifactMetadataRetrievalException(String message) { + this(message, null, null); } /** @@ -46,9 +42,8 @@ public class ArtifactMetadataRetrievalException * @deprecated use {@link #ArtifactMetadataRetrievalException(String, Throwable, Artifact)} */ @Deprecated - public ArtifactMetadataRetrievalException( Throwable cause ) - { - this( null, cause, null ); + public ArtifactMetadataRetrievalException(Throwable cause) { + this(null, cause, null); } /** @@ -57,22 +52,16 @@ public class ArtifactMetadataRetrievalException * @deprecated use {@link #ArtifactMetadataRetrievalException(String, Throwable, Artifact)} */ @Deprecated - public ArtifactMetadataRetrievalException( String message, - Throwable cause ) - { - this( message, cause, null ); + public ArtifactMetadataRetrievalException(String message, Throwable cause) { + this(message, cause, null); } - public ArtifactMetadataRetrievalException( String message, - Throwable cause, - Artifact artifact ) - { - super( message, cause ); + public ArtifactMetadataRetrievalException(String message, Throwable cause, Artifact artifact) { + super(message, cause); this.artifact = artifact; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } } diff --git a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataSource.java b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataSource.java index e46e33ba85..2ef71a17f7 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataSource.java +++ b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ArtifactMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.metadata; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -31,15 +29,13 @@ import org.apache.maven.artifact.versioning.ArtifactVersion; * * @author Jason van Zyl */ -public interface ArtifactMetadataSource -{ +public interface ArtifactMetadataSource { - ResolutionGroup retrieve( MetadataResolutionRequest request ) - throws ArtifactMetadataRetrievalException; + ResolutionGroup retrieve(MetadataResolutionRequest request) throws ArtifactMetadataRetrievalException; - ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException; + ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException; /** * Get a list of available versions for an artifact in the remote repository @@ -53,9 +49,9 @@ public interface ArtifactMetadataSource * @throws ArtifactMetadataRetrievalException * in case of error while retrieving repository metadata from the repository. */ - List retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException; + List retrieveAvailableVersions( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException; /** * Get a list of available versions for an artifact in the remote deployment repository. This ignores any update @@ -70,9 +66,7 @@ public interface ArtifactMetadataSource * @throws ArtifactMetadataRetrievalException * in case of error while retrieving repository metadata from the repository. */ - List retrieveAvailableVersionsFromDeploymentRepository( Artifact artifact, - ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) - throws ArtifactMetadataRetrievalException; - -} \ No newline at end of file + List retrieveAvailableVersionsFromDeploymentRepository( + Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws ArtifactMetadataRetrievalException; +} diff --git a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/DefaultMetadataResolutionRequest.java b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/DefaultMetadataResolutionRequest.java index 93b9d5da4b..6356b7889d 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/DefaultMetadataResolutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/DefaultMetadataResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.DefaultRepositoryRequest; @@ -32,9 +30,7 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; * * @author Benjamin Bentmann */ -public class DefaultMetadataResolutionRequest - implements MetadataResolutionRequest -{ +public class DefaultMetadataResolutionRequest implements MetadataResolutionRequest { private Artifact artifact; @@ -42,91 +38,75 @@ public class DefaultMetadataResolutionRequest private RepositoryRequest repositoryRequest; - public DefaultMetadataResolutionRequest() - { + public DefaultMetadataResolutionRequest() { repositoryRequest = new DefaultRepositoryRequest(); } - public DefaultMetadataResolutionRequest( RepositoryRequest repositoryRequest ) - { - this.repositoryRequest = new DefaultRepositoryRequest( repositoryRequest ); + public DefaultMetadataResolutionRequest(RepositoryRequest repositoryRequest) { + this.repositoryRequest = new DefaultRepositoryRequest(repositoryRequest); } - public DefaultMetadataResolutionRequest( ArtifactResolutionRequest resolutionRequest ) - { - this.repositoryRequest = new DefaultRepositoryRequest( resolutionRequest ); + public DefaultMetadataResolutionRequest(ArtifactResolutionRequest resolutionRequest) { + this.repositoryRequest = new DefaultRepositoryRequest(resolutionRequest); } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public DefaultMetadataResolutionRequest setArtifact( Artifact artifact ) - { + public DefaultMetadataResolutionRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return repositoryRequest.getLocalRepository(); } - public DefaultMetadataResolutionRequest setLocalRepository( ArtifactRepository localRepository ) - { - repositoryRequest.setLocalRepository( localRepository ); + public DefaultMetadataResolutionRequest setLocalRepository(ArtifactRepository localRepository) { + repositoryRequest.setLocalRepository(localRepository); return this; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return repositoryRequest.getRemoteRepositories(); } - public DefaultMetadataResolutionRequest setRemoteRepositories( List remoteRepositories ) - { - repositoryRequest.setRemoteRepositories( remoteRepositories ); + public DefaultMetadataResolutionRequest setRemoteRepositories(List remoteRepositories) { + repositoryRequest.setRemoteRepositories(remoteRepositories); return this; } - public boolean isResolveManagedVersions() - { + public boolean isResolveManagedVersions() { return resolveManagedVersions; } - public DefaultMetadataResolutionRequest setResolveManagedVersions( boolean resolveManagedVersions ) - { + public DefaultMetadataResolutionRequest setResolveManagedVersions(boolean resolveManagedVersions) { this.resolveManagedVersions = resolveManagedVersions; return this; } - public boolean isOffline() - { + public boolean isOffline() { return repositoryRequest.isOffline(); } - public DefaultMetadataResolutionRequest setOffline( boolean offline ) - { - repositoryRequest.setOffline( offline ); + public DefaultMetadataResolutionRequest setOffline(boolean offline) { + repositoryRequest.setOffline(offline); return this; } - public boolean isForceUpdate() - { + public boolean isForceUpdate() { return repositoryRequest.isForceUpdate(); } - public DefaultMetadataResolutionRequest setForceUpdate( boolean forceUpdate ) - { - repositoryRequest.setForceUpdate( forceUpdate ); + public DefaultMetadataResolutionRequest setForceUpdate(boolean forceUpdate) { + repositoryRequest.setForceUpdate(forceUpdate); return this; } - } diff --git a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/MetadataResolutionRequest.java b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/MetadataResolutionRequest.java index 028c4d4025..734de97bd0 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/MetadataResolutionRequest.java +++ b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/MetadataResolutionRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.RepositoryRequest; @@ -30,9 +28,7 @@ import org.apache.maven.artifact.repository.RepositoryRequest; * * @author Benjamin Bentmann */ -public interface MetadataResolutionRequest - extends RepositoryRequest -{ +public interface MetadataResolutionRequest extends RepositoryRequest { /** * Indicates whether network access to remote repositories has been disabled. @@ -47,7 +43,7 @@ public interface MetadataResolutionRequest * @param offline {@code true} to disable remote access, {@code false} to allow network access. * @return This request, never {@code null}. */ - MetadataResolutionRequest setOffline( boolean offline ); + MetadataResolutionRequest setOffline(boolean offline); /** * Gets the artifact to resolve metadata for. @@ -62,7 +58,7 @@ public interface MetadataResolutionRequest * @param artifact The artifact for which to resolve metadata. * @return This request, never {@code null}. */ - MetadataResolutionRequest setArtifact( Artifact artifact ); + MetadataResolutionRequest setArtifact(Artifact artifact); /** * Gets the local repository to use for the resolution. @@ -77,7 +73,7 @@ public interface MetadataResolutionRequest * @param localRepository The local repository to use for the resolution. * @return This request, never {@code null}. */ - MetadataResolutionRequest setLocalRepository( ArtifactRepository localRepository ); + MetadataResolutionRequest setLocalRepository(ArtifactRepository localRepository); /** * Gets the remote repositories to use for the resolution. @@ -92,7 +88,7 @@ public interface MetadataResolutionRequest * @param remoteRepositories The remote repositories to use for the resolution. * @return This request, never {@code null}. */ - MetadataResolutionRequest setRemoteRepositories( List remoteRepositories ); + MetadataResolutionRequest setRemoteRepositories(List remoteRepositories); /** * Determines whether the managed version information should be retrieved. @@ -108,6 +104,5 @@ public interface MetadataResolutionRequest * false} otherwise. * @return This request, never {@code null}. */ - MetadataResolutionRequest setResolveManagedVersions( boolean resolveManagedVersions ); - + MetadataResolutionRequest setResolveManagedVersions(boolean resolveManagedVersions); } diff --git a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ResolutionGroup.java b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ResolutionGroup.java index ae1019a6fd..ef51f63eea 100644 --- a/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ResolutionGroup.java +++ b/maven-core/src/main/java/org/apache/maven/repository/legacy/metadata/ResolutionGroup.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository.legacy.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.repository.legacy.metadata; * "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 + * 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 @@ -18,19 +16,18 @@ package org.apache.maven.repository.legacy.metadata; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository.legacy.metadata; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; /** * ResolutionGroup */ -public class ResolutionGroup -{ +public class ResolutionGroup { private final Set artifacts; @@ -42,15 +39,17 @@ public class ResolutionGroup private final Map managedVersions; - public ResolutionGroup( Artifact pomArtifact, Set artifacts, - List resolutionRepositories ) - { - this( pomArtifact, null, artifacts, null, resolutionRepositories ); + public ResolutionGroup( + Artifact pomArtifact, Set artifacts, List resolutionRepositories) { + this(pomArtifact, null, artifacts, null, resolutionRepositories); } - public ResolutionGroup( Artifact pomArtifact, Artifact relocatedArtifact, Set artifacts, - Map managedVersions, List resolutionRepositories ) - { + public ResolutionGroup( + Artifact pomArtifact, + Artifact relocatedArtifact, + Set artifacts, + Map managedVersions, + List resolutionRepositories) { this.pomArtifact = pomArtifact; this.relocatedArtifact = relocatedArtifact; this.artifacts = artifacts; @@ -58,29 +57,23 @@ public class ResolutionGroup this.resolutionRepositories = resolutionRepositories; } - public Artifact getPomArtifact() - { + public Artifact getPomArtifact() { return pomArtifact; } - public Artifact getRelocatedArtifact() - { + public Artifact getRelocatedArtifact() { return relocatedArtifact; } - public Set getArtifacts() - { + public Set getArtifacts() { return artifacts; } - public List getResolutionRepositories() - { + public List getResolutionRepositories() { return resolutionRepositories; } - public Map getManagedVersions() - { + public Map getManagedVersions() { return managedVersions; } - } diff --git a/maven-core/src/main/java/org/apache/maven/rtinfo/RuntimeInformation.java b/maven-core/src/main/java/org/apache/maven/rtinfo/RuntimeInformation.java index 4e3520dbfe..847c8b09f8 100644 --- a/maven-core/src/main/java/org/apache/maven/rtinfo/RuntimeInformation.java +++ b/maven-core/src/main/java/org/apache/maven/rtinfo/RuntimeInformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.rtinfo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,14 @@ package org.apache.maven.rtinfo; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.rtinfo; /** * Provides information about the current Maven runtime. * * @since 3.0.2 */ -public interface RuntimeInformation -{ +public interface RuntimeInformation { /** * Retrieves the current Maven version, for example "3.0.2". @@ -44,6 +42,5 @@ public interface RuntimeInformation * @throws IllegalArgumentException If the specified version range is {@code null}, empty or otherwise not a valid * version specification. */ - boolean isMavenVersion( String versionRange ); - + boolean isMavenVersion(String versionRange); } diff --git a/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java b/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java index fc0a8bfe10..3593aefd04 100644 --- a/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java +++ b/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java @@ -1,5 +1,3 @@ -package org.apache.maven.rtinfo.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,7 +16,14 @@ package org.apache.maven.rtinfo.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.rtinfo.internal; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.maven.rtinfo.RuntimeInformation; @@ -29,117 +34,82 @@ import org.eclipse.aether.version.VersionScheme; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - /** * Provides information about the current Maven runtime. */ @Named @Singleton -public class DefaultRuntimeInformation - implements RuntimeInformation -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultRuntimeInformation implements RuntimeInformation { + private final Logger logger = LoggerFactory.getLogger(getClass()); private final VersionScheme versionScheme; private final String mavenVersion; @Inject - public DefaultRuntimeInformation( final VersionScheme versionScheme ) - { + public DefaultRuntimeInformation(final VersionScheme versionScheme) { this.versionScheme = versionScheme; this.mavenVersion = loadMavenVersion(); } @Override - public String getMavenVersion() - { + public String getMavenVersion() { return mavenVersion; } - private String loadMavenVersion() - { + private String loadMavenVersion() { Properties props = new Properties(); String resource = "META-INF/maven/org.apache.maven/maven-core/pom.properties"; - try ( InputStream is = DefaultRuntimeInformation.class.getResourceAsStream( "/" + resource ) ) - { - if ( is != null ) - { - props.load( is ); + try (InputStream is = DefaultRuntimeInformation.class.getResourceAsStream("/" + resource)) { + if (is != null) { + props.load(is); + } else { + logger.warn("Could not locate " + resource + " on classpath, Maven runtime information not available"); } - else - { - logger.warn( - "Could not locate " + resource + " on classpath, Maven runtime information not available" ); - } - } - catch ( IOException e ) - { + } catch (IOException e) { String msg = "Could not parse " + resource + ", Maven runtime information not available"; - if ( logger.isDebugEnabled() ) - { - logger.warn( msg, e ); - } - else - { - logger.warn( msg ); + if (logger.isDebugEnabled()) { + logger.warn(msg, e); + } else { + logger.warn(msg); } } - String version = props.getProperty( "version", "" ).trim(); + String version = props.getProperty("version", "").trim(); - if ( !version.startsWith( "${" ) ) - { + if (!version.startsWith("${")) { return version; - } - else - { + } else { return ""; } } @Override - public boolean isMavenVersion( String versionRange ) - { - Validate.notBlank( versionRange, "versionRange can neither be null, empty nor blank" ); + public boolean isMavenVersion(String versionRange) { + Validate.notBlank(versionRange, "versionRange can neither be null, empty nor blank"); VersionConstraint constraint; - try - { - constraint = versionScheme.parseVersionConstraint( versionRange ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( e.getMessage(), e ); + try { + constraint = versionScheme.parseVersionConstraint(versionRange); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException(e.getMessage(), e); } Version current; - try - { + try { String mavenVersion = getMavenVersion(); - Validate.validState( StringUtils.isNotEmpty( mavenVersion ), "Could not determine current Maven version" ); + Validate.validState(StringUtils.isNotEmpty(mavenVersion), "Could not determine current Maven version"); - current = versionScheme.parseVersion( mavenVersion ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalStateException( "Could not parse current Maven version: " + e.getMessage(), e ); + current = versionScheme.parseVersion(mavenVersion); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalStateException("Could not parse current Maven version: " + e.getMessage(), e); } - if ( constraint.getRange() == null ) - { - return constraint.getVersion().compareTo( current ) <= 0; + if (constraint.getRange() == null) { + return constraint.getVersion().compareTo(current) <= 0; } - return constraint.containsVersion( current ); + return constraint.containsVersion(current); } - } diff --git a/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java b/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java index 7bbf477988..546cc980e0 100644 --- a/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java +++ b/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java @@ -1,5 +1,3 @@ -package org.apache.maven.session.scope.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,124 +16,102 @@ package org.apache.maven.session.scope.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.session.scope.internal; +import com.google.inject.Key; +import com.google.inject.OutOfScopeException; +import com.google.inject.Provider; +import com.google.inject.Scope; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; -import com.google.inject.Key; -import com.google.inject.OutOfScopeException; -import com.google.inject.Provider; -import com.google.inject.Scope; - /** * SessionScope */ -public class SessionScope - implements Scope -{ +public class SessionScope implements Scope { - private static final Provider SEEDED_KEY_PROVIDER = () -> - { + private static final Provider SEEDED_KEY_PROVIDER = () -> { throw new IllegalStateException(); }; /** * ScopeState */ - protected static final class ScopeState - { + protected static final class ScopeState { private final Map, CachingProvider> provided = new ConcurrentHashMap<>(); - public void seed( Class clazz, Provider value ) - { - provided.put( Key.get( clazz ), new CachingProvider<>( value ) ); + public void seed(Class clazz, Provider value) { + provided.put(Key.get(clazz), new CachingProvider<>(value)); } - @SuppressWarnings( "unchecked" ) - public Provider scope( Key key, Provider unscoped ) - { - Provider provider = provided.computeIfAbsent( key, k -> new CachingProvider<>( unscoped ) ); - return ( Provider ) provider; + @SuppressWarnings("unchecked") + public Provider scope(Key key, Provider unscoped) { + Provider provider = provided.computeIfAbsent(key, k -> new CachingProvider<>(unscoped)); + return (Provider) provider; } - public Collection> providers() - { + public Collection> providers() { return provided.values(); } } private final List values = new CopyOnWriteArrayList<>(); - public void enter() - { - values.add( 0, new ScopeState() ); + public void enter() { + values.add(0, new ScopeState()); } - protected ScopeState getScopeState() - { - if ( values.isEmpty() ) - { - throw new OutOfScopeException( "Cannot access session scope outside of a scoping block" ); + protected ScopeState getScopeState() { + if (values.isEmpty()) { + throw new OutOfScopeException("Cannot access session scope outside of a scoping block"); } - return values.get( 0 ); + return values.get(0); } - public void exit() - { - if ( values.isEmpty() ) - { + public void exit() { + if (values.isEmpty()) { throw new IllegalStateException(); } - values.remove( 0 ); + values.remove(0); } - public void seed( Class clazz, Provider value ) - { - getScopeState().seed( clazz, value ); + public void seed(Class clazz, Provider value) { + getScopeState().seed(clazz, value); } - public void seed( Class clazz, final T value ) - { - seed( clazz, ( Provider ) () -> value ); + public void seed(Class clazz, final T value) { + seed(clazz, (Provider) () -> value); } - public Provider scope( final Key key, final Provider unscoped ) - { + public Provider scope(final Key key, final Provider unscoped) { // Lazy evaluating provider - return () -> getScopeState().scope( key, unscoped ).get(); + return () -> getScopeState().scope(key, unscoped).get(); } /** * A provider wrapping an existing provider with a cache * @param the provided type */ - protected static class CachingProvider implements Provider - { + protected static class CachingProvider implements Provider { private final Provider provider; private volatile T value; - CachingProvider( Provider provider ) - { + CachingProvider(Provider provider) { this.provider = provider; } - public T value() - { + public T value() { return value; } @Override - public T get() - { - if ( value == null ) - { - synchronized ( this ) - { - if ( value == null ) - { + public T get() { + if (value == null) { + synchronized (this) { + if (value == null) { value = provider.get(); } } @@ -144,9 +120,8 @@ public class SessionScope } } - @SuppressWarnings( { "unchecked" } ) - public static Provider seededKeyProvider() - { + @SuppressWarnings({"unchecked"}) + public static Provider seededKeyProvider() { return (Provider) SEEDED_KEY_PROVIDER; } } diff --git a/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScopeModule.java b/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScopeModule.java index 650fd512db..f2c2e00437 100644 --- a/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScopeModule.java +++ b/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScopeModule.java @@ -1,5 +1,3 @@ -package org.apache.maven.session.scope.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.session.scope.internal; * "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 + * 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 @@ -18,10 +16,11 @@ package org.apache.maven.session.scope.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.session.scope.internal; +import com.google.inject.AbstractModule; import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.SessionScoped; import org.apache.maven.api.Session; import org.apache.maven.execution.MavenSession; @@ -29,42 +28,33 @@ import org.apache.maven.internal.impl.DefaultSession; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import com.google.inject.AbstractModule; - /** * SessionScopeModule */ @Named -public class SessionScopeModule - extends AbstractModule -{ +public class SessionScopeModule extends AbstractModule { private final SessionScope scope; @Inject - public SessionScopeModule() - { - this( new SessionScope() ); + public SessionScopeModule() { + this(new SessionScope()); } - public SessionScopeModule( PlexusContainer container ) - throws ComponentLookupException - { - this( container.lookup( SessionScope.class ) ); + public SessionScopeModule(PlexusContainer container) throws ComponentLookupException { + this(container.lookup(SessionScope.class)); } - private SessionScopeModule( SessionScope scope ) - { + private SessionScopeModule(SessionScope scope) { this.scope = scope; } @Override - protected void configure() - { - bindScope( SessionScoped.class, scope ); - bind( SessionScope.class ).toInstance( scope ); + protected void configure() { + bindScope(SessionScoped.class, scope); + bind(SessionScope.class).toInstance(scope); - bind( MavenSession.class ).toProvider( SessionScope.seededKeyProvider() ).in( scope ); - bind( Session.class ).toProvider( SessionScope.seededKeyProvider() ).in( scope ); - bind( DefaultSession.class ).toProvider( SessionScope.seededKeyProvider() ).in( scope ); + bind(MavenSession.class).toProvider(SessionScope.seededKeyProvider()).in(scope); + bind(Session.class).toProvider(SessionScope.seededKeyProvider()).in(scope); + bind(DefaultSession.class).toProvider(SessionScope.seededKeyProvider()).in(scope); } } diff --git a/maven-core/src/main/java/org/apache/maven/settings/DefaultMavenSettingsBuilder.java b/maven-core/src/main/java/org/apache/maven/settings/DefaultMavenSettingsBuilder.java index 2f2c4075e7..997b61bec8 100644 --- a/maven-core/src/main/java/org/apache/maven/settings/DefaultMavenSettingsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/settings/DefaultMavenSettingsBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.settings; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; import java.io.File; import java.io.IOException; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.properties.internal.SystemProperties; import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; @@ -41,83 +38,62 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; */ @Named @Singleton -public class DefaultMavenSettingsBuilder - extends AbstractLogEnabled - implements MavenSettingsBuilder -{ +public class DefaultMavenSettingsBuilder extends AbstractLogEnabled implements MavenSettingsBuilder { private final SettingsBuilder settingsBuilder; @Inject - public DefaultMavenSettingsBuilder( SettingsBuilder settingsBuilder ) - { + public DefaultMavenSettingsBuilder(SettingsBuilder settingsBuilder) { this.settingsBuilder = settingsBuilder; } - public Settings buildSettings() - throws IOException, XmlPullParserException - { - File userSettingsFile = - getFile( "${user.home}/.m2/settings.xml", "user.home", - MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION ); + public Settings buildSettings() throws IOException, XmlPullParserException { + File userSettingsFile = getFile( + "${user.home}/.m2/settings.xml", "user.home", MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION); - return buildSettings( userSettingsFile ); + return buildSettings(userSettingsFile); } - public Settings buildSettings( boolean useCachedSettings ) - throws IOException, XmlPullParserException - { + public Settings buildSettings(boolean useCachedSettings) throws IOException, XmlPullParserException { return buildSettings(); } - public Settings buildSettings( File userSettingsFile ) - throws IOException, XmlPullParserException - { - File globalSettingsFile = - getFile( "${maven.conf}/settings.xml", "maven.conf", - MavenSettingsBuilder.ALT_GLOBAL_SETTINGS_XML_LOCATION ); + public Settings buildSettings(File userSettingsFile) throws IOException, XmlPullParserException { + File globalSettingsFile = getFile( + "${maven.conf}/settings.xml", "maven.conf", MavenSettingsBuilder.ALT_GLOBAL_SETTINGS_XML_LOCATION); SettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); - request.setUserSettingsFile( userSettingsFile ); - request.setGlobalSettingsFile( globalSettingsFile ); - request.setSystemProperties( SystemProperties.getSystemProperties() ); - return build( request ); + request.setUserSettingsFile(userSettingsFile); + request.setGlobalSettingsFile(globalSettingsFile); + request.setSystemProperties(SystemProperties.getSystemProperties()); + return build(request); } - public Settings buildSettings( File userSettingsFile, boolean useCachedSettings ) - throws IOException, XmlPullParserException - { - return buildSettings( userSettingsFile ); + public Settings buildSettings(File userSettingsFile, boolean useCachedSettings) + throws IOException, XmlPullParserException { + return buildSettings(userSettingsFile); } - private Settings build( SettingsBuildingRequest request ) - throws IOException, XmlPullParserException - { - try - { - return settingsBuilder.build( request ).getEffectiveSettings(); - } - catch ( SettingsBuildingException e ) - { - throw new IOException( e.getMessage(), e ); + private Settings build(SettingsBuildingRequest request) throws IOException, XmlPullParserException { + try { + return settingsBuilder.build(request).getEffectiveSettings(); + } catch (SettingsBuildingException e) { + throw new IOException(e.getMessage(), e); } } /** @since 2.1 */ - public Settings buildSettings( MavenExecutionRequest request ) - throws IOException, XmlPullParserException - { + public Settings buildSettings(MavenExecutionRequest request) throws IOException, XmlPullParserException { SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest(); - settingsRequest.setUserSettingsFile( request.getUserSettingsFile() ); - settingsRequest.setGlobalSettingsFile( request.getGlobalSettingsFile() ); - settingsRequest.setUserProperties( request.getUserProperties() ); - settingsRequest.setSystemProperties( request.getSystemProperties() ); + settingsRequest.setUserSettingsFile(request.getUserSettingsFile()); + settingsRequest.setGlobalSettingsFile(request.getGlobalSettingsFile()); + settingsRequest.setUserProperties(request.getUserProperties()); + settingsRequest.setSystemProperties(request.getSystemProperties()); - return build( settingsRequest ); + return build(settingsRequest); } - private File getFile( String pathPattern, String basedirSysProp, String altLocationSysProp ) - { + private File getFile(String pathPattern, String basedirSysProp, String altLocationSysProp) { // ------------------------------------------------------------------------------------- // Alright, here's the justification for all the regexp wizardry below... // @@ -131,23 +107,21 @@ public class DefaultMavenSettingsBuilder // in order to avoid surprises with the File construction... // ------------------------------------------------------------------------------------- - String path = System.getProperty( altLocationSysProp ); + String path = System.getProperty(altLocationSysProp); - if ( StringUtils.isEmpty( path ) ) - { + if (StringUtils.isEmpty(path)) { // TODO This replacing shouldn't be necessary as user.home should be in the // context of the container and thus the value would be interpolated by Plexus - String basedir = System.getProperty( basedirSysProp ); - if ( basedir == null ) - { - basedir = System.getProperty( "user.dir" ); + String basedir = System.getProperty(basedirSysProp); + if (basedir == null) { + basedir = System.getProperty("user.dir"); } - basedir = basedir.replaceAll( "\\\\", "/" ); - basedir = basedir.replaceAll( "\\$", "\\\\\\$" ); + basedir = basedir.replaceAll("\\\\", "/"); + basedir = basedir.replaceAll("\\$", "\\\\\\$"); - path = pathPattern.replaceAll( "\\$\\{" + basedirSysProp + "\\}", basedir ); - path = path.replaceAll( "\\\\", "/" ); + path = pathPattern.replaceAll("\\$\\{" + basedirSysProp + "\\}", basedir); + path = path.replaceAll("\\\\", "/"); // --------------------------------------------------------------------------------- // I'm not sure if this last regexp was really intended to disallow the usage of // network paths as user.home directory. Unfortunately it did. I removed it and @@ -156,7 +130,6 @@ public class DefaultMavenSettingsBuilder // path = path.replaceAll( "//", "/" ); } - return new File( path ).getAbsoluteFile(); + return new File(path).getAbsoluteFile(); } - } diff --git a/maven-core/src/main/java/org/apache/maven/settings/MavenSettingsBuilder.java b/maven-core/src/main/java/org/apache/maven/settings/MavenSettingsBuilder.java index c79a843d91..36d512d90e 100644 --- a/maven-core/src/main/java/org/apache/maven/settings/MavenSettingsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/settings/MavenSettingsBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.settings; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; import java.io.File; import java.io.IOException; - import org.apache.maven.execution.MavenExecutionRequest; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -30,8 +28,7 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; * @author Jason van Zyl */ @Deprecated -public interface MavenSettingsBuilder -{ +public interface MavenSettingsBuilder { String ROLE = MavenSettingsBuilder.class.getName(); @@ -39,16 +36,14 @@ public interface MavenSettingsBuilder String ALT_GLOBAL_SETTINGS_XML_LOCATION = "org.apache.maven.global-settings"; String ALT_LOCAL_REPOSITORY_LOCATION = "maven.repo.local"; - Settings buildSettings( MavenExecutionRequest request ) - throws IOException, XmlPullParserException; + Settings buildSettings(MavenExecutionRequest request) throws IOException, XmlPullParserException; /** * @return a Settings object from the user settings file. * @throws IOException if any * @throws XmlPullParserException if any */ - Settings buildSettings() - throws IOException, XmlPullParserException; + Settings buildSettings() throws IOException, XmlPullParserException; /** * @param useCachedSettings if true, doesn't reload the user settings @@ -56,8 +51,7 @@ public interface MavenSettingsBuilder * @throws IOException if any * @throws XmlPullParserException if any */ - Settings buildSettings( boolean useCachedSettings ) - throws IOException, XmlPullParserException; + Settings buildSettings(boolean useCachedSettings) throws IOException, XmlPullParserException; /** * @param userSettingsFile a given user settings file @@ -65,8 +59,7 @@ public interface MavenSettingsBuilder * @throws IOException if any * @throws XmlPullParserException if any */ - Settings buildSettings( File userSettingsFile ) - throws IOException, XmlPullParserException; + Settings buildSettings(File userSettingsFile) throws IOException, XmlPullParserException; /** * @param userSettingsFile a given user settings file @@ -75,7 +68,5 @@ public interface MavenSettingsBuilder * @throws IOException if any * @throws XmlPullParserException if any */ - Settings buildSettings( File userSettingsFile, boolean useCachedSettings ) - throws IOException, XmlPullParserException; - + Settings buildSettings(File userSettingsFile, boolean useCachedSettings) throws IOException, XmlPullParserException; } diff --git a/maven-core/src/main/java/org/apache/maven/settings/SettingsConfigurationException.java b/maven-core/src/main/java/org/apache/maven/settings/SettingsConfigurationException.java index 7e03bfc66c..dac66ac811 100644 --- a/maven-core/src/main/java/org/apache/maven/settings/SettingsConfigurationException.java +++ b/maven-core/src/main/java/org/apache/maven/settings/SettingsConfigurationException.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.settings; * "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 + * 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 @@ -18,46 +16,41 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; /** * If there was an error in the settings file. * * @author Brett Porter */ -public class SettingsConfigurationException - extends Exception -{ +public class SettingsConfigurationException extends Exception { private int lineNumber; private int columnNumber; - public SettingsConfigurationException( String message ) - { - super( message ); + public SettingsConfigurationException(String message) { + super(message); } - public SettingsConfigurationException( String message, Throwable cause ) - { - super( message, cause ); + public SettingsConfigurationException(String message, Throwable cause) { + super(message, cause); } - public SettingsConfigurationException( String message, Throwable cause, int lineNumber, int columnNumber ) - { - super( message + ( lineNumber > 0 ? System.lineSeparator() + " Line: " + lineNumber : "" ) - + ( columnNumber > 0 ? System.lineSeparator() + " Column: " + columnNumber : "" ), cause ); + public SettingsConfigurationException(String message, Throwable cause, int lineNumber, int columnNumber) { + super( + message + + (lineNumber > 0 ? System.lineSeparator() + " Line: " + lineNumber : "") + + (columnNumber > 0 ? System.lineSeparator() + " Column: " + columnNumber : ""), + cause); this.lineNumber = lineNumber; this.columnNumber = columnNumber; } - public int getColumnNumber() - { + public int getColumnNumber() { return columnNumber; } - public int getLineNumber() - { + public int getLineNumber() { return lineNumber; } - - } diff --git a/maven-core/src/main/java/org/apache/maven/settings/SettingsUtils.java b/maven-core/src/main/java/org/apache/maven/settings/SettingsUtils.java index d6d65a75e3..f60f83b416 100644 --- a/maven-core/src/main/java/org/apache/maven/settings/SettingsUtils.java +++ b/maven-core/src/main/java/org/apache/maven/settings/SettingsUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.settings; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; - import org.apache.maven.api.model.ActivationFile; import org.apache.maven.api.settings.Activation; import org.apache.maven.api.settings.ActivationOS; @@ -38,11 +36,9 @@ import org.apache.maven.settings.merge.MavenSettingsMerger; * * @author Vincent Siveton */ -public final class SettingsUtils -{ +public final class SettingsUtils { - private SettingsUtils() - { + private SettingsUtils() { // don't allow construction. } @@ -51,95 +47,86 @@ public final class SettingsUtils * @param recessive * @param recessiveSourceLevel */ - public static Settings merge( Settings dominant, Settings recessive, String recessiveSourceLevel ) - { - return new MavenSettingsMerger().merge( dominant, recessive, recessiveSourceLevel ); + public static Settings merge(Settings dominant, Settings recessive, String recessiveSourceLevel) { + return new MavenSettingsMerger().merge(dominant, recessive, recessiveSourceLevel); } /** * @param modelProfile * @return a profile */ - public static Profile convertToSettingsProfile( org.apache.maven.model.Profile modelProfile ) - { + public static Profile convertToSettingsProfile(org.apache.maven.model.Profile modelProfile) { Profile.Builder profile = Profile.newBuilder(); - profile.id( modelProfile.getId() ); + profile.id(modelProfile.getId()); org.apache.maven.model.Activation modelActivation = modelProfile.getActivation(); - if ( modelActivation != null ) - { + if (modelActivation != null) { Activation.Builder activation = Activation.newBuilder(); - activation.activeByDefault( modelActivation.isActiveByDefault() ); + activation.activeByDefault(modelActivation.isActiveByDefault()); - activation.jdk( modelActivation.getJdk() ); + activation.jdk(modelActivation.getJdk()); org.apache.maven.model.ActivationProperty modelProp = modelActivation.getProperty(); - if ( modelProp != null ) - { + if (modelProp != null) { ActivationProperty prop = ActivationProperty.newBuilder() - .name( modelProp.getName() ) - .value( modelProp.getValue() ) - .build(); - activation.property( prop ); + .name(modelProp.getName()) + .value(modelProp.getValue()) + .build(); + activation.property(prop); } org.apache.maven.model.ActivationOS modelOs = modelActivation.getOs(); - if ( modelOs != null ) - { + if (modelOs != null) { ActivationOS os = ActivationOS.newBuilder() - .arch( modelOs.getArch() ) - .family( modelOs.getFamily() ) - .name( modelOs.getName() ) - .version( modelOs.getVersion() ) - .build(); + .arch(modelOs.getArch()) + .family(modelOs.getFamily()) + .name(modelOs.getName()) + .version(modelOs.getVersion()) + .build(); - activation.os( os ); + activation.os(os); } org.apache.maven.model.ActivationFile modelFile = modelActivation.getFile(); - if ( modelFile != null ) - { - org.apache.maven.api.settings.ActivationFile file - = org.apache.maven.api.settings.ActivationFile.newBuilder() - .exists( modelFile.getExists() ) - .missing( modelFile.getMissing() ) + if (modelFile != null) { + org.apache.maven.api.settings.ActivationFile file = + org.apache.maven.api.settings.ActivationFile.newBuilder() + .exists(modelFile.getExists()) + .missing(modelFile.getMissing()) .build(); - activation.file( file ); + activation.file(file); } - profile.activation( activation.build() ); + profile.activation(activation.build()); } - profile.properties( modelProfile.getProperties().entrySet().stream() - .collect( Collectors.toMap( e -> e.getKey().toString(), e -> e.getValue().toString() ) ) ); + profile.properties(modelProfile.getProperties().entrySet().stream() + .collect(Collectors.toMap( + e -> e.getKey().toString(), e -> e.getValue().toString()))); List repos = modelProfile.getRepositories(); - if ( repos != null ) - { + if (repos != null) { List repositories = new ArrayList<>(); - for ( org.apache.maven.model.Repository repo : repos ) - { - repositories.add( convertToSettingsRepository( repo ) ); + for (org.apache.maven.model.Repository repo : repos) { + repositories.add(convertToSettingsRepository(repo)); } - profile.repositories( repositories ); + profile.repositories(repositories); } List pluginRepos = modelProfile.getPluginRepositories(); - if ( pluginRepos != null ) - { + if (pluginRepos != null) { List repositories = new ArrayList<>(); - for ( org.apache.maven.model.Repository pluginRepo : pluginRepos ) - { - repositories.add( convertToSettingsRepository( pluginRepo ) ); + for (org.apache.maven.model.Repository pluginRepo : pluginRepos) { + repositories.add(convertToSettingsRepository(pluginRepo)); } - profile.pluginRepositories( repositories ); + profile.pluginRepositories(repositories); } return profile.build(); @@ -149,75 +136,68 @@ public final class SettingsUtils * @param settingsProfile * @return a profile */ - public static org.apache.maven.model.Profile convertFromSettingsProfile( Profile settingsProfile ) - { + public static org.apache.maven.model.Profile convertFromSettingsProfile(Profile settingsProfile) { org.apache.maven.api.model.Profile.Builder profile = org.apache.maven.api.model.Profile.newBuilder(); - profile.id( settingsProfile.getId() ); + profile.id(settingsProfile.getId()); Activation settingsActivation = settingsProfile.getActivation(); - if ( settingsActivation != null ) - { - org.apache.maven.api.model.Activation.Builder activation - = org.apache.maven.api.model.Activation.newBuilder(); + if (settingsActivation != null) { + org.apache.maven.api.model.Activation.Builder activation = + org.apache.maven.api.model.Activation.newBuilder(); - activation.activeByDefault( settingsActivation.isActiveByDefault() ); + activation.activeByDefault(settingsActivation.isActiveByDefault()); - activation.jdk( settingsActivation.getJdk() ); + activation.jdk(settingsActivation.getJdk()); ActivationProperty settingsProp = settingsActivation.getProperty(); - if ( settingsProp != null ) - { - activation.property( org.apache.maven.api.model.ActivationProperty.newBuilder() - .name( settingsProp.getName() ) - .value( settingsProp.getValue() ) - .build() ); + if (settingsProp != null) { + activation.property(org.apache.maven.api.model.ActivationProperty.newBuilder() + .name(settingsProp.getName()) + .value(settingsProp.getValue()) + .build()); } ActivationOS settingsOs = settingsActivation.getOs(); - if ( settingsOs != null ) - { - activation.os( org.apache.maven.api.model.ActivationOS.newBuilder() - .arch( settingsOs.getArch() ) - .family( settingsOs.getFamily() ) - .name( settingsOs.getName() ) - .version( settingsOs.getVersion() ) - .build() ); + if (settingsOs != null) { + activation.os(org.apache.maven.api.model.ActivationOS.newBuilder() + .arch(settingsOs.getArch()) + .family(settingsOs.getFamily()) + .name(settingsOs.getName()) + .version(settingsOs.getVersion()) + .build()); } org.apache.maven.api.settings.ActivationFile settingsFile = settingsActivation.getFile(); - if ( settingsFile != null ) - { - activation.file( ActivationFile.newBuilder() - .exists( settingsFile.getExists() ) - .missing( settingsFile.getMissing() ) - .build() ); + if (settingsFile != null) { + activation.file(ActivationFile.newBuilder() + .exists(settingsFile.getExists()) + .missing(settingsFile.getMissing()) + .build()); } - profile.activation( activation.build() ); + profile.activation(activation.build()); } - profile.properties( settingsProfile.getProperties() ); + profile.properties(settingsProfile.getProperties()); List repos = settingsProfile.getRepositories(); - if ( repos != null ) - { - profile.repositories( repos.stream() - .map( SettingsUtils::convertFromSettingsRepository ) - .collect( Collectors.toList() ) ); + if (repos != null) { + profile.repositories(repos.stream() + .map(SettingsUtils::convertFromSettingsRepository) + .collect(Collectors.toList())); } List pluginRepos = settingsProfile.getPluginRepositories(); - if ( pluginRepos != null ) - { - profile.pluginRepositories( pluginRepos.stream() - .map( SettingsUtils::convertFromSettingsRepository ) - .collect( Collectors.toList() ) ); + if (pluginRepos != null) { + profile.pluginRepositories(pluginRepos.stream() + .map(SettingsUtils::convertFromSettingsRepository) + .collect(Collectors.toList())); } - org.apache.maven.model.Profile value = new org.apache.maven.model.Profile( profile.build() ); - value.setSource( "settings.xml" ); + org.apache.maven.model.Profile value = new org.apache.maven.model.Profile(profile.build()); + value.setSource("settings.xml"); return value; } @@ -225,22 +205,19 @@ public final class SettingsUtils * @param settingsRepo * @return a repository */ - private static org.apache.maven.api.model.Repository convertFromSettingsRepository( Repository settingsRepo ) - { + private static org.apache.maven.api.model.Repository convertFromSettingsRepository(Repository settingsRepo) { org.apache.maven.api.model.Repository.Builder repo = org.apache.maven.api.model.Repository.newBuilder(); - repo.id( settingsRepo.getId() ); - repo.layout( settingsRepo.getLayout() ); - repo.name( settingsRepo.getName() ); - repo.url( settingsRepo.getUrl() ); + repo.id(settingsRepo.getId()); + repo.layout(settingsRepo.getLayout()); + repo.name(settingsRepo.getName()); + repo.url(settingsRepo.getUrl()); - if ( settingsRepo.getSnapshots() != null ) - { - repo.snapshots( convertRepositoryPolicy( settingsRepo.getSnapshots() ) ); + if (settingsRepo.getSnapshots() != null) { + repo.snapshots(convertRepositoryPolicy(settingsRepo.getSnapshots())); } - if ( settingsRepo.getReleases() != null ) - { - repo.releases( convertRepositoryPolicy( settingsRepo.getReleases() ) ); + if (settingsRepo.getReleases() != null) { + repo.releases(convertRepositoryPolicy(settingsRepo.getReleases())); } return repo.build(); @@ -251,12 +228,11 @@ public final class SettingsUtils * @return a RepositoryPolicy */ private static org.apache.maven.api.model.RepositoryPolicy convertRepositoryPolicy( - RepositoryPolicy settingsPolicy ) - { + RepositoryPolicy settingsPolicy) { org.apache.maven.api.model.RepositoryPolicy policy = org.apache.maven.api.model.RepositoryPolicy.newBuilder() - .enabled( Boolean.toString( settingsPolicy.isEnabled() ) ) - .updatePolicy( settingsPolicy.getUpdatePolicy() ) - .checksumPolicy( settingsPolicy.getChecksumPolicy() ) + .enabled(Boolean.toString(settingsPolicy.isEnabled())) + .updatePolicy(settingsPolicy.getUpdatePolicy()) + .checksumPolicy(settingsPolicy.getChecksumPolicy()) .build(); return policy; } @@ -265,18 +241,15 @@ public final class SettingsUtils * @param modelRepo * @return a repository */ - private static Repository convertToSettingsRepository( org.apache.maven.model.Repository modelRepo ) - { + private static Repository convertToSettingsRepository(org.apache.maven.model.Repository modelRepo) { Repository repo = Repository.newBuilder() - .id( modelRepo.getId() ) - .layout( modelRepo.getLayout() ) - .name( modelRepo.getName() ) - .url( modelRepo.getUrl() ) - .snapshots( modelRepo.getSnapshots() != null - ? convertRepositoryPolicy( modelRepo.getSnapshots() ) : null ) - .releases( modelRepo.getReleases() != null - ? convertRepositoryPolicy( modelRepo.getReleases() ) : null ) - .build(); + .id(modelRepo.getId()) + .layout(modelRepo.getLayout()) + .name(modelRepo.getName()) + .url(modelRepo.getUrl()) + .snapshots(modelRepo.getSnapshots() != null ? convertRepositoryPolicy(modelRepo.getSnapshots()) : null) + .releases(modelRepo.getReleases() != null ? convertRepositoryPolicy(modelRepo.getReleases()) : null) + .build(); return repo; } @@ -285,13 +258,12 @@ public final class SettingsUtils * @param modelPolicy * @return a RepositoryPolicy */ - private static RepositoryPolicy convertRepositoryPolicy( org.apache.maven.model.RepositoryPolicy modelPolicy ) - { + private static RepositoryPolicy convertRepositoryPolicy(org.apache.maven.model.RepositoryPolicy modelPolicy) { RepositoryPolicy policy = RepositoryPolicy.newBuilder() - .enabled( modelPolicy.isEnabled() ) - .updatePolicy( modelPolicy.getUpdatePolicy() ) - .checksumPolicy( modelPolicy.getUpdatePolicy() ) - .build(); + .enabled(modelPolicy.isEnabled()) + .updatePolicy(modelPolicy.getUpdatePolicy()) + .checksumPolicy(modelPolicy.getUpdatePolicy()) + .build(); return policy; } @@ -299,12 +271,10 @@ public final class SettingsUtils * @param settings could be null * @return a new instance of settings or null if settings was null. */ - public static org.apache.maven.settings.Settings copySettings( org.apache.maven.settings.Settings settings ) - { - if ( settings == null ) - { + public static org.apache.maven.settings.Settings copySettings(org.apache.maven.settings.Settings settings) { + if (settings == null) { return null; } - return new org.apache.maven.settings.Settings( settings.getDelegate() ); + return new org.apache.maven.settings.Settings(settings.getDelegate()); } } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchain.java b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchain.java index 8b44552b14..ce93dfe7b7 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchain.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchain.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.Properties; import java.util.Objects; - +import java.util.Properties; import org.apache.maven.toolchain.model.ToolchainModel; import org.slf4j.Logger; @@ -36,15 +34,14 @@ import org.slf4j.Logger; * @since 2.0.9 */ public abstract class DefaultToolchain // should have been AbstractToolchain... - implements Toolchain, ToolchainPrivate -{ +implements Toolchain, ToolchainPrivate { private final Logger logger; private String type; private Map provides = new HashMap<>(); - public static final String KEY_TYPE = "type"; //NOI18N + public static final String KEY_TYPE = "type"; // NOI18N private ToolchainModel model; @@ -53,8 +50,7 @@ public abstract class DefaultToolchain // should have been AbstractToolchain... * @param model the model, must not be {@code null} * @param logger the logger, must not be {@code null} */ - protected DefaultToolchain( ToolchainModel model, Logger logger ) - { + protected DefaultToolchain(ToolchainModel model, Logger logger) { this.model = model; this.logger = logger; } @@ -65,119 +61,101 @@ public abstract class DefaultToolchain // should have been AbstractToolchain... * @param type the type * @param logger the logger, must not be {@code null} */ - protected DefaultToolchain( ToolchainModel model, String type, Logger logger ) - { - this( model, logger ); + protected DefaultToolchain(ToolchainModel model, String type, Logger logger) { + this(model, logger); this.type = type; } @Override - public final String getType() - { + public final String getType() { return type != null ? type : model.getType(); } @Override - public final ToolchainModel getModel() - { + public final ToolchainModel getModel() { return model; } - public final void addProvideToken( String type, RequirementMatcher matcher ) - { - provides.put( type, matcher ); + public final void addProvideToken(String type, RequirementMatcher matcher) { + provides.put(type, matcher); } @Override - public boolean matchesRequirements( Map requirements ) - { - for ( Map.Entry requirement : requirements.entrySet() ) - { + public boolean matchesRequirements(Map requirements) { + for (Map.Entry requirement : requirements.entrySet()) { String key = requirement.getKey(); - RequirementMatcher matcher = provides.get( key ); + RequirementMatcher matcher = provides.get(key); - if ( matcher == null ) - { - getLog().debug( "Toolchain " + this + " is missing required property: " + key ); + if (matcher == null) { + getLog().debug("Toolchain " + this + " is missing required property: " + key); return false; } - if ( !matcher.matches( requirement.getValue() ) ) - { - getLog().debug( "Toolchain " + this + " doesn't match required property: " + key ); + if (!matcher.matches(requirement.getValue())) { + getLog().debug("Toolchain " + this + " doesn't match required property: " + key); return false; } } return true; } - protected Logger getLog() - { + protected Logger getLog() { return logger; } @Override - public boolean equals( Object obj ) - { - if ( obj == null ) - { + public boolean equals(Object obj) { + if (obj == null) { return false; } - if ( this == obj ) - { + if (this == obj) { return true; } - if ( !( obj instanceof DefaultToolchain ) ) - { + if (!(obj instanceof DefaultToolchain)) { return false; } DefaultToolchain other = (DefaultToolchain) obj; - if ( !Objects.equals( type, other.type ) ) - { + if (!Objects.equals(type, other.type)) { return false; } Properties thisProvides = this.getModel().getProvides(); Properties otherProvides = other.getModel().getProvides(); - return Objects.equals( thisProvides, otherProvides ); + return Objects.equals(thisProvides, otherProvides); } @Override - public int hashCode() - { - int hashCode = ( type == null ) ? 0 : type.hashCode(); + public int hashCode() { + int hashCode = (type == null) ? 0 : type.hashCode(); - if ( this.getModel().getProvides() != null ) - { + if (this.getModel().getProvides() != null) { hashCode = 31 * hashCode + this.getModel().getProvides().hashCode(); } return hashCode; } @Override - public String toString() - { + public String toString() { StringBuilder builder = new StringBuilder(); - builder.append( "type:" ).append( getType() ); - builder.append( '{' ); + builder.append("type:").append(getType()); + builder.append('{'); - Iterator> providesIter = provides.entrySet().iterator(); - while ( providesIter.hasNext() ) - { + Iterator> providesIter = + provides.entrySet().iterator(); + while (providesIter.hasNext()) { Map.Entry provideEntry = providesIter.next(); - builder.append( provideEntry.getKey() ).append( " = " ).append( provideEntry.getValue() ); - if ( providesIter.hasNext() ) - { - builder.append( ';' ); + builder.append(provideEntry.getKey()).append(" = ").append(provideEntry.getValue()); + if (providesIter.hasNext()) { + builder.append(';'); } } - builder.append( '}' ); + builder.append('}'); return builder.toString(); } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManager.java b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManager.java index 74cb9c6c0b..b6cc966efd 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManager.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,17 +16,18 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; + +import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.project.MavenProject; @@ -36,50 +35,41 @@ import org.apache.maven.toolchain.model.ToolchainModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static java.util.Objects.requireNonNull; - /** * @author mkleint */ @Named @Singleton -public class DefaultToolchainManager - implements ToolchainManager -{ +public class DefaultToolchainManager implements ToolchainManager { protected final Logger logger; // TODO this class is extended, needs refactoring final Map factories; @Inject - public DefaultToolchainManager( Map factories ) - { + public DefaultToolchainManager(Map factories) { this.factories = factories; - this.logger = LoggerFactory.getLogger( DefaultToolchainManager.class ); + this.logger = LoggerFactory.getLogger(DefaultToolchainManager.class); } /** * Ctor needed for UT. */ - DefaultToolchainManager( Map factories, Logger logger ) - { + DefaultToolchainManager(Map factories, Logger logger) { this.factories = factories; - this.logger = requireNonNull( logger ); + this.logger = requireNonNull(logger); } @Override - public Toolchain getToolchainFromBuildContext( String type, MavenSession session ) - { - Map context = retrieveContext( session ); + public Toolchain getToolchainFromBuildContext(String type, MavenSession session) { + Map context = retrieveContext(session); - ToolchainModel model = (ToolchainModel) context.get( getStorageKey( type ) ); + ToolchainModel model = (ToolchainModel) context.get(getStorageKey(type)); - if ( model != null ) - { - List toolchains = selectToolchains( Collections.singletonList( model ), type, null ); + if (model != null) { + List toolchains = selectToolchains(Collections.singletonList(model), type, null); - if ( !toolchains.isEmpty() ) - { - return toolchains.get( 0 ); + if (!toolchains.isEmpty()) { + return toolchains.get(0); } } @@ -87,42 +77,31 @@ public class DefaultToolchainManager } @Override - public List getToolchains( MavenSession session, String type, Map requirements ) - { - List models = session.getRequest().getToolchains().get( type ); + public List getToolchains(MavenSession session, String type, Map requirements) { + List models = session.getRequest().getToolchains().get(type); - return selectToolchains( models, type, requirements ); + return selectToolchains(models, type, requirements); } - private List selectToolchains( List models, String type, - Map requirements ) - { + private List selectToolchains( + List models, String type, Map requirements) { List toolchains = new ArrayList<>(); - if ( models != null ) - { - ToolchainFactory fact = factories.get( type ); + if (models != null) { + ToolchainFactory fact = factories.get(type); - if ( fact == null ) - { - logger.error( "Missing toolchain factory for type: " + type - + ". Possibly caused by misconfigured project." ); - } - else - { - for ( ToolchainModel model : models ) - { - try - { - ToolchainPrivate toolchain = fact.createToolchain( model ); - if ( requirements == null || toolchain.matchesRequirements( requirements ) ) - { - toolchains.add( toolchain ); + if (fact == null) { + logger.error( + "Missing toolchain factory for type: " + type + ". Possibly caused by misconfigured project."); + } else { + for (ToolchainModel model : models) { + try { + ToolchainPrivate toolchain = fact.createToolchain(model); + if (requirements == null || toolchain.matchesRequirements(requirements)) { + toolchains.add(toolchain); } - } - catch ( MisconfiguredToolchainException ex ) - { - logger.error( "Misconfigured toolchain.", ex ); + } catch (MisconfiguredToolchainException ex) { + logger.error("Misconfigured toolchain.", ex); } } } @@ -130,31 +109,26 @@ public class DefaultToolchainManager return toolchains; } - Map retrieveContext( MavenSession session ) - { + Map retrieveContext(MavenSession session) { Map context = null; - if ( session != null ) - { + if (session != null) { PluginDescriptor desc = new PluginDescriptor(); - desc.setGroupId( PluginDescriptor.getDefaultPluginGroupId() ); - desc.setArtifactId( PluginDescriptor.getDefaultPluginArtifactId( "toolchains" ) ); + desc.setGroupId(PluginDescriptor.getDefaultPluginGroupId()); + desc.setArtifactId(PluginDescriptor.getDefaultPluginArtifactId("toolchains")); MavenProject current = session.getCurrentProject(); - if ( current != null ) - { - //TODO why is this using the context - context = session.getPluginContext( desc, current ); + if (current != null) { + // TODO why is this using the context + context = session.getPluginContext(desc, current); } } - return ( context != null ) ? context : new HashMap<>(); + return (context != null) ? context : new HashMap<>(); } - public static final String getStorageKey( String type ) - { + public static final String getStorageKey(String type) { return "toolchain-" + type; // NOI18N } - } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java index bd4df0188b..28e382d3ce 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,17 +16,16 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import java.util.ArrayList; import java.util.List; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - -import org.apache.maven.execution.MavenSession; import org.apache.maven.api.toolchain.ToolchainModel; +import org.apache.maven.execution.MavenSession; import org.slf4j.Logger; /** @@ -39,68 +36,53 @@ import org.slf4j.Logger; */ @Named @Singleton -public class DefaultToolchainManagerPrivate - extends DefaultToolchainManager - implements ToolchainManagerPrivate -{ +public class DefaultToolchainManagerPrivate extends DefaultToolchainManager implements ToolchainManagerPrivate { @Inject - public DefaultToolchainManagerPrivate( Map factories ) - { - super( factories ); + public DefaultToolchainManagerPrivate(Map factories) { + super(factories); } /** * Ctor needed for UT. */ - DefaultToolchainManagerPrivate( Map factories, Logger logger ) - { - super( factories, logger ); + DefaultToolchainManagerPrivate(Map factories, Logger logger) { + super(factories, logger); } @Override - public ToolchainPrivate[] getToolchainsForType( String type, MavenSession session ) - throws MisconfiguredToolchainException - { + public ToolchainPrivate[] getToolchainsForType(String type, MavenSession session) + throws MisconfiguredToolchainException { List toRet = new ArrayList<>(); - ToolchainFactory fact = factories.get( type ); - if ( fact == null ) - { - logger.error( "Missing toolchain factory for type: " + type - + ". Possibly caused by misconfigured project." ); - } - else - { + ToolchainFactory fact = factories.get(type); + if (fact == null) { + logger.error("Missing toolchain factory for type: " + type + ". Possibly caused by misconfigured project."); + } else { List availableToolchains = org.apache.maven.toolchain.model.ToolchainModel.toolchainModelToApiV4( - session.getRequest().getToolchains().get( type ) ); + session.getRequest().getToolchains().get(type)); - if ( availableToolchains != null ) - { - for ( ToolchainModel toolchainModel : availableToolchains ) - { + if (availableToolchains != null) { + for (ToolchainModel toolchainModel : availableToolchains) { org.apache.maven.toolchain.model.ToolchainModel tm = - new org.apache.maven.toolchain.model.ToolchainModel( toolchainModel ); - toRet.add( fact.createToolchain( tm ) ); + new org.apache.maven.toolchain.model.ToolchainModel(toolchainModel); + toRet.add(fact.createToolchain(tm)); } } // add default toolchain ToolchainPrivate tool = fact.createDefaultToolchain(); - if ( tool != null ) - { - toRet.add( tool ); + if (tool != null) { + toRet.add(tool); } } - return toRet.toArray( new ToolchainPrivate[0] ); + return toRet.toArray(new ToolchainPrivate[0]); } @Override - public void storeToolchainToBuildContext( ToolchainPrivate toolchain, MavenSession session ) - { - Map context = retrieveContext( session ); - context.put( getStorageKey( toolchain.getType() ), toolchain.getModel() ); + public void storeToolchainToBuildContext(ToolchainPrivate toolchain, MavenSession session) { + Map context = retrieveContext(session); + context.put(getStorageKey(toolchain.getType()), toolchain.getModel()); } - } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java index 619aef6c12..5a254a1bc8 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,55 +16,43 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; +import java.io.File; +import java.io.Reader; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.toolchain.PersistedToolchains; import org.apache.maven.toolchain.v4.MavenToolchainsXpp3Reader; import org.codehaus.plexus.util.ReaderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.Reader; - -import javax.inject.Named; -import javax.inject.Singleton; - /** * @author Benjamin Bentmann * @deprecated instead use {@link org.apache.maven.toolchain.building.DefaultToolchainsBuilder} */ @Deprecated -@Named( "default" ) +@Named("default") @Singleton -public class DefaultToolchainsBuilder - implements ToolchainsBuilder -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class DefaultToolchainsBuilder implements ToolchainsBuilder { + private final Logger logger = LoggerFactory.getLogger(getClass()); - public PersistedToolchains build( File userToolchainsFile ) - throws MisconfiguredToolchainException - { + public PersistedToolchains build(File userToolchainsFile) throws MisconfiguredToolchainException { PersistedToolchains toolchains = null; - if ( userToolchainsFile != null && userToolchainsFile.isFile() ) - { - try ( Reader in = ReaderFactory.newXmlReader( userToolchainsFile ) ) - { - toolchains = new MavenToolchainsXpp3Reader().read( in ); - } - catch ( Exception e ) - { + if (userToolchainsFile != null && userToolchainsFile.isFile()) { + try (Reader in = ReaderFactory.newXmlReader(userToolchainsFile)) { + toolchains = new MavenToolchainsXpp3Reader().read(in); + } catch (Exception e) { throw new MisconfiguredToolchainException( - "Cannot read toolchains file at " + userToolchainsFile.getAbsolutePath(), e ); + "Cannot read toolchains file at " + userToolchainsFile.getAbsolutePath(), e); } - } - else if ( userToolchainsFile != null ) - { - logger.debug( "Toolchains configuration was not found at " + userToolchainsFile ); + } else if (userToolchainsFile != null) { + logger.debug("Toolchains configuration was not found at " + userToolchainsFile); } return toolchains; } - } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/MisconfiguredToolchainException.java b/maven-core/src/main/java/org/apache/maven/toolchain/MisconfiguredToolchainException.java index 140bc804ae..e30633d7ad 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/MisconfiguredToolchainException.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/MisconfiguredToolchainException.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,22 +16,19 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; /** * * @author mkleint */ -public class MisconfiguredToolchainException - extends Exception -{ +public class MisconfiguredToolchainException extends Exception { - public MisconfiguredToolchainException( String message ) - { - super( message ); + public MisconfiguredToolchainException(String message) { + super(message); } - public MisconfiguredToolchainException( String message, Throwable orig ) - { - super( message, orig ); + public MisconfiguredToolchainException(String message, Throwable orig) { + super(message, orig); } -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcher.java b/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcher.java index 26390e405c..8547553ccc 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcher.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,13 +16,13 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; /** * * @author mkleint */ -public interface RequirementMatcher -{ +public interface RequirementMatcher { - boolean matches( String requirement ); -} \ No newline at end of file + boolean matches(String requirement); +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcherFactory.java b/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcherFactory.java index 02f5cc0a42..4c7476bdc1 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcherFactory.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcherFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; @@ -27,83 +26,62 @@ import org.apache.maven.artifact.versioning.VersionRange; * * @author mkleint */ -public final class RequirementMatcherFactory -{ - private RequirementMatcherFactory() - { +public final class RequirementMatcherFactory { + private RequirementMatcherFactory() {} + + public static RequirementMatcher createExactMatcher(String provideValue) { + return new ExactMatcher(provideValue); } - public static RequirementMatcher createExactMatcher( String provideValue ) - { - return new ExactMatcher( provideValue ); + public static RequirementMatcher createVersionMatcher(String provideValue) { + return new VersionMatcher(provideValue); } - public static RequirementMatcher createVersionMatcher( String provideValue ) - { - return new VersionMatcher( provideValue ); - } - - private static final class ExactMatcher - implements RequirementMatcher - { + private static final class ExactMatcher implements RequirementMatcher { private String provides; - private ExactMatcher( String provides ) - { + private ExactMatcher(String provides) { this.provides = provides; } @Override - public boolean matches( String requirement ) - { - return provides.equalsIgnoreCase( requirement ); + public boolean matches(String requirement) { + return provides.equalsIgnoreCase(requirement); } @Override - public String toString() - { + public String toString() { return provides; } } - private static final class VersionMatcher - implements RequirementMatcher - { + private static final class VersionMatcher implements RequirementMatcher { DefaultArtifactVersion version; - private VersionMatcher( String version ) - { - this.version = new DefaultArtifactVersion( version ); + private VersionMatcher(String version) { + this.version = new DefaultArtifactVersion(version); } @Override - public boolean matches( String requirement ) - { - try - { - VersionRange range = VersionRange.createFromVersionSpec( requirement ); - if ( range.hasRestrictions() ) - { - return range.containsVersion( version ); + public boolean matches(String requirement) { + try { + VersionRange range = VersionRange.createFromVersionSpec(requirement); + if (range.hasRestrictions()) { + return range.containsVersion(version); + } else { + return range.getRecommendedVersion().compareTo(version) == 0; } - else - { - return range.getRecommendedVersion().compareTo( version ) == 0; - } - } - catch ( InvalidVersionSpecificationException ex ) - { - //TODO error reporting + } catch (InvalidVersionSpecificationException ex) { + // TODO error reporting ex.printStackTrace(); return false; } } @Override - public String toString() - { + public String toString() { return version.toString(); } } -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/Toolchain.java b/maven-core/src/main/java/org/apache/maven/toolchain/Toolchain.java index 2a71346542..121b183ebd 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/Toolchain.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/Toolchain.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; /** * Toolchain interface. @@ -26,8 +25,7 @@ package org.apache.maven.toolchain; * @author Jason van Zyl * @since 2.0.9 */ -public interface Toolchain -{ +public interface Toolchain { /** * get the type of toolchain. @@ -42,5 +40,5 @@ public interface Toolchain * @param toolName the tool platform independent tool name. * @return file representing the tool executable, or null if the tool can not be found */ - String findTool( String toolName ); -} \ No newline at end of file + String findTool(String toolName); +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainFactory.java b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainFactory.java index c99a3cd8ac..7c64944f76 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainFactory.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,7 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.toolchain; import org.apache.maven.toolchain.model.ToolchainModel; @@ -28,13 +26,11 @@ import org.apache.maven.toolchain.model.ToolchainModel; * @author mkleint * @since 2.0.9 */ -public interface ToolchainFactory -{ +public interface ToolchainFactory { /** * Create instance of toolchain. **/ - ToolchainPrivate createToolchain( ToolchainModel model ) - throws MisconfiguredToolchainException; + ToolchainPrivate createToolchain(ToolchainModel model) throws MisconfiguredToolchainException; /** * Returns the default instance of the particular type of toolchain, can return null @@ -42,4 +38,4 @@ public interface ToolchainFactory * TODO keep around?? **/ ToolchainPrivate createDefaultToolchain(); -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManager.java b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManager.java index 134c24da0a..ddd0adfd65 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManager.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,13 +16,12 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import java.util.List; import java.util.Map; - import org.apache.maven.execution.MavenSession; - /** * Public API for a toolchain-aware plugin to get expected toolchain instance. * @@ -32,8 +29,7 @@ import org.apache.maven.execution.MavenSession; * @author Robert Scholte * @since 2.0.9 */ -public interface ToolchainManager -{ +public interface ToolchainManager { // NOTE: Some plugins like Surefire access this field directly! @Deprecated @@ -48,7 +44,7 @@ public interface ToolchainManager * @param context the Maven session, must not be {@code null} * @return the toolchain selected by maven-toolchains-plugin */ - Toolchain getToolchainFromBuildContext( String type, MavenSession context ); + Toolchain getToolchainFromBuildContext(String type, MavenSession context); /** * Select all toolchains available in user settings matching the type and requirements, @@ -60,5 +56,5 @@ public interface ToolchainManager * @return the matching toolchains, never {@code null} * @since 3.3.0 */ - List getToolchains( MavenSession session, String type, Map requirements ); + List getToolchains(MavenSession session, String type, Map requirements); } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManagerPrivate.java b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManagerPrivate.java index ed50bd46ab..0b67e59092 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManagerPrivate.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainManagerPrivate.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import org.apache.maven.execution.MavenSession; @@ -32,8 +31,7 @@ import org.apache.maven.execution.MavenSession; * @since 2.0.9 * @see ToolchainManager#getToolchainFromBuildContext(String, MavenSession) */ -public interface ToolchainManagerPrivate -{ +public interface ToolchainManagerPrivate { /** * Retrieves every toolchains of given type available in user settings. @@ -42,8 +40,7 @@ public interface ToolchainManagerPrivate * @param context the Maven session, must not be {@code null} * @since 3.0 (addition of the MavenSession parameter) */ - ToolchainPrivate[] getToolchainsForType( String type, MavenSession context ) - throws MisconfiguredToolchainException; + ToolchainPrivate[] getToolchainsForType(String type, MavenSession context) throws MisconfiguredToolchainException; /** * Stores the toolchain into build context for later use by toolchain-aware plugins. @@ -53,6 +50,5 @@ public interface ToolchainManagerPrivate * @since 2.0.9 * @see ToolchainManager#getToolchainFromBuildContext(String, MavenSession) */ - void storeToolchainToBuildContext( ToolchainPrivate toolchain, MavenSession context ); - + void storeToolchainToBuildContext(ToolchainPrivate toolchain, MavenSession context); } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainPrivate.java b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainPrivate.java index 90e0f30563..53760b6c95 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainPrivate.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainPrivate.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,18 +16,16 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import java.util.Map; - import org.apache.maven.toolchain.model.ToolchainModel; /** * a private contract between the toolchains plugin and the components. * @author mkleint */ -public interface ToolchainPrivate - extends Toolchain -{ +public interface ToolchainPrivate extends Toolchain { /** * Let the toolchain decide if it matches requirements defined @@ -37,12 +33,11 @@ public interface ToolchainPrivate * @param requirements Map<String, String> key value pair, may not be {@code null} * @return {@code true} if the requirements match, otherwise {@code false} */ - boolean matchesRequirements( Map requirements ); + boolean matchesRequirements(Map requirements); /** * * @return the original model wrapped by this interface */ ToolchainModel getModel(); - -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainsBuilder.java b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainsBuilder.java index 8d4a9787c4..37fadd9c7c 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/ToolchainsBuilder.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import java.io.File; - import org.apache.maven.api.toolchain.PersistedToolchains; /** @@ -29,8 +27,7 @@ import org.apache.maven.api.toolchain.PersistedToolchains; * * @author Benjamin Bentmann */ -public interface ToolchainsBuilder -{ +public interface ToolchainsBuilder { /** * Builds the toolchains model from the configured toolchain files. @@ -40,7 +37,5 @@ public interface ToolchainsBuilder * not exist. * @throws MisconfiguredToolchainException If the toolchain file exists but cannot be parsed. */ - PersistedToolchains build( File userToolchainsFile ) - throws MisconfiguredToolchainException; - + PersistedToolchains build(File userToolchainsFile) throws MisconfiguredToolchainException; } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/java/DefaultJavaToolChain.java b/maven-core/src/main/java/org/apache/maven/toolchain/java/DefaultJavaToolChain.java index e264e601fd..b9341d3060 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/java/DefaultJavaToolChain.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/java/DefaultJavaToolChain.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain.java; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain.java; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain.java; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain.java; import org.apache.maven.toolchain.model.ToolchainModel; import org.slf4j.Logger; @@ -30,26 +29,20 @@ import org.slf4j.Logger; * @deprecated clients that do not require compatibility with Maven 3.2.3 and earlier should link to * {@link JavaToolchainImpl} instead. */ -public class DefaultJavaToolChain - extends JavaToolchainImpl -{ +public class DefaultJavaToolChain extends JavaToolchainImpl { public static final String KEY_JAVAHOME = JavaToolchainImpl.KEY_JAVAHOME; - public DefaultJavaToolChain( ToolchainModel model, Logger logger ) - { - super( model, logger ); + public DefaultJavaToolChain(ToolchainModel model, Logger logger) { + super(model, logger); } @Override - public String getJavaHome() - { + public String getJavaHome() { return super.getJavaHome(); } @Override - public void setJavaHome( String javaHome ) - { - super.setJavaHome( javaHome ); + public void setJavaHome(String javaHome) { + super.setJavaHome(javaHome); } - -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchain.java b/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchain.java index cb14ada17d..dec3988baa 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchain.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchain.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain.java; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain.java; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain.java; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain.java; import org.apache.maven.toolchain.Toolchain; @@ -28,40 +27,38 @@ import org.apache.maven.toolchain.Toolchain; * @author Milos Kleint * @since 2.0.9, renamed from JavaToolChain in 3.2.4 */ -public interface JavaToolchain - extends Toolchain -{ -// /** -// * Returns a list of {@link java.io.File}s which represents the bootstrap libraries for the -// * runtime environment. The Bootstrap libraries include libraries in JRE's -// * extension directory, if there are any. -// * -// * @return List -// */ -// List getBootstrapLibraries(); -// -// /** -// * Returns a list of {@link java.io.File}s which represent the libraries recognized by -// * default by the platform. Usually it corresponds to contents of CLASSPATH -// * environment variable. -// * -// * @return List -// */ -// List getStandardLibraries(); -// -// /** -// * Returns a {@link java.io.File}s which represent the locations of the source of the JDK, -// * or an empty collection when the location is not set or is invalid. -// * -// * @return List -// */ -// List getSourceDirectories(); -// -// /** -// * Returns a {@link java.io.File}s which represent the locations of the Javadoc for this platform, -// * or empty collection if the location is not set or invalid -// * -// * @return List -// */ -// List getJavadocFolders(); +public interface JavaToolchain extends Toolchain { + // /** + // * Returns a list of {@link java.io.File}s which represents the bootstrap libraries for the + // * runtime environment. The Bootstrap libraries include libraries in JRE's + // * extension directory, if there are any. + // * + // * @return List + // */ + // List getBootstrapLibraries(); + // + // /** + // * Returns a list of {@link java.io.File}s which represent the libraries recognized by + // * default by the platform. Usually it corresponds to contents of CLASSPATH + // * environment variable. + // * + // * @return List + // */ + // List getStandardLibraries(); + // + // /** + // * Returns a {@link java.io.File}s which represent the locations of the source of the JDK, + // * or an empty collection when the location is not set or is invalid. + // * + // * @return List + // */ + // List getSourceDirectories(); + // + // /** + // * Returns a {@link java.io.File}s which represent the locations of the Javadoc for this platform, + // * or empty collection if the location is not set or invalid + // * + // * @return List + // */ + // List getJavadocFolders(); } diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainFactory.java b/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainFactory.java index 09c721fa88..f8eb2bd192 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainFactory.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain.java; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain.java; * "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 + * 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 @@ -18,14 +16,13 @@ package org.apache.maven.toolchain.java; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain.java; import java.io.File; import java.util.Map.Entry; import java.util.Properties; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.toolchain.MisconfiguredToolchainException; import org.apache.maven.toolchain.RequirementMatcher; import org.apache.maven.toolchain.RequirementMatcherFactory; @@ -45,84 +42,67 @@ import org.slf4j.LoggerFactory; * @author mkleint * @since 2.0.9, renamed from DefaultJavaToolchainFactory in 3.2.4 */ -@Named( "jdk" ) +@Named("jdk") @Singleton -public class JavaToolchainFactory - implements ToolchainFactory -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public class JavaToolchainFactory implements ToolchainFactory { + private final Logger logger = LoggerFactory.getLogger(getClass()); - public ToolchainPrivate createToolchain( ToolchainModel model ) - throws MisconfiguredToolchainException - { - if ( model == null ) - { + public ToolchainPrivate createToolchain(ToolchainModel model) throws MisconfiguredToolchainException { + if (model == null) { return null; } // use DefaultJavaToolChain for compatibility with maven 3.2.3 and earlier - @SuppressWarnings( "deprecation" ) - JavaToolchainImpl jtc = new DefaultJavaToolChain( model, logger ); + @SuppressWarnings("deprecation") + JavaToolchainImpl jtc = new DefaultJavaToolChain(model, logger); // populate the provides section Properties provides = model.getProvides(); - for ( Entry provide : provides.entrySet() ) - { + for (Entry provide : provides.entrySet()) { String key = (String) provide.getKey(); String value = (String) provide.getValue(); - if ( value == null ) - { + if (value == null) { throw new MisconfiguredToolchainException( - "Provides token '" + key + "' doesn't have any value configured." ); + "Provides token '" + key + "' doesn't have any value configured."); } RequirementMatcher matcher; - if ( "version".equals( key ) ) - { - matcher = RequirementMatcherFactory.createVersionMatcher( value ); - } - else - { - matcher = RequirementMatcherFactory.createExactMatcher( value ); + if ("version".equals(key)) { + matcher = RequirementMatcherFactory.createVersionMatcher(value); + } else { + matcher = RequirementMatcherFactory.createExactMatcher(value); } - jtc.addProvideToken( key, matcher ); + jtc.addProvideToken(key, matcher); } // populate the configuration section - Xpp3Dom dom = ( Xpp3Dom ) model.getConfiguration(); - Xpp3Dom javahome = dom != null ? dom.getChild( JavaToolchainImpl.KEY_JAVAHOME ) : null; - if ( javahome == null ) - { - throw new MisconfiguredToolchainException( "Java toolchain without the " - + JavaToolchainImpl.KEY_JAVAHOME + " configuration element." ); + Xpp3Dom dom = (Xpp3Dom) model.getConfiguration(); + Xpp3Dom javahome = dom != null ? dom.getChild(JavaToolchainImpl.KEY_JAVAHOME) : null; + if (javahome == null) { + throw new MisconfiguredToolchainException( + "Java toolchain without the " + JavaToolchainImpl.KEY_JAVAHOME + " configuration element."); } - File normal = new File( FileUtils.normalize( javahome.getValue() ) ); - if ( normal.exists() ) - { - jtc.setJavaHome( FileUtils.normalize( javahome.getValue() ) ); - } - else - { - throw new MisconfiguredToolchainException( "Non-existing JDK home configuration at " - + normal.getAbsolutePath() ); + File normal = new File(FileUtils.normalize(javahome.getValue())); + if (normal.exists()) { + jtc.setJavaHome(FileUtils.normalize(javahome.getValue())); + } else { + throw new MisconfiguredToolchainException( + "Non-existing JDK home configuration at " + normal.getAbsolutePath()); } return jtc; } - public ToolchainPrivate createDefaultToolchain() - { - //not sure it's necessary to provide a default toolchain here. - //only version can be eventually supplied, and + public ToolchainPrivate createDefaultToolchain() { + // not sure it's necessary to provide a default toolchain here. + // only version can be eventually supplied, and return null; } - protected Logger getLogger() - { + protected Logger getLogger() { return logger; } - -} \ No newline at end of file +} diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainImpl.java b/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainImpl.java index af5a88cc42..543906d708 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainImpl.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainImpl.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain.java; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain.java; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.toolchain.java; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain.java; import java.io.File; - import org.apache.maven.toolchain.DefaultToolchain; import org.apache.maven.toolchain.model.ToolchainModel; import org.codehaus.plexus.util.FileUtils; @@ -33,55 +31,43 @@ import org.slf4j.Logger; * @author Milos Kleint * @since 2.0.9, renamed from DefaultJavaToolChain in 3.2.4 */ -class JavaToolchainImpl - extends DefaultToolchain - implements JavaToolchain -{ +class JavaToolchainImpl extends DefaultToolchain implements JavaToolchain { private String javaHome; - public static final String KEY_JAVAHOME = "jdkHome"; //NOI18N + public static final String KEY_JAVAHOME = "jdkHome"; // NOI18N - JavaToolchainImpl( ToolchainModel model, Logger logger ) - { - super( model, "jdk", logger ); + JavaToolchainImpl(ToolchainModel model, Logger logger) { + super(model, "jdk", logger); } - public String getJavaHome() - { + public String getJavaHome() { return javaHome; } - public void setJavaHome( String javaHome ) - { + public void setJavaHome(String javaHome) { this.javaHome = javaHome; } - public String toString() - { + public String toString() { return "JDK[" + getJavaHome() + "]"; } - public String findTool( String toolName ) - { - File toRet = findTool( toolName, new File( FileUtils.normalize( getJavaHome() ) ) ); - if ( toRet != null ) - { + public String findTool(String toolName) { + File toRet = findTool(toolName, new File(FileUtils.normalize(getJavaHome()))); + if (toRet != null) { return toRet.getAbsolutePath(); } return null; } - private static File findTool( String toolName, File installFolder ) - { - File bin = new File( installFolder, "bin" ); //NOI18N - if ( bin.exists() ) - { - File tool = new File( bin, toolName + ( Os.isFamily( "windows" ) ? ".exe" : "" ) ); // NOI18N - if ( tool.exists() ) - { + private static File findTool(String toolName, File installFolder) { + File bin = new File(installFolder, "bin"); // NOI18N + if (bin.exists()) { + File tool = new File(bin, toolName + (Os.isFamily("windows") ? ".exe" : "")); // NOI18N + if (tool.exists()) { return tool; } } return null; - } -} \ No newline at end of file + } +} diff --git a/maven-core/src/main/java/org/apache/maven/xml/internal/DefaultConsumerPomXMLFilterFactory.java b/maven-core/src/main/java/org/apache/maven/xml/internal/DefaultConsumerPomXMLFilterFactory.java index fa2159199a..715be335f2 100644 --- a/maven-core/src/main/java/org/apache/maven/xml/internal/DefaultConsumerPomXMLFilterFactory.java +++ b/maven-core/src/main/java/org/apache/maven/xml/internal/DefaultConsumerPomXMLFilterFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.xml.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.xml.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.xml.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.xml.internal; import org.apache.maven.model.building.DefaultBuildPomXMLFilterFactory; import org.apache.maven.model.transform.RawToConsumerPomXMLFilterFactory; @@ -29,10 +28,8 @@ import org.apache.maven.model.transform.RawToConsumerPomXMLFilterFactory; * @author Robert Scholte * @since 4.0.0 */ -public class DefaultConsumerPomXMLFilterFactory extends RawToConsumerPomXMLFilterFactory -{ - public DefaultConsumerPomXMLFilterFactory( DefaultBuildPomXMLFilterFactory buildPomXMLFilterFactory ) - { - super( buildPomXMLFilterFactory ); +public class DefaultConsumerPomXMLFilterFactory extends RawToConsumerPomXMLFilterFactory { + public DefaultConsumerPomXMLFilterFactory(DefaultBuildPomXMLFilterFactory buildPomXMLFilterFactory) { + super(buildPomXMLFilterFactory); } } diff --git a/maven-core/src/test/java/org/apache/maven/AbstractCoreMavenComponentTestCase.java b/maven-core/src/test/java/org/apache/maven/AbstractCoreMavenComponentTestCase.java index 4bd6acb350..cc25834e3f 100644 --- a/maven-core/src/test/java/org/apache/maven/AbstractCoreMavenComponentTestCase.java +++ b/maven-core/src/test/java/org/apache/maven/AbstractCoreMavenComponentTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,16 @@ package org.apache.maven; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; -import javax.inject.Inject; +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; - +import javax.inject.Inject; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -55,11 +54,8 @@ import org.eclipse.aether.internal.impl.DefaultRepositorySystem; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; - @PlexusTest -public abstract class AbstractCoreMavenComponentTestCase -{ +public abstract class AbstractCoreMavenComponentTestCase { @Inject protected PlexusContainer container; @@ -70,38 +66,32 @@ public abstract class AbstractCoreMavenComponentTestCase @Inject protected org.apache.maven.project.ProjectBuilder projectBuilder; - abstract protected String getProjectsDirectory(); + protected abstract String getProjectsDirectory(); - protected PlexusContainer getContainer() - { + protected PlexusContainer getContainer() { return container; } - protected File getProject(String name ) - throws Exception - { - File source = new File( new File( getBasedir(), getProjectsDirectory() ), name ); - File target = new File( new File( getBasedir(), "target" ), name ); - FileUtils.copyDirectoryStructureIfModified( source, target ); - return new File( target, "pom.xml" ); + protected File getProject(String name) throws Exception { + File source = new File(new File(getBasedir(), getProjectsDirectory()), name); + File target = new File(new File(getBasedir(), "target"), name); + FileUtils.copyDirectoryStructureIfModified(source, target); + return new File(target, "pom.xml"); } - protected MavenExecutionRequest createMavenExecutionRequest( File pom ) - throws Exception - { + protected MavenExecutionRequest createMavenExecutionRequest(File pom) throws Exception { MavenExecutionRequest request = new DefaultMavenExecutionRequest() - .setPom( pom ) - .setProjectPresent( true ) - .setShowErrors( true ) - .setPluginGroups( Arrays.asList( "org.apache.maven.plugins" ) ) - .setLocalRepository( getLocalRepository() ) - .setRemoteRepositories( getRemoteRepositories() ) - .setPluginArtifactRepositories( getPluginArtifactRepositories() ) - .setGoals( Arrays.asList( "package" ) ); + .setPom(pom) + .setProjectPresent(true) + .setShowErrors(true) + .setPluginGroups(Arrays.asList("org.apache.maven.plugins")) + .setLocalRepository(getLocalRepository()) + .setRemoteRepositories(getRemoteRepositories()) + .setPluginArtifactRepositories(getPluginArtifactRepositories()) + .setGoals(Arrays.asList("package")); - if ( pom != null ) - { - request.setMultiModuleProjectDirectory( pom.getParentFile() ); + if (pom != null) { + request.setMultiModuleProjectDirectory(pom.getParentFile()); } return request; @@ -110,214 +100,183 @@ public abstract class AbstractCoreMavenComponentTestCase // layer the creation of a project builder configuration with a request, but this will need to be // a Maven subclass because we don't want to couple maven to the project builder which we need to // separate. - protected MavenSession createMavenSession( File pom ) - throws Exception - { - return createMavenSession( pom, new Properties() ); + protected MavenSession createMavenSession(File pom) throws Exception { + return createMavenSession(pom, new Properties()); } - protected MavenSession createMavenSession( File pom, Properties executionProperties ) - throws Exception - { - return createMavenSession( pom, executionProperties, false ); + protected MavenSession createMavenSession(File pom, Properties executionProperties) throws Exception { + return createMavenSession(pom, executionProperties, false); } - protected MavenSession createMavenSession( File pom, Properties executionProperties, boolean includeModules ) - throws Exception - { - MavenExecutionRequest request = createMavenExecutionRequest( pom ); + protected MavenSession createMavenSession(File pom, Properties executionProperties, boolean includeModules) + throws Exception { + MavenExecutionRequest request = createMavenExecutionRequest(pom); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest() - .setLocalRepository( request.getLocalRepository() ) - .setRemoteRepositories( request.getRemoteRepositories() ) - .setPluginArtifactRepositories( request.getPluginArtifactRepositories() ) - .setSystemProperties( executionProperties ) - .setUserProperties( new Properties() ); + .setLocalRepository(request.getLocalRepository()) + .setRemoteRepositories(request.getRemoteRepositories()) + .setPluginArtifactRepositories(request.getPluginArtifactRepositories()) + .setSystemProperties(executionProperties) + .setUserProperties(new Properties()); List projects = new ArrayList<>(); - if ( pom != null ) - { - MavenProject project = projectBuilder.build( pom, configuration ).getProject(); + if (pom != null) { + MavenProject project = projectBuilder.build(pom, configuration).getProject(); - projects.add( project ); - if ( includeModules ) - { - for ( String module : project.getModules() ) - { - File modulePom = new File( pom.getParentFile(), module ); - if ( modulePom.isDirectory() ) - { - modulePom = new File( modulePom, "pom.xml" ); + projects.add(project); + if (includeModules) { + for (String module : project.getModules()) { + File modulePom = new File(pom.getParentFile(), module); + if (modulePom.isDirectory()) { + modulePom = new File(modulePom, "pom.xml"); } - projects.add( projectBuilder.build( modulePom, configuration ).getProject() ); + projects.add(projectBuilder.build(modulePom, configuration).getProject()); } } - } - else - { + } else { MavenProject project = createStubMavenProject(); - project.setRemoteArtifactRepositories( request.getRemoteRepositories() ); - project.setPluginArtifactRepositories( request.getPluginArtifactRepositories() ); - projects.add( project ); + project.setRemoteArtifactRepositories(request.getRemoteRepositories()); + project.setPluginArtifactRepositories(request.getPluginArtifactRepositories()); + projects.add(project); } - initRepoSession( configuration ); + initRepoSession(configuration); - MavenSession session = - new MavenSession( getContainer(), configuration.getRepositorySession(), request, - new DefaultMavenExecutionResult() ); - session.setProjects( projects ); - session.setAllProjects( session.getProjects() ); - session.setSession( new DefaultSession( session, new DefaultRepositorySystem(), null, - null, null, null ) ); + MavenSession session = new MavenSession( + getContainer(), configuration.getRepositorySession(), request, new DefaultMavenExecutionResult()); + session.setProjects(projects); + session.setAllProjects(session.getProjects()); + session.setSession(new DefaultSession(session, new DefaultRepositorySystem(), null, null, null, null)); return session; } - protected void initRepoSession( ProjectBuildingRequest request ) - throws Exception - { - File localRepoDir = new File( request.getLocalRepository().getBasedir() ); - LocalRepository localRepo = new LocalRepository( localRepoDir ); + protected void initRepoSession(ProjectBuildingRequest request) throws Exception { + File localRepoDir = new File(request.getLocalRepository().getBasedir()); + LocalRepository localRepo = new LocalRepository(localRepoDir); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - session.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( session, localRepo ) ); - request.setRepositorySession( session ); + session.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepo)); + request.setRepositorySession(session); } - protected MavenProject createStubMavenProject() - { + protected MavenProject createStubMavenProject() { Model model = new Model(); - model.setGroupId( "org.apache.maven.test" ); - model.setArtifactId( "maven-test" ); - model.setVersion( "1.0" ); - return new MavenProject( model ); + model.setGroupId("org.apache.maven.test"); + model.setArtifactId("maven-test"); + model.setVersion("1.0"); + return new MavenProject(model); } - protected List getRemoteRepositories() - throws InvalidRepositoryException - { - File repoDir = new File( getBasedir(), "src/test/remote-repo" ).getAbsoluteFile(); + protected List getRemoteRepositories() throws InvalidRepositoryException { + File repoDir = new File(getBasedir(), "src/test/remote-repo").getAbsoluteFile(); RepositoryPolicy policy = new RepositoryPolicy(); - policy.setEnabled( true ); - policy.setChecksumPolicy( "ignore" ); - policy.setUpdatePolicy( "always" ); + policy.setEnabled(true); + policy.setChecksumPolicy("ignore"); + policy.setUpdatePolicy("always"); Repository repository = new Repository(); - repository.setId( RepositorySystem.DEFAULT_REMOTE_REPO_ID ); - repository.setUrl( "file://" + repoDir.toURI().getPath() ); - repository.setReleases( policy ); - repository.setSnapshots( policy ); + repository.setId(RepositorySystem.DEFAULT_REMOTE_REPO_ID); + repository.setUrl("file://" + repoDir.toURI().getPath()); + repository.setReleases(policy); + repository.setSnapshots(policy); - return Arrays.asList( repositorySystem.buildArtifactRepository( repository ) ); + return Arrays.asList(repositorySystem.buildArtifactRepository(repository)); } - protected List getPluginArtifactRepositories() - throws InvalidRepositoryException - { + protected List getPluginArtifactRepositories() throws InvalidRepositoryException { return getRemoteRepositories(); } - protected ArtifactRepository getLocalRepository() - throws InvalidRepositoryException - { - File repoDir = new File( getBasedir(), "target/local-repo" ).getAbsoluteFile(); + protected ArtifactRepository getLocalRepository() throws InvalidRepositoryException { + File repoDir = new File(getBasedir(), "target/local-repo").getAbsoluteFile(); - return repositorySystem.createLocalRepository( repoDir ); + return repositorySystem.createLocalRepository(repoDir); } - protected class ProjectBuilder - { + protected class ProjectBuilder { private MavenProject project; - public ProjectBuilder( MavenProject project ) - { + public ProjectBuilder(MavenProject project) { this.project = project; } - public ProjectBuilder( String groupId, String artifactId, String version ) - { + public ProjectBuilder(String groupId, String artifactId, String version) { Model model = new Model(); - model.setModelVersion( "4.0.0" ); - model.setGroupId( groupId ); - model.setArtifactId( artifactId ); - model.setVersion( version ); - model.setBuild( new Build() ); - project = new MavenProject( model ); + model.setModelVersion("4.0.0"); + model.setGroupId(groupId); + model.setArtifactId(artifactId); + model.setVersion(version); + model.setBuild(new Build()); + project = new MavenProject(model); } - public ProjectBuilder setGroupId( String groupId ) - { - project.setGroupId( groupId ); + public ProjectBuilder setGroupId(String groupId) { + project.setGroupId(groupId); return this; } - public ProjectBuilder setArtifactId( String artifactId ) - { - project.setArtifactId( artifactId ); + public ProjectBuilder setArtifactId(String artifactId) { + project.setArtifactId(artifactId); return this; } - public ProjectBuilder setVersion( String version ) - { - project.setVersion( version ); + public ProjectBuilder setVersion(String version) { + project.setVersion(version); return this; } // Dependencies // - public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope ) - { - return addDependency( groupId, artifactId, version, scope, (Exclusion) null ); + public ProjectBuilder addDependency(String groupId, String artifactId, String version, String scope) { + return addDependency(groupId, artifactId, version, scope, (Exclusion) null); } - public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope, - Exclusion exclusion ) - { - return addDependency( groupId, artifactId, version, scope, null, exclusion ); + public ProjectBuilder addDependency( + String groupId, String artifactId, String version, String scope, Exclusion exclusion) { + return addDependency(groupId, artifactId, version, scope, null, exclusion); } - public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope, - String systemPath ) - { - return addDependency( groupId, artifactId, version, scope, systemPath, null ); + public ProjectBuilder addDependency( + String groupId, String artifactId, String version, String scope, String systemPath) { + return addDependency(groupId, artifactId, version, scope, systemPath, null); } - public ProjectBuilder addDependency( String groupId, String artifactId, String version, String scope, - String systemPath, Exclusion exclusion ) - { + public ProjectBuilder addDependency( + String groupId, + String artifactId, + String version, + String scope, + String systemPath, + Exclusion exclusion) { Dependency d = new Dependency(); - d.setGroupId( groupId ); - d.setArtifactId( artifactId ); - d.setVersion( version ); - d.setScope( scope ); + d.setGroupId(groupId); + d.setArtifactId(artifactId); + d.setVersion(version); + d.setScope(scope); - if ( systemPath != null && scope.equals( Artifact.SCOPE_SYSTEM ) ) - { - d.setSystemPath( systemPath ); + if (systemPath != null && scope.equals(Artifact.SCOPE_SYSTEM)) { + d.setSystemPath(systemPath); } - if ( exclusion != null ) - { - d.addExclusion( exclusion ); + if (exclusion != null) { + d.addExclusion(exclusion); } - project.getDependencies().add( d ); + project.getDependencies().add(d); return this; } // Plugins // - public ProjectBuilder addPlugin( Plugin plugin ) - { - project.getBuildPlugins().add( plugin ); + public ProjectBuilder addPlugin(Plugin plugin) { + project.getBuildPlugins().add(plugin); return this; } - public MavenProject get() - { + public MavenProject get() { return project; } } diff --git a/maven-core/src/test/java/org/apache/maven/DefaultMavenTest.java b/maven-core/src/test/java/org/apache/maven/DefaultMavenTest.java index 9075e79c7a..0b9fe0b30c 100644 --- a/maven-core/src/test/java/org/apache/maven/DefaultMavenTest.java +++ b/maven-core/src/test/java/org/apache/maven/DefaultMavenTest.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -18,14 +18,17 @@ */ package org.apache.maven; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.nio.file.Files; import java.util.concurrent.atomic.AtomicReference; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.execution.MavenExecutionRequest; @@ -36,24 +39,15 @@ import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.repository.internal.MavenWorkspaceReader; import org.junit.jupiter.api.Test; -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class DefaultMavenTest - extends AbstractCoreMavenComponentTestCase -{ +public class DefaultMavenTest extends AbstractCoreMavenComponentTestCase { @Singleton - @Named( "WsrClassCatcher" ) - private static final class WsrClassCatcher extends AbstractMavenLifecycleParticipant - { - private final AtomicReference> wsrClassRef = new AtomicReference<>( null ); + @Named("WsrClassCatcher") + private static final class WsrClassCatcher extends AbstractMavenLifecycleParticipant { + private final AtomicReference> wsrClassRef = new AtomicReference<>(null); @Override - public void afterProjectsRead( MavenSession session ) throws MavenExecutionException - { - wsrClassRef.set( session.getRepositorySession().getWorkspaceReader().getClass() ); + public void afterProjectsRead(MavenSession session) throws MavenExecutionException { + wsrClassRef.set(session.getRepositorySession().getWorkspaceReader().getClass()); } } @@ -61,56 +55,48 @@ public class DefaultMavenTest private Maven maven; @Override - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/default-maven"; } @Test - public void testEnsureResolverSessionHasMavenWorkspaceReader() - throws Exception - { - WsrClassCatcher wsrClassCatcher = ( WsrClassCatcher ) getContainer() - .lookup( AbstractMavenLifecycleParticipant.class, "WsrClassCatcher" ); - Maven maven = getContainer().lookup( Maven.class ); - MavenExecutionRequest request = createMavenExecutionRequest( getProject( "simple" ) ).setGoals( asList("validate") ); + public void testEnsureResolverSessionHasMavenWorkspaceReader() throws Exception { + WsrClassCatcher wsrClassCatcher = + (WsrClassCatcher) getContainer().lookup(AbstractMavenLifecycleParticipant.class, "WsrClassCatcher"); + Maven maven = getContainer().lookup(Maven.class); + MavenExecutionRequest request = + createMavenExecutionRequest(getProject("simple")).setGoals(asList("validate")); - MavenExecutionResult result = maven.execute( request ); + MavenExecutionResult result = maven.execute(request); Class wsrClass = wsrClassCatcher.wsrClassRef.get(); - assertNotNull( wsrClass, "wsr cannot be null" ); - assertTrue( MavenWorkspaceReader.class.isAssignableFrom( wsrClass ), String.valueOf( wsrClass ) ); + assertNotNull(wsrClass, "wsr cannot be null"); + assertTrue(MavenWorkspaceReader.class.isAssignableFrom(wsrClass), String.valueOf(wsrClass)); } @Test - public void testThatErrorDuringProjectDependencyGraphCreationAreStored() - throws Exception - { - MavenExecutionRequest request = createMavenExecutionRequest( getProject( "cyclic-reference" ) ).setGoals( asList("validate") ); + public void testThatErrorDuringProjectDependencyGraphCreationAreStored() throws Exception { + MavenExecutionRequest request = + createMavenExecutionRequest(getProject("cyclic-reference")).setGoals(asList("validate")); - MavenExecutionResult result = maven.execute( request ); + MavenExecutionResult result = maven.execute(request); - assertEquals( ProjectCycleException.class, result.getExceptions().get( 0 ).getClass() ); + assertEquals(ProjectCycleException.class, result.getExceptions().get(0).getClass()); } @Test - public void testMavenProjectNoDuplicateArtifacts() - throws Exception - { - MavenProjectHelper mavenProjectHelper = getContainer().lookup( MavenProjectHelper.class ); + public void testMavenProjectNoDuplicateArtifacts() throws Exception { + MavenProjectHelper mavenProjectHelper = getContainer().lookup(MavenProjectHelper.class); MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "g", "a", "1.0", Artifact.SCOPE_TEST, "jar", "", null ) ); - File artifactFile = Files.createTempFile( "foo", "tmp").toFile(); - try - { - mavenProjectHelper.attachArtifact( mavenProject, "sources", artifactFile ); - assertEquals( 1, mavenProject.getAttachedArtifacts().size() ); - mavenProjectHelper.attachArtifact( mavenProject, "sources", artifactFile ); - assertEquals( 1, mavenProject.getAttachedArtifacts().size() ); - } finally - { - Files.deleteIfExists( artifactFile.toPath() ); + mavenProject.setArtifact(new DefaultArtifact("g", "a", "1.0", Artifact.SCOPE_TEST, "jar", "", null)); + File artifactFile = Files.createTempFile("foo", "tmp").toFile(); + try { + mavenProjectHelper.attachArtifact(mavenProject, "sources", artifactFile); + assertEquals(1, mavenProject.getAttachedArtifacts().size()); + mavenProjectHelper.attachArtifact(mavenProject, "sources", artifactFile); + assertEquals(1, mavenProject.getAttachedArtifacts().size()); + } finally { + Files.deleteIfExists(artifactFile.toPath()); } } - } diff --git a/maven-core/src/test/java/org/apache/maven/MavenLifecycleParticipantTest.java b/maven-core/src/test/java/org/apache/maven/MavenLifecycleParticipantTest.java index 6d8f975123..9297c46d56 100644 --- a/maven-core/src/test/java/org/apache/maven/MavenLifecycleParticipantTest.java +++ b/maven-core/src/test/java/org/apache/maven/MavenLifecycleParticipantTest.java @@ -1,26 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenExecutionResult; @@ -31,142 +36,115 @@ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -public class MavenLifecycleParticipantTest - extends AbstractCoreMavenComponentTestCase -{ +public class MavenLifecycleParticipantTest extends AbstractCoreMavenComponentTestCase { private static final String INJECTED_ARTIFACT_ID = "injected"; - public static class InjectDependencyLifecycleListener - extends AbstractMavenLifecycleParticipant - { + public static class InjectDependencyLifecycleListener extends AbstractMavenLifecycleParticipant { @Override - public void afterProjectsRead( MavenSession session ) - { - MavenProject project = session.getProjects().get( 0 ); + public void afterProjectsRead(MavenSession session) { + MavenProject project = session.getProjects().get(0); Dependency dependency = new Dependency(); - dependency.setArtifactId( INJECTED_ARTIFACT_ID ); - dependency.setGroupId( "foo" ); - dependency.setVersion( "1.2.3" ); - dependency.setScope( "system" ); - try - { - dependency.setSystemPath( new File( - "src/test/projects/lifecycle-executor/project-with-additional-lifecycle-elements/pom.xml" ).getCanonicalPath() ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + dependency.setArtifactId(INJECTED_ARTIFACT_ID); + dependency.setGroupId("foo"); + dependency.setVersion("1.2.3"); + dependency.setScope("system"); + try { + dependency.setSystemPath(new File( + "src/test/projects/lifecycle-executor/project-with-additional-lifecycle-elements/pom.xml") + .getCanonicalPath()); + } catch (IOException e) { + throw new RuntimeException(e); } - project.getModel().addDependency( dependency ); + project.getModel().addDependency(dependency); } @Override - public void afterSessionStart( MavenSession session ) - { - session.getUserProperties().setProperty( "injected", "bar" ); + public void afterSessionStart(MavenSession session) { + session.getUserProperties().setProperty("injected", "bar"); } - } - public static class InjectReactorDependency - extends AbstractMavenLifecycleParticipant - { + public static class InjectReactorDependency extends AbstractMavenLifecycleParticipant { @Override - public void afterProjectsRead( MavenSession session ) - { - injectReactorDependency( session.getProjects(), "module-a", "module-b" ); + public void afterProjectsRead(MavenSession session) { + injectReactorDependency(session.getProjects(), "module-a", "module-b"); } - private void injectReactorDependency( List projects, String moduleFrom, String moduleTo ) - { - for ( MavenProject project : projects ) - { - if ( moduleFrom.equals( project.getArtifactId() ) ) - { + private void injectReactorDependency(List projects, String moduleFrom, String moduleTo) { + for (MavenProject project : projects) { + if (moduleFrom.equals(project.getArtifactId())) { Dependency dependency = new Dependency(); - dependency.setArtifactId( moduleTo ); - dependency.setGroupId( project.getGroupId() ); - dependency.setVersion( project.getVersion() ); + dependency.setArtifactId(moduleTo); + dependency.setGroupId(project.getGroupId()); + dependency.setVersion(project.getVersion()); - project.getModel().addDependency( dependency ); + project.getModel().addDependency(dependency); } } } } @Override - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/lifecycle-listener"; } @Test - public void testDependencyInjection() - throws Exception - { + public void testDependencyInjection() throws Exception { PlexusContainer container = getContainer(); ComponentDescriptor cd = - new ComponentDescriptor<>( InjectDependencyLifecycleListener.class, - container.getContainerRealm() ); - cd.setRoleClass( AbstractMavenLifecycleParticipant.class ); - container.addComponentDescriptor( cd ); + new ComponentDescriptor<>(InjectDependencyLifecycleListener.class, container.getContainerRealm()); + cd.setRoleClass(AbstractMavenLifecycleParticipant.class); + container.addComponentDescriptor(cd); - Maven maven = container.lookup( Maven.class ); - File pom = getProject( "lifecycle-listener-dependency-injection" ); - MavenExecutionRequest request = createMavenExecutionRequest( pom ); - request.setGoals( Arrays.asList( "validate" ) ); - MavenExecutionResult result = maven.execute( request ); + Maven maven = container.lookup(Maven.class); + File pom = getProject("lifecycle-listener-dependency-injection"); + MavenExecutionRequest request = createMavenExecutionRequest(pom); + request.setGoals(Arrays.asList("validate")); + MavenExecutionResult result = maven.execute(request); - assertFalse( result.hasExceptions(), result.getExceptions().toString() ); + assertFalse(result.hasExceptions(), result.getExceptions().toString()); MavenProject project = result.getProject(); - assertEquals( "bar", project.getProperties().getProperty( "foo" ) ); + assertEquals("bar", project.getProperties().getProperty("foo")); - ArrayList artifacts = new ArrayList<>( project.getArtifacts() ); + ArrayList artifacts = new ArrayList<>(project.getArtifacts()); - assertEquals( 1, artifacts.size() ); - assertEquals( INJECTED_ARTIFACT_ID, artifacts.get( 0 ).getArtifactId() ); + assertEquals(1, artifacts.size()); + assertEquals(INJECTED_ARTIFACT_ID, artifacts.get(0).getArtifactId()); } @Test - public void testReactorDependencyInjection() - throws Exception - { + public void testReactorDependencyInjection() throws Exception { List reactorOrder = - getReactorOrder( "lifecycle-participant-reactor-dependency-injection", InjectReactorDependency.class ); - assertEquals( Arrays.asList( "parent", "module-b", "module-a" ), reactorOrder ); + getReactorOrder("lifecycle-participant-reactor-dependency-injection", InjectReactorDependency.class); + assertEquals(Arrays.asList("parent", "module-b", "module-a"), reactorOrder); } - private List getReactorOrder( String testProject, Class participant ) - throws Exception - { + private List getReactorOrder(String testProject, Class participant) throws Exception { PlexusContainer container = getContainer(); - ComponentDescriptor cd = new ComponentDescriptor<>( participant, container.getContainerRealm() ); - cd.setRoleClass( AbstractMavenLifecycleParticipant.class ); - container.addComponentDescriptor( cd ); + ComponentDescriptor cd = new ComponentDescriptor<>(participant, container.getContainerRealm()); + cd.setRoleClass(AbstractMavenLifecycleParticipant.class); + container.addComponentDescriptor(cd); - Maven maven = container.lookup( Maven.class ); - File pom = getProject( testProject ); - MavenExecutionRequest request = createMavenExecutionRequest( pom ); - request.setGoals( Arrays.asList( "validate" ) ); - MavenExecutionResult result = maven.execute( request ); + Maven maven = container.lookup(Maven.class); + File pom = getProject(testProject); + MavenExecutionRequest request = createMavenExecutionRequest(pom); + request.setGoals(Arrays.asList("validate")); + MavenExecutionResult result = maven.execute(request); - assertFalse( result.hasExceptions(), result.getExceptions().toString() ); + assertFalse(result.hasExceptions(), result.getExceptions().toString()); List order = new ArrayList<>(); - for ( MavenProject project : result.getTopologicallySortedProjects() ) - { - order.add( project.getArtifactId() ); + for (MavenProject project : result.getTopologicallySortedProjects()) { + order.add(project.getArtifactId()); } return order; } diff --git a/maven-core/src/test/java/org/apache/maven/MavenTest.java b/maven-core/src/test/java/org/apache/maven/MavenTest.java index 991e61d0a7..d9b5cdad0c 100644 --- a/maven-core/src/test/java/org/apache/maven/MavenTest.java +++ b/maven-core/src/test/java/org/apache/maven/MavenTest.java @@ -1,55 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - - +import javax.inject.Inject; import org.apache.maven.exception.ExceptionHandler; import org.junit.jupiter.api.Test; -import javax.inject.Inject; - -public class MavenTest - extends AbstractCoreMavenComponentTestCase -{ +public class MavenTest extends AbstractCoreMavenComponentTestCase { @Inject private Maven maven; @Inject private ExceptionHandler exceptionHandler; - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/lifecycle-executor"; } @Test - public void testLifecycleExecutionUsingADefaultLifecyclePhase() - throws Exception - { -/* - File pom = getProject( "project-with-additional-lifecycle-elements" ); - MavenExecutionRequest request = createMavenExecutionRequest( pom ); - MavenExecutionResult result = maven.execute( request ); - if ( result.hasExceptions() ) - { - ExceptionSummary es = exceptionHandler.handleException( result.getExceptions().get( 0 ) ); - System.out.println( es.getMessage() ); - es.getException().printStackTrace(); - fail( "Maven did not execute correctly." ); - } -*/ + public void testLifecycleExecutionUsingADefaultLifecyclePhase() throws Exception { + /* + File pom = getProject( "project-with-additional-lifecycle-elements" ); + MavenExecutionRequest request = createMavenExecutionRequest( pom ); + MavenExecutionResult result = maven.execute( request ); + if ( result.hasExceptions() ) + { + ExceptionSummary es = exceptionHandler.handleException( result.getExceptions().get( 0 ) ); + System.out.println( es.getMessage() ); + es.getException().printStackTrace(); + fail( "Maven did not execute correctly." ); + } + */ } } diff --git a/maven-core/src/test/java/org/apache/maven/ProjectDependenciesResolverTest.java b/maven-core/src/test/java/org/apache/maven/ProjectDependenciesResolverTest.java index b648f2aec4..ab9ef97fec 100644 --- a/maven-core/src/test/java/org/apache/maven/ProjectDependenciesResolverTest.java +++ b/maven-core/src/test/java/org/apache/maven/ProjectDependenciesResolverTest.java @@ -1,46 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.endsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; - +import javax.inject.Inject; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; - -import javax.inject.Inject; import org.junit.jupiter.api.Test; -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.hamcrest.Matchers.endsWith; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - -public class ProjectDependenciesResolverTest - extends AbstractCoreMavenComponentTestCase -{ +public class ProjectDependenciesResolverTest extends AbstractCoreMavenComponentTestCase { @Inject private ProjectDependenciesResolver resolver; - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/project-dependencies-resolver"; } @@ -70,40 +68,41 @@ public class ProjectDependenciesResolverTest */ @Test - public void testSystemScopeDependencies() - throws Exception - { - MavenSession session = createMavenSession( null ); + public void testSystemScopeDependencies() throws Exception { + MavenSession session = createMavenSession(null); MavenProject project = session.getCurrentProject(); - new ProjectBuilder( project ) - .addDependency( "com.mycompany", "system-dependency", "1.0", Artifact.SCOPE_SYSTEM, new File( getBasedir(), "pom.xml" ).getAbsolutePath() ); + new ProjectBuilder(project) + .addDependency( + "com.mycompany", + "system-dependency", + "1.0", + Artifact.SCOPE_SYSTEM, + new File(getBasedir(), "pom.xml").getAbsolutePath()); Set artifactDependencies = - resolver.resolve( project, Collections.singleton( Artifact.SCOPE_COMPILE ), session ); - assertEquals( 1, artifactDependencies.size() ); + resolver.resolve(project, Collections.singleton(Artifact.SCOPE_COMPILE), session); + assertEquals(1, artifactDependencies.size()); } @Test - public void testSystemScopeDependencyIsPresentInTheCompileClasspathElements() - throws Exception - { - File pom = getProject( "it0063" ); + public void testSystemScopeDependencyIsPresentInTheCompileClasspathElements() throws Exception { + File pom = getProject("it0063"); Properties eps = new Properties(); - eps.setProperty( "jre.home", new File( pom.getParentFile(), "jdk/jre" ).getPath() ); + eps.setProperty("jre.home", new File(pom.getParentFile(), "jdk/jre").getPath()); - MavenSession session = createMavenSession( pom, eps ); + MavenSession session = createMavenSession(pom, eps); MavenProject project = session.getCurrentProject(); - project.setArtifacts( resolver.resolve( project, Collections.singleton( Artifact.SCOPE_COMPILE ), session ) ); + project.setArtifacts(resolver.resolve(project, Collections.singleton(Artifact.SCOPE_COMPILE), session)); List elements = project.getCompileClasspathElements(); - assertEquals( 2, elements.size() ); + assertEquals(2, elements.size()); - @SuppressWarnings( "deprecation" ) + @SuppressWarnings("deprecation") List artifacts = project.getCompileArtifacts(); - assertEquals( 1, artifacts.size() ); - assertThat( artifacts.get( 0 ).getFile().getName(), endsWith( "tools.jar" ) ); + assertEquals(1, artifacts.size()); + assertThat(artifacts.get(0).getFile().getName(), endsWith("tools.jar")); } } diff --git a/maven-core/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerTest.java b/maven-core/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerTest.java index 9dd5cf19d1..055f1f471c 100644 --- a/maven-core/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerTest.java +++ b/maven-core/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.handler; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.handler; * "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 + * 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 @@ -18,82 +16,83 @@ package org.apache.maven.artifact.handler; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.List; - -import javax.inject.Inject; - -import org.codehaus.plexus.testing.PlexusTest; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.util.FileUtils; -import org.junit.jupiter.api.Test; +package org.apache.maven.artifact.handler; import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.File; +import java.util.List; +import javax.inject.Inject; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; +import org.codehaus.plexus.util.FileUtils; +import org.junit.jupiter.api.Test; + @PlexusTest -public class ArtifactHandlerTest -{ +public class ArtifactHandlerTest { @Inject PlexusContainer container; @Test - public void testAptConsistency() - throws Exception - { - File apt = getTestFile( "src/site/apt/artifact-handlers.apt" ); + public void testAptConsistency() throws Exception { + File apt = getTestFile("src/site/apt/artifact-handlers.apt"); - List lines = FileUtils.loadFile( apt ); + List lines = FileUtils.loadFile(apt); - for ( String line : lines ) - { - if ( line.startsWith( "||" ) ) - { - String[] cols = line.split( "\\|\\|" ); - String[] expected = - new String[] { "", "type", "classifier", "extension", "packaging", "language", "added to classpath", - "includesDependencies", "" }; + for (String line : lines) { + if (line.startsWith("||")) { + String[] cols = line.split("\\|\\|"); + String[] expected = new String[] { + "", + "type", + "classifier", + "extension", + "packaging", + "language", + "added to classpath", + "includesDependencies", + "" + }; int i = 0; - for ( String col : cols ) - { - assertEquals( expected[i++], col.trim(), "Wrong column header" ); + for (String col : cols) { + assertEquals(expected[i++], col.trim(), "Wrong column header"); } - } - else if ( line.startsWith( "|" ) ) - { - String[] cols = line.split( "\\|" ); + } else if (line.startsWith("|")) { + String[] cols = line.split("\\|"); - String type = trimApt( cols[1] ); - String classifier = trimApt( cols[2] ); - String extension = trimApt( cols[3], type ); - String packaging = trimApt( cols[4], type ); - String language = trimApt( cols[5] ); - String addedToClasspath = trimApt( cols[6] ); - String includesDependencies = trimApt( cols[7] ); + String type = trimApt(cols[1]); + String classifier = trimApt(cols[2]); + String extension = trimApt(cols[3], type); + String packaging = trimApt(cols[4], type); + String language = trimApt(cols[5]); + String addedToClasspath = trimApt(cols[6]); + String includesDependencies = trimApt(cols[7]); - ArtifactHandler handler = container.lookup( ArtifactHandler.class, type ); - assertEquals( handler.getExtension(), extension, type + " extension" ); - assertEquals( handler.getPackaging(), packaging, type + " packaging" ); - assertEquals( handler.getClassifier(), classifier, type + " classifier" ); - assertEquals( handler.getLanguage(), language, type + " language" ); - assertEquals( handler.isAddedToClasspath() ? "true" : null, addedToClasspath, type + " addedToClasspath" ); - assertEquals( handler.isIncludesDependencies() ? "true" : null, includesDependencies, type + " includesDependencies" ); + ArtifactHandler handler = container.lookup(ArtifactHandler.class, type); + assertEquals(handler.getExtension(), extension, type + " extension"); + assertEquals(handler.getPackaging(), packaging, type + " packaging"); + assertEquals(handler.getClassifier(), classifier, type + " classifier"); + assertEquals(handler.getLanguage(), language, type + " language"); + assertEquals( + handler.isAddedToClasspath() ? "true" : null, addedToClasspath, type + " addedToClasspath"); + assertEquals( + handler.isIncludesDependencies() ? "true" : null, + includesDependencies, + type + " includesDependencies"); } } } - private String trimApt( String content, String type ) - { - String value = trimApt( content ); - return "= type".equals( value ) ? type : value; + private String trimApt(String content, String type) { + String value = trimApt(content); + return "= type".equals(value) ? type : value; } - private String trimApt( String content ) - { - content = content.replace( '<', ' ' ).replace( '>', ' ' ).trim(); + private String trimApt(String content) { + content = content.replace('<', ' ').replace('>', ' ').trim(); - return ( content.length() == 0 ) ? null : content; + return (content.length() == 0) ? null : content; } } diff --git a/maven-core/src/test/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilterTest.java b/maven-core/src/test/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilterTest.java index 76b1654644..040c804d5a 100644 --- a/maven-core/src/test/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilterTest.java +++ b/maven-core/src/test/java/org/apache/maven/artifact/resolver/filter/ExclusionArtifactFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.artifact.resolver.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.artifact.resolver.filter; * "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 + * 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 @@ -18,139 +16,127 @@ package org.apache.maven.artifact.resolver.filter; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Exclusion; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; - -import java.util.Arrays; -import java.util.Collections; +package org.apache.maven.artifact.resolver.filter; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ExclusionArtifactFilterTest -{ +import java.util.Arrays; +import java.util.Collections; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Exclusion; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ExclusionArtifactFilterTest { private Artifact artifact; @BeforeEach - public void setup() - { - artifact = mock( Artifact.class ); - when( artifact.getGroupId() ).thenReturn( "org.apache.maven" ); - when( artifact.getArtifactId() ).thenReturn( "maven-core" ); + public void setup() { + artifact = mock(Artifact.class); + when(artifact.getGroupId()).thenReturn("org.apache.maven"); + when(artifact.getArtifactId()).thenReturn("maven-core"); } @Test - public void testExcludeExact() - { + public void testExcludeExact() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "org.apache.maven" ); - exclusion.setArtifactId( "maven-core" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("org.apache.maven"); + exclusion.setArtifactId("maven-core"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( false ) ); + assertThat(filter.include(artifact), is(false)); } @Test - public void testExcludeNoMatch() - { + public void testExcludeNoMatch() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "org.apache.maven" ); - exclusion.setArtifactId( "maven-model" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("org.apache.maven"); + exclusion.setArtifactId("maven-model"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( true ) ); + assertThat(filter.include(artifact), is(true)); } @Test - public void testExcludeGroupIdWildcard() - { + public void testExcludeGroupIdWildcard() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "*" ); - exclusion.setArtifactId( "maven-core" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("*"); + exclusion.setArtifactId("maven-core"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( false ) ); + assertThat(filter.include(artifact), is(false)); } - @Test - public void testExcludeGroupIdWildcardNoMatch() - { + public void testExcludeGroupIdWildcardNoMatch() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "*" ); - exclusion.setArtifactId( "maven-compat" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("*"); + exclusion.setArtifactId("maven-compat"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( true ) ); + assertThat(filter.include(artifact), is(true)); } @Test - public void testExcludeArtifactIdWildcard() - { + public void testExcludeArtifactIdWildcard() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "org.apache.maven" ); - exclusion.setArtifactId( "*" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("org.apache.maven"); + exclusion.setArtifactId("*"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( false ) ); + assertThat(filter.include(artifact), is(false)); } @Test - public void testExcludeArtifactIdWildcardNoMatch() - { + public void testExcludeArtifactIdWildcardNoMatch() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "org.apache.groovy" ); - exclusion.setArtifactId( "*" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("org.apache.groovy"); + exclusion.setArtifactId("*"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( true ) ); + assertThat(filter.include(artifact), is(true)); } @Test - public void testExcludeAllWildcard() - { + public void testExcludeAllWildcard() { Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( "*" ); - exclusion.setArtifactId( "*" ); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Collections.singletonList( exclusion ) ); + exclusion.setGroupId("*"); + exclusion.setArtifactId("*"); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Collections.singletonList(exclusion)); - assertThat( filter.include( artifact ), is( false ) ); + assertThat(filter.include(artifact), is(false)); } @Test - public void testMultipleExclusionsExcludeArtifactIdWildcard() - { + public void testMultipleExclusionsExcludeArtifactIdWildcard() { Exclusion exclusion1 = new Exclusion(); - exclusion1.setGroupId( "org.apache.groovy" ); - exclusion1.setArtifactId( "*" ); + exclusion1.setGroupId("org.apache.groovy"); + exclusion1.setArtifactId("*"); Exclusion exclusion2 = new Exclusion(); - exclusion2.setGroupId( "org.apache.maven" ); - exclusion2.setArtifactId( "maven-core" ); + exclusion2.setGroupId("org.apache.maven"); + exclusion2.setArtifactId("maven-core"); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Arrays.asList( exclusion1, exclusion2 ) ); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Arrays.asList(exclusion1, exclusion2)); - assertThat( filter.include( artifact ), is( false ) ); + assertThat(filter.include(artifact), is(false)); } @Test - public void testMultipleExclusionsExcludeGroupIdWildcard() - { + public void testMultipleExclusionsExcludeGroupIdWildcard() { Exclusion exclusion1 = new Exclusion(); - exclusion1.setGroupId( "*" ); - exclusion1.setArtifactId( "maven-model" ); + exclusion1.setGroupId("*"); + exclusion1.setArtifactId("maven-model"); Exclusion exclusion2 = new Exclusion(); - exclusion2.setGroupId( "org.apache.maven" ); - exclusion2.setArtifactId( "maven-core" ); + exclusion2.setGroupId("org.apache.maven"); + exclusion2.setArtifactId("maven-core"); - ExclusionArtifactFilter filter = new ExclusionArtifactFilter( Arrays.asList( exclusion1, exclusion2 ) ); + ExclusionArtifactFilter filter = new ExclusionArtifactFilter(Arrays.asList(exclusion1, exclusion2)); - assertThat( filter.include( artifact ), is( false ) ); + assertThat(filter.include(artifact), is(false)); } -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorPathTest.java b/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorPathTest.java index c7cf0884b1..878e2c5077 100644 --- a/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorPathTest.java +++ b/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorPathTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,16 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.file.Path; import java.nio.file.Paths; - import org.apache.maven.configuration.internal.DefaultBeanConfigurator; -import org.apache.maven.configuration.internal.EnhancedComponentConfigurator; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -34,107 +33,85 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Benjamin Bentmann */ -public class DefaultBeanConfiguratorPathTest -{ +public class DefaultBeanConfiguratorPathTest { private BeanConfigurator configurator; @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { configurator = new DefaultBeanConfigurator(); } @AfterEach - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { configurator = null; } - private Xpp3Dom toConfig( String xml ) - { - try - { - return Xpp3DomBuilder.build( new StringReader( "" + xml + "" ) ); - } - catch ( XmlPullParserException | IOException e ) - { - throw new IllegalArgumentException( e ); + private Xpp3Dom toConfig(String xml) { + try { + return Xpp3DomBuilder.build(new StringReader("" + xml + "")); + } catch (XmlPullParserException | IOException e) { + throw new IllegalArgumentException(e); } } @Test - public void testMinimal() - throws BeanConfigurationException - { + public void testMinimal() throws BeanConfigurationException { SomeBean bean = new SomeBean(); - Xpp3Dom config = toConfig( "test" ); + Xpp3Dom config = toConfig("test"); DefaultBeanConfigurationRequest request = new DefaultBeanConfigurationRequest(); - request.setBean( bean ).setConfiguration( config ); + request.setBean(bean).setConfiguration(config); - configurator.configureBean( request ); + configurator.configureBean(request); - assertEquals( Paths.get( "test" ), bean.file ); + assertEquals(Paths.get("test"), bean.file); } @Test - public void testPreAndPostProcessing() - throws BeanConfigurationException - { + public void testPreAndPostProcessing() throws BeanConfigurationException { SomeBean bean = new SomeBean(); - Xpp3Dom config = toConfig( "${test}" ); + Xpp3Dom config = toConfig("${test}"); - BeanConfigurationValuePreprocessor preprocessor = ( value, type ) -> - { - if ( value != null && value.startsWith( "${" ) && value.endsWith( "}" ) ) - { - return value.substring( 2, value.length() - 1 ); + BeanConfigurationValuePreprocessor preprocessor = (value, type) -> { + if (value != null && value.startsWith("${") && value.endsWith("}")) { + return value.substring(2, value.length() - 1); } return value; }; - BeanConfigurationPathTranslator translator = path -> new File( "base", path.getPath() ).getAbsoluteFile(); + BeanConfigurationPathTranslator translator = path -> new File("base", path.getPath()).getAbsoluteFile(); DefaultBeanConfigurationRequest request = new DefaultBeanConfigurationRequest(); - request.setBean( bean ).setConfiguration( config ); - request.setValuePreprocessor( preprocessor ).setPathTranslator( translator ); + request.setBean(bean).setConfiguration(config); + request.setValuePreprocessor(preprocessor).setPathTranslator(translator); - configurator.configureBean( request ); + configurator.configureBean(request); - assertEquals( Paths.get( "base/test" ).toAbsolutePath(), bean.file ); + assertEquals(Paths.get("base/test").toAbsolutePath(), bean.file); } @Test - public void testChildConfigurationElement() - throws BeanConfigurationException - { + public void testChildConfigurationElement() throws BeanConfigurationException { SomeBean bean = new SomeBean(); - Xpp3Dom config = toConfig( "test" ); + Xpp3Dom config = toConfig("test"); DefaultBeanConfigurationRequest request = new DefaultBeanConfigurationRequest(); - request.setBean( bean ).setConfiguration( config, "wrapper" ); + request.setBean(bean).setConfiguration(config, "wrapper"); - configurator.configureBean( request ); + configurator.configureBean(request); - assertEquals( Paths.get( "test" ), bean.file ); + assertEquals(Paths.get("test"), bean.file); } - static class SomeBean - { + static class SomeBean { Path file; - } - } diff --git a/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorTest.java b/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorTest.java index 3dd3eff7f5..9da160012c 100644 --- a/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorTest.java +++ b/maven-core/src/test/java/org/apache/maven/configuration/DefaultBeanConfiguratorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.configuration; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,13 @@ package org.apache.maven.configuration; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.configuration; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; import java.io.StringReader; - import org.apache.maven.configuration.internal.DefaultBeanConfigurator; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; @@ -31,107 +31,85 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Benjamin Bentmann */ -public class DefaultBeanConfiguratorTest -{ +public class DefaultBeanConfiguratorTest { private BeanConfigurator configurator; @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { configurator = new DefaultBeanConfigurator(); } @AfterEach - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { configurator = null; } - private Xpp3Dom toConfig( String xml ) - { - try - { - return Xpp3DomBuilder.build( new StringReader( "" + xml + "" ) ); - } - catch ( XmlPullParserException | IOException e ) - { - throw new IllegalArgumentException( e ); + private Xpp3Dom toConfig(String xml) { + try { + return Xpp3DomBuilder.build(new StringReader("" + xml + "")); + } catch (XmlPullParserException | IOException e) { + throw new IllegalArgumentException(e); } } @Test - public void testMinimal() - throws BeanConfigurationException - { + public void testMinimal() throws BeanConfigurationException { SomeBean bean = new SomeBean(); - Xpp3Dom config = toConfig( "test" ); + Xpp3Dom config = toConfig("test"); DefaultBeanConfigurationRequest request = new DefaultBeanConfigurationRequest(); - request.setBean( bean ).setConfiguration( config ); + request.setBean(bean).setConfiguration(config); - configurator.configureBean( request ); + configurator.configureBean(request); - assertEquals( new File( "test" ), bean.file ); + assertEquals(new File("test"), bean.file); } @Test - public void testPreAndPostProcessing() - throws BeanConfigurationException - { + public void testPreAndPostProcessing() throws BeanConfigurationException { SomeBean bean = new SomeBean(); - Xpp3Dom config = toConfig( "${test}" ); + Xpp3Dom config = toConfig("${test}"); - BeanConfigurationValuePreprocessor preprocessor = ( value, type ) -> - { - if ( value != null && value.startsWith( "${" ) && value.endsWith( "}" ) ) - { - return value.substring( 2, value.length() - 1 ); + BeanConfigurationValuePreprocessor preprocessor = (value, type) -> { + if (value != null && value.startsWith("${") && value.endsWith("}")) { + return value.substring(2, value.length() - 1); } return value; }; - BeanConfigurationPathTranslator translator = path -> new File( "base", path.getPath() ).getAbsoluteFile(); + BeanConfigurationPathTranslator translator = path -> new File("base", path.getPath()).getAbsoluteFile(); DefaultBeanConfigurationRequest request = new DefaultBeanConfigurationRequest(); - request.setBean( bean ).setConfiguration( config ); - request.setValuePreprocessor( preprocessor ).setPathTranslator( translator ); + request.setBean(bean).setConfiguration(config); + request.setValuePreprocessor(preprocessor).setPathTranslator(translator); - configurator.configureBean( request ); + configurator.configureBean(request); - assertEquals( new File( "base/test" ).getAbsoluteFile(), bean.file ); + assertEquals(new File("base/test").getAbsoluteFile(), bean.file); } @Test - public void testChildConfigurationElement() - throws BeanConfigurationException - { + public void testChildConfigurationElement() throws BeanConfigurationException { SomeBean bean = new SomeBean(); - Xpp3Dom config = toConfig( "test" ); + Xpp3Dom config = toConfig("test"); DefaultBeanConfigurationRequest request = new DefaultBeanConfigurationRequest(); - request.setBean( bean ).setConfiguration( config, "wrapper" ); + request.setBean(bean).setConfiguration(config, "wrapper"); - configurator.configureBean( request ); + configurator.configureBean(request); - assertEquals( new File( "test" ), bean.file ); + assertEquals(new File("test"), bean.file); } - static class SomeBean - { + static class SomeBean { File file; - } - } diff --git a/maven-core/src/test/java/org/apache/maven/exception/DefaultExceptionHandlerTest.java b/maven-core/src/test/java/org/apache/maven/exception/DefaultExceptionHandlerTest.java index 48cdb2fba1..aa21d77a8c 100644 --- a/maven-core/src/test/java/org/apache/maven/exception/DefaultExceptionHandlerTest.java +++ b/maven-core/src/test/java/org/apache/maven/exception/DefaultExceptionHandlerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.exception; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.exception; * "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 + * 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 @@ -18,27 +16,25 @@ package org.apache.maven.exception; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.exception; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.net.ConnectException; - import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; - import org.apache.maven.plugin.PluginContainerException; import org.apache.maven.plugin.PluginExecutionException; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Barrie Treloar */ -public class DefaultExceptionHandlerTest -{ +public class DefaultExceptionHandlerTest { /** * Running Maven under JDK7 may cause connection issues because IPv6 is used by default. *

    @@ -50,56 +46,52 @@ public class DefaultExceptionHandlerTest *

    */ @Test - public void testJdk7ipv6() - { - ConnectException connEx = new ConnectException( "Connection refused: connect" ); - IOException ioEx = new IOException( "Unable to establish loopback connection", connEx ); + public void testJdk7ipv6() { + ConnectException connEx = new ConnectException("Connection refused: connect"); + IOException ioEx = new IOException("Unable to establish loopback connection", connEx); MojoExecutionException mojoEx = - new MojoExecutionException( "Error executing Jetty: Unable to establish loopback connection", ioEx ); + new MojoExecutionException("Error executing Jetty: Unable to establish loopback connection", ioEx); ExceptionHandler exceptionHandler = new DefaultExceptionHandler(); - ExceptionSummary exceptionSummary = exceptionHandler.handleException( mojoEx ); + ExceptionSummary exceptionSummary = exceptionHandler.handleException(mojoEx); String expectedReference = "http://cwiki.apache.org/confluence/display/MAVEN/ConnectException"; - assertEquals( expectedReference, exceptionSummary.getReference() ); - + assertEquals(expectedReference, exceptionSummary.getReference()); } @Test - public void testHandleExceptionAetherClassNotFound() - { - Throwable cause2 = new NoClassDefFoundError( "org/sonatype/aether/RepositorySystem" ); + public void testHandleExceptionAetherClassNotFound() { + Throwable cause2 = new NoClassDefFoundError("org/sonatype/aether/RepositorySystem"); Plugin plugin = new Plugin(); - Exception cause = new PluginContainerException( plugin, null, null, cause2 ); + Exception cause = new PluginContainerException(plugin, null, null, cause2); PluginDescriptor pluginDescriptor = new PluginDescriptor(); MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setPluginDescriptor( pluginDescriptor ); + mojoDescriptor.setPluginDescriptor(pluginDescriptor); MojoExecution mojoExecution = new MojoExecution(mojoDescriptor); - Throwable exception = new PluginExecutionException( mojoExecution, null, cause ); + Throwable exception = new PluginExecutionException(mojoExecution, null, cause); DefaultExceptionHandler handler = new DefaultExceptionHandler(); - ExceptionSummary summary = handler.handleException( exception ); + ExceptionSummary summary = handler.handleException(exception); String expectedReference = "http://cwiki.apache.org/confluence/display/MAVEN/AetherClassNotFound"; - assertEquals( expectedReference, summary.getReference() ); + assertEquals(expectedReference, summary.getReference()); } @Test - public void testHandleExceptionNoClassDefFoundErrorNull() - { + public void testHandleExceptionNoClassDefFoundErrorNull() { Throwable cause2 = new NoClassDefFoundError(); Plugin plugin = new Plugin(); - Exception cause = new PluginContainerException( plugin, null, null, cause2 ); + Exception cause = new PluginContainerException(plugin, null, null, cause2); PluginDescriptor pluginDescriptor = new PluginDescriptor(); MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setPluginDescriptor( pluginDescriptor ); + mojoDescriptor.setPluginDescriptor(pluginDescriptor); MojoExecution mojoExecution = new MojoExecution(mojoDescriptor); - Throwable exception = new PluginExecutionException( mojoExecution, null, cause ); + Throwable exception = new PluginExecutionException(mojoExecution, null, cause); DefaultExceptionHandler handler = new DefaultExceptionHandler(); - ExceptionSummary summary = handler.handleException( exception ); + ExceptionSummary summary = handler.handleException(exception); String expectedReference = "http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException"; - assertEquals( expectedReference, summary.getReference() ); + assertEquals(expectedReference, summary.getReference()); } } diff --git a/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzerTest.java b/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzerTest.java index eba0e4d52d..d08943f4d4 100644 --- a/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzerTest.java +++ b/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,22 +16,21 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.lifecycle.LifecycleExecutionException; -import org.apache.maven.model.Dependency; -import org.apache.maven.project.MavenProject; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.Optional; +package org.apache.maven.execution; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class DefaultBuildResumptionAnalyzerTest -{ +import java.util.Optional; +import org.apache.maven.lifecycle.LifecycleExecutionException; +import org.apache.maven.model.Dependency; +import org.apache.maven.project.MavenProject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class DefaultBuildResumptionAnalyzerTest { private final DefaultBuildResumptionAnalyzer analyzer = new DefaultBuildResumptionAnalyzer(); private MavenExecutionResult executionResult; @@ -44,108 +41,98 @@ public class DefaultBuildResumptionAnalyzerTest } @Test - public void resumeFromGetsDetermined() - { - MavenProject projectA = createSucceededMavenProject( "A" ); - MavenProject projectB = createFailedMavenProject( "B" ); - executionResult.setTopologicallySortedProjects( asList( projectA, projectB ) ); + public void resumeFromGetsDetermined() { + MavenProject projectA = createSucceededMavenProject("A"); + MavenProject projectB = createFailedMavenProject("B"); + executionResult.setTopologicallySortedProjects(asList(projectA, projectB)); - Optional result = analyzer.determineBuildResumptionData( executionResult ); + Optional result = analyzer.determineBuildResumptionData(executionResult); - assertThat( result.isPresent(), is( true ) ); - assertThat( result.get().getRemainingProjects(), is( asList ( "test:B" ) ) ); + assertThat(result.isPresent(), is(true)); + assertThat(result.get().getRemainingProjects(), is(asList("test:B"))); } @Test - public void resumeFromIsIgnoredWhenFirstProjectFails() - { - MavenProject projectA = createFailedMavenProject( "A" ); - MavenProject projectB = createMavenProject( "B" ); - executionResult.setTopologicallySortedProjects( asList( projectA, projectB ) ); + public void resumeFromIsIgnoredWhenFirstProjectFails() { + MavenProject projectA = createFailedMavenProject("A"); + MavenProject projectB = createMavenProject("B"); + executionResult.setTopologicallySortedProjects(asList(projectA, projectB)); - Optional result = analyzer.determineBuildResumptionData( executionResult ); + Optional result = analyzer.determineBuildResumptionData(executionResult); - assertThat( result.isPresent(), is( false ) ); + assertThat(result.isPresent(), is(false)); } @Test - public void projectsSucceedingAfterFailedProjectsAreExcluded() - { - MavenProject projectA = createSucceededMavenProject( "A" ); - MavenProject projectB = createFailedMavenProject( "B" ); - MavenProject projectC = createSucceededMavenProject( "C" ); - executionResult.setTopologicallySortedProjects( asList( projectA, projectB, projectC ) ); + public void projectsSucceedingAfterFailedProjectsAreExcluded() { + MavenProject projectA = createSucceededMavenProject("A"); + MavenProject projectB = createFailedMavenProject("B"); + MavenProject projectC = createSucceededMavenProject("C"); + executionResult.setTopologicallySortedProjects(asList(projectA, projectB, projectC)); - Optional result = analyzer.determineBuildResumptionData( executionResult ); + Optional result = analyzer.determineBuildResumptionData(executionResult); - assertThat( result.isPresent(), is( true ) ); - assertThat( result.get().getRemainingProjects(), is( asList( "test:B" ) ) ); + assertThat(result.isPresent(), is(true)); + assertThat(result.get().getRemainingProjects(), is(asList("test:B"))); } @Test - public void projectsDependingOnFailedProjectsAreNotExcluded() - { - MavenProject projectA = createSucceededMavenProject( "A" ); - MavenProject projectB = createFailedMavenProject( "B" ); - MavenProject projectC = createSkippedMavenProject( "C" ); - projectC.setDependencies( singletonList( toDependency( projectB ) ) ); - executionResult.setTopologicallySortedProjects( asList( projectA, projectB, projectC ) ); + public void projectsDependingOnFailedProjectsAreNotExcluded() { + MavenProject projectA = createSucceededMavenProject("A"); + MavenProject projectB = createFailedMavenProject("B"); + MavenProject projectC = createSkippedMavenProject("C"); + projectC.setDependencies(singletonList(toDependency(projectB))); + executionResult.setTopologicallySortedProjects(asList(projectA, projectB, projectC)); - Optional result = analyzer.determineBuildResumptionData( executionResult ); + Optional result = analyzer.determineBuildResumptionData(executionResult); - assertThat( result.isPresent(), is( true ) ); - assertThat( result.get().getRemainingProjects(), is( asList( "test:B", "test:C" ) ) ); + assertThat(result.isPresent(), is(true)); + assertThat(result.get().getRemainingProjects(), is(asList("test:B", "test:C"))); } @Test - public void projectsFailingAfterAnotherFailedProjectAreNotExcluded() - { - MavenProject projectA = createSucceededMavenProject( "A" ); - MavenProject projectB = createFailedMavenProject( "B" ); - MavenProject projectC = createSucceededMavenProject( "C" ); - MavenProject projectD = createFailedMavenProject( "D" ); - executionResult.setTopologicallySortedProjects( asList( projectA, projectB, projectC, projectD ) ); + public void projectsFailingAfterAnotherFailedProjectAreNotExcluded() { + MavenProject projectA = createSucceededMavenProject("A"); + MavenProject projectB = createFailedMavenProject("B"); + MavenProject projectC = createSucceededMavenProject("C"); + MavenProject projectD = createFailedMavenProject("D"); + executionResult.setTopologicallySortedProjects(asList(projectA, projectB, projectC, projectD)); - Optional result = analyzer.determineBuildResumptionData( executionResult ); + Optional result = analyzer.determineBuildResumptionData(executionResult); - assertThat( result.isPresent(), is( true ) ); - assertThat( result.get().getRemainingProjects(), is( asList ( "test:B", "test:D" ) ) ); + assertThat(result.isPresent(), is(true)); + assertThat(result.get().getRemainingProjects(), is(asList("test:B", "test:D"))); } - private MavenProject createMavenProject( String artifactId ) - { + private MavenProject createMavenProject(String artifactId) { MavenProject project = new MavenProject(); - project.setGroupId( "test" ); - project.setArtifactId( artifactId ); + project.setGroupId("test"); + project.setArtifactId(artifactId); return project; } - private Dependency toDependency(MavenProject mavenProject ) - { + private Dependency toDependency(MavenProject mavenProject) { Dependency dependency = new Dependency(); - dependency.setGroupId( mavenProject.getGroupId() ); - dependency.setArtifactId( mavenProject.getArtifactId() ); - dependency.setVersion( mavenProject.getVersion() ); + dependency.setGroupId(mavenProject.getGroupId()); + dependency.setArtifactId(mavenProject.getArtifactId()); + dependency.setVersion(mavenProject.getVersion()); return dependency; } - private MavenProject createSkippedMavenProject( String artifactId ) - { - return createMavenProject( artifactId ); + private MavenProject createSkippedMavenProject(String artifactId) { + return createMavenProject(artifactId); } - private MavenProject createSucceededMavenProject( String artifactId ) - { - MavenProject project = createMavenProject( artifactId ); - executionResult.addBuildSummary( new BuildSuccess( project, 0 ) ); + private MavenProject createSucceededMavenProject(String artifactId) { + MavenProject project = createMavenProject(artifactId); + executionResult.addBuildSummary(new BuildSuccess(project, 0)); return project; } - private MavenProject createFailedMavenProject( String artifactId ) - { - MavenProject project = createMavenProject( artifactId ); - executionResult.addBuildSummary( new BuildFailure( project, 0, new Exception() ) ); - executionResult.addException( new LifecycleExecutionException( "", project ) ); + private MavenProject createFailedMavenProject(String artifactId) { + MavenProject project = createMavenProject(artifactId); + executionResult.addBuildSummary(new BuildFailure(project, 0, new Exception())); + executionResult.addException(new LifecycleExecutionException("", project)); return project; } -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionDataRepositoryTest.java b/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionDataRepositoryTest.java index ce7ab6a470..05fd948bf2 100644 --- a/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionDataRepositoryTest.java +++ b/maven-core/src/test/java/org/apache/maven/execution/DefaultBuildResumptionDataRepositoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,7 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.model.Build; -import org.apache.maven.project.MavenProject; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; +package org.apache.maven.execution; import static java.util.Collections.singleton; import static org.hamcrest.MatcherAssert.assertThat; @@ -33,73 +24,78 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; -public class DefaultBuildResumptionDataRepositoryTest -{ +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.apache.maven.model.Build; +import org.apache.maven.project.MavenProject; +import org.junit.jupiter.api.Test; + +public class DefaultBuildResumptionDataRepositoryTest { private final DefaultBuildResumptionDataRepository repository = new DefaultBuildResumptionDataRepository(); @Test - public void resumeFromPropertyGetsApplied() - { + public void resumeFromPropertyGetsApplied() { MavenExecutionRequest request = new DefaultMavenExecutionRequest(); Properties properties = new Properties(); - properties.setProperty( "remainingProjects", ":module-a" ); + properties.setProperty("remainingProjects", ":module-a"); - repository.applyResumptionProperties( request, properties ); + repository.applyResumptionProperties(request, properties); - assertThat( request.getProjectActivation().getOptionalActiveProjectSelectors(), is( singleton( ":module-a" ) ) ); + assertThat(request.getProjectActivation().getOptionalActiveProjectSelectors(), is(singleton(":module-a"))); } @Test - public void resumeFromPropertyDoesNotOverrideExistingRequestParameters() - { + public void resumeFromPropertyDoesNotOverrideExistingRequestParameters() { MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setResumeFrom( ":module-b" ); + request.setResumeFrom(":module-b"); Properties properties = new Properties(); - properties.setProperty( "remainingProjects", ":module-a" ); + properties.setProperty("remainingProjects", ":module-a"); - repository.applyResumptionProperties( request, properties ); + repository.applyResumptionProperties(request, properties); - assertThat( request.getResumeFrom(), is( ":module-b" ) ); + assertThat(request.getResumeFrom(), is(":module-b")); } @Test - public void projectsFromPropertyGetsAddedToExistingRequestParameters() - { + public void projectsFromPropertyGetsAddedToExistingRequestParameters() { MavenExecutionRequest request = new DefaultMavenExecutionRequest(); List selectedProjects = new ArrayList<>(); - selectedProjects.add( ":module-a" ); - request.setSelectedProjects( selectedProjects ); + selectedProjects.add(":module-a"); + request.setSelectedProjects(selectedProjects); Properties properties = new Properties(); - properties.setProperty( "remainingProjects", ":module-b, :module-c" ); + properties.setProperty("remainingProjects", ":module-b, :module-c"); - repository.applyResumptionProperties( request, properties ); + repository.applyResumptionProperties(request, properties); - assertThat( request.getProjectActivation().getOptionalActiveProjectSelectors(), containsInAnyOrder( ":module-a", ":module-b", ":module-c" ) ); + assertThat( + request.getProjectActivation().getOptionalActiveProjectSelectors(), + containsInAnyOrder(":module-a", ":module-b", ":module-c")); } @Test - public void selectedProjectsAreNotAddedWhenPropertyValueIsEmpty() - { + public void selectedProjectsAreNotAddedWhenPropertyValueIsEmpty() { MavenExecutionRequest request = new DefaultMavenExecutionRequest(); Properties properties = new Properties(); - properties.setProperty( "remainingProjects", "" ); + properties.setProperty("remainingProjects", ""); - repository.applyResumptionProperties( request, properties ); + repository.applyResumptionProperties(request, properties); - assertThat( request.getProjectActivation().getOptionalActiveProjectSelectors(), is( empty() ) ); + assertThat(request.getProjectActivation().getOptionalActiveProjectSelectors(), is(empty())); } @Test - public void applyResumptionData_shouldLoadData() - { + public void applyResumptionData_shouldLoadData() { MavenExecutionRequest request = new DefaultMavenExecutionRequest(); Build build = new Build(); - build.setDirectory( "src/test/resources/org/apache/maven/execution/" ); + build.setDirectory("src/test/resources/org/apache/maven/execution/"); MavenProject rootProject = new MavenProject(); - rootProject.setBuild( build ); + rootProject.setBuild(build); - repository.applyResumptionData( request, rootProject ); + repository.applyResumptionData(request, rootProject); - assertThat( request.getProjectActivation().getOptionalActiveProjectSelectors(), containsInAnyOrder( "example:module-c" ) ); + assertThat( + request.getProjectActivation().getOptionalActiveProjectSelectors(), + containsInAnyOrder("example:module-c")); } } diff --git a/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulatorTest.java b/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulatorTest.java index 02be60e0fd..804ff52358 100644 --- a/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulatorTest.java +++ b/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionRequestPopulatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,11 +16,12 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; - import javax.inject.Inject; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Repository; @@ -30,37 +29,32 @@ import org.apache.maven.settings.Settings; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - @PlexusTest -public class DefaultMavenExecutionRequestPopulatorTest -{ +public class DefaultMavenExecutionRequestPopulatorTest { @Inject MavenExecutionRequestPopulator testee; @Test - public void testPluginRepositoryInjection() - throws Exception - { + public void testPluginRepositoryInjection() throws Exception { MavenExecutionRequest request = new DefaultMavenExecutionRequest(); Repository r = new Repository(); - r.setId( "test" ); - r.setUrl( "file:///test" ); + r.setId("test"); + r.setUrl("file:///test"); Profile p = new Profile(); - p.setId( "test" ); - p.addPluginRepository( r ); + p.setId("test"); + p.addPluginRepository(r); Settings settings = new Settings(); - settings.addProfile( p ); - settings.addActiveProfile( p.getId() ); + settings.addProfile(p); + settings.addActiveProfile(p.getId()); - testee.populateFromSettings( request, settings ); + testee.populateFromSettings(request, settings); List repositories = request.getPluginArtifactRepositories(); - assertEquals( 1, repositories.size() ); - assertEquals( r.getId(), repositories.get( 0 ).getId() ); - assertEquals( r.getUrl(), repositories.get( 0 ).getUrl() ); + assertEquals(1, repositories.size()); + assertEquals(r.getId(), repositories.get(0).getId()); + assertEquals(r.getUrl(), repositories.get(0).getUrl()); } } diff --git a/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionTest.java b/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionTest.java index f8f5e0afbf..e07d1b9ddc 100644 --- a/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionTest.java +++ b/maven-core/src/test/java/org/apache/maven/execution/DefaultMavenExecutionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.execution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.execution; * "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 + * 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 @@ -18,40 +16,36 @@ package org.apache.maven.execution; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.execution; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.hamcrest.MatcherAssert.assertThat; import java.util.List; - import org.apache.maven.project.MavenProject; import org.junit.jupiter.api.Test; /** * @author Benjamin Bentmann */ -public class DefaultMavenExecutionTest -{ +public class DefaultMavenExecutionTest { @Test - public void testCopyDefault() - { + public void testCopyDefault() { MavenExecutionRequest original = new DefaultMavenExecutionRequest(); - MavenExecutionRequest copy = DefaultMavenExecutionRequest.copy( original ); - assertNotNull( copy ); - assertNotSame( copy, original ); + MavenExecutionRequest copy = DefaultMavenExecutionRequest.copy(original); + assertNotNull(copy); + assertNotSame(copy, original); } @Test - public void testResultWithNullTopologicallySortedProjectsIsEmptyList() - { + public void testResultWithNullTopologicallySortedProjectsIsEmptyList() { MavenExecutionResult result = new DefaultMavenExecutionResult(); - result.setTopologicallySortedProjects( null ); + result.setTopologicallySortedProjects(null); List projects = result.getTopologicallySortedProjects(); - assertNotNull( projects ); - assertThat( projects, is( empty() ) ); + assertNotNull(projects); + assertThat(projects, is(empty())); } - } diff --git a/maven-core/src/test/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeTest.java b/maven-core/src/test/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeTest.java index 0dda0501b0..c5787d5729 100644 --- a/maven-core/src/test/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeTest.java +++ b/maven-core/src/test/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeTest.java @@ -1,101 +1,96 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.maven.execution.scope.internal; -import java.util.concurrent.atomic.AtomicInteger; - -import com.google.inject.Key; -import org.apache.maven.execution.MojoExecutionEvent; -import org.apache.maven.execution.scope.WeakMojoExecutionListener; -import org.apache.maven.plugin.MojoExecutionException; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; -public class MojoExecutionScopeTest -{ +import com.google.inject.Key; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.maven.execution.MojoExecutionEvent; +import org.apache.maven.execution.scope.WeakMojoExecutionListener; +import org.apache.maven.plugin.MojoExecutionException; +import org.junit.jupiter.api.Test; + +public class MojoExecutionScopeTest { @Test - public void testNestedEnter() - throws Exception - { + public void testNestedEnter() throws Exception { MojoExecutionScope scope = new MojoExecutionScope(); scope.enter(); Object o1 = new Object(); - scope.seed( Object.class, o1 ); - assertSame( o1, scope.scope( Key.get( Object.class ), null ).get() ); + scope.seed(Object.class, o1); + assertSame(o1, scope.scope(Key.get(Object.class), null).get()); scope.enter(); Object o2 = new Object(); - scope.seed( Object.class, o2 ); - assertSame( o2, scope.scope( Key.get( Object.class ), null ).get() ); + scope.seed(Object.class, o2); + assertSame(o2, scope.scope(Key.get(Object.class), null).get()); scope.exit(); - assertSame( o1, scope.scope( Key.get( Object.class ), null ).get() ); + assertSame(o1, scope.scope(Key.get(Object.class), null).get()); scope.exit(); - assertThrows( IllegalStateException.class, () -> scope.exit() ); + assertThrows(IllegalStateException.class, () -> scope.exit()); } @Test - public void testMultiKeyInstance() - throws Exception - { + public void testMultiKeyInstance() throws Exception { MojoExecutionScope scope = new MojoExecutionScope(); scope.enter(); final AtomicInteger beforeExecution = new AtomicInteger(); final AtomicInteger afterExecutionSuccess = new AtomicInteger(); final AtomicInteger afterExecutionFailure = new AtomicInteger(); - final WeakMojoExecutionListener instance = new WeakMojoExecutionListener() - { + final WeakMojoExecutionListener instance = new WeakMojoExecutionListener() { @Override - public void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException - { + public void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException { beforeExecution.incrementAndGet(); } @Override - public void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException - { + public void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException { afterExecutionSuccess.incrementAndGet(); } @Override - public void afterExecutionFailure( MojoExecutionEvent event ) - { + public void afterExecutionFailure(MojoExecutionEvent event) { afterExecutionFailure.incrementAndGet(); } }; - assertSame( instance, scope.scope( Key.get( Object.class ), () -> instance ).get() ); - assertSame( instance, scope.scope( Key.get( WeakMojoExecutionListener.class ), () -> instance ).get() ); + assertSame(instance, scope.scope(Key.get(Object.class), () -> instance).get()); + assertSame( + instance, + scope.scope(Key.get(WeakMojoExecutionListener.class), () -> instance) + .get()); - final MojoExecutionEvent event = new MojoExecutionEvent( null, null, null, null ); - scope.beforeMojoExecution( event ); - scope.afterMojoExecutionSuccess( event ); - scope.afterExecutionFailure( event ); + final MojoExecutionEvent event = new MojoExecutionEvent(null, null, null, null); + scope.beforeMojoExecution(event); + scope.afterMojoExecutionSuccess(event); + scope.afterExecutionFailure(event); - assertEquals( 1, beforeExecution.get() ); - assertEquals( 1, afterExecutionSuccess.get() ); - assertEquals( 1, afterExecutionFailure.get() ); + assertEquals(1, beforeExecution.get()); + assertEquals(1, afterExecutionSuccess.get()); + assertEquals(1, afterExecutionFailure.get()); scope.exit(); } diff --git a/maven-core/src/test/java/org/apache/maven/graph/DefaultGraphBuilderTest.java b/maven-core/src/test/java/org/apache/maven/graph/DefaultGraphBuilderTest.java index 8ff4711446..5744ab74cf 100644 --- a/maven-core/src/test/java/org/apache/maven/graph/DefaultGraphBuilderTest.java +++ b/maven-core/src/test/java/org/apache/maven/graph/DefaultGraphBuilderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.graph; * "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 + * 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 @@ -18,7 +16,32 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.graph; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toList; +import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM; +import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_UPSTREAM; +import static org.apache.maven.graph.DefaultGraphBuilderTest.ScenarioBuilder.scenario; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.maven.MavenExecutionException; import org.apache.maven.execution.BuildResumptionDataRepository; import org.apache.maven.execution.MavenExecutionRequest; @@ -45,33 +68,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.toList; -import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM; -import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_UPSTREAM; -import static org.apache.maven.graph.DefaultGraphBuilderTest.ScenarioBuilder.scenario; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class DefaultGraphBuilderTest -{ +class DefaultGraphBuilderTest { /* The multi-module structure in this project is displayed as follows: @@ -94,167 +91,184 @@ class DefaultGraphBuilderTest private DefaultGraphBuilder graphBuilder; - private final ProjectBuilder projectBuilder = mock( ProjectBuilder.class ); - private final MavenSession session = mock( MavenSession.class ); - private final MavenExecutionRequest mavenExecutionRequest = mock( MavenExecutionRequest.class ); + private final ProjectBuilder projectBuilder = mock(ProjectBuilder.class); + private final MavenSession session = mock(MavenSession.class); + private final MavenExecutionRequest mavenExecutionRequest = mock(MavenExecutionRequest.class); - private final ProjectsSelector projectsSelector = new DefaultProjectsSelector( projectBuilder ); + private final ProjectsSelector projectsSelector = new DefaultProjectsSelector(projectBuilder); // Not using mocks for these strategies - a mock would just copy the actual implementation. private final ModelLocator modelLocator = new DefaultModelLocator(); - private final PomlessCollectionStrategy pomlessCollectionStrategy = new PomlessCollectionStrategy( projectBuilder ); - private final MultiModuleCollectionStrategy multiModuleCollectionStrategy = new MultiModuleCollectionStrategy( modelLocator, projectsSelector ); - private final RequestPomCollectionStrategy requestPomCollectionStrategy = new RequestPomCollectionStrategy( projectsSelector ); + private final PomlessCollectionStrategy pomlessCollectionStrategy = new PomlessCollectionStrategy(projectBuilder); + private final MultiModuleCollectionStrategy multiModuleCollectionStrategy = + new MultiModuleCollectionStrategy(modelLocator, projectsSelector); + private final RequestPomCollectionStrategy requestPomCollectionStrategy = + new RequestPomCollectionStrategy(projectsSelector); private Map artifactIdProjectMap; - public static Stream parameters() - { + public static Stream parameters() { return Stream.of( - scenario( "Full reactor in order" ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Selected project" ) - .activeRequiredProjects( MODULE_B ) - .expectResult( MODULE_B ), - scenario( "Selected aggregator project (including child modules)" ) - .activeRequiredProjects( MODULE_C ) - .expectResult( MODULE_C, MODULE_C_1, MODULE_C_2 ), - scenario( "Selected aggregator project with non-recursive" ) - .activeRequiredProjects( MODULE_C ) + scenario("Full reactor in order") + .expectResult( + PARENT_MODULE, + MODULE_C, + MODULE_C_1, + MODULE_A, + MODULE_B, + MODULE_C_2, + INDEPENDENT_MODULE), + scenario("Selected project").activeRequiredProjects(MODULE_B).expectResult(MODULE_B), + scenario("Selected aggregator project (including child modules)") + .activeRequiredProjects(MODULE_C) + .expectResult(MODULE_C, MODULE_C_1, MODULE_C_2), + scenario("Selected aggregator project with non-recursive") + .activeRequiredProjects(MODULE_C) .nonRecursive() - .expectResult( MODULE_C ), - scenario( "Selected optional project" ) - .activeOptionalProjects( MODULE_B ) - .expectResult( MODULE_B ), - scenario( "Selected missing optional project" ) - .activeOptionalProjects( "non-existing-module" ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Selected missing optional and required project" ) - .activeOptionalProjects( "non-existing-module" ) - .activeRequiredProjects( MODULE_B ) - .expectResult( MODULE_B ), - scenario( "Excluded project" ) - .inactiveRequiredProjects( MODULE_B ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Excluded optional project" ) - .inactiveOptionalProjects( MODULE_B ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Excluded missing optional project" ) - .inactiveOptionalProjects( "non-existing-module" ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Excluded missing optional and required project" ) - .inactiveOptionalProjects( "non-existing-module" ) - .inactiveRequiredProjects( MODULE_B ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Excluded aggregator project with non-recursive" ) - .inactiveRequiredProjects( MODULE_C ) + .expectResult(MODULE_C), + scenario("Selected optional project") + .activeOptionalProjects(MODULE_B) + .expectResult(MODULE_B), + scenario("Selected missing optional project") + .activeOptionalProjects("non-existing-module") + .expectResult( + PARENT_MODULE, + MODULE_C, + MODULE_C_1, + MODULE_A, + MODULE_B, + MODULE_C_2, + INDEPENDENT_MODULE), + scenario("Selected missing optional and required project") + .activeOptionalProjects("non-existing-module") + .activeRequiredProjects(MODULE_B) + .expectResult(MODULE_B), + scenario("Excluded project") + .inactiveRequiredProjects(MODULE_B) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Excluded optional project") + .inactiveOptionalProjects(MODULE_B) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Excluded missing optional project") + .inactiveOptionalProjects("non-existing-module") + .expectResult( + PARENT_MODULE, + MODULE_C, + MODULE_C_1, + MODULE_A, + MODULE_B, + MODULE_C_2, + INDEPENDENT_MODULE), + scenario("Excluded missing optional and required project") + .inactiveOptionalProjects("non-existing-module") + .inactiveRequiredProjects(MODULE_B) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Excluded aggregator project with non-recursive") + .inactiveRequiredProjects(MODULE_C) .nonRecursive() - .expectResult( PARENT_MODULE, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Selected and excluded same project" ) - .activeRequiredProjects( MODULE_A ) - .inactiveRequiredProjects( MODULE_A ) - .expectResult( MavenExecutionException.class, "empty reactor" ), - scenario( "Excluded aggregator, but selected child" ) - .activeRequiredProjects( MODULE_C_1 ) - .inactiveRequiredProjects( MODULE_C ) - .expectResult( MavenExecutionException.class, "empty reactor" ), - scenario( "Project selected with different selector resolves to same project" ) - .activeRequiredProjects( GROUP_ID + ":" + MODULE_A ) - .inactiveRequiredProjects( MODULE_A ) - .expectResult( MavenExecutionException.class, "empty reactor" ), - scenario( "Selected and excluded same project, but also selected another project" ) - .activeRequiredProjects( MODULE_A, MODULE_B ) - .inactiveRequiredProjects( MODULE_A ) - .expectResult( MODULE_B ), - scenario( "Selected missing project as required and as optional" ) - .activeRequiredProjects( "non-existing-module" ) - .activeOptionalProjects( "non-existing-module" ) - .expectResult( MavenExecutionException.class, "not find the selected project" ), - scenario( "Resuming from project" ) - .resumeFrom( MODULE_B ) - .expectResult( MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Selected project with also make dependencies" ) - .activeRequiredProjects( MODULE_C_2 ) - .makeBehavior( REACTOR_MAKE_UPSTREAM ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2 ), - scenario( "Selected project with also make dependents" ) - .activeRequiredProjects( MODULE_B ) - .makeBehavior( REACTOR_MAKE_DOWNSTREAM ) - .expectResult( MODULE_B, MODULE_C_2 ), - scenario( "Resuming from project with also make dependencies" ) - .makeBehavior( REACTOR_MAKE_UPSTREAM ) - .resumeFrom( MODULE_C_2 ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Selected project with resume from and also make dependency (MNG-4960 IT#1)" ) - .activeRequiredProjects( MODULE_C_2 ) - .resumeFrom( MODULE_B ) - .makeBehavior( REACTOR_MAKE_UPSTREAM ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2 ), - scenario( "Selected project with resume from and also make dependent (MNG-4960 IT#2)" ) - .activeRequiredProjects( MODULE_B ) - .resumeFrom( MODULE_C_2 ) - .makeBehavior( REACTOR_MAKE_DOWNSTREAM ) - .expectResult( MODULE_C_2 ), - scenario( "Excluding an also make dependency from selectedProject does take its transitive dependency" ) - .activeRequiredProjects( MODULE_C_2 ) - .inactiveRequiredProjects( MODULE_B ) - .makeBehavior( REACTOR_MAKE_UPSTREAM ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_C_2 ), - scenario( "Excluding a project also excludes its children" ) - .inactiveRequiredProjects( MODULE_C ) - .expectResult( PARENT_MODULE, MODULE_A, MODULE_B, INDEPENDENT_MODULE ), - scenario( "Excluding an also make dependency from resumeFrom does take its transitive dependency" ) - .resumeFrom( MODULE_C_2 ) - .inactiveRequiredProjects( MODULE_B ) - .makeBehavior( REACTOR_MAKE_UPSTREAM ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Resume from exclude project downstream" ) - .resumeFrom( MODULE_A ) - .inactiveRequiredProjects( MODULE_B ) - .expectResult( MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Exclude the project we are resuming from (as proposed in MNG-6676)" ) - .resumeFrom( MODULE_B ) - .inactiveRequiredProjects( MODULE_B ) - .expectResult( MODULE_C_2, INDEPENDENT_MODULE ), - scenario( "Selected projects in wrong order are resumed correctly in order" ) - .activeRequiredProjects( MODULE_C_2, MODULE_B, MODULE_A ) - .resumeFrom( MODULE_B ) - .expectResult( MODULE_B, MODULE_C_2 ), - scenario( "Duplicate projects are filtered out" ) - .activeRequiredProjects( MODULE_A, MODULE_A ) - .expectResult( MODULE_A ), - scenario( "Select reactor by specific pom" ) - .requestedPom( MODULE_C ) - .expectResult( MODULE_C, MODULE_C_1, MODULE_C_2 ), - scenario( "Select reactor by specific pom with also make dependencies" ) - .requestedPom( MODULE_C ) - .makeBehavior( REACTOR_MAKE_UPSTREAM ) - .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2 ), - scenario( "Select reactor by specific pom with also make dependents" ) - .requestedPom( MODULE_B ) - .makeBehavior( REACTOR_MAKE_DOWNSTREAM ) - .expectResult( MODULE_B, MODULE_C_2 ) - ); + .expectResult(PARENT_MODULE, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Selected and excluded same project") + .activeRequiredProjects(MODULE_A) + .inactiveRequiredProjects(MODULE_A) + .expectResult(MavenExecutionException.class, "empty reactor"), + scenario("Excluded aggregator, but selected child") + .activeRequiredProjects(MODULE_C_1) + .inactiveRequiredProjects(MODULE_C) + .expectResult(MavenExecutionException.class, "empty reactor"), + scenario("Project selected with different selector resolves to same project") + .activeRequiredProjects(GROUP_ID + ":" + MODULE_A) + .inactiveRequiredProjects(MODULE_A) + .expectResult(MavenExecutionException.class, "empty reactor"), + scenario("Selected and excluded same project, but also selected another project") + .activeRequiredProjects(MODULE_A, MODULE_B) + .inactiveRequiredProjects(MODULE_A) + .expectResult(MODULE_B), + scenario("Selected missing project as required and as optional") + .activeRequiredProjects("non-existing-module") + .activeOptionalProjects("non-existing-module") + .expectResult(MavenExecutionException.class, "not find the selected project"), + scenario("Resuming from project") + .resumeFrom(MODULE_B) + .expectResult(MODULE_B, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Selected project with also make dependencies") + .activeRequiredProjects(MODULE_C_2) + .makeBehavior(REACTOR_MAKE_UPSTREAM) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2), + scenario("Selected project with also make dependents") + .activeRequiredProjects(MODULE_B) + .makeBehavior(REACTOR_MAKE_DOWNSTREAM) + .expectResult(MODULE_B, MODULE_C_2), + scenario("Resuming from project with also make dependencies") + .makeBehavior(REACTOR_MAKE_UPSTREAM) + .resumeFrom(MODULE_C_2) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Selected project with resume from and also make dependency (MNG-4960 IT#1)") + .activeRequiredProjects(MODULE_C_2) + .resumeFrom(MODULE_B) + .makeBehavior(REACTOR_MAKE_UPSTREAM) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2), + scenario("Selected project with resume from and also make dependent (MNG-4960 IT#2)") + .activeRequiredProjects(MODULE_B) + .resumeFrom(MODULE_C_2) + .makeBehavior(REACTOR_MAKE_DOWNSTREAM) + .expectResult(MODULE_C_2), + scenario("Excluding an also make dependency from selectedProject does take its transitive dependency") + .activeRequiredProjects(MODULE_C_2) + .inactiveRequiredProjects(MODULE_B) + .makeBehavior(REACTOR_MAKE_UPSTREAM) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_A, MODULE_C_2), + scenario("Excluding a project also excludes its children") + .inactiveRequiredProjects(MODULE_C) + .expectResult(PARENT_MODULE, MODULE_A, MODULE_B, INDEPENDENT_MODULE), + scenario("Excluding an also make dependency from resumeFrom does take its transitive dependency") + .resumeFrom(MODULE_C_2) + .inactiveRequiredProjects(MODULE_B) + .makeBehavior(REACTOR_MAKE_UPSTREAM) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Resume from exclude project downstream") + .resumeFrom(MODULE_A) + .inactiveRequiredProjects(MODULE_B) + .expectResult(MODULE_A, MODULE_C_2, INDEPENDENT_MODULE), + scenario("Exclude the project we are resuming from (as proposed in MNG-6676)") + .resumeFrom(MODULE_B) + .inactiveRequiredProjects(MODULE_B) + .expectResult(MODULE_C_2, INDEPENDENT_MODULE), + scenario("Selected projects in wrong order are resumed correctly in order") + .activeRequiredProjects(MODULE_C_2, MODULE_B, MODULE_A) + .resumeFrom(MODULE_B) + .expectResult(MODULE_B, MODULE_C_2), + scenario("Duplicate projects are filtered out") + .activeRequiredProjects(MODULE_A, MODULE_A) + .expectResult(MODULE_A), + scenario("Select reactor by specific pom") + .requestedPom(MODULE_C) + .expectResult(MODULE_C, MODULE_C_1, MODULE_C_2), + scenario("Select reactor by specific pom with also make dependencies") + .requestedPom(MODULE_C) + .makeBehavior(REACTOR_MAKE_UPSTREAM) + .expectResult(PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2), + scenario("Select reactor by specific pom with also make dependents") + .requestedPom(MODULE_B) + .makeBehavior(REACTOR_MAKE_DOWNSTREAM) + .expectResult(MODULE_B, MODULE_C_2)); } - interface ExpectedResult { + interface ExpectedResult {} - } static class SelectedProjectsResult implements ExpectedResult { final List projectNames; - public SelectedProjectsResult( List projectSelectors ) - { + public SelectedProjectsResult(List projectSelectors) { this.projectNames = projectSelectors; } } + static class ExceptionThrown implements ExpectedResult { final Class expected; final String partOfMessage; - public ExceptionThrown( final Class expected, final String partOfMessage ) - { + public ExceptionThrown(final Class expected, final String partOfMessage) { this.expected = expected; this.partOfMessage = partOfMessage; } @@ -272,130 +286,136 @@ class DefaultGraphBuilderTest String parameterMakeBehavior, ExpectedResult parameterExpectedResult, File parameterRequestedPom, - boolean parameterRecursive ) - { + boolean parameterRecursive) { // Given ProjectActivation projectActivation = new ProjectActivation(); - parameterActiveRequiredProjects.forEach( projectActivation::activateRequiredProject ); - parameterActiveOptionalProjects.forEach( projectActivation::activateOptionalProject ); - parameterInactiveRequiredProjects.forEach( projectActivation::deactivateRequiredProject ); - parameterInactiveOptionalProjects.forEach( projectActivation::deactivateOptionalProject ); + parameterActiveRequiredProjects.forEach(projectActivation::activateRequiredProject); + parameterActiveOptionalProjects.forEach(projectActivation::activateOptionalProject); + parameterInactiveRequiredProjects.forEach(projectActivation::deactivateRequiredProject); + parameterInactiveOptionalProjects.forEach(projectActivation::deactivateOptionalProject); - when( mavenExecutionRequest.getProjectActivation() ).thenReturn( projectActivation ); - when( mavenExecutionRequest.getMakeBehavior() ).thenReturn( parameterMakeBehavior ); - when( mavenExecutionRequest.getPom() ).thenReturn( parameterRequestedPom ); - when( mavenExecutionRequest.isRecursive() ).thenReturn( parameterRecursive ); - if ( StringUtils.isNotEmpty( parameterResumeFrom ) ) - { - when( mavenExecutionRequest.getResumeFrom() ).thenReturn( ":" + parameterResumeFrom ); + when(mavenExecutionRequest.getProjectActivation()).thenReturn(projectActivation); + when(mavenExecutionRequest.getMakeBehavior()).thenReturn(parameterMakeBehavior); + when(mavenExecutionRequest.getPom()).thenReturn(parameterRequestedPom); + when(mavenExecutionRequest.isRecursive()).thenReturn(parameterRecursive); + if (StringUtils.isNotEmpty(parameterResumeFrom)) { + when(mavenExecutionRequest.getResumeFrom()).thenReturn(":" + parameterResumeFrom); } // When - Result result = graphBuilder.build( session ); + Result result = graphBuilder.build(session); // Then - if ( parameterExpectedResult instanceof SelectedProjectsResult ) - { - assertThat( result.hasErrors() ).withFailMessage( "Expected result not to have errors" ).isFalse(); + if (parameterExpectedResult instanceof SelectedProjectsResult) { + assertThat(result.hasErrors()) + .withFailMessage("Expected result not to have errors") + .isFalse(); List expectedProjectNames = ((SelectedProjectsResult) parameterExpectedResult).projectNames; List actualReactorProjects = result.get().getSortedProjects(); - List expectedReactorProjects = expectedProjectNames.stream() - .map( artifactIdProjectMap::get ) - .collect( toList() ); - assertEquals( expectedReactorProjects, actualReactorProjects, parameterDescription ); - } - else - { - assertThat( result.hasErrors() ).withFailMessage( "Expected result to have errors" ).isTrue(); + List expectedReactorProjects = + expectedProjectNames.stream().map(artifactIdProjectMap::get).collect(toList()); + assertEquals(expectedReactorProjects, actualReactorProjects, parameterDescription); + } else { + assertThat(result.hasErrors()) + .withFailMessage("Expected result to have errors") + .isTrue(); Class expectedException = ((ExceptionThrown) parameterExpectedResult).expected; String partOfMessage = ((ExceptionThrown) parameterExpectedResult).partOfMessage; - assertThat( result.getProblems() ).hasSize( 1 ); - result.getProblems().forEach( p -> - assertThat( p.getException() ).isInstanceOf( expectedException ).hasMessageContaining( partOfMessage ) - ); + assertThat(result.getProblems()).hasSize(1); + result.getProblems().forEach(p -> assertThat(p.getException()) + .isInstanceOf(expectedException) + .hasMessageContaining(partOfMessage)); } } @BeforeEach - public void before() throws Exception - { + public void before() throws Exception { graphBuilder = new DefaultGraphBuilder( - mock( BuildResumptionDataRepository.class ), + mock(BuildResumptionDataRepository.class), pomlessCollectionStrategy, multiModuleCollectionStrategy, - requestPomCollectionStrategy - ); + requestPomCollectionStrategy); // Create projects - MavenProject projectParent = getMavenProject( PARENT_MODULE ); - MavenProject projectIndependentModule = getMavenProject( INDEPENDENT_MODULE ); - MavenProject projectModuleA = getMavenProject( MODULE_A, projectParent ); - MavenProject projectModuleB = getMavenProject( MODULE_B, projectParent ); - MavenProject projectModuleC = getMavenProject( MODULE_C, projectParent ); - MavenProject projectModuleC1 = getMavenProject( MODULE_C_1, projectModuleC ); - MavenProject projectModuleC2 = getMavenProject( MODULE_C_2, projectModuleC ); + MavenProject projectParent = getMavenProject(PARENT_MODULE); + MavenProject projectIndependentModule = getMavenProject(INDEPENDENT_MODULE); + MavenProject projectModuleA = getMavenProject(MODULE_A, projectParent); + MavenProject projectModuleB = getMavenProject(MODULE_B, projectParent); + MavenProject projectModuleC = getMavenProject(MODULE_C, projectParent); + MavenProject projectModuleC1 = getMavenProject(MODULE_C_1, projectModuleC); + MavenProject projectModuleC2 = getMavenProject(MODULE_C_2, projectModuleC); - artifactIdProjectMap = Stream.of( projectParent, projectIndependentModule, projectModuleA, projectModuleB, projectModuleC, projectModuleC1, projectModuleC2 ) - .collect( Collectors.toMap( MavenProject::getArtifactId, identity() ) ); + artifactIdProjectMap = Stream.of( + projectParent, + projectIndependentModule, + projectModuleA, + projectModuleB, + projectModuleC, + projectModuleC1, + projectModuleC2) + .collect(Collectors.toMap(MavenProject::getArtifactId, identity())); // Set dependencies and modules - projectModuleB.setDependencies( singletonList( toDependency( projectModuleA ) ) ); - projectModuleC2.setDependencies( singletonList( toDependency( projectModuleB ) ) ); - projectParent.setCollectedProjects( asList( projectIndependentModule, projectModuleA, projectModuleB, projectModuleC, projectModuleC1, projectModuleC2 ) ); - projectModuleC.setCollectedProjects( asList( projectModuleC1, projectModuleC2 ) ); + projectModuleB.setDependencies(singletonList(toDependency(projectModuleA))); + projectModuleC2.setDependencies(singletonList(toDependency(projectModuleB))); + projectParent.setCollectedProjects(asList( + projectIndependentModule, + projectModuleA, + projectModuleB, + projectModuleC, + projectModuleC1, + projectModuleC2)); + projectModuleC.setCollectedProjects(asList(projectModuleC1, projectModuleC2)); // Set up needed mocks - when( session.getRequest() ).thenReturn( mavenExecutionRequest ); - when( session.getProjects() ).thenReturn( null ); // needed, otherwise it will be an empty list by default - when( mavenExecutionRequest.getProjectBuildingRequest() ).thenReturn( mock( ProjectBuildingRequest.class ) ); - List projectBuildingResults = createProjectBuildingResultMocks( artifactIdProjectMap.values() ); - when( projectBuilder.build( anyList(), anyBoolean(), any( ProjectBuildingRequest.class ) ) ).thenReturn( projectBuildingResults ); + when(session.getRequest()).thenReturn(mavenExecutionRequest); + when(session.getProjects()).thenReturn(null); // needed, otherwise it will be an empty list by default + when(mavenExecutionRequest.getProjectBuildingRequest()).thenReturn(mock(ProjectBuildingRequest.class)); + List projectBuildingResults = + createProjectBuildingResultMocks(artifactIdProjectMap.values()); + when(projectBuilder.build(anyList(), anyBoolean(), any(ProjectBuildingRequest.class))) + .thenReturn(projectBuildingResults); } - private MavenProject getMavenProject( String artifactId, MavenProject parentProject ) - { - MavenProject project = getMavenProject( artifactId ); + private MavenProject getMavenProject(String artifactId, MavenProject parentProject) { + MavenProject project = getMavenProject(artifactId); Parent parent = new Parent(); - parent.setGroupId( parentProject.getGroupId() ); - parent.setArtifactId( parentProject.getArtifactId() ); - project.getModel().setParent( parent ); + parent.setGroupId(parentProject.getGroupId()); + parent.setArtifactId(parentProject.getArtifactId()); + project.getModel().setParent(parent); return project; } - private MavenProject getMavenProject( String artifactId ) - { + private MavenProject getMavenProject(String artifactId) { MavenProject mavenProject = new MavenProject(); - mavenProject.setGroupId( GROUP_ID ); - mavenProject.setArtifactId( artifactId ); - mavenProject.setVersion( "1.0" ); - mavenProject.setPomFile( new File ( artifactId, "pom.xml" ) ); - mavenProject.setCollectedProjects( new ArrayList<>() ); + mavenProject.setGroupId(GROUP_ID); + mavenProject.setArtifactId(artifactId); + mavenProject.setVersion("1.0"); + mavenProject.setPomFile(new File(artifactId, "pom.xml")); + mavenProject.setCollectedProjects(new ArrayList<>()); return mavenProject; } - private Dependency toDependency( MavenProject mavenProject ) - { + private Dependency toDependency(MavenProject mavenProject) { Dependency dependency = new Dependency(); - dependency.setGroupId( mavenProject.getGroupId() ); - dependency.setArtifactId( mavenProject.getArtifactId() ); - dependency.setVersion( mavenProject.getVersion() ); + dependency.setGroupId(mavenProject.getGroupId()); + dependency.setArtifactId(mavenProject.getArtifactId()); + dependency.setVersion(mavenProject.getVersion()); return dependency; } - private List createProjectBuildingResultMocks( Collection projects ) - { + private List createProjectBuildingResultMocks(Collection projects) { return projects.stream() - .map( project -> { - ProjectBuildingResult result = mock( ProjectBuildingResult.class ); - when( result.getProject() ).thenReturn( project ); + .map(project -> { + ProjectBuildingResult result = mock(ProjectBuildingResult.class); + when(result.getProject()).thenReturn(project); return result; - } ) - .collect( toList() ); + }) + .collect(toList()); } - static class ScenarioBuilder - { + static class ScenarioBuilder { private String description; private List activeRequiredProjects = emptyList(); private List activeOptionalProjects = emptyList(); @@ -403,94 +423,87 @@ class DefaultGraphBuilderTest private List inactiveOptionalProjects = emptyList(); private String resumeFrom = ""; private String makeBehavior = ""; - private File requestedPom = new File( PARENT_MODULE, "pom.xml" ); + private File requestedPom = new File(PARENT_MODULE, "pom.xml"); private boolean recursive = true; - private ScenarioBuilder() { } + private ScenarioBuilder() {} - public static ScenarioBuilder scenario( String description ) - { + public static ScenarioBuilder scenario(String description) { ScenarioBuilder scenarioBuilder = new ScenarioBuilder(); scenarioBuilder.description = description; return scenarioBuilder; } - public ScenarioBuilder activeRequiredProjects( String... activeRequiredProjects ) - { - this.activeRequiredProjects = prependWithColonIfNeeded( activeRequiredProjects ); + public ScenarioBuilder activeRequiredProjects(String... activeRequiredProjects) { + this.activeRequiredProjects = prependWithColonIfNeeded(activeRequiredProjects); return this; } - public ScenarioBuilder activeOptionalProjects( String... activeOptionalProjects ) - { - this.activeOptionalProjects = prependWithColonIfNeeded( activeOptionalProjects ); + public ScenarioBuilder activeOptionalProjects(String... activeOptionalProjects) { + this.activeOptionalProjects = prependWithColonIfNeeded(activeOptionalProjects); return this; } - public ScenarioBuilder inactiveRequiredProjects( String... inactiveRequiredProjects ) - { - this.inactiveRequiredProjects = prependWithColonIfNeeded( inactiveRequiredProjects ); + public ScenarioBuilder inactiveRequiredProjects(String... inactiveRequiredProjects) { + this.inactiveRequiredProjects = prependWithColonIfNeeded(inactiveRequiredProjects); return this; } - public ScenarioBuilder inactiveOptionalProjects( String... inactiveOptionalProjects ) - { - this.inactiveOptionalProjects = prependWithColonIfNeeded( inactiveOptionalProjects ); + public ScenarioBuilder inactiveOptionalProjects(String... inactiveOptionalProjects) { + this.inactiveOptionalProjects = prependWithColonIfNeeded(inactiveOptionalProjects); return this; } - public ScenarioBuilder resumeFrom( String resumeFrom ) - { + public ScenarioBuilder resumeFrom(String resumeFrom) { this.resumeFrom = resumeFrom; return this; } - public ScenarioBuilder makeBehavior( String makeBehavior ) - { + public ScenarioBuilder makeBehavior(String makeBehavior) { this.makeBehavior = makeBehavior; return this; } - public ScenarioBuilder requestedPom( String requestedPom ) - { - this.requestedPom = new File( requestedPom, "pom.xml" ); + public ScenarioBuilder requestedPom(String requestedPom) { + this.requestedPom = new File(requestedPom, "pom.xml"); return this; } - public ScenarioBuilder nonRecursive() - { + public ScenarioBuilder nonRecursive() { this.recursive = false; return this; } - public Arguments expectResult( String... expectedReactorProjects ) - { - ExpectedResult expectedResult = new SelectedProjectsResult( asList( expectedReactorProjects ) ); - return createTestArguments( expectedResult ); + public Arguments expectResult(String... expectedReactorProjects) { + ExpectedResult expectedResult = new SelectedProjectsResult(asList(expectedReactorProjects)); + return createTestArguments(expectedResult); } - public Arguments expectResult( Class expected, final String partOfMessage ) - { - ExpectedResult expectedResult = new ExceptionThrown( expected, partOfMessage ); - return createTestArguments( expectedResult ); + public Arguments expectResult(Class expected, final String partOfMessage) { + ExpectedResult expectedResult = new ExceptionThrown(expected, partOfMessage); + return createTestArguments(expectedResult); } - private Arguments createTestArguments( ExpectedResult expectedResult ) - { - return Arguments.arguments( description, activeRequiredProjects, activeOptionalProjects, - inactiveRequiredProjects, inactiveOptionalProjects, resumeFrom, makeBehavior, expectedResult, - requestedPom, recursive ); + private Arguments createTestArguments(ExpectedResult expectedResult) { + return Arguments.arguments( + description, + activeRequiredProjects, + activeOptionalProjects, + inactiveRequiredProjects, + inactiveOptionalProjects, + resumeFrom, + makeBehavior, + expectedResult, + requestedPom, + recursive); } - private List prependWithColonIfNeeded( String[] selectors ) - { - return Arrays.stream( selectors ) - .map( this::prependWithColonIfNeeded ) - .collect( toList() ); + private List prependWithColonIfNeeded(String[] selectors) { + return Arrays.stream(selectors).map(this::prependWithColonIfNeeded).collect(toList()); } - private String prependWithColonIfNeeded( String selector ) { - return selector.indexOf( ':' ) == -1 ? ":" + selector : selector; + private String prependWithColonIfNeeded(String selector) { + return selector.indexOf(':') == -1 ? ":" + selector : selector; } } -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/graph/DefaultProjectDependencyGraphTest.java b/maven-core/src/test/java/org/apache/maven/graph/DefaultProjectDependencyGraphTest.java index 94737fb514..04d3c0886a 100644 --- a/maven-core/src/test/java/org/apache/maven/graph/DefaultProjectDependencyGraphTest.java +++ b/maven-core/src/test/java/org/apache/maven/graph/DefaultProjectDependencyGraphTest.java @@ -1,22 +1,27 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.maven.graph; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Arrays; import java.util.List; - import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.model.Dependency; import org.apache.maven.project.DuplicateProjectException; @@ -24,158 +29,134 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.dag.CycleDetectedException; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Kristian Rosenvold */ -public class DefaultProjectDependencyGraphTest -{ +public class DefaultProjectDependencyGraphTest { private final MavenProject aProject = createA(); - private final MavenProject depender1 = createProject( Arrays.asList( toDependency( aProject ) ), "depender1" ); + private final MavenProject depender1 = createProject(Arrays.asList(toDependency(aProject)), "depender1"); - private final MavenProject depender2 = createProject( Arrays.asList( toDependency( aProject ) ), "depender2" ); + private final MavenProject depender2 = createProject(Arrays.asList(toDependency(aProject)), "depender2"); - private final MavenProject depender3 = createProject( Arrays.asList( toDependency( aProject ) ), "depender3" ); + private final MavenProject depender3 = createProject(Arrays.asList(toDependency(aProject)), "depender3"); private final MavenProject depender4 = - createProject( Arrays.asList( toDependency( aProject ), toDependency( depender3 ) ), "depender4" ); + createProject(Arrays.asList(toDependency(aProject), toDependency(depender3)), "depender4"); - private final MavenProject transitiveOnly = - createProject( Arrays.asList( toDependency( depender3 ) ), "depender5" ); + private final MavenProject transitiveOnly = createProject(Arrays.asList(toDependency(depender3)), "depender5"); @Test - public void testGetSortedProjects() - throws DuplicateProjectException, CycleDetectedException - { - ProjectDependencyGraph graph = new DefaultProjectDependencyGraph( Arrays.asList( depender1, aProject ) ); + public void testGetSortedProjects() throws DuplicateProjectException, CycleDetectedException { + ProjectDependencyGraph graph = new DefaultProjectDependencyGraph(Arrays.asList(depender1, aProject)); final List sortedProjects = graph.getSortedProjects(); - assertEquals( aProject, sortedProjects.get( 0 ) ); - assertEquals( depender1, sortedProjects.get( 1 ) ); + assertEquals(aProject, sortedProjects.get(0)); + assertEquals(depender1, sortedProjects.get(1)); } @Test - public void testVerifyExpectedParentStructure() - throws CycleDetectedException, DuplicateProjectException - { + public void testVerifyExpectedParentStructure() throws CycleDetectedException, DuplicateProjectException { // This test verifies the baseline structure used in subsequent tests. If this fails, the rest will fail. ProjectDependencyGraph graph = threeProjectsDependingOnASingle(); final List sortedProjects = graph.getSortedProjects(); - assertEquals( aProject, sortedProjects.get( 0 ) ); - assertEquals( depender1, sortedProjects.get( 1 ) ); - assertEquals( depender2, sortedProjects.get( 2 ) ); - assertEquals( depender3, sortedProjects.get( 3 ) ); + assertEquals(aProject, sortedProjects.get(0)); + assertEquals(depender1, sortedProjects.get(1)); + assertEquals(depender2, sortedProjects.get(2)); + assertEquals(depender3, sortedProjects.get(3)); } @Test public void testVerifyThatDownstreamProjectsComeInSortedOrder() - throws CycleDetectedException, DuplicateProjectException - { + throws CycleDetectedException, DuplicateProjectException { final List downstreamProjects = - threeProjectsDependingOnASingle().getDownstreamProjects( aProject, true ); - assertEquals( depender1, downstreamProjects.get( 0 ) ); - assertEquals( depender2, downstreamProjects.get( 1 ) ); - assertEquals( depender3, downstreamProjects.get( 2 ) ); + threeProjectsDependingOnASingle().getDownstreamProjects(aProject, true); + assertEquals(depender1, downstreamProjects.get(0)); + assertEquals(depender2, downstreamProjects.get(1)); + assertEquals(depender3, downstreamProjects.get(2)); } @Test - public void testTransitivesInOrder() - throws CycleDetectedException, DuplicateProjectException - { + public void testTransitivesInOrder() throws CycleDetectedException, DuplicateProjectException { final ProjectDependencyGraph graph = - new DefaultProjectDependencyGraph( Arrays.asList( depender1, depender4, depender2, depender3, aProject ) ); + new DefaultProjectDependencyGraph(Arrays.asList(depender1, depender4, depender2, depender3, aProject)); - final List downstreamProjects = graph.getDownstreamProjects( aProject, true ); - assertEquals( depender1, downstreamProjects.get( 0 ) ); - assertEquals( depender3, downstreamProjects.get( 1 ) ); - assertEquals( depender4, downstreamProjects.get( 2 ) ); - assertEquals( depender2, downstreamProjects.get( 3 ) ); + final List downstreamProjects = graph.getDownstreamProjects(aProject, true); + assertEquals(depender1, downstreamProjects.get(0)); + assertEquals(depender3, downstreamProjects.get(1)); + assertEquals(depender4, downstreamProjects.get(2)); + assertEquals(depender2, downstreamProjects.get(3)); } @Test - public void testNonTransitivesInOrder() - throws CycleDetectedException, DuplicateProjectException - { + public void testNonTransitivesInOrder() throws CycleDetectedException, DuplicateProjectException { final ProjectDependencyGraph graph = - new DefaultProjectDependencyGraph( Arrays.asList( depender1, depender4, depender2, depender3, aProject ) ); + new DefaultProjectDependencyGraph(Arrays.asList(depender1, depender4, depender2, depender3, aProject)); - final List downstreamProjects = graph.getDownstreamProjects( aProject, false ); - assertEquals( depender1, downstreamProjects.get( 0 ) ); - assertEquals( depender3, downstreamProjects.get( 1 ) ); - assertEquals( depender4, downstreamProjects.get( 2 ) ); - assertEquals( depender2, downstreamProjects.get( 3 ) ); + final List downstreamProjects = graph.getDownstreamProjects(aProject, false); + assertEquals(depender1, downstreamProjects.get(0)); + assertEquals(depender3, downstreamProjects.get(1)); + assertEquals(depender4, downstreamProjects.get(2)); + assertEquals(depender2, downstreamProjects.get(3)); } @Test - public void testWithTransitiveOnly() - throws CycleDetectedException, DuplicateProjectException - { + public void testWithTransitiveOnly() throws CycleDetectedException, DuplicateProjectException { final ProjectDependencyGraph graph = new DefaultProjectDependencyGraph( - Arrays.asList( depender1, transitiveOnly, depender2, depender3, aProject ) ); + Arrays.asList(depender1, transitiveOnly, depender2, depender3, aProject)); - final List downstreamProjects = graph.getDownstreamProjects( aProject, true ); - assertEquals( depender1, downstreamProjects.get( 0 ) ); - assertEquals( depender3, downstreamProjects.get( 1 ) ); - assertEquals( transitiveOnly, downstreamProjects.get( 2 ) ); - assertEquals( depender2, downstreamProjects.get( 3 ) ); + final List downstreamProjects = graph.getDownstreamProjects(aProject, true); + assertEquals(depender1, downstreamProjects.get(0)); + assertEquals(depender3, downstreamProjects.get(1)); + assertEquals(transitiveOnly, downstreamProjects.get(2)); + assertEquals(depender2, downstreamProjects.get(3)); } @Test - public void testWithMissingTransitiveOnly() - throws CycleDetectedException, DuplicateProjectException - { + public void testWithMissingTransitiveOnly() throws CycleDetectedException, DuplicateProjectException { final ProjectDependencyGraph graph = new DefaultProjectDependencyGraph( - Arrays.asList( depender1, transitiveOnly, depender2, depender3, aProject ) ); + Arrays.asList(depender1, transitiveOnly, depender2, depender3, aProject)); - final List downstreamProjects = graph.getDownstreamProjects( aProject, false ); - assertEquals( depender1, downstreamProjects.get( 0 ) ); - assertEquals( depender3, downstreamProjects.get( 1 ) ); - assertEquals( depender2, downstreamProjects.get( 2 ) ); + final List downstreamProjects = graph.getDownstreamProjects(aProject, false); + assertEquals(depender1, downstreamProjects.get(0)); + assertEquals(depender3, downstreamProjects.get(1)); + assertEquals(depender2, downstreamProjects.get(2)); } @Test - public void testGetUpstreamProjects() - throws CycleDetectedException, DuplicateProjectException - { + public void testGetUpstreamProjects() throws CycleDetectedException, DuplicateProjectException { ProjectDependencyGraph graph = threeProjectsDependingOnASingle(); - final List downstreamProjects = graph.getUpstreamProjects( depender1, true ); - assertEquals( aProject, downstreamProjects.get( 0 ) ); + final List downstreamProjects = graph.getUpstreamProjects(depender1, true); + assertEquals(aProject, downstreamProjects.get(0)); } private ProjectDependencyGraph threeProjectsDependingOnASingle() - throws CycleDetectedException, DuplicateProjectException - { - return new DefaultProjectDependencyGraph( Arrays.asList( depender1, depender2, depender3, aProject ) ); + throws CycleDetectedException, DuplicateProjectException { + return new DefaultProjectDependencyGraph(Arrays.asList(depender1, depender2, depender3, aProject)); } - private static MavenProject createA() - { + private static MavenProject createA() { MavenProject result = new MavenProject(); - result.setGroupId( "org.apache" ); - result.setArtifactId( "A" ); - result.setVersion( "1.2" ); + result.setGroupId("org.apache"); + result.setArtifactId("A"); + result.setVersion("1.2"); return result; } - static Dependency toDependency( MavenProject mavenProject ) - { + static Dependency toDependency(MavenProject mavenProject) { final Dependency dependency = new Dependency(); - dependency.setArtifactId( mavenProject.getArtifactId() ); - dependency.setGroupId( mavenProject.getGroupId() ); - dependency.setVersion( mavenProject.getVersion() ); + dependency.setArtifactId(mavenProject.getArtifactId()); + dependency.setGroupId(mavenProject.getGroupId()); + dependency.setVersion(mavenProject.getVersion()); return dependency; } - private static MavenProject createProject( List dependencies, String artifactId ) - { + private static MavenProject createProject(List dependencies, String artifactId) { MavenProject result = new MavenProject(); - result.setGroupId( "org.apache" ); - result.setArtifactId( artifactId ); - result.setVersion( "1.2" ); - result.setDependencies( dependencies ); + result.setGroupId("org.apache"); + result.setArtifactId(artifactId); + result.setVersion("1.2"); + result.setDependencies(dependencies); return result; } - -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/graph/ProjectSelectorTest.java b/maven-core/src/test/java/org/apache/maven/graph/ProjectSelectorTest.java index 34bb4453ff..02cc39f6dc 100644 --- a/maven-core/src/test/java/org/apache/maven/graph/ProjectSelectorTest.java +++ b/maven-core/src/test/java/org/apache/maven/graph/ProjectSelectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.graph; * "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 + * 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 @@ -18,23 +16,7 @@ package org.apache.maven.graph; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.MavenExecutionException; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.project.MavenProject; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EmptySource; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +package org.apache.maven.graph; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -46,176 +28,179 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -class ProjectSelectorTest -{ +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.maven.MavenExecutionException; +import org.apache.maven.execution.MavenExecutionRequest; +import org.apache.maven.project.MavenProject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class ProjectSelectorTest { private final ProjectSelector sut = new ProjectSelector(); - private final MavenExecutionRequest mavenExecutionRequest = mock( MavenExecutionRequest.class ); + private final MavenExecutionRequest mavenExecutionRequest = mock(MavenExecutionRequest.class); @Test - void getBaseDirectoryFromRequestWhenDirectoryIsNullReturnNull() - { - when( mavenExecutionRequest.getBaseDirectory() ).thenReturn( null ); + void getBaseDirectoryFromRequestWhenDirectoryIsNullReturnNull() { + when(mavenExecutionRequest.getBaseDirectory()).thenReturn(null); - final File baseDirectoryFromRequest = sut.getBaseDirectoryFromRequest( mavenExecutionRequest ); + final File baseDirectoryFromRequest = sut.getBaseDirectoryFromRequest(mavenExecutionRequest); - assertThat( baseDirectoryFromRequest, nullValue() ); + assertThat(baseDirectoryFromRequest, nullValue()); } @Test - void getBaseDirectoryFromRequestWhenDirectoryIsValidReturnFile() - { - when( mavenExecutionRequest.getBaseDirectory() ).thenReturn( "path/to/file" ); + void getBaseDirectoryFromRequestWhenDirectoryIsValidReturnFile() { + when(mavenExecutionRequest.getBaseDirectory()).thenReturn("path/to/file"); - final File baseDirectoryFromRequest = sut.getBaseDirectoryFromRequest( mavenExecutionRequest ); + final File baseDirectoryFromRequest = sut.getBaseDirectoryFromRequest(mavenExecutionRequest); - assertThat( baseDirectoryFromRequest, notNullValue() ); - assertThat( baseDirectoryFromRequest.getPath(), is( new File( "path/to/file" ).getPath() ) ); + assertThat(baseDirectoryFromRequest, notNullValue()); + assertThat(baseDirectoryFromRequest.getPath(), is(new File("path/to/file").getPath())); } @ParameterizedTest - @ValueSource( strings = {":wrong-selector", "wrong-selector"} ) + @ValueSource(strings = {":wrong-selector", "wrong-selector"}) @EmptySource - void isMatchingProjectNoMatchOnSelectorReturnsFalse( String selector ) - { - final boolean result = sut.isMatchingProject( createMavenProject("maven-core" ), selector, null ); - assertThat( result, is( false ) ); + void isMatchingProjectNoMatchOnSelectorReturnsFalse(String selector) { + final boolean result = sut.isMatchingProject(createMavenProject("maven-core"), selector, null); + assertThat(result, is(false)); } @ParameterizedTest - @ValueSource( strings = {":maven-core", "org.apache.maven:maven-core"} ) - void isMatchingProjectMatchOnSelectorReturnsTrue( String selector ) - { - final boolean result = sut.isMatchingProject( createMavenProject("maven-core" ), selector, null ); - assertThat( result, is( true ) ); + @ValueSource(strings = {":maven-core", "org.apache.maven:maven-core"}) + void isMatchingProjectMatchOnSelectorReturnsTrue(String selector) { + final boolean result = sut.isMatchingProject(createMavenProject("maven-core"), selector, null); + assertThat(result, is(true)); } @Test - void isMatchingProjectMatchOnFileReturnsTrue() throws IOException - { - final File tempFile = File.createTempFile( "maven-core-unit-test-pom", ".xml" ); + void isMatchingProjectMatchOnFileReturnsTrue() throws IOException { + final File tempFile = File.createTempFile("maven-core-unit-test-pom", ".xml"); final String selector = tempFile.getName(); - final MavenProject mavenProject = createMavenProject("maven-core" ); - mavenProject.setFile( tempFile ); + final MavenProject mavenProject = createMavenProject("maven-core"); + mavenProject.setFile(tempFile); - final boolean result = sut.isMatchingProject( mavenProject, selector, tempFile.getParentFile() ); + final boolean result = sut.isMatchingProject(mavenProject, selector, tempFile.getParentFile()); tempFile.delete(); - assertThat( result, is( true ) ); + assertThat(result, is(true)); } @Test - void isMatchingProjectMatchOnDirectoryReturnsTrue(@TempDir File tempDir) - { + void isMatchingProjectMatchOnDirectoryReturnsTrue(@TempDir File tempDir) { String selector = "maven-core"; - final File tempProjectDir = new File( tempDir, "maven-core" ); + final File tempProjectDir = new File(tempDir, "maven-core"); tempProjectDir.mkdir(); - final MavenProject mavenProject = createMavenProject("maven-core" ); - mavenProject.setFile( new File( tempProjectDir, "some-file.xml" ) ); + final MavenProject mavenProject = createMavenProject("maven-core"); + mavenProject.setFile(new File(tempProjectDir, "some-file.xml")); - final boolean result = sut.isMatchingProject( mavenProject, selector, tempDir ); + final boolean result = sut.isMatchingProject(mavenProject, selector, tempDir); tempProjectDir.delete(); - assertThat( result, is( true ) ); + assertThat(result, is(true)); } @Test - void getOptionalProjectsBySelectorsReturnsMatches() - { + void getOptionalProjectsBySelectorsReturnsMatches() { final HashSet selectors = new HashSet<>(); - selectors.add( ":maven-core" ); - selectors.add( ":optional" ); + selectors.add(":maven-core"); + selectors.add(":optional"); - final MavenProject mavenProject = createMavenProject("maven-core" ); - final List listOfProjects = Collections.singletonList( mavenProject ); + final MavenProject mavenProject = createMavenProject("maven-core"); + final List listOfProjects = Collections.singletonList(mavenProject); final Set optionalProjectsBySelectors = - sut.getOptionalProjectsBySelectors( mavenExecutionRequest, listOfProjects, selectors ); + sut.getOptionalProjectsBySelectors(mavenExecutionRequest, listOfProjects, selectors); - assertThat( optionalProjectsBySelectors.size(), is( 1 ) ); - assertThat( optionalProjectsBySelectors, contains( mavenProject ) ); + assertThat(optionalProjectsBySelectors.size(), is(1)); + assertThat(optionalProjectsBySelectors, contains(mavenProject)); } @Test - void getRequiredProjectsBySelectorsThrowsMavenExecutionException() - { + void getRequiredProjectsBySelectorsThrowsMavenExecutionException() { final HashSet selectors = new HashSet<>(); - selectors.add( ":maven-core" ); - selectors.add( ":required" ); + selectors.add(":maven-core"); + selectors.add(":required"); - final MavenProject mavenProject = createMavenProject("maven-core" ); - final List listOfProjects = Collections.singletonList( mavenProject ); + final MavenProject mavenProject = createMavenProject("maven-core"); + final List listOfProjects = Collections.singletonList(mavenProject); - final MavenExecutionException exception = assertThrows( MavenExecutionException.class, - () -> sut.getRequiredProjectsBySelectors( mavenExecutionRequest, listOfProjects, selectors ) ); - assertThat( exception.getMessage(), containsString( "Could not find" ) ); - assertThat( exception.getMessage(), containsString( ":required" ) ); + final MavenExecutionException exception = assertThrows( + MavenExecutionException.class, + () -> sut.getRequiredProjectsBySelectors(mavenExecutionRequest, listOfProjects, selectors)); + assertThat(exception.getMessage(), containsString("Could not find")); + assertThat(exception.getMessage(), containsString(":required")); } @Test - void getRequiredProjectsBySelectorsReturnsProject() throws MavenExecutionException - { + void getRequiredProjectsBySelectorsReturnsProject() throws MavenExecutionException { final HashSet selectors = new HashSet<>(); - selectors.add( ":maven-core" ); + selectors.add(":maven-core"); - final MavenProject mavenProject = createMavenProject("maven-core" ); - final List listOfProjects = Collections.singletonList( mavenProject ); + final MavenProject mavenProject = createMavenProject("maven-core"); + final List listOfProjects = Collections.singletonList(mavenProject); final Set requiredProjectsBySelectors = - sut.getRequiredProjectsBySelectors( mavenExecutionRequest, listOfProjects, selectors ); + sut.getRequiredProjectsBySelectors(mavenExecutionRequest, listOfProjects, selectors); - assertThat( requiredProjectsBySelectors.size(), is( 1 ) ); - assertThat( requiredProjectsBySelectors, contains( mavenProject ) ); + assertThat(requiredProjectsBySelectors.size(), is(1)); + assertThat(requiredProjectsBySelectors, contains(mavenProject)); } @Test - void getRequiredProjectsBySelectorsReturnsProjectWithChildProjects() throws MavenExecutionException - { - when( mavenExecutionRequest.isRecursive() ).thenReturn( true ); + void getRequiredProjectsBySelectorsReturnsProjectWithChildProjects() throws MavenExecutionException { + when(mavenExecutionRequest.isRecursive()).thenReturn(true); final HashSet selectors = new HashSet<>(); - selectors.add( ":maven-core" ); + selectors.add(":maven-core"); - final MavenProject mavenProject = createMavenProject("maven-core" ); - final MavenProject child = createMavenProject("maven-core-child" ); - mavenProject.setCollectedProjects( Collections.singletonList( child ) ); - final List listOfProjects = Collections.singletonList( mavenProject ); + final MavenProject mavenProject = createMavenProject("maven-core"); + final MavenProject child = createMavenProject("maven-core-child"); + mavenProject.setCollectedProjects(Collections.singletonList(child)); + final List listOfProjects = Collections.singletonList(mavenProject); final Set requiredProjectsBySelectors = - sut.getRequiredProjectsBySelectors( mavenExecutionRequest, listOfProjects, selectors ); + sut.getRequiredProjectsBySelectors(mavenExecutionRequest, listOfProjects, selectors); - assertThat( requiredProjectsBySelectors.size(), is( 2 ) ); - assertThat( requiredProjectsBySelectors, contains( mavenProject, child ) ); + assertThat(requiredProjectsBySelectors.size(), is(2)); + assertThat(requiredProjectsBySelectors, contains(mavenProject, child)); } @Test - void getOptionalProjectsBySelectorsReturnsProjectWithChildProjects() - { - when( mavenExecutionRequest.isRecursive() ).thenReturn( true ); + void getOptionalProjectsBySelectorsReturnsProjectWithChildProjects() { + when(mavenExecutionRequest.isRecursive()).thenReturn(true); final HashSet selectors = new HashSet<>(); - selectors.add( ":maven-core" ); + selectors.add(":maven-core"); - final MavenProject mavenProject = createMavenProject("maven-core" ); - final MavenProject child = createMavenProject("maven-core-child" ); - mavenProject.setCollectedProjects( Collections.singletonList( child ) ); - final List listOfProjects = Collections.singletonList( mavenProject ); + final MavenProject mavenProject = createMavenProject("maven-core"); + final MavenProject child = createMavenProject("maven-core-child"); + mavenProject.setCollectedProjects(Collections.singletonList(child)); + final List listOfProjects = Collections.singletonList(mavenProject); final Set optionalProjectsBySelectors = - sut.getOptionalProjectsBySelectors( mavenExecutionRequest, listOfProjects, selectors ); + sut.getOptionalProjectsBySelectors(mavenExecutionRequest, listOfProjects, selectors); - assertThat( optionalProjectsBySelectors.size(), is( 2 ) ); - assertThat( optionalProjectsBySelectors, contains( mavenProject, child ) ); + assertThat(optionalProjectsBySelectors.size(), is(2)); + assertThat(optionalProjectsBySelectors, contains(mavenProject, child)); } - private MavenProject createMavenProject(String artifactId ) - { + private MavenProject createMavenProject(String artifactId) { MavenProject mavenProject = new MavenProject(); - mavenProject.setGroupId( "org.apache.maven" ); - mavenProject.setArtifactId( artifactId ); - mavenProject.setVersion( "1.0" ); - mavenProject.setFile( new File( artifactId, "some-dir" ) ); - mavenProject.setCollectedProjects( new ArrayList<>() ); + mavenProject.setGroupId("org.apache.maven"); + mavenProject.setArtifactId(artifactId); + mavenProject.setVersion("1.0"); + mavenProject.setFile(new File(artifactId, "some-dir")); + mavenProject.setCollectedProjects(new ArrayList<>()); return mavenProject; } - } diff --git a/maven-core/src/test/java/org/apache/maven/internal/MultilineMessageHelperTest.java b/maven-core/src/test/java/org/apache/maven/internal/MultilineMessageHelperTest.java index 904b39c9a9..68d56ad343 100644 --- a/maven-core/src/test/java/org/apache/maven/internal/MultilineMessageHelperTest.java +++ b/maven-core/src/test/java/org/apache/maven/internal/MultilineMessageHelperTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,54 +16,54 @@ package org.apache.maven.internal; * specific language governing permissions and limitations * under the License. */ - -import java.util.ArrayList; -import java.util.List; - -import org.junit.jupiter.api.Test; +package org.apache.maven.internal; import static org.junit.jupiter.api.Assertions.assertEquals; -public class MultilineMessageHelperTest -{ +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class MultilineMessageHelperTest { @Test - public void testBuilderCommon() - { + public void testBuilderCommon() { List msgs = new ArrayList<>(); - msgs.add( "*****************************************************************" ); - msgs.add( "* Your build is requesting parallel execution, but project *" ); - msgs.add( "* contains the following plugin(s) that have goals not marked *" ); - msgs.add( "* as @threadSafe to support parallel building. *" ); - msgs.add( "* While this /may/ work fine, please look for plugin updates *" ); - msgs.add( "* and/or request plugins be made thread-safe. *" ); - msgs.add( "* If reporting an issue, report it against the plugin in *" ); - msgs.add( "* question, not against maven-core *" ); - msgs.add( "*****************************************************************" ); + msgs.add("*****************************************************************"); + msgs.add("* Your build is requesting parallel execution, but project *"); + msgs.add("* contains the following plugin(s) that have goals not marked *"); + msgs.add("* as @threadSafe to support parallel building. *"); + msgs.add("* While this /may/ work fine, please look for plugin updates *"); + msgs.add("* and/or request plugins be made thread-safe. *"); + msgs.add("* If reporting an issue, report it against the plugin in *"); + msgs.add("* question, not against maven-core *"); + msgs.add("*****************************************************************"); - assertEquals( msgs, MultilineMessageHelper.format( - "Your build is requesting parallel execution, but project contains the following " - + "plugin(s) that have goals not marked as @threadSafe to support parallel building.", - "While this /may/ work fine, please look for plugin updates and/or " - + "request plugins be made thread-safe.", - "If reporting an issue, report it against the plugin in question, not against maven-core" - ) ); + assertEquals( + msgs, + MultilineMessageHelper.format( + "Your build is requesting parallel execution, but project contains the following " + + "plugin(s) that have goals not marked as @threadSafe to support parallel building.", + "While this /may/ work fine, please look for plugin updates and/or " + + "request plugins be made thread-safe.", + "If reporting an issue, report it against the plugin in question, not against maven-core")); } @Test - public void testMojoExecutor() - { + public void testMojoExecutor() { List msgs = new ArrayList<>(); - msgs.add( "*****************************************************************" ); - msgs.add( "* An aggregator Mojo is already executing in parallel build, *" ); - msgs.add( "* but aggregator Mojos require exclusive access to reactor to *" ); - msgs.add( "* prevent race conditions. This mojo execution will be blocked *" ); - msgs.add( "* until the aggregator work is done. *" ); - msgs.add( "*****************************************************************" ); + msgs.add("*****************************************************************"); + msgs.add("* An aggregator Mojo is already executing in parallel build, *"); + msgs.add("* but aggregator Mojos require exclusive access to reactor to *"); + msgs.add("* prevent race conditions. This mojo execution will be blocked *"); + msgs.add("* until the aggregator work is done. *"); + msgs.add("*****************************************************************"); - assertEquals( msgs, MultilineMessageHelper.format( - "An aggregator Mojo is already executing in parallel build, but aggregator " - + "Mojos require exclusive access to reactor to prevent race conditions. This " - + "mojo execution will be blocked until the aggregator work is done." ) ); + assertEquals( + msgs, + MultilineMessageHelper.format( + "An aggregator Mojo is already executing in parallel build, but aggregator " + + "Mojos require exclusive access to reactor to prevent race conditions. This " + + "mojo execution will be blocked until the aggregator work is done.")); } } diff --git a/maven-core/src/test/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformerTest.java b/maven-core/src/test/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformerTest.java index 50506239fb..0fe6adbe62 100644 --- a/maven-core/src/test/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformerTest.java +++ b/maven-core/src/test/java/org/apache/maven/internal/aether/ConsumerModelSourceTransformerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.internal.aether; * "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 + * 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 @@ -18,52 +16,46 @@ package org.apache.maven.internal.aether; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.aether; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; - import org.apache.maven.model.Model; import org.apache.maven.model.building.TransformerContext; import org.junit.jupiter.api.Test; import org.xmlunit.assertj.XmlAssert; -public class ConsumerModelSourceTransformerTest -{ +public class ConsumerModelSourceTransformerTest { private ConsumerModelSourceTransformer transformer = new ConsumerModelSourceTransformer(); @Test - public void transform() throws Exception - { - Path beforePomFile = Paths.get( "src/test/resources/projects/transform/before.pom").toAbsolutePath(); - Path afterPomFile = Paths.get( "src/test/resources/projects/transform/after.pom").toAbsolutePath(); + public void transform() throws Exception { + Path beforePomFile = + Paths.get("src/test/resources/projects/transform/before.pom").toAbsolutePath(); + Path afterPomFile = + Paths.get("src/test/resources/projects/transform/after.pom").toAbsolutePath(); - try( InputStream expected = Files.newInputStream( afterPomFile ); - InputStream result = transformer.transform( beforePomFile, new NoTransformerContext() ) ) - { - XmlAssert.assertThat( result ).and( expected ).areIdentical(); + try (InputStream expected = Files.newInputStream(afterPomFile); + InputStream result = transformer.transform(beforePomFile, new NoTransformerContext())) { + XmlAssert.assertThat(result).and(expected).areIdentical(); } } - private static class NoTransformerContext implements TransformerContext - { + private static class NoTransformerContext implements TransformerContext { @Override - public String getUserProperty( String key ) - { + public String getUserProperty(String key) { return null; } @Override - public Model getRawModel( String groupId, String artifactId ) - throws IllegalStateException - { + public Model getRawModel(String groupId, String artifactId) throws IllegalStateException { return null; } @Override - public Model getRawModel( Path p ) - { + public Model getRawModel(Path p) { return null; } } diff --git a/maven-core/src/test/java/org/apache/maven/internal/impl/PropertiesAsMapTest.java b/maven-core/src/test/java/org/apache/maven/internal/impl/PropertiesAsMapTest.java index 04456dede6..914d6d5b92 100644 --- a/maven-core/src/test/java/org/apache/maven/internal/impl/PropertiesAsMapTest.java +++ b/maven-core/src/test/java/org/apache/maven/internal/impl/PropertiesAsMapTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,14 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.Set; - -import org.junit.jupiter.api.Test; +package org.apache.maven.internal.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -33,29 +24,34 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -public class PropertiesAsMapTest -{ +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import java.util.Properties; +import java.util.Set; +import org.junit.jupiter.api.Test; + +public class PropertiesAsMapTest { @Test - public void testPropertiesAsMap() - { + public void testPropertiesAsMap() { Properties props = new Properties(); - props.setProperty( "foo1", "bar1" ); - props.setProperty( "foo2", "bar2" ); - PropertiesAsMap pam = new PropertiesAsMap( props ); - assertEquals( 2, pam.size() ); + props.setProperty("foo1", "bar1"); + props.setProperty("foo2", "bar2"); + PropertiesAsMap pam = new PropertiesAsMap(props); + assertEquals(2, pam.size()); Set> set = pam.entrySet(); - assertNotNull( set ); - assertEquals( 2, set.size() ); + assertNotNull(set); + assertEquals(2, set.size()); Iterator> iterator = set.iterator(); - assertNotNull( iterator ); - assertTrue( iterator.hasNext() ); - assertTrue( iterator.hasNext() ); + assertNotNull(iterator); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); Entry entry = iterator.next(); - assertNotNull( entry ); + assertNotNull(entry); entry = iterator.next(); - assertNotNull( entry ); - assertThrows(NoSuchElementException.class, () -> iterator.next() ); - assertFalse( iterator.hasNext() ); + assertNotNull(entry); + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertFalse(iterator.hasNext()); } } diff --git a/maven-core/src/test/java/org/apache/maven/internal/impl/TestApi.java b/maven-core/src/test/java/org/apache/maven/internal/impl/TestApi.java index 1596f5005e..31a36dbf89 100644 --- a/maven-core/src/test/java/org/apache/maven/internal/impl/TestApi.java +++ b/maven-core/src/test/java/org/apache/maven/internal/impl/TestApi.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,15 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; -import javax.inject.Inject; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Path; import java.util.Collections; import java.util.Optional; - +import javax.inject.Inject; import org.apache.maven.api.Artifact; import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.Node; @@ -52,12 +52,8 @@ import org.eclipse.aether.repository.RemoteRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - @PlexusTest -public class TestApi -{ +public class TestApi { Session session; @@ -95,51 +91,52 @@ public class TestApi ToolchainsBuilder toolchainsBuilder; @BeforeEach - void setup() - { + void setup() { RepositorySystemSession rss = MavenRepositorySystemUtils.newSession(); DefaultMavenExecutionRequest mer = new DefaultMavenExecutionRequest(); - MavenSession ms = new MavenSession( null, rss, mer, null ); - DefaultSession session = new DefaultSession( ms, repositorySystem, - Collections.emptyList(), - mavenRepositorySystem, - plexusContainer, - runtimeInformation ); - DefaultLocalRepository localRepository = new DefaultLocalRepository( - new LocalRepository( "target/test-classes/apiv4-repo" ) ); + MavenSession ms = new MavenSession(null, rss, mer, null); + DefaultSession session = new DefaultSession( + ms, + repositorySystem, + Collections.emptyList(), + mavenRepositorySystem, + plexusContainer, + runtimeInformation); + DefaultLocalRepository localRepository = + new DefaultLocalRepository(new LocalRepository("target/test-classes/apiv4-repo")); org.apache.maven.api.RemoteRepository remoteRepository = session.getRemoteRepository( - new RemoteRepository.Builder( "mirror", "default", - "file:target/test-classes/repo" ).build() ); - this.session = session - .withLocalRepository( localRepository ) - .withRemoteRepositories( Collections.singletonList( remoteRepository ) ); + new RemoteRepository.Builder("mirror", "default", "file:target/test-classes/repo").build()); + this.session = session.withLocalRepository(localRepository) + .withRemoteRepositories(Collections.singletonList(remoteRepository)); sessionScope.enter(); - sessionScope.seed( DefaultSession.class, (DefaultSession) this.session ); + sessionScope.seed(DefaultSession.class, (DefaultSession) this.session); } @Test - void testCreateAndResolveArtifact() throws Exception - { + void testCreateAndResolveArtifact() throws Exception { ArtifactCoordinate coord = - session.createArtifactCoordinate( "org.codehaus.plexus", "plexus-utils", "1.4.5", "pom" ); + session.createArtifactCoordinate("org.codehaus.plexus", "plexus-utils", "1.4.5", "pom"); - Artifact resolved = session.resolveArtifact( coord ); - Optional op = session.getArtifactPath( resolved ); - assertTrue( op.isPresent() ); - assertNotNull( op.get() ); + Artifact resolved = session.resolveArtifact(coord); + Optional op = session.getArtifactPath(resolved); + assertTrue(op.isPresent()); + assertNotNull(op.get()); - Project project = session.getService( ProjectBuilder.class ).build( - ProjectBuilderRequest.builder().session( session ).path( op.get() ) - .processPlugins( false ).resolveDependencies( false ).build() ) - .getProject().get(); - assertNotNull( project ); + Project project = session.getService(ProjectBuilder.class) + .build(ProjectBuilderRequest.builder() + .session(session) + .path(op.get()) + .processPlugins(false) + .resolveDependencies(false) + .build()) + .getProject() + .get(); + assertNotNull(project); Artifact artifact = - session.createArtifact( "org.codehaus.plexus", "plexus-container-default", "1.0-alpha-32", "jar" ); - Node root = session.collectDependencies( artifact ); - assertNotNull( root ); + session.createArtifact("org.codehaus.plexus", "plexus-container-default", "1.0-alpha-32", "jar"); + Node root = session.collectDependencies(artifact); + assertNotNull(root); } - - } diff --git a/maven-core/src/test/java/org/apache/maven/internal/impl/TestArtifactHandler.java b/maven-core/src/test/java/org/apache/maven/internal/impl/TestArtifactHandler.java index 3db6e830e5..c461331497 100644 --- a/maven-core/src/test/java/org/apache/maven/internal/impl/TestArtifactHandler.java +++ b/maven-core/src/test/java/org/apache/maven/internal/impl/TestArtifactHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.internal.impl; import org.apache.maven.artifact.handler.ArtifactHandler; @@ -26,58 +25,46 @@ import org.apache.maven.artifact.handler.ArtifactHandler; * * @author Benjamin Bentmann */ -class TestArtifactHandler - implements ArtifactHandler -{ +class TestArtifactHandler implements ArtifactHandler { private String type; private String extension; - public TestArtifactHandler( String type ) - { - this( type, type ); + public TestArtifactHandler(String type) { + this(type, type); } - public TestArtifactHandler( String type, String extension ) - { + public TestArtifactHandler(String type, String extension) { this.type = type; this.extension = extension; } - public String getClassifier() - { + public String getClassifier() { return null; } - public String getDirectory() - { + public String getDirectory() { return getPackaging() + "s"; } - public String getExtension() - { + public String getExtension() { return extension; } - public String getLanguage() - { + public String getLanguage() { return "java"; } - public String getPackaging() - { + public String getPackaging() { return type; } - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return true; } - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return false; } - } diff --git a/maven-core/src/test/java/org/apache/maven/internal/impl/TestRepositorySystem.java b/maven-core/src/test/java/org/apache/maven/internal/impl/TestRepositorySystem.java index 6bba90b06b..856fb828b0 100644 --- a/maven-core/src/test/java/org/apache/maven/internal/impl/TestRepositorySystem.java +++ b/maven-core/src/test/java/org/apache/maven/internal/impl/TestRepositorySystem.java @@ -1,5 +1,3 @@ -package org.apache.maven.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,7 @@ package org.apache.maven.internal.impl; * specific language governing permissions and limitations * under the License. */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +package org.apache.maven.internal.impl; import java.io.File; import java.io.IOException; @@ -29,7 +24,9 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.api.model.Model; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -65,221 +62,189 @@ import org.eclipse.aether.RepositorySystemSession; */ @Named @Singleton -public class TestRepositorySystem - implements RepositorySystem -{ +public class TestRepositorySystem implements RepositorySystem { private final ModelReader modelReader; private final ArtifactFactory artifactFactory; @Inject - public TestRepositorySystem( ModelReader modelReader, ArtifactFactory artifactFactory ) - { + public TestRepositorySystem(ModelReader modelReader, ArtifactFactory artifactFactory) { this.modelReader = modelReader; this.artifactFactory = artifactFactory; } - public ArtifactRepository buildArtifactRepository( Repository repository ) - throws InvalidRepositoryException - { - return new MavenArtifactRepository( repository.getId(), repository.getUrl(), new DefaultRepositoryLayout(), - new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy() ); + public ArtifactRepository buildArtifactRepository(Repository repository) throws InvalidRepositoryException { + return new MavenArtifactRepository( + repository.getId(), + repository.getUrl(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - public Artifact createArtifact( String groupId, String artifactId, String version, String packaging ) - { - return createArtifact( groupId, artifactId, version, null, packaging ); + public Artifact createArtifact(String groupId, String artifactId, String version, String packaging) { + return createArtifact(groupId, artifactId, version, null, packaging); } - public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ) - { - return new DefaultArtifact( groupId, artifactId, version, scope, type, null, new TestArtifactHandler( type ) ); + public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) { + return new DefaultArtifact(groupId, artifactId, version, scope, type, null, new TestArtifactHandler(type)); } - public ArtifactRepository createArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - { - return new MavenArtifactRepository( id, url, repositoryLayout, snapshots, releases ); + public ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + return new MavenArtifactRepository(id, url, repositoryLayout, snapshots, releases); } - public Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, - String classifier ) - { - return new DefaultArtifact( groupId, artifactId, version, null, type, classifier, - new TestArtifactHandler( type ) ); + public Artifact createArtifactWithClassifier( + String groupId, String artifactId, String version, String type, String classifier) { + return new DefaultArtifact(groupId, artifactId, version, null, type, classifier, new TestArtifactHandler(type)); } - public ArtifactRepository createDefaultLocalRepository() - throws InvalidRepositoryException - { - return createLocalRepository( new File( System.getProperty( "basedir", "." ), "target/local-repo" ).getAbsoluteFile() ); + public ArtifactRepository createDefaultLocalRepository() throws InvalidRepositoryException { + return createLocalRepository( + new File(System.getProperty("basedir", "."), "target/local-repo").getAbsoluteFile()); } - public ArtifactRepository createDefaultRemoteRepository() - throws InvalidRepositoryException - { - return new MavenArtifactRepository( DEFAULT_REMOTE_REPO_ID, "file://" - + new File( System.getProperty( "basedir", "." ), "src/test/remote-repo" ).getAbsoluteFile().toURI().getPath(), - new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + public ArtifactRepository createDefaultRemoteRepository() throws InvalidRepositoryException { + return new MavenArtifactRepository( + DEFAULT_REMOTE_REPO_ID, + "file://" + + new File(System.getProperty("basedir", "."), "src/test/remote-repo") + .getAbsoluteFile() + .toURI() + .getPath(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - public Artifact createDependencyArtifact( Dependency dependency ) - { - Artifact artifact = - new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), - dependency.getScope(), dependency.getType(), dependency.getClassifier(), - new TestArtifactHandler( dependency.getType() ) ); + public Artifact createDependencyArtifact(Dependency dependency) { + Artifact artifact = new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + dependency.getScope(), + dependency.getType(), + dependency.getClassifier(), + new TestArtifactHandler(dependency.getType())); - if ( Artifact.SCOPE_SYSTEM.equals( dependency.getScope() ) ) - { - artifact.setFile( new File( dependency.getSystemPath() ) ); - artifact.setResolved( true ); + if (Artifact.SCOPE_SYSTEM.equals(dependency.getScope())) { + artifact.setFile(new File(dependency.getSystemPath())); + artifact.setResolved(true); } return artifact; } - public ArtifactRepository createLocalRepository( File localRepository ) - throws InvalidRepositoryException - { - return new MavenArtifactRepository( DEFAULT_LOCAL_REPO_ID, "file://" + localRepository.toURI().getPath(), - new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + public ArtifactRepository createLocalRepository(File localRepository) throws InvalidRepositoryException { + return new MavenArtifactRepository( + DEFAULT_LOCAL_REPO_ID, + "file://" + localRepository.toURI().getPath(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - public Artifact createPluginArtifact( Plugin plugin ) - { + public Artifact createPluginArtifact(Plugin plugin) { VersionRange versionRange; - try - { + try { String version = plugin.getVersion(); - if ( StringUtils.isEmpty( version ) ) - { + if (StringUtils.isEmpty(version)) { version = "RELEASE"; } - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { return null; } - return artifactFactory.createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange ); + return artifactFactory.createPluginArtifact(plugin.getGroupId(), plugin.getArtifactId(), versionRange); } - public Artifact createProjectArtifact( String groupId, String artifactId, String version ) - { - return createArtifact( groupId, artifactId, version, "pom" ); + public Artifact createProjectArtifact(String groupId, String artifactId, String version) { + return createArtifact(groupId, artifactId, version, "pom"); } - public List getEffectiveRepositories( List repositories ) - { + public List getEffectiveRepositories(List repositories) { return repositories; } - public Mirror getMirror( ArtifactRepository repository, List mirrors ) - { + public Mirror getMirror(ArtifactRepository repository, List mirrors) { return null; } - public void injectAuthentication( List repositories, List servers ) - { - } + public void injectAuthentication(List repositories, List servers) {} - public void injectMirror( List repositories, List mirrors ) - { - } + public void injectMirror(List repositories, List mirrors) {} - public void injectProxy( List repositories, List proxies ) - { - } + public void injectProxy(List repositories, List proxies) {} - public void publish( ArtifactRepository repository, File source, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException - { + public void publish( + ArtifactRepository repository, File source, String remotePath, ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException { // TODO Auto-generated method stub } - public ArtifactResolutionResult resolve( ArtifactResolutionRequest request ) - { + public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) { ArtifactResolutionResult result = new ArtifactResolutionResult(); - if ( request.isResolveRoot() ) - { - try - { - resolve( request.getArtifact(), request ); - result.addArtifact( request.getArtifact() ); - } - catch ( IOException e ) - { - result.addMissingArtifact( request.getArtifact() ); + if (request.isResolveRoot()) { + try { + resolve(request.getArtifact(), request); + result.addArtifact(request.getArtifact()); + } catch (IOException e) { + result.addMissingArtifact(request.getArtifact()); } } - if ( request.isResolveTransitively() ) - { + if (request.isResolveTransitively()) { Map artifacts = new LinkedHashMap<>(); - if ( request.getArtifactDependencies() != null ) - { - for ( Artifact artifact : request.getArtifactDependencies() ) - { - artifacts.put( artifact.getDependencyConflictId(), artifact ); + if (request.getArtifactDependencies() != null) { + for (Artifact artifact : request.getArtifactDependencies()) { + artifacts.put(artifact.getDependencyConflictId(), artifact); } } List dependencies = new ArrayList<>(); - if ( request.getArtifact() instanceof ArtifactWithDependencies ) - { - dependencies = ( (ArtifactWithDependencies) request.getArtifact() ).getDependencies(); - } - else - { - Artifact pomArtifact = - createProjectArtifact( request.getArtifact().getGroupId(), request.getArtifact().getArtifactId(), - request.getArtifact().getVersion() ); - File pomFile = - new File( request.getLocalRepository().getBasedir(), - request.getLocalRepository().pathOf( pomArtifact ) ); + if (request.getArtifact() instanceof ArtifactWithDependencies) { + dependencies = ((ArtifactWithDependencies) request.getArtifact()).getDependencies(); + } else { + Artifact pomArtifact = createProjectArtifact( + request.getArtifact().getGroupId(), + request.getArtifact().getArtifactId(), + request.getArtifact().getVersion()); + File pomFile = new File( + request.getLocalRepository().getBasedir(), + request.getLocalRepository().pathOf(pomArtifact)); - try - { - Model model = modelReader.read( pomFile, null ).getDelegate(); + try { + Model model = modelReader.read(pomFile, null).getDelegate(); - dependencies = Dependency.dependencyToApiV3( model.getDependencies() ); - } - catch ( IOException e ) - { + dependencies = Dependency.dependencyToApiV3(model.getDependencies()); + } catch (IOException e) { e.printStackTrace(); } } - for ( Dependency dependency : dependencies ) - { - Artifact artifact = createDependencyArtifact( dependency ); - if ( !artifacts.containsKey( artifact.getDependencyConflictId() ) ) - { - artifacts.put( artifact.getDependencyConflictId(), artifact ); + for (Dependency dependency : dependencies) { + Artifact artifact = createDependencyArtifact(dependency); + if (!artifacts.containsKey(artifact.getDependencyConflictId())) { + artifacts.put(artifact.getDependencyConflictId(), artifact); } } - for ( Artifact artifact : artifacts.values() ) - { - try - { - resolve( artifact, request ); - result.addArtifact( artifact ); - } - catch ( IOException e ) - { - result.addMissingArtifact( artifact ); + for (Artifact artifact : artifacts.values()) { + try { + resolve(artifact, request); + result.addArtifact(artifact); + } catch (IOException e) { + result.addMissingArtifact(artifact); } } } @@ -287,55 +252,45 @@ public class TestRepositorySystem return result; } - private void resolve( Artifact artifact, ArtifactResolutionRequest request ) - throws IOException - { - if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) - { + private void resolve(Artifact artifact, ArtifactResolutionRequest request) throws IOException { + if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { return; } ArtifactRepository localRepo = request.getLocalRepository(); - File localFile = new File( localRepo.getBasedir(), localRepo.pathOf( artifact ) ); + File localFile = new File(localRepo.getBasedir(), localRepo.pathOf(artifact)); - artifact.setFile( localFile ); + artifact.setFile(localFile); - if ( !localFile.exists() ) - { - if ( request.getRemoteRepositories().isEmpty() ) - { - throw new IOException( localFile + " does not exist and no remote repositories are configured" ); + if (!localFile.exists()) { + if (request.getRemoteRepositories().isEmpty()) { + throw new IOException(localFile + " does not exist and no remote repositories are configured"); } - ArtifactRepository remoteRepo = request.getRemoteRepositories().get( 0 ); + ArtifactRepository remoteRepo = request.getRemoteRepositories().get(0); - File remoteFile = new File( remoteRepo.getBasedir(), remoteRepo.pathOf( artifact ) ); + File remoteFile = new File(remoteRepo.getBasedir(), remoteRepo.pathOf(artifact)); - FileUtils.copyFile( remoteFile, localFile ); + FileUtils.copyFile(remoteFile, localFile); } - artifact.setResolved( true ); + artifact.setResolved(true); } - public void retrieve( ArtifactRepository repository, File destination, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException, ArtifactDoesNotExistException - { + public void retrieve( + ArtifactRepository repository, + File destination, + String remotePath, + ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException, ArtifactDoesNotExistException { // TODO Auto-generated method stub } - public void injectMirror( RepositorySystemSession session, List repositories ) - { - } + public void injectMirror(RepositorySystemSession session, List repositories) {} - public void injectProxy( RepositorySystemSession session, List repositories ) - { - } - - public void injectAuthentication( RepositorySystemSession session, List repositories ) - { - } + public void injectProxy(RepositorySystemSession session, List repositories) {} + public void injectAuthentication(RepositorySystemSession session, List repositories) {} } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/DefaultLifecyclesTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/DefaultLifecyclesTest.java index 8ad2785ae8..e820c36488 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/DefaultLifecyclesTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/DefaultLifecyclesTest.java @@ -1,33 +1,22 @@ -package org.apache.maven.lifecycle; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.inject.Inject; - -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.testing.PlexusTest; -import org.junit.jupiter.api.Test; +package org.apache.maven.lifecycle; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayWithSize; @@ -36,85 +25,86 @@ import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.inject.Inject; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.Test; + /** * @author Kristian Rosenvold */ @PlexusTest -public class DefaultLifecyclesTest -{ +public class DefaultLifecyclesTest { @Inject private DefaultLifecycles defaultLifeCycles; @Test - public void testDefaultLifecycles() - { + public void testDefaultLifecycles() { final List lifecycles = defaultLifeCycles.getLifeCycles(); - assertThat( lifecycles, hasSize( 4 ) ); - assertThat( DefaultLifecycles.STANDARD_LIFECYCLES, arrayWithSize( 4 ) ); + assertThat(lifecycles, hasSize(4)); + assertThat(DefaultLifecycles.STANDARD_LIFECYCLES, arrayWithSize(4)); } @Test - public void testDefaultLifecycle() - { - final Lifecycle lifecycle = getLifeCycleById( "default" ); - assertThat( lifecycle.getId(), is( "default" ) ); - assertThat( lifecycle.getPhases(), hasSize( 23 ) ); + public void testDefaultLifecycle() { + final Lifecycle lifecycle = getLifeCycleById("default"); + assertThat(lifecycle.getId(), is("default")); + assertThat(lifecycle.getPhases(), hasSize(23)); } @Test - public void testCleanLifecycle() - { - final Lifecycle lifecycle = getLifeCycleById( "clean" ); - assertThat( lifecycle.getId(), is( "clean" ) ); - assertThat( lifecycle.getPhases(), hasSize( 3 ) ); + public void testCleanLifecycle() { + final Lifecycle lifecycle = getLifeCycleById("clean"); + assertThat(lifecycle.getId(), is("clean")); + assertThat(lifecycle.getPhases(), hasSize(3)); } @Test - public void testSiteLifecycle() - { - final Lifecycle lifecycle = getLifeCycleById( "site" ); - assertThat( lifecycle.getId(), is( "site" ) ); - assertThat( lifecycle.getPhases(), hasSize( 4 ) ); + public void testSiteLifecycle() { + final Lifecycle lifecycle = getLifeCycleById("site"); + assertThat(lifecycle.getId(), is("site")); + assertThat(lifecycle.getPhases(), hasSize(4)); } @Test - public void testWrapperLifecycle() - { - final Lifecycle lifecycle = getLifeCycleById( "wrapper" ); - assertThat( lifecycle.getId(), is( "wrapper" ) ); - assertThat( lifecycle.getPhases(), hasSize( 1 ) ); + public void testWrapperLifecycle() { + final Lifecycle lifecycle = getLifeCycleById("wrapper"); + assertThat(lifecycle.getId(), is("wrapper")); + assertThat(lifecycle.getPhases(), hasSize(1)); } @Test - public void testCustomLifecycle() - throws ComponentLookupException - { + public void testCustomLifecycle() throws ComponentLookupException { List myLifecycles = new ArrayList<>(); - Lifecycle myLifecycle = new Lifecycle( "etl", - Arrays.asList( "extract", "transform", "load" ), - Collections.emptyMap() ); - myLifecycles.add( myLifecycle ); - myLifecycles.addAll( defaultLifeCycles.getLifeCycles() ); + Lifecycle myLifecycle = + new Lifecycle("etl", Arrays.asList("extract", "transform", "load"), Collections.emptyMap()); + myLifecycles.add(myLifecycle); + myLifecycles.addAll(defaultLifeCycles.getLifeCycles()); - Map lifeCycles = myLifecycles.stream() - .collect( Collectors.toMap( Lifecycle::getId, l -> l ) ); - PlexusContainer mockedPlexusContainer = mock( PlexusContainer.class ); - when( mockedPlexusContainer.lookupMap( Lifecycle.class ) ).thenReturn( lifeCycles ); + Map lifeCycles = myLifecycles.stream().collect(Collectors.toMap(Lifecycle::getId, l -> l)); + PlexusContainer mockedPlexusContainer = mock(PlexusContainer.class); + when(mockedPlexusContainer.lookupMap(Lifecycle.class)).thenReturn(lifeCycles); - DefaultLifecycles dl = new DefaultLifecycles( mockedPlexusContainer ); + DefaultLifecycles dl = new DefaultLifecycles(mockedPlexusContainer); - assertThat( dl.getLifeCycles().get( 0 ).getId(), is( "clean" ) ); - assertThat( dl.getLifeCycles().get( 1 ).getId(), is( "default" ) ); - assertThat( dl.getLifeCycles().get( 2 ).getId(), is( "site" ) ); - assertThat( dl.getLifeCycles().get( 3 ).getId(), is( "wrapper" ) ); - assertThat( dl.getLifeCycles().get( 4 ).getId(), is( "etl" ) ); + assertThat(dl.getLifeCycles().get(0).getId(), is("clean")); + assertThat(dl.getLifeCycles().get(1).getId(), is("default")); + assertThat(dl.getLifeCycles().get(2).getId(), is("site")); + assertThat(dl.getLifeCycles().get(3).getId(), is("wrapper")); + assertThat(dl.getLifeCycles().get(4).getId(), is("etl")); } - private Lifecycle getLifeCycleById( String id ) - { + private Lifecycle getLifeCycleById(String id) { return defaultLifeCycles.getLifeCycles().stream() - .filter( l -> id.equals( l.getId() ) ) - .findFirst() - .orElseThrow( IllegalArgumentException::new ); + .filter(l -> id.equals(l.getId())) + .findFirst() + .orElseThrow(IllegalArgumentException::new); } -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingMojoExecutionListener.java b/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingMojoExecutionListener.java index b111969733..9c7a742d0c 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingMojoExecutionListener.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingMojoExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,58 +16,44 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.MojoExecutionEvent; import org.apache.maven.execution.MojoExecutionListener; import org.apache.maven.plugin.MojoExecutionException; @Named @Singleton -public class DelegatingMojoExecutionListener - implements MojoExecutionListener -{ +public class DelegatingMojoExecutionListener implements MojoExecutionListener { private final List listeners = new CopyOnWriteArrayList<>(); - public void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException - { - for ( MojoExecutionListener listener : listeners ) - { - listener.beforeMojoExecution( event ); + public void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException { + for (MojoExecutionListener listener : listeners) { + listener.beforeMojoExecution(event); } } - public void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException - { - for ( MojoExecutionListener listener : listeners ) - { - listener.afterMojoExecutionSuccess( event ); + public void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException { + for (MojoExecutionListener listener : listeners) { + listener.afterMojoExecutionSuccess(event); } } - public void afterExecutionFailure( MojoExecutionEvent event ) - { - for ( MojoExecutionListener listener : listeners ) - { - listener.afterExecutionFailure( event ); + public void afterExecutionFailure(MojoExecutionEvent event) { + for (MojoExecutionListener listener : listeners) { + listener.afterExecutionFailure(event); } } - public void addMojoExecutionListener( MojoExecutionListener listener ) - { - this.listeners.add( listener ); + public void addMojoExecutionListener(MojoExecutionListener listener) { + this.listeners.add(listener); } - public void removeMojoExecutionListener( MojoExecutionListener listener ) - { - this.listeners.remove( listener ); + public void removeMojoExecutionListener(MojoExecutionListener listener) { + this.listeners.remove(listener); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingProjectExecutionListener.java b/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingProjectExecutionListener.java index 4266c154d2..b0b192e7cf 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingProjectExecutionListener.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/DelegatingProjectExecutionListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,65 +16,49 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.execution.ProjectExecutionEvent; import org.apache.maven.execution.ProjectExecutionListener; @Named @Singleton -public class DelegatingProjectExecutionListener - implements ProjectExecutionListener -{ +public class DelegatingProjectExecutionListener implements ProjectExecutionListener { private final List listeners = new CopyOnWriteArrayList<>(); - public void beforeProjectExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.beforeProjectExecution( event ); + public void beforeProjectExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { + for (ProjectExecutionListener listener : listeners) { + listener.beforeProjectExecution(event); } } - public void beforeProjectLifecycleExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.beforeProjectLifecycleExecution( event ); + public void beforeProjectLifecycleExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { + for (ProjectExecutionListener listener : listeners) { + listener.beforeProjectLifecycleExecution(event); } } - public void afterProjectExecutionSuccess( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.afterProjectExecutionSuccess( event ); + public void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException { + for (ProjectExecutionListener listener : listeners) { + listener.afterProjectExecutionSuccess(event); } } - public void afterProjectExecutionFailure( ProjectExecutionEvent event ) - { - for ( ProjectExecutionListener listener : listeners ) - { - listener.afterProjectExecutionFailure( event ); + public void afterProjectExecutionFailure(ProjectExecutionEvent event) { + for (ProjectExecutionListener listener : listeners) { + listener.afterProjectExecutionFailure(event); } } - public void addProjectExecutionListener( ProjectExecutionListener listener ) - { - this.listeners.add( listener ); + public void addProjectExecutionListener(ProjectExecutionListener listener) { + this.listeners.add(listener); } - public void removeProjectExecutionListener( ProjectExecutionListener listener ) - { - this.listeners.remove( listener ); + public void removeProjectExecutionListener(ProjectExecutionListener listener) { + this.listeners.remove(listener); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/EmptyLifecyclePluginAnalyzer.java b/maven-core/src/test/java/org/apache/maven/lifecycle/EmptyLifecyclePluginAnalyzer.java index a812c26900..3e0242f4de 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/EmptyLifecyclePluginAnalyzer.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/EmptyLifecyclePluginAnalyzer.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,60 +16,51 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; /** * @author Benjamin Bentmann */ -public class EmptyLifecyclePluginAnalyzer - implements LifeCyclePluginAnalyzer -{ - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { +public class EmptyLifecyclePluginAnalyzer implements LifeCyclePluginAnalyzer { + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { Set plugins; // NOTE: The upper-case packaging name is intentional, that's a special hinting mode used for certain tests - if ( "JAR".equals( packaging ) ) - { + if ("JAR".equals(packaging)) { plugins = new LinkedHashSet<>(); - plugins.add( newPlugin( "maven-compiler-plugin", "compile", "testCompile" ) ); - plugins.add( newPlugin( "maven-resources-plugin", "resources", "testResources" ) ); - plugins.add( newPlugin( "maven-surefire-plugin", "test" ) ); - plugins.add( newPlugin( "maven-jar-plugin", "jar" ) ); - plugins.add( newPlugin( "maven-install-plugin", "install" ) ); - plugins.add( newPlugin( "maven-deploy-plugin", "deploy" ) ); - } - else - { + plugins.add(newPlugin("maven-compiler-plugin", "compile", "testCompile")); + plugins.add(newPlugin("maven-resources-plugin", "resources", "testResources")); + plugins.add(newPlugin("maven-surefire-plugin", "test")); + plugins.add(newPlugin("maven-jar-plugin", "jar")); + plugins.add(newPlugin("maven-install-plugin", "install")); + plugins.add(newPlugin("maven-deploy-plugin", "deploy")); + } else { plugins = Collections.emptySet(); } return plugins; } - private Plugin newPlugin( String artifactId, String... goals ) - { + private Plugin newPlugin(String artifactId, String... goals) { Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.plugins" ); - plugin.setArtifactId( artifactId ); + plugin.setGroupId("org.apache.maven.plugins"); + plugin.setArtifactId(artifactId); - for ( String goal : goals ) - { + for (String goal : goals) { PluginExecution pluginExecution = new PluginExecution(); - pluginExecution.setId( "default-" + goal ); - pluginExecution.addGoal( goal ); - plugin.addExecution( pluginExecution ); + pluginExecution.setId("default-" + goal); + pluginExecution.addGoal(goal); + plugin.addExecution(pluginExecution); } return plugin; } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorSubModulesTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorSubModulesTest.java index cc2961f91b..cbf48525bd 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorSubModulesTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorSubModulesTest.java @@ -1,21 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - - package org.apache.maven.lifecycle; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import javax.inject.Inject; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.exception.ExceptionHandler; import org.apache.maven.lifecycle.internal.LifecycleDependencyResolver; @@ -23,22 +28,14 @@ import org.apache.maven.lifecycle.internal.LifecycleExecutionPlanCalculator; import org.apache.maven.lifecycle.internal.LifecycleModuleBuilder; import org.apache.maven.lifecycle.internal.LifecycleTaskSegmentCalculator; import org.apache.maven.lifecycle.internal.MojoExecutor; - -import javax.inject.Inject; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * Just asserts that it's able to create those components. Handy when CDI container gets a nervous breakdown. * * @author Kristian Rosenvold */ - -public class LifecycleExecutorSubModulesTest - extends AbstractCoreMavenComponentTestCase -{ +public class LifecycleExecutorSubModulesTest extends AbstractCoreMavenComponentTestCase { @Inject private DefaultLifecycles defaultLifeCycles; @@ -63,23 +60,19 @@ public class LifecycleExecutorSubModulesTest @Inject private ExceptionHandler exceptionHandler; - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/lifecycle-executor"; } @Test - public void testCreation() - throws Exception - { - assertNotNull( defaultLifeCycles ); - assertNotNull( mojoExecutor ); - assertNotNull( lifeCycleBuilder ); - assertNotNull( lifeCycleDependencyResolver ); - assertNotNull( lifeCycleExecutionPlanCalculator ); - assertNotNull( lifeCyclePluginAnalyzer ); - assertNotNull( lifeCycleTaskSegmentCalculator ); - assertNotNull( exceptionHandler ); + public void testCreation() throws Exception { + assertNotNull(defaultLifeCycles); + assertNotNull(mojoExecutor); + assertNotNull(lifeCycleBuilder); + assertNotNull(lifeCycleDependencyResolver); + assertNotNull(lifeCycleExecutionPlanCalculator); + assertNotNull(lifeCyclePluginAnalyzer); + assertNotNull(lifeCycleTaskSegmentCalculator); + assertNotNull(exceptionHandler); } - -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorTest.java index b9720370ca..31698b09a4 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/LifecycleExecutorTest.java @@ -1,19 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.util.ArrayList; @@ -21,7 +31,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.api.xml.Dom; import org.apache.maven.execution.MavenSession; @@ -44,18 +54,7 @@ import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.project.MavenProject; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import javax.inject.Inject; - -public class LifecycleExecutorTest - extends AbstractCoreMavenComponentTestCase -{ +public class LifecycleExecutorTest extends AbstractCoreMavenComponentTestCase { @Inject private DefaultLifecycleExecutor lifecycleExecutor; @@ -68,8 +67,7 @@ public class LifecycleExecutorTest @Inject private MojoDescriptorCreator mojoDescriptorCreator; - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/lifecycle-executor"; } @@ -78,470 +76,453 @@ public class LifecycleExecutorTest // ----------------------------------------------------------------------------------------------- @Test - public void testCalculationOfBuildPlanWithIndividualTaskWherePluginIsSpecifiedInThePom() - throws Exception - { + public void testCalculationOfBuildPlanWithIndividualTaskWherePluginIsSpecifiedInThePom() throws Exception { // We are doing something like "mvn resources:resources" where no version is specified but this // project we are working on has the version specified in the POM so the version should come from there. - File pom = getProject( "project-basic" ); - MavenSession session = createMavenSession( pom ); - assertEquals( "project-basic", session.getCurrentProject().getArtifactId() ); - assertEquals( "1.0", session.getCurrentProject().getVersion() ); - List executionPlan = getExecutions( calculateExecutionPlan( session, "resources:resources" ) ); - assertEquals( 1, executionPlan.size() ); - MojoExecution mojoExecution = executionPlan.get( 0 ); - assertNotNull( mojoExecution ); - assertEquals( "org.apache.maven.plugins", - mojoExecution.getMojoDescriptor().getPluginDescriptor().getGroupId() ); - assertEquals( "maven-resources-plugin", - mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifactId() ); - assertEquals( "0.1", mojoExecution.getMojoDescriptor().getPluginDescriptor().getVersion() ); + File pom = getProject("project-basic"); + MavenSession session = createMavenSession(pom); + assertEquals("project-basic", session.getCurrentProject().getArtifactId()); + assertEquals("1.0", session.getCurrentProject().getVersion()); + List executionPlan = getExecutions(calculateExecutionPlan(session, "resources:resources")); + assertEquals(1, executionPlan.size()); + MojoExecution mojoExecution = executionPlan.get(0); + assertNotNull(mojoExecution); + assertEquals( + "org.apache.maven.plugins", + mojoExecution.getMojoDescriptor().getPluginDescriptor().getGroupId()); + assertEquals( + "maven-resources-plugin", + mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifactId()); + assertEquals( + "0.1", mojoExecution.getMojoDescriptor().getPluginDescriptor().getVersion()); } @Test - public void testCalculationOfBuildPlanWithIndividualTaskOfTheCleanLifecycle() - throws Exception - { + public void testCalculationOfBuildPlanWithIndividualTaskOfTheCleanLifecycle() throws Exception { // We are doing something like "mvn clean:clean" where no version is specified but this // project we are working on has the version specified in the POM so the version should come from there. - File pom = getProject( "project-basic" ); - MavenSession session = createMavenSession( pom ); - assertEquals( "project-basic", session.getCurrentProject().getArtifactId() ); - assertEquals( "1.0", session.getCurrentProject().getVersion() ); - List executionPlan = getExecutions( calculateExecutionPlan( session, "clean" ) ); - assertEquals( 1, executionPlan.size() ); - MojoExecution mojoExecution = executionPlan.get( 0 ); - assertNotNull( mojoExecution ); - assertEquals( "org.apache.maven.plugins", - mojoExecution.getMojoDescriptor().getPluginDescriptor().getGroupId() ); - assertEquals( "maven-clean-plugin", mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifactId() ); - assertEquals( "0.1", mojoExecution.getMojoDescriptor().getPluginDescriptor().getVersion() ); + File pom = getProject("project-basic"); + MavenSession session = createMavenSession(pom); + assertEquals("project-basic", session.getCurrentProject().getArtifactId()); + assertEquals("1.0", session.getCurrentProject().getVersion()); + List executionPlan = getExecutions(calculateExecutionPlan(session, "clean")); + assertEquals(1, executionPlan.size()); + MojoExecution mojoExecution = executionPlan.get(0); + assertNotNull(mojoExecution); + assertEquals( + "org.apache.maven.plugins", + mojoExecution.getMojoDescriptor().getPluginDescriptor().getGroupId()); + assertEquals( + "maven-clean-plugin", + mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifactId()); + assertEquals( + "0.1", mojoExecution.getMojoDescriptor().getPluginDescriptor().getVersion()); } @Test - public void testCalculationOfBuildPlanWithIndividualTaskOfTheCleanCleanGoal() - throws Exception - { + public void testCalculationOfBuildPlanWithIndividualTaskOfTheCleanCleanGoal() throws Exception { // We are doing something like "mvn clean:clean" where no version is specified but this // project we are working on has the version specified in the POM so the version should come from there. - File pom = getProject( "project-basic" ); - MavenSession session = createMavenSession( pom ); - assertEquals( "project-basic", session.getCurrentProject().getArtifactId() ); - assertEquals( "1.0", session.getCurrentProject().getVersion() ); - List executionPlan = getExecutions( calculateExecutionPlan( session, "clean:clean" ) ); - assertEquals( 1, executionPlan.size() ); - MojoExecution mojoExecution = executionPlan.get( 0 ); - assertNotNull( mojoExecution ); - assertEquals( "org.apache.maven.plugins", - mojoExecution.getMojoDescriptor().getPluginDescriptor().getGroupId() ); - assertEquals( "maven-clean-plugin", mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifactId() ); - assertEquals( "0.1", mojoExecution.getMojoDescriptor().getPluginDescriptor().getVersion() ); + File pom = getProject("project-basic"); + MavenSession session = createMavenSession(pom); + assertEquals("project-basic", session.getCurrentProject().getArtifactId()); + assertEquals("1.0", session.getCurrentProject().getVersion()); + List executionPlan = getExecutions(calculateExecutionPlan(session, "clean:clean")); + assertEquals(1, executionPlan.size()); + MojoExecution mojoExecution = executionPlan.get(0); + assertNotNull(mojoExecution); + assertEquals( + "org.apache.maven.plugins", + mojoExecution.getMojoDescriptor().getPluginDescriptor().getGroupId()); + assertEquals( + "maven-clean-plugin", + mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifactId()); + assertEquals( + "0.1", mojoExecution.getMojoDescriptor().getPluginDescriptor().getVersion()); } - List getExecutions( MavenExecutionPlan mavenExecutionPlan ) - { + List getExecutions(MavenExecutionPlan mavenExecutionPlan) { List result = new ArrayList<>(); - for ( ExecutionPlanItem executionPlanItem : mavenExecutionPlan ) - { - result.add( executionPlanItem.getMojoExecution() ); + for (ExecutionPlanItem executionPlanItem : mavenExecutionPlan) { + result.add(executionPlanItem.getMojoExecution()); } return result; } // We need to take in multiple lifecycles - public void testCalculationOfBuildPlanTasksOfTheCleanLifecycleAndTheInstallLifecycle() - throws Exception - { - File pom = getProject( "project-with-additional-lifecycle-elements" ); - MavenSession session = createMavenSession( pom ); - assertEquals( "project-with-additional-lifecycle-elements", session.getCurrentProject().getArtifactId() ); - assertEquals( "1.0", session.getCurrentProject().getVersion() ); - List executionPlan = getExecutions( calculateExecutionPlan( session, "clean", "install" ) ); + public void testCalculationOfBuildPlanTasksOfTheCleanLifecycleAndTheInstallLifecycle() throws Exception { + File pom = getProject("project-with-additional-lifecycle-elements"); + MavenSession session = createMavenSession(pom); + assertEquals( + "project-with-additional-lifecycle-elements", + session.getCurrentProject().getArtifactId()); + assertEquals("1.0", session.getCurrentProject().getVersion()); + List executionPlan = getExecutions(calculateExecutionPlan(session, "clean", "install")); - //[01] clean:clean - //[02] resources:resources - //[03] compiler:compile - //[04] it:generate-metadata - //[05] resources:testResources - //[06] compiler:testCompile - //[07] it:generate-test-metadata - //[08] surefire:test - //[09] jar:jar - //[10] install:install + // [01] clean:clean + // [02] resources:resources + // [03] compiler:compile + // [04] it:generate-metadata + // [05] resources:testResources + // [06] compiler:testCompile + // [07] it:generate-test-metadata + // [08] surefire:test + // [09] jar:jar + // [10] install:install // - assertEquals( 10, executionPlan.size() ); + assertEquals(10, executionPlan.size()); - assertEquals( "clean:clean", executionPlan.get( 0 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "resources:resources", executionPlan.get( 1 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "compiler:compile", executionPlan.get( 2 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:generate-metadata", executionPlan.get( 3 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "resources:testResources", executionPlan.get( 4 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "compiler:testCompile", executionPlan.get( 5 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:generate-test-metadata", executionPlan.get( 6 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "surefire:test", executionPlan.get( 7 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "jar:jar", executionPlan.get( 8 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "install:install", executionPlan.get( 9 ).getMojoDescriptor().getFullGoalName() ); + assertEquals("clean:clean", executionPlan.get(0).getMojoDescriptor().getFullGoalName()); + assertEquals( + "resources:resources", executionPlan.get(1).getMojoDescriptor().getFullGoalName()); + assertEquals( + "compiler:compile", executionPlan.get(2).getMojoDescriptor().getFullGoalName()); + assertEquals( + "it:generate-metadata", executionPlan.get(3).getMojoDescriptor().getFullGoalName()); + assertEquals( + "resources:testResources", + executionPlan.get(4).getMojoDescriptor().getFullGoalName()); + assertEquals( + "compiler:testCompile", executionPlan.get(5).getMojoDescriptor().getFullGoalName()); + assertEquals( + "it:generate-test-metadata", + executionPlan.get(6).getMojoDescriptor().getFullGoalName()); + assertEquals("surefire:test", executionPlan.get(7).getMojoDescriptor().getFullGoalName()); + assertEquals("jar:jar", executionPlan.get(8).getMojoDescriptor().getFullGoalName()); + assertEquals("install:install", executionPlan.get(9).getMojoDescriptor().getFullGoalName()); } // We need to take in multiple lifecycles - public void testCalculationOfBuildPlanWithMultipleExecutionsOfModello() - throws Exception - { - File pom = getProject( "project-with-multiple-executions" ); - MavenSession session = createMavenSession( pom ); - assertEquals( "project-with-multiple-executions", session.getCurrentProject().getArtifactId() ); - assertEquals( "1.0.1", session.getCurrentProject().getVersion() ); + public void testCalculationOfBuildPlanWithMultipleExecutionsOfModello() throws Exception { + File pom = getProject("project-with-multiple-executions"); + MavenSession session = createMavenSession(pom); + assertEquals( + "project-with-multiple-executions", session.getCurrentProject().getArtifactId()); + assertEquals("1.0.1", session.getCurrentProject().getVersion()); - MavenExecutionPlan plan = calculateExecutionPlan( session, "clean", "install" ); + MavenExecutionPlan plan = calculateExecutionPlan(session, "clean", "install"); - List executions = getExecutions( plan ); + List executions = getExecutions(plan); - //[01] clean:clean - //[02] modello:xpp3-writer - //[03] modello:java - //[04] modello:xpp3-reader - //[05] modello:xpp3-writer - //[06] modello:java - //[07] modello:xpp3-reader - //[08] plugin:descriptor - //[09] resources:resources - //[10] compiler:compile - //[11] resources:testResources - //[12] compiler:testCompile - //[13] surefire:test - //[14] jar:jar - //[15] plugin:addPluginArtifactMetadata - //[16] install:install + // [01] clean:clean + // [02] modello:xpp3-writer + // [03] modello:java + // [04] modello:xpp3-reader + // [05] modello:xpp3-writer + // [06] modello:java + // [07] modello:xpp3-reader + // [08] plugin:descriptor + // [09] resources:resources + // [10] compiler:compile + // [11] resources:testResources + // [12] compiler:testCompile + // [13] surefire:test + // [14] jar:jar + // [15] plugin:addPluginArtifactMetadata + // [16] install:install // - assertEquals( 16, executions.size() ); + assertEquals(16, executions.size()); - assertEquals( "clean:clean", executions.get( 0 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:xpp3-writer", executions.get( 1 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:java", executions.get( 2 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:xpp3-reader", executions.get( 3 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:xpp3-writer", executions.get( 4 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:java", executions.get( 5 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:xpp3-reader", executions.get( 6 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "resources:resources", executions.get( 7 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "compiler:compile", executions.get( 8 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "plugin:descriptor", executions.get( 9 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "resources:testResources", executions.get( 10 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "compiler:testCompile", executions.get( 11 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "surefire:test", executions.get( 12 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "jar:jar", executions.get( 13 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "plugin:addPluginArtifactMetadata", executions.get( 14 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "install:install", executions.get( 15 ).getMojoDescriptor().getFullGoalName() ); + assertEquals("clean:clean", executions.get(0).getMojoDescriptor().getFullGoalName()); + assertEquals("it:xpp3-writer", executions.get(1).getMojoDescriptor().getFullGoalName()); + assertEquals("it:java", executions.get(2).getMojoDescriptor().getFullGoalName()); + assertEquals("it:xpp3-reader", executions.get(3).getMojoDescriptor().getFullGoalName()); + assertEquals("it:xpp3-writer", executions.get(4).getMojoDescriptor().getFullGoalName()); + assertEquals("it:java", executions.get(5).getMojoDescriptor().getFullGoalName()); + assertEquals("it:xpp3-reader", executions.get(6).getMojoDescriptor().getFullGoalName()); + assertEquals( + "resources:resources", executions.get(7).getMojoDescriptor().getFullGoalName()); + assertEquals("compiler:compile", executions.get(8).getMojoDescriptor().getFullGoalName()); + assertEquals("plugin:descriptor", executions.get(9).getMojoDescriptor().getFullGoalName()); + assertEquals( + "resources:testResources", + executions.get(10).getMojoDescriptor().getFullGoalName()); + assertEquals( + "compiler:testCompile", executions.get(11).getMojoDescriptor().getFullGoalName()); + assertEquals("surefire:test", executions.get(12).getMojoDescriptor().getFullGoalName()); + assertEquals("jar:jar", executions.get(13).getMojoDescriptor().getFullGoalName()); + assertEquals( + "plugin:addPluginArtifactMetadata", + executions.get(14).getMojoDescriptor().getFullGoalName()); + assertEquals("install:install", executions.get(15).getMojoDescriptor().getFullGoalName()); - assertEquals( "src/main/mdo/remote-resources.mdo", - new MojoExecutionXPathContainer( executions.get( 1 ) ).getValue( - "configuration/models[1]/model" ) ); - assertEquals( "src/main/mdo/supplemental-model.mdo", - new MojoExecutionXPathContainer( executions.get( 4 ) ).getValue( - "configuration/models[1]/model" ) ); + assertEquals( + "src/main/mdo/remote-resources.mdo", + new MojoExecutionXPathContainer(executions.get(1)).getValue("configuration/models[1]/model")); + assertEquals( + "src/main/mdo/supplemental-model.mdo", + new MojoExecutionXPathContainer(executions.get(4)).getValue("configuration/models[1]/model")); } @Test - public void testLifecycleQueryingUsingADefaultLifecyclePhase() - throws Exception - { - File pom = getProject( "project-with-additional-lifecycle-elements" ); - MavenSession session = createMavenSession( pom ); - assertEquals( "project-with-additional-lifecycle-elements", session.getCurrentProject().getArtifactId() ); - assertEquals( "1.0", session.getCurrentProject().getVersion() ); - List executionPlan = getExecutions( calculateExecutionPlan( session, "package" ) ); + public void testLifecycleQueryingUsingADefaultLifecyclePhase() throws Exception { + File pom = getProject("project-with-additional-lifecycle-elements"); + MavenSession session = createMavenSession(pom); + assertEquals( + "project-with-additional-lifecycle-elements", + session.getCurrentProject().getArtifactId()); + assertEquals("1.0", session.getCurrentProject().getVersion()); + List executionPlan = getExecutions(calculateExecutionPlan(session, "package")); - //[01] resources:resources - //[02] compiler:compile - //[03] it:generate-metadata - //[04] resources:testResources - //[05] compiler:testCompile - //[06] plexus-component-metadata:generate-test-metadata - //[07] surefire:test - //[08] jar:jar + // [01] resources:resources + // [02] compiler:compile + // [03] it:generate-metadata + // [04] resources:testResources + // [05] compiler:testCompile + // [06] plexus-component-metadata:generate-test-metadata + // [07] surefire:test + // [08] jar:jar // - assertEquals( 8, executionPlan.size() ); + assertEquals(8, executionPlan.size()); - assertEquals( "resources:resources", executionPlan.get( 0 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "compiler:compile", executionPlan.get( 1 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:generate-metadata", executionPlan.get( 2 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "resources:testResources", executionPlan.get( 3 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "compiler:testCompile", executionPlan.get( 4 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "it:generate-test-metadata", executionPlan.get( 5 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "surefire:test", executionPlan.get( 6 ).getMojoDescriptor().getFullGoalName() ); - assertEquals( "jar:jar", executionPlan.get( 7 ).getMojoDescriptor().getFullGoalName() ); + assertEquals( + "resources:resources", executionPlan.get(0).getMojoDescriptor().getFullGoalName()); + assertEquals( + "compiler:compile", executionPlan.get(1).getMojoDescriptor().getFullGoalName()); + assertEquals( + "it:generate-metadata", executionPlan.get(2).getMojoDescriptor().getFullGoalName()); + assertEquals( + "resources:testResources", + executionPlan.get(3).getMojoDescriptor().getFullGoalName()); + assertEquals( + "compiler:testCompile", executionPlan.get(4).getMojoDescriptor().getFullGoalName()); + assertEquals( + "it:generate-test-metadata", + executionPlan.get(5).getMojoDescriptor().getFullGoalName()); + assertEquals("surefire:test", executionPlan.get(6).getMojoDescriptor().getFullGoalName()); + assertEquals("jar:jar", executionPlan.get(7).getMojoDescriptor().getFullGoalName()); } @Test - public void testLifecyclePluginsRetrievalForDefaultLifecycle() - throws Exception - { - List plugins = - new ArrayList<>( lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles( "jar" ) ); + public void testLifecyclePluginsRetrievalForDefaultLifecycle() throws Exception { + List plugins = new ArrayList<>(lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles("jar")); - assertThat( plugins.toString(), plugins, hasSize( 9 ) ); + assertThat(plugins.toString(), plugins, hasSize(9)); } @Test - public void testPluginConfigurationCreation() - throws Exception - { - File pom = getProject( "project-with-additional-lifecycle-elements" ); - MavenSession session = createMavenSession( pom ); - MojoDescriptor mojoDescriptor = - mojoDescriptorCreator.getMojoDescriptor( "org.apache.maven.its.plugins:maven-it-plugin:0.1:java", session, - session.getCurrentProject() ); - Dom dom = MojoDescriptorCreator.convert( mojoDescriptor ).getDom(); - System.out.println( dom ); + public void testPluginConfigurationCreation() throws Exception { + File pom = getProject("project-with-additional-lifecycle-elements"); + MavenSession session = createMavenSession(pom); + MojoDescriptor mojoDescriptor = mojoDescriptorCreator.getMojoDescriptor( + "org.apache.maven.its.plugins:maven-it-plugin:0.1:java", session, session.getCurrentProject()); + Dom dom = MojoDescriptorCreator.convert(mojoDescriptor).getDom(); + System.out.println(dom); } - MavenExecutionPlan calculateExecutionPlan( MavenSession session, String... tasks ) - throws Exception - { + MavenExecutionPlan calculateExecutionPlan(MavenSession session, String... tasks) throws Exception { List taskSegments = - lifeCycleTaskSegmentCalculator.calculateTaskSegments( session, Arrays.asList( tasks ) ); + lifeCycleTaskSegmentCalculator.calculateTaskSegments(session, Arrays.asList(tasks)); - TaskSegment mergedSegment = new TaskSegment( false ); + TaskSegment mergedSegment = new TaskSegment(false); - for ( TaskSegment taskSegment : taskSegments ) - { - mergedSegment.getTasks().addAll( taskSegment.getTasks() ); + for (TaskSegment taskSegment : taskSegments) { + mergedSegment.getTasks().addAll(taskSegment.getTasks()); } - return lifeCycleExecutionPlanCalculator.calculateExecutionPlan( session, session.getCurrentProject(), - mergedSegment.getTasks() ); + return lifeCycleExecutionPlanCalculator.calculateExecutionPlan( + session, session.getCurrentProject(), mergedSegment.getTasks()); } @Test - public void testInvalidGoalName() - throws Exception - { - File pom = getProject( "project-basic" ); - MavenSession session = createMavenSession( pom ); + public void testInvalidGoalName() throws Exception { + File pom = getProject("project-basic"); + MavenSession session = createMavenSession(pom); MojoNotFoundException e = assertThrows( MojoNotFoundException.class, - () -> getExecutions( calculateExecutionPlan( session, "resources:" ) ), - "expected a MojoNotFoundException" ); - assertEquals( "", e.getGoal() ); + () -> getExecutions(calculateExecutionPlan(session, "resources:")), + "expected a MojoNotFoundException"); + assertEquals("", e.getGoal()); e = assertThrows( MojoNotFoundException.class, - () -> getExecutions( calculateExecutionPlan( session, "org.apache.maven.plugins:maven-resources-plugin:0.1:resources:toomany" ) ), - "expected a MojoNotFoundException" ); - assertEquals( "resources:toomany", e.getGoal() ); + () -> getExecutions(calculateExecutionPlan( + session, "org.apache.maven.plugins:maven-resources-plugin:0.1:resources:toomany")), + "expected a MojoNotFoundException"); + assertEquals("resources:toomany", e.getGoal()); } - @Test - public void testPluginPrefixRetrieval() - throws Exception - { - File pom = getProject( "project-basic" ); - MavenSession session = createMavenSession( pom ); - Plugin plugin = mojoDescriptorCreator.findPluginForPrefix( "resources", session ); - assertEquals( "org.apache.maven.plugins", plugin.getGroupId() ); - assertEquals( "maven-resources-plugin", plugin.getArtifactId() ); + public void testPluginPrefixRetrieval() throws Exception { + File pom = getProject("project-basic"); + MavenSession session = createMavenSession(pom); + Plugin plugin = mojoDescriptorCreator.findPluginForPrefix("resources", session); + assertEquals("org.apache.maven.plugins", plugin.getGroupId()); + assertEquals("maven-resources-plugin", plugin.getArtifactId()); } // Prefixes @Test - public void testFindingPluginPrefixForCleanClean() - throws Exception - { - File pom = getProject( "project-basic" ); - MavenSession session = createMavenSession( pom ); - Plugin plugin = mojoDescriptorCreator.findPluginForPrefix( "clean", session ); - assertNotNull( plugin ); + public void testFindingPluginPrefixForCleanClean() throws Exception { + File pom = getProject("project-basic"); + MavenSession session = createMavenSession(pom); + Plugin plugin = mojoDescriptorCreator.findPluginForPrefix("clean", session); + assertNotNull(plugin); } @Test - public void testSetupMojoExecution() - throws Exception - { - File pom = getProject( "mojo-configuration" ); + public void testSetupMojoExecution() throws Exception { + File pom = getProject("mojo-configuration"); - MavenSession session = createMavenSession( pom ); + MavenSession session = createMavenSession(pom); - LifecycleTask task = new LifecycleTask( "generate-sources" ); - MavenExecutionPlan executionPlan = - lifeCycleExecutionPlanCalculator.calculateExecutionPlan( session, session.getCurrentProject(), - Arrays.asList( (Object) task ), false ); + LifecycleTask task = new LifecycleTask("generate-sources"); + MavenExecutionPlan executionPlan = lifeCycleExecutionPlanCalculator.calculateExecutionPlan( + session, session.getCurrentProject(), Arrays.asList((Object) task), false); MojoExecution execution = executionPlan.getMojoExecutions().get(0); - assertEquals( "maven-it-plugin", execution.getArtifactId(), execution.toString() ); + assertEquals("maven-it-plugin", execution.getArtifactId(), execution.toString()); assertNull(execution.getConfiguration()); - lifeCycleExecutionPlanCalculator.setupMojoExecution( session, session.getCurrentProject(), execution, - new HashSet<>() ); + lifeCycleExecutionPlanCalculator.setupMojoExecution( + session, session.getCurrentProject(), execution, new HashSet<>()); assertNotNull(execution.getConfiguration()); - assertEquals("1.0", execution.getConfiguration().getChild( "version" ).getAttribute( "default-value" )); + assertEquals("1.0", execution.getConfiguration().getChild("version").getAttribute("default-value")); } @Test - public void testExecutionListeners() - throws Exception - { - final File pom = getProject( "project-basic" ); - final MavenSession session = createMavenSession( pom ); - session.setProjectDependencyGraph( new ProjectDependencyGraph() - { + public void testExecutionListeners() throws Exception { + final File pom = getProject("project-basic"); + final MavenSession session = createMavenSession(pom); + session.setProjectDependencyGraph(new ProjectDependencyGraph() { @Override - public List getUpstreamProjects( MavenProject project, boolean transitive ) - { + public List getUpstreamProjects(MavenProject project, boolean transitive) { return Collections.emptyList(); } @Override - public List getAllProjects() - { + public List getAllProjects() { return session.getAllProjects(); } @Override - public List getSortedProjects() - { - return Collections.singletonList( session.getCurrentProject() ); + public List getSortedProjects() { + return Collections.singletonList(session.getCurrentProject()); } @Override - public List getDownstreamProjects( MavenProject project, boolean transitive ) - { + public List getDownstreamProjects(MavenProject project, boolean transitive) { return Collections.emptyList(); } - } ); + }); final List log = new ArrayList<>(); - MojoExecutionListener mojoListener = new MojoExecutionListener() - { - public void beforeMojoExecution( MojoExecutionEvent event ) - throws MojoExecutionException - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNotNull( event.getExecution() ); - assertNotNull( event.getMojo() ); - assertNull( event.getCause() ); + MojoExecutionListener mojoListener = new MojoExecutionListener() { + public void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNotNull(event.getExecution()); + assertNotNull(event.getMojo()); + assertNull(event.getCause()); - log.add( "beforeMojoExecution " + event.getProject().getArtifactId() + ":" - + event.getExecution().getExecutionId() ); + log.add("beforeMojoExecution " + event.getProject().getArtifactId() + ":" + + event.getExecution().getExecutionId()); } - public void afterMojoExecutionSuccess( MojoExecutionEvent event ) - throws MojoExecutionException - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNotNull( event.getExecution() ); - assertNotNull( event.getMojo() ); - assertNull( event.getCause() ); + public void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNotNull(event.getExecution()); + assertNotNull(event.getMojo()); + assertNull(event.getCause()); - log.add( "afterMojoExecutionSuccess " + event.getProject().getArtifactId() + ":" - + event.getExecution().getExecutionId() ); + log.add("afterMojoExecutionSuccess " + event.getProject().getArtifactId() + ":" + + event.getExecution().getExecutionId()); } - public void afterExecutionFailure( MojoExecutionEvent event ) - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNotNull( event.getExecution() ); - assertNotNull( event.getMojo() ); - assertNotNull( event.getCause() ); + public void afterExecutionFailure(MojoExecutionEvent event) { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNotNull(event.getExecution()); + assertNotNull(event.getMojo()); + assertNotNull(event.getCause()); - log.add( "afterExecutionFailure " + event.getProject().getArtifactId() + ":" - + event.getExecution().getExecutionId() ); + log.add("afterExecutionFailure " + event.getProject().getArtifactId() + ":" + + event.getExecution().getExecutionId()); } }; - ProjectExecutionListener projectListener = new ProjectExecutionListener() - { - public void beforeProjectExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNull( event.getExecutionPlan() ); - assertNull( event.getCause() ); + ProjectExecutionListener projectListener = new ProjectExecutionListener() { + public void beforeProjectExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNull(event.getExecutionPlan()); + assertNull(event.getCause()); - log.add( "beforeProjectExecution " + event.getProject().getArtifactId() ); + log.add("beforeProjectExecution " + event.getProject().getArtifactId()); } - public void beforeProjectLifecycleExecution( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNotNull( event.getExecutionPlan() ); - assertNull( event.getCause() ); + public void beforeProjectLifecycleExecution(ProjectExecutionEvent event) + throws LifecycleExecutionException { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNotNull(event.getExecutionPlan()); + assertNull(event.getCause()); - log.add( "beforeProjectLifecycleExecution " + event.getProject().getArtifactId() ); + log.add("beforeProjectLifecycleExecution " + event.getProject().getArtifactId()); } - public void afterProjectExecutionSuccess( ProjectExecutionEvent event ) - throws LifecycleExecutionException - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNotNull( event.getExecutionPlan() ); - assertNull( event.getCause() ); + public void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNotNull(event.getExecutionPlan()); + assertNull(event.getCause()); - log.add( "afterProjectExecutionSuccess " + event.getProject().getArtifactId() ); + log.add("afterProjectExecutionSuccess " + event.getProject().getArtifactId()); } - public void afterProjectExecutionFailure( ProjectExecutionEvent event ) - { - assertNotNull( event.getSession() ); - assertNotNull( event.getProject() ); - assertNull( event.getExecutionPlan() ); - assertNotNull( event.getCause() ); + public void afterProjectExecutionFailure(ProjectExecutionEvent event) { + assertNotNull(event.getSession()); + assertNotNull(event.getProject()); + assertNull(event.getExecutionPlan()); + assertNotNull(event.getCause()); - log.add( "afterProjectExecutionFailure " + event.getProject().getArtifactId() ); + log.add("afterProjectExecutionFailure " + event.getProject().getArtifactId()); } }; - getContainer().lookup( DelegatingProjectExecutionListener.class ).addProjectExecutionListener( projectListener ); - getContainer().lookup( DelegatingMojoExecutionListener.class ).addMojoExecutionListener( mojoListener ); + getContainer().lookup(DelegatingProjectExecutionListener.class).addProjectExecutionListener(projectListener); + getContainer().lookup(DelegatingMojoExecutionListener.class).addMojoExecutionListener(mojoListener); - try - { - lifecycleExecutor.execute( session ); - } - finally - { - getContainer().lookup( DelegatingProjectExecutionListener.class ).removeProjectExecutionListener( projectListener ); - getContainer().lookup( DelegatingMojoExecutionListener.class ).removeMojoExecutionListener( mojoListener ); + try { + lifecycleExecutor.execute(session); + } finally { + getContainer() + .lookup(DelegatingProjectExecutionListener.class) + .removeProjectExecutionListener(projectListener); + getContainer().lookup(DelegatingMojoExecutionListener.class).removeMojoExecutionListener(mojoListener); } - List expectedLog = Arrays.asList( "beforeProjectExecution project-basic", // - "beforeProjectLifecycleExecution project-basic", // - "beforeMojoExecution project-basic:default-resources", // - "afterMojoExecutionSuccess project-basic:default-resources", // - "beforeMojoExecution project-basic:default-compile", // - "afterMojoExecutionSuccess project-basic:default-compile", // - "beforeMojoExecution project-basic:default-testResources", // - "afterMojoExecutionSuccess project-basic:default-testResources", // - "beforeMojoExecution project-basic:default-testCompile", // - "afterMojoExecutionSuccess project-basic:default-testCompile", // - "beforeMojoExecution project-basic:default-test", // - "afterMojoExecutionSuccess project-basic:default-test", // - "beforeMojoExecution project-basic:default-jar", // - "afterMojoExecutionSuccess project-basic:default-jar", // - "afterProjectExecutionSuccess project-basic" // - ); + List expectedLog = Arrays.asList( + "beforeProjectExecution project-basic", // + "beforeProjectLifecycleExecution project-basic", // + "beforeMojoExecution project-basic:default-resources", // + "afterMojoExecutionSuccess project-basic:default-resources", // + "beforeMojoExecution project-basic:default-compile", // + "afterMojoExecutionSuccess project-basic:default-compile", // + "beforeMojoExecution project-basic:default-testResources", // + "afterMojoExecutionSuccess project-basic:default-testResources", // + "beforeMojoExecution project-basic:default-testCompile", // + "afterMojoExecutionSuccess project-basic:default-testCompile", // + "beforeMojoExecution project-basic:default-test", // + "afterMojoExecutionSuccess project-basic:default-test", // + "beforeMojoExecution project-basic:default-jar", // + "afterMojoExecutionSuccess project-basic:default-jar", // + "afterProjectExecutionSuccess project-basic" // + ); - assertEventLog( expectedLog, log ); + assertEventLog(expectedLog, log); } - private static void assertEventLog( List expectedList, List actualList ) - { - assertEquals( toString( expectedList ), toString( actualList ) ); + private static void assertEventLog(List expectedList, List actualList) { + assertEquals(toString(expectedList), toString(actualList)); } - private static String toString( List lines ) - { + private static String toString(List lines) { StringBuilder sb = new StringBuilder(); - for ( String line : lines ) - { - sb.append( line ).append( '\n' ); + for (String line : lines) { + sb.append(line).append('\n'); } return sb.toString(); } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/MavenExecutionPlanTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/MavenExecutionPlanTest.java index 179dfe0719..d1dcd39448 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/MavenExecutionPlanTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/MavenExecutionPlanTest.java @@ -1,80 +1,71 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle; -import java.util.Set; - -import org.apache.maven.lifecycle.internal.ExecutionPlanItem; -import org.apache.maven.lifecycle.internal.stub.LifecycleExecutionPlanCalculatorStub; -import org.apache.maven.model.Plugin; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import java.util.Set; +import org.apache.maven.lifecycle.internal.ExecutionPlanItem; +import org.apache.maven.lifecycle.internal.stub.LifecycleExecutionPlanCalculatorStub; +import org.apache.maven.model.Plugin; +import org.junit.jupiter.api.Test; + /** * @author Kristian Rosenvold */ -public class MavenExecutionPlanTest -{ +public class MavenExecutionPlanTest { @Test - public void testFindLastInPhase() - throws Exception - { + public void testFindLastInPhase() throws Exception { MavenExecutionPlan plan = LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan(); - ExecutionPlanItem expected = plan.findLastInPhase( "package" ); - ExecutionPlanItem beerPhase = plan.findLastInPhase( "BEER" ); // Beer comes straight after package in stub - assertEquals( expected, beerPhase ); - assertNotNull( expected ); + ExecutionPlanItem expected = plan.findLastInPhase("package"); + ExecutionPlanItem beerPhase = plan.findLastInPhase("BEER"); // Beer comes straight after package in stub + assertEquals(expected, beerPhase); + assertNotNull(expected); } @Test - public void testThreadSafeMojos() - throws Exception - { + public void testThreadSafeMojos() throws Exception { MavenExecutionPlan plan = LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan(); final Set unSafePlugins = plan.getNonThreadSafePlugins(); // There is only a single threadsafe plugin here... - assertEquals( plan.size() - 1, unSafePlugins.size() ); - + assertEquals(plan.size() - 1, unSafePlugins.size()); } - @Test - public void testFindLastWhenFirst() - throws Exception - { + public void testFindLastWhenFirst() throws Exception { MavenExecutionPlan plan = LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan(); ExecutionPlanItem beerPhase = plan.findLastInPhase( - LifecycleExecutionPlanCalculatorStub.VALIDATE.getPhase() ); // Beer comes straight after package in stub - assertNull( beerPhase ); + LifecycleExecutionPlanCalculatorStub.VALIDATE.getPhase()); // Beer comes straight after package in stub + assertNull(beerPhase); } @Test - public void testFindLastInPhaseMisc() - throws Exception - { + public void testFindLastInPhaseMisc() throws Exception { MavenExecutionPlan plan = LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan(); - assertNull( plan.findLastInPhase( "pacXkage" ) ); + assertNull(plan.findLastInPhase("pacXkage")); // Beer comes straight after package in stub, much like real life. - assertNotNull( plan.findLastInPhase( LifecycleExecutionPlanCalculatorStub.INITIALIZE.getPhase() ) ); + assertNotNull(plan.findLastInPhase(LifecycleExecutionPlanCalculatorStub.INITIALIZE.getPhase())); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/MojoExecutionXPathContainer.java b/maven-core/src/test/java/org/apache/maven/lifecycle/MojoExecutionXPathContainer.java index ce81c85ebf..577579080d 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/MojoExecutionXPathContainer.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/MojoExecutionXPathContainer.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle; * "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 + * 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 @@ -18,55 +16,45 @@ package org.apache.maven.lifecycle; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle; import java.io.IOException; import java.util.Iterator; - import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathNotFoundException; import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.harness.Xpp3DomPointerFactory; -public class MojoExecutionXPathContainer -{ +public class MojoExecutionXPathContainer { private JXPathContext context; - static - { - JXPathContextReferenceImpl.addNodePointerFactory( new Xpp3DomPointerFactory() ); + static { + JXPathContextReferenceImpl.addNodePointerFactory(new Xpp3DomPointerFactory()); } - public MojoExecutionXPathContainer( MojoExecution mojoExecution ) - throws IOException - { - context = JXPathContext.newContext( mojoExecution ); + public MojoExecutionXPathContainer(MojoExecution mojoExecution) throws IOException { + context = JXPathContext.newContext(mojoExecution); } - public Iterator getIteratorForXPathExpression( String expression ) - { - return context.iterate( expression ); + public Iterator getIteratorForXPathExpression(String expression) { + return context.iterate(expression); } - public boolean containsXPathExpression( String expression ) - { - return context.getValue( expression ) != null; + public boolean containsXPathExpression(String expression) { + return context.getValue(expression) != null; } - public Object getValue( String expression ) - { - try - { - return context.getValue( expression ); - } - catch ( JXPathNotFoundException e ) - { + public Object getValue(String expression) { + try { + return context.getValue(expression); + } catch (JXPathNotFoundException e) { return null; } } - public boolean xPathExpressionEqualsValue( String expression, String value ) - { - return context.getValue( expression ) != null && context.getValue( expression ).equals( value ); + public boolean xPathExpressionEqualsValue(String expression, String value) { + return context.getValue(expression) != null + && context.getValue(expression).equals(value); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java index 4f0b0591e4..f5e040ad2d 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java @@ -1,58 +1,54 @@ -package org.apache.maven.lifecycle.internal; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - -import java.util.List; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.lifecycle.internal.stub.LifecycleTaskSegmentCalculatorStub; -import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; -import org.junit.jupiter.api.Test; +package org.apache.maven.lifecycle.internal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; -public class BuildListCalculatorTest -{ +import java.util.List; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.internal.stub.LifecycleTaskSegmentCalculatorStub; +import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; +import org.junit.jupiter.api.Test; + +public class BuildListCalculatorTest { @Test - public void testCalculateProjectBuilds() - throws Exception - { + public void testCalculateProjectBuilds() throws Exception { LifecycleTaskSegmentCalculator lifecycleTaskSegmentCalculator = getTaskSegmentCalculator(); BuildListCalculator buildListCalculator = new BuildListCalculator(); final MavenSession session = ProjectDependencyGraphStub.getMavenSession(); - List taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments( session ); - final ProjectBuildList buildList = buildListCalculator.calculateProjectBuilds( session, taskSegments ); - final ProjectBuildList segments = buildList.getByTaskSegment( taskSegments.get( 0 ) ); - assertEquals( 3, taskSegments.size(), "Stub data contains 3 segments" ); - assertEquals( 6, segments.size(), "Stub data contains 6 items" ); - final ProjectSegment build = segments.get( 0 ); - assertNotNull( build ); + List taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments(session); + final ProjectBuildList buildList = buildListCalculator.calculateProjectBuilds(session, taskSegments); + final ProjectBuildList segments = buildList.getByTaskSegment(taskSegments.get(0)); + assertEquals(3, taskSegments.size(), "Stub data contains 3 segments"); + assertEquals(6, segments.size(), "Stub data contains 6 items"); + final ProjectSegment build = segments.get(0); + assertNotNull(build); - for ( ProjectSegment segment : segments ) - { - assertSame( session, segment.getSession() ); + for (ProjectSegment segment : segments) { + assertSame(session, segment.getSession()); } } - private static LifecycleTaskSegmentCalculator getTaskSegmentCalculator() - { + private static LifecycleTaskSegmentCalculator getTaskSegmentCalculator() { return new LifecycleTaskSegmentCalculatorStub(); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ConcurrencyDependencyGraphTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ConcurrencyDependencyGraphTest.java index c2971f1c50..98248c1f1b 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ConcurrencyDependencyGraphTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ConcurrencyDependencyGraphTest.java @@ -1,22 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.A; +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.B; +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.C; +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.X; +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.Y; +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.Z; +import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.getProjectBuildList; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.lifecycle.LifecycleNotFoundException; @@ -33,71 +44,58 @@ import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; import org.junit.jupiter.api.Test; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.A; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.B; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.C; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.X; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.Y; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.Z; -import static org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub.getProjectBuildList; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Kristian Rosenvold */ -public class ConcurrencyDependencyGraphTest -{ +public class ConcurrencyDependencyGraphTest { @Test public void testConcurrencyGraphPrimaryVersion() - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { ProjectDependencyGraph dependencyGraph = new ProjectDependencyGraphStub(); final MavenSession session = ProjectDependencyGraphStub.getMavenSession(); ConcurrencyDependencyGraph graph = - new ConcurrencyDependencyGraph( getProjectBuildList( session ), dependencyGraph ); + new ConcurrencyDependencyGraph(getProjectBuildList(session), dependencyGraph); final List projectBuilds = graph.getRootSchedulableBuilds(); - assertEquals( 1, projectBuilds.size() ); - assertEquals( A, projectBuilds.iterator().next() ); + assertEquals(1, projectBuilds.size()); + assertEquals(A, projectBuilds.iterator().next()); - final List subsequent = graph.markAsFinished( A ); - assertEquals( 2, subsequent.size() ); - assertEquals( ProjectDependencyGraphStub.B, subsequent.get( 0 ) ); - assertEquals( C, subsequent.get( 1 ) ); + final List subsequent = graph.markAsFinished(A); + assertEquals(2, subsequent.size()); + assertEquals(ProjectDependencyGraphStub.B, subsequent.get(0)); + assertEquals(C, subsequent.get(1)); - final List bDescendants = graph.markAsFinished( B ); - assertEquals( 1, bDescendants.size() ); - assertEquals( Y, bDescendants.get( 0 ) ); + final List bDescendants = graph.markAsFinished(B); + assertEquals(1, bDescendants.size()); + assertEquals(Y, bDescendants.get(0)); - final List cDescendants = graph.markAsFinished( C ); - assertEquals( 2, cDescendants.size() ); - assertEquals( X, cDescendants.get( 0 ) ); - assertEquals( Z, cDescendants.get( 1 ) ); + final List cDescendants = graph.markAsFinished(C); + assertEquals(2, cDescendants.size()); + assertEquals(X, cDescendants.get(0)); + assertEquals(Z, cDescendants.get(1)); } @Test public void testConcurrencyGraphDifferentCompletionOrder() - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { ProjectDependencyGraph dependencyGraph = new ProjectDependencyGraphStub(); final MavenSession session = ProjectDependencyGraphStub.getMavenSession(); ConcurrencyDependencyGraph graph = - new ConcurrencyDependencyGraph( getProjectBuildList( session ), dependencyGraph ); + new ConcurrencyDependencyGraph(getProjectBuildList(session), dependencyGraph); - graph.markAsFinished( A ); - final List cDescendants = graph.markAsFinished( C ); - assertEquals( 1, cDescendants.size() ); - assertEquals( Z, cDescendants.get( 0 ) ); + graph.markAsFinished(A); + final List cDescendants = graph.markAsFinished(C); + assertEquals(1, cDescendants.size()); + assertEquals(Z, cDescendants.get(0)); - final List bDescendants = graph.markAsFinished( B ); - assertEquals( 2, bDescendants.size() ); - assertEquals( X, bDescendants.get( 0 ) ); - assertEquals( Y, bDescendants.get( 1 ) ); + final List bDescendants = graph.markAsFinished(B); + assertEquals(2, bDescendants.size()); + assertEquals(X, bDescendants.get(0)); + assertEquals(Y, bDescendants.get(1)); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolverTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolverTest.java index 9413111e44..5eeafb5dbc 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolverTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,6 +16,10 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.File; import java.util.Collection; @@ -25,55 +27,54 @@ import java.util.Collections; import java.util.HashSet; import java.util.Properties; import java.util.Set; - +import javax.inject.Inject; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; - -import javax.inject.Inject; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -public class LifecycleDependencyResolverTest extends AbstractCoreMavenComponentTestCase -{ +public class LifecycleDependencyResolverTest extends AbstractCoreMavenComponentTestCase { @Inject private LifecycleDependencyResolver resolver; @Override - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return null; } @Test - public void testCachedReactorProjectDependencies() throws Exception - { - MavenSession session = createMavenSession( new File( "src/test/projects/lifecycle-dependency-resolver/pom.xml" ), new Properties(), true ); + public void testCachedReactorProjectDependencies() throws Exception { + MavenSession session = createMavenSession( + new File("src/test/projects/lifecycle-dependency-resolver/pom.xml"), new Properties(), true); Collection scopesToCollect = null; - Collection scopesToResolve = Collections.singletonList( "compile" ); + Collection scopesToResolve = Collections.singletonList("compile"); boolean aggregating = false; - Set reactorArtifacts = new HashSet<>( 3 ); - for ( MavenProject reactorProject : session.getProjects() ) - { - reactorProject.setArtifactFilter( artifact -> true ); - resolver.resolveProjectDependencies( reactorProject, scopesToCollect, scopesToResolve, session, aggregating, reactorArtifacts ); - reactorArtifacts.add( reactorProject.getArtifact() ); + Set reactorArtifacts = new HashSet<>(3); + for (MavenProject reactorProject : session.getProjects()) { + reactorProject.setArtifactFilter(artifact -> true); + resolver.resolveProjectDependencies( + reactorProject, scopesToCollect, scopesToResolve, session, aggregating, reactorArtifacts); + reactorArtifacts.add(reactorProject.getArtifact()); } - MavenProject lib = session.getProjects().get( 1 ); - MavenProject war = session.getProjects().get( 2 ); + MavenProject lib = session.getProjects().get(1); + MavenProject war = session.getProjects().get(2); - assertNull( war.getArtifactMap().get( "org.apache.maven.its.mng6300:mng6300-lib" ).getFile() ); + assertNull(war.getArtifactMap() + .get("org.apache.maven.its.mng6300:mng6300-lib") + .getFile()); - lib.getArtifact().setFile( new File( "lib.jar" ) ); + lib.getArtifact().setFile(new File("lib.jar")); - resolver.resolveProjectDependencies( war, scopesToCollect, scopesToResolve, session, aggregating, reactorArtifacts ); + resolver.resolveProjectDependencies( + war, scopesToCollect, scopesToResolve, session, aggregating, reactorArtifacts); - assertEquals( new File( "lib.jar" ) , war.getArtifactMap().get("org.apache.maven.its.mng6300:mng6300-lib").getFile() ); + assertEquals( + new File("lib.jar"), + war.getArtifactMap() + .get("org.apache.maven.its.mng6300:mng6300-lib") + .getFile()); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculatorTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculatorTest.java index dc5f922d16..2a9dc96423 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculatorTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculatorTest.java @@ -1,19 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.execution.MavenSession; @@ -26,63 +31,55 @@ import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Kristian Rosenvold */ -public class LifecycleExecutionPlanCalculatorTest - extends AbstractCoreMavenComponentTestCase -{ +public class LifecycleExecutionPlanCalculatorTest extends AbstractCoreMavenComponentTestCase { @Test - public void testCalculateExecutionPlanWithGoalTasks() - throws Exception - { + public void testCalculateExecutionPlanWithGoalTasks() throws Exception { MojoDescriptorCreator mojoDescriptorCreator = createMojoDescriptorCreator(); LifecycleExecutionPlanCalculator lifecycleExecutionPlanCalculator = - createExecutionPlaceCalculator( mojoDescriptorCreator ); + createExecutionPlaceCalculator(mojoDescriptorCreator); - final GoalTask goalTask1 = new GoalTask( "compiler:compile" ); - final GoalTask goalTask2 = new GoalTask( "surefire:test" ); - final TaskSegment taskSegment1 = new TaskSegment( false, goalTask1, goalTask2 ); - final MavenSession session1 = ProjectDependencyGraphStub.getMavenSession( ProjectDependencyGraphStub.A ); + final GoalTask goalTask1 = new GoalTask("compiler:compile"); + final GoalTask goalTask2 = new GoalTask("surefire:test"); + final TaskSegment taskSegment1 = new TaskSegment(false, goalTask1, goalTask2); + final MavenSession session1 = ProjectDependencyGraphStub.getMavenSession(ProjectDependencyGraphStub.A); - MavenExecutionPlan executionPlan = - lifecycleExecutionPlanCalculator.calculateExecutionPlan( session1, ProjectDependencyGraphStub.A, - taskSegment1.getTasks() ); - assertEquals( 2, executionPlan.size() ); + MavenExecutionPlan executionPlan = lifecycleExecutionPlanCalculator.calculateExecutionPlan( + session1, ProjectDependencyGraphStub.A, taskSegment1.getTasks()); + assertEquals(2, executionPlan.size()); - final GoalTask goalTask3 = new GoalTask( "surefire:test" ); - final TaskSegment taskSegment2 = new TaskSegment( false, goalTask1, goalTask2, goalTask3 ); - MavenExecutionPlan executionPlan2 = - lifecycleExecutionPlanCalculator.calculateExecutionPlan( session1, ProjectDependencyGraphStub.A, - taskSegment2.getTasks() ); - assertEquals( 3, executionPlan2.size() ); + final GoalTask goalTask3 = new GoalTask("surefire:test"); + final TaskSegment taskSegment2 = new TaskSegment(false, goalTask1, goalTask2, goalTask3); + MavenExecutionPlan executionPlan2 = lifecycleExecutionPlanCalculator.calculateExecutionPlan( + session1, ProjectDependencyGraphStub.A, taskSegment2.getTasks()); + assertEquals(3, executionPlan2.size()); } // Maybe also make one with LifeCycleTasks - public static LifecycleExecutionPlanCalculator createExecutionPlaceCalculator( MojoDescriptorCreator mojoDescriptorCreator ) - throws ComponentLookupException - { - LifecyclePluginResolver lifecyclePluginResolver = new LifecyclePluginResolver( new PluginVersionResolverStub() ); - return new DefaultLifecycleExecutionPlanCalculator( new BuildPluginManagerStub(), - DefaultLifecyclesStub.createDefaultLifecycles(), - mojoDescriptorCreator, lifecyclePluginResolver ); + public static LifecycleExecutionPlanCalculator createExecutionPlaceCalculator( + MojoDescriptorCreator mojoDescriptorCreator) throws ComponentLookupException { + LifecyclePluginResolver lifecyclePluginResolver = new LifecyclePluginResolver(new PluginVersionResolverStub()); + return new DefaultLifecycleExecutionPlanCalculator( + new BuildPluginManagerStub(), + DefaultLifecyclesStub.createDefaultLifecycles(), + mojoDescriptorCreator, + lifecyclePluginResolver); } - public static MojoDescriptorCreator createMojoDescriptorCreator() - { - return new MojoDescriptorCreator( new PluginVersionResolverStub(), new BuildPluginManagerStub(), - new PluginPrefixResolverStub(), - new LifecyclePluginResolver( new PluginVersionResolverStub() ) ); + public static MojoDescriptorCreator createMojoDescriptorCreator() { + return new MojoDescriptorCreator( + new PluginVersionResolverStub(), + new BuildPluginManagerStub(), + new PluginPrefixResolverStub(), + new LifecyclePluginResolver(new PluginVersionResolverStub())); } @Override - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/lifecycle-executor"; } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java index 2e0eaa7000..9c492a336d 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java @@ -1,27 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -import javax.inject.Inject; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.execution.AbstractExecutionListener; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.DefaultMavenExecutionResult; @@ -36,55 +40,53 @@ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - @PlexusTest -public class LifecycleModuleBuilderTest -{ +public class LifecycleModuleBuilderTest { @Inject PlexusContainer container; @Test - public void testCurrentProject() throws Exception - { + public void testCurrentProject() throws Exception { List currentProjects = new ArrayList<>(); - MojoExecutorStub mojoExecutor = new MojoExecutorStub() - { + MojoExecutorStub mojoExecutor = new MojoExecutorStub() { @Override - public void execute( MavenSession session, List mojoExecutions, ProjectIndex projectIndex ) - throws LifecycleExecutionException - { - super.execute( session, mojoExecutions, projectIndex ); - currentProjects.add( session.getCurrentProject() ); + public void execute(MavenSession session, List mojoExecutions, ProjectIndex projectIndex) + throws LifecycleExecutionException { + super.execute(session, mojoExecutions, projectIndex); + currentProjects.add(session.getCurrentProject()); } }; final DefaultMavenExecutionResult defaultMavenExecutionResult = new DefaultMavenExecutionResult(); MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest(); - mavenExecutionRequest.setExecutionListener( new AbstractExecutionListener() ); - mavenExecutionRequest.setGoals( Arrays.asList( "clean" ) ); - final MavenSession session = new MavenSession( null, null, mavenExecutionRequest, defaultMavenExecutionResult ); + mavenExecutionRequest.setExecutionListener(new AbstractExecutionListener()); + mavenExecutionRequest.setGoals(Arrays.asList("clean")); + final MavenSession session = new MavenSession(null, null, mavenExecutionRequest, defaultMavenExecutionResult); final ProjectDependencyGraphStub dependencyGraphStub = new ProjectDependencyGraphStub(); - session.setProjectDependencyGraph( dependencyGraphStub ); - session.setProjects( dependencyGraphStub.getSortedProjects() ); + session.setProjectDependencyGraph(dependencyGraphStub); + session.setProjects(dependencyGraphStub.getSortedProjects()); - LifecycleModuleBuilder moduleBuilder = container.lookup( LifecycleModuleBuilder.class ); - set( moduleBuilder, "mojoExecutor", mojoExecutor ); + LifecycleModuleBuilder moduleBuilder = container.lookup(LifecycleModuleBuilder.class); + set(moduleBuilder, "mojoExecutor", mojoExecutor); - LifecycleStarter ls = container.lookup( LifecycleStarter.class ); - ls.execute( session ); + LifecycleStarter ls = container.lookup(LifecycleStarter.class); + ls.execute(session); - assertNull( session.getCurrentProject() ); - assertEquals( Arrays.asList( ProjectDependencyGraphStub.A, ProjectDependencyGraphStub.B, ProjectDependencyGraphStub.C, - ProjectDependencyGraphStub.X, ProjectDependencyGraphStub.Y, ProjectDependencyGraphStub.Z ), currentProjects ); + assertNull(session.getCurrentProject()); + assertEquals( + Arrays.asList( + ProjectDependencyGraphStub.A, + ProjectDependencyGraphStub.B, + ProjectDependencyGraphStub.C, + ProjectDependencyGraphStub.X, + ProjectDependencyGraphStub.Y, + ProjectDependencyGraphStub.Z), + currentProjects); } - static void set( Object obj, String field, Object v ) throws NoSuchFieldException, IllegalAccessException - { - Field f = obj.getClass().getDeclaredField( field ); - f.setAccessible( true ); - f.set( obj, v ); + static void set(Object obj, String field, Object v) throws NoSuchFieldException, IllegalAccessException { + Field f = obj.getClass().getDeclaredField(field); + f.setAccessible(true); + f.set(obj, v); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculatorImplTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculatorImplTest.java index e5a44d645e..ce8d0454df 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculatorImplTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculatorImplTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.lifecycle.internal; * "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 + * 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 @@ -18,43 +16,37 @@ package org.apache.maven.lifecycle.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.stub.LifecycleTaskSegmentCalculatorStub; import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * @author Kristian Rosenvold */ -public class LifecycleTaskSegmentCalculatorImplTest -{ +public class LifecycleTaskSegmentCalculatorImplTest { @Test - public void testCalculateProjectBuilds() - throws Exception - { + public void testCalculateProjectBuilds() throws Exception { LifecycleTaskSegmentCalculator lifecycleTaskSegmentCalculator = getTaskSegmentCalculator(); BuildListCalculator buildListCalculator = new BuildListCalculator(); final MavenSession session = ProjectDependencyGraphStub.getMavenSession(); - List taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments( session ); + List taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments(session); - final ProjectBuildList buildList = buildListCalculator.calculateProjectBuilds( session, taskSegments ); - final ProjectBuildList segments = buildList.getByTaskSegment( taskSegments.get( 0 ) ); - assertEquals( 3, taskSegments.size(), "Stub data contains 3 segments" ); - assertEquals( 6, segments.size(), "Stub data contains 6 items" ); - final ProjectSegment build = segments.get( 0 ); - assertNotNull( build ); + final ProjectBuildList buildList = buildListCalculator.calculateProjectBuilds(session, taskSegments); + final ProjectBuildList segments = buildList.getByTaskSegment(taskSegments.get(0)); + assertEquals(3, taskSegments.size(), "Stub data contains 3 segments"); + assertEquals(6, segments.size(), "Stub data contains 6 items"); + final ProjectSegment build = segments.get(0); + assertNotNull(build); } - private static LifecycleTaskSegmentCalculator getTaskSegmentCalculator() - { + private static LifecycleTaskSegmentCalculator getTaskSegmentCalculator() { return new LifecycleTaskSegmentCalculatorStub(); } - - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/PhaseRecorderTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/PhaseRecorderTest.java index f995d56e42..c2410fa7d8 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/PhaseRecorderTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/PhaseRecorderTest.java @@ -1,52 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; - import org.apache.maven.lifecycle.MavenExecutionPlan; import org.apache.maven.lifecycle.internal.stub.LifecycleExecutionPlanCalculatorStub; import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; import org.apache.maven.plugin.MojoExecution; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * @author Kristian Rosenvold */ -public class PhaseRecorderTest -{ +public class PhaseRecorderTest { @Test public void testObserveExecution() throws Exception { - PhaseRecorder phaseRecorder = new PhaseRecorder( ProjectDependencyGraphStub.A); + PhaseRecorder phaseRecorder = new PhaseRecorder(ProjectDependencyGraphStub.A); MavenExecutionPlan plan = LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan(); final List executions = plan.getMojoExecutions(); - final MojoExecution mojoExecution1 = executions.get( 0 ); - final MojoExecution mojoExecution2 = executions.get( 1 ); - phaseRecorder.observeExecution( mojoExecution1 ); + final MojoExecution mojoExecution1 = executions.get(0); + final MojoExecution mojoExecution2 = executions.get(1); + phaseRecorder.observeExecution(mojoExecution1); - assertTrue( ProjectDependencyGraphStub.A.hasLifecyclePhase( mojoExecution1.getLifecyclePhase() )); - assertFalse( ProjectDependencyGraphStub.A.hasLifecyclePhase( mojoExecution2.getLifecyclePhase() )); - - assertFalse( phaseRecorder.isDifferentPhase( mojoExecution1)); - assertTrue( phaseRecorder.isDifferentPhase( mojoExecution2)); + assertTrue(ProjectDependencyGraphStub.A.hasLifecyclePhase(mojoExecution1.getLifecyclePhase())); + assertFalse(ProjectDependencyGraphStub.A.hasLifecyclePhase(mojoExecution2.getLifecyclePhase())); + assertFalse(phaseRecorder.isDifferentPhase(mojoExecution1)); + assertTrue(phaseRecorder.isDifferentPhase(mojoExecution2)); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ProjectBuildListTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ProjectBuildListTest.java index 106c311987..85d25257b0 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ProjectBuildListTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/ProjectBuildListTest.java @@ -1,24 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; @@ -27,21 +30,18 @@ import org.junit.jupiter.api.Test; /** * @author Kristian Rosenvold */ -public class ProjectBuildListTest -{ +public class ProjectBuildListTest { @Test - public void testGetByTaskSegment() - throws Exception - { + public void testGetByTaskSegment() throws Exception { final MavenSession session = ProjectDependencyGraphStub.getMavenSession(); - ProjectBuildList projectBuildList = ProjectDependencyGraphStub.getProjectBuildList( session ); - TaskSegment taskSegment = projectBuildList.get( 0 ).getTaskSegment(); - assertThat( "This test assumes there are at least 6 elements in projectBuilds", - projectBuildList.size(), is( greaterThanOrEqualTo( 6 ) ) ); + ProjectBuildList projectBuildList = ProjectDependencyGraphStub.getProjectBuildList(session); + TaskSegment taskSegment = projectBuildList.get(0).getTaskSegment(); + assertThat( + "This test assumes there are at least 6 elements in projectBuilds", + projectBuildList.size(), + is(greaterThanOrEqualTo(6))); - final ProjectBuildList byTaskSegment = projectBuildList.getByTaskSegment( taskSegment ); - assertEquals( projectBuildList.size(), - byTaskSegment.size() ); // TODO Make multiple segments on projectBuildList + final ProjectBuildList byTaskSegment = projectBuildList.getByTaskSegment(taskSegment); + assertEquals(projectBuildList.size(), byTaskSegment.size()); // TODO Make multiple segments on projectBuildList } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/BuilderCommonTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/BuilderCommonTest.java index edb0892533..66ab90ec3d 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/BuilderCommonTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/BuilderCommonTest.java @@ -1,22 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal.builder; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import java.util.HashSet; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.MavenExecutionPlan; import org.apache.maven.lifecycle.internal.ExecutionEventCatapult; @@ -27,81 +33,63 @@ import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; import org.junit.jupiter.api.Test; import org.slf4j.Logger; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - /** * @author Kristian Rosenvold */ -public class BuilderCommonTest -{ - private Logger logger = mock( Logger.class ); +public class BuilderCommonTest { + private Logger logger = mock(Logger.class); @Test - public void testResolveBuildPlan() - throws Exception - { + public void testResolveBuildPlan() throws Exception { MavenSession original = ProjectDependencyGraphStub.getMavenSession(); - final TaskSegment taskSegment1 = new TaskSegment( false ); + final TaskSegment taskSegment1 = new TaskSegment(false); final MavenSession session1 = original.clone(); - session1.setCurrentProject( ProjectDependencyGraphStub.A ); + session1.setCurrentProject(ProjectDependencyGraphStub.A); - final BuilderCommon builderCommon = getBuilderCommon( logger ); + final BuilderCommon builderCommon = getBuilderCommon(logger); final MavenExecutionPlan plan = - builderCommon.resolveBuildPlan( session1, ProjectDependencyGraphStub.A, taskSegment1, - new HashSet<>() ); - assertEquals( LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan().size(), plan.size() ); + builderCommon.resolveBuildPlan(session1, ProjectDependencyGraphStub.A, taskSegment1, new HashSet<>()); + assertEquals( + LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan().size(), plan.size()); } @Test - public void testDefaultBindingPluginsWarning() - throws Exception - { + public void testDefaultBindingPluginsWarning() throws Exception { MavenSession original = ProjectDependencyGraphStub.getMavenSession(); - final TaskSegment taskSegment1 = new TaskSegment( false ); + final TaskSegment taskSegment1 = new TaskSegment(false); final MavenSession session1 = original.clone(); - session1.setCurrentProject( ProjectDependencyGraphStub.A ); + session1.setCurrentProject(ProjectDependencyGraphStub.A); - getBuilderCommon( logger ).resolveBuildPlan( session1, ProjectDependencyGraphStub.A, taskSegment1, new HashSet<>() ); + getBuilderCommon(logger) + .resolveBuildPlan(session1, ProjectDependencyGraphStub.A, taskSegment1, new HashSet<>()); - verify( logger ).warn("Version not locked for default bindings plugins [" - + "stub-plugin-initialize, " - + "stub-plugin-process-resources, " - + "stub-plugin-compile, " - + "stub-plugin-process-test-resources, " - + "stub-plugin-test-compile, " - + "stub-plugin-test, " - + "stub-plugin-package, " - + "stub-plugin-install], " - + "you should define versions in pluginManagement section of your pom.xml or parent"); + verify(logger) + .warn("Version not locked for default bindings plugins [" + + "stub-plugin-initialize, " + + "stub-plugin-process-resources, " + + "stub-plugin-compile, " + + "stub-plugin-process-test-resources, " + + "stub-plugin-test-compile, " + + "stub-plugin-test, " + + "stub-plugin-package, " + + "stub-plugin-install], " + + "you should define versions in pluginManagement section of your pom.xml or parent"); } @Test - public void testHandleBuildError() - throws Exception - { - } + public void testHandleBuildError() throws Exception {} @Test - public void testAttachToThread() - throws Exception - { - } + public void testAttachToThread() throws Exception {} @Test - public void testGetKey() - throws Exception - { - } + public void testGetKey() throws Exception {} - public BuilderCommon getBuilderCommon( Logger logger ) - { + public BuilderCommon getBuilderCommon(Logger logger) { final LifecycleDebugLogger debugLogger = new LifecycleDebugLogger(); - return new BuilderCommon( debugLogger, new LifecycleExecutionPlanCalculatorStub(), mock( - ExecutionEventCatapult.class ), logger ); + return new BuilderCommon( + debugLogger, new LifecycleExecutionPlanCalculatorStub(), mock(ExecutionEventCatapult.class), logger); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraphTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraphTest.java index 674435c42a..68427261a5 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraphTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraphTest.java @@ -1,86 +1,90 @@ -package org.apache.maven.lifecycle.internal.builder.multithreaded; /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ +package org.apache.maven.lifecycle.internal.builder.multithreaded; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.Set; - import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.lifecycle.internal.ProjectBuildList; import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub; import org.apache.maven.project.MavenProject; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class ConcurrencyDependencyGraphTest { @Test public void testGraph() throws Exception { - ProjectBuildList projectBuildList = ProjectDependencyGraphStub.getProjectBuildList( - ProjectDependencyGraphStub.getMavenSession() ); + ProjectBuildList projectBuildList = + ProjectDependencyGraphStub.getProjectBuildList(ProjectDependencyGraphStub.getMavenSession()); ProjectDependencyGraph projectDependencyGraph = new ProjectDependencyGraphStub(); - ConcurrencyDependencyGraph graph = new ConcurrencyDependencyGraph( projectBuildList, projectDependencyGraph ); + ConcurrencyDependencyGraph graph = new ConcurrencyDependencyGraph(projectBuildList, projectDependencyGraph); // start - assertEquals( 0, graph.getFinishedProjects().size() ); - assertEquals( 6, graph.getNumberOfBuilds() ); + assertEquals(0, graph.getFinishedProjects().size()); + assertEquals(6, graph.getNumberOfBuilds()); List rootSchedulableBuilds = graph.getRootSchedulableBuilds(); // only Project.A has no dependencies - assertEquals( 1, rootSchedulableBuilds.size() ); - assertEquals( ProjectDependencyGraphStub.A, rootSchedulableBuilds.iterator().next() ); + assertEquals(1, rootSchedulableBuilds.size()); + assertEquals( + ProjectDependencyGraphStub.A, rootSchedulableBuilds.iterator().next()); // double check A deps - List dependenciesA = graph.getDependencies( ProjectDependencyGraphStub.A ); - assertEquals( 0, dependenciesA.size() ); + List dependenciesA = graph.getDependencies(ProjectDependencyGraphStub.A); + assertEquals(0, dependenciesA.size()); - assertEquals( 6, graph.getUnfinishedProjects().size() ); + assertEquals(6, graph.getUnfinishedProjects().size()); - List schedulableNewProcesses = graph.markAsFinished( ProjectDependencyGraphStub.A ); + List schedulableNewProcesses = graph.markAsFinished(ProjectDependencyGraphStub.A); // expect Project B, C - assertEquals( 2, schedulableNewProcesses.size() ); - assertEquals( 1, graph.getFinishedProjects().size() ); + assertEquals(2, schedulableNewProcesses.size()); + assertEquals(1, graph.getFinishedProjects().size()); - graph.markAsFinished( ProjectDependencyGraphStub.A ); + graph.markAsFinished(ProjectDependencyGraphStub.A); // still only A - assertEquals( 1, graph.getFinishedProjects().size() ); + assertEquals(1, graph.getFinishedProjects().size()); Set unfinishedProjects = graph.getUnfinishedProjects(); - assertEquals( 5, unfinishedProjects.size() ); + assertEquals(5, unfinishedProjects.size()); - graph.markAsFinished( schedulableNewProcesses.get( 0 ) ); - assertEquals( 2, graph.getFinishedProjects().size() ); - assertEquals( 4, graph.getUnfinishedProjects().size() ); + graph.markAsFinished(schedulableNewProcesses.get(0)); + assertEquals(2, graph.getFinishedProjects().size()); + assertEquals(4, graph.getUnfinishedProjects().size()); - List dependenciesC = graph.getDependencies( ProjectDependencyGraphStub.C ); + List dependenciesC = graph.getDependencies(ProjectDependencyGraphStub.C); // C depends only on A - assertEquals( 1, dependenciesC.size() ); + assertEquals(1, dependenciesC.size()); - List dependenciesX = graph.getDependencies( ProjectDependencyGraphStub.X ); + List dependenciesX = graph.getDependencies(ProjectDependencyGraphStub.X); // X depends only on B and C - assertEquals( 2, dependenciesX.size() ); + assertEquals(2, dependenciesX.size()); - List activeDependenciesC = graph.getActiveDependencies( ProjectDependencyGraphStub.C ); + List activeDependenciesC = graph.getActiveDependencies(ProjectDependencyGraphStub.C); // A already finished - assertEquals( 0, activeDependenciesC.size() ); + assertEquals(0, activeDependenciesC.size()); - List activeDependenciesX = graph.getActiveDependencies( ProjectDependencyGraphStub.X ); + List activeDependenciesX = graph.getActiveDependencies(ProjectDependencyGraphStub.X); // waiting for C - assertEquals( 1, activeDependenciesX.size() ); + assertEquals(1, activeDependenciesX.size()); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxerTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxerTest.java index 549e90b8b8..bda22526b3 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxerTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxerTest.java @@ -1,19 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal.builder.multithreaded; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -27,7 +32,6 @@ import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleNotFoundException; import org.apache.maven.lifecycle.LifecyclePhaseNotFoundException; @@ -43,13 +47,10 @@ import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Kristian Rosenvold */ -public class ThreadOutputMuxerTest -{ +public class ThreadOutputMuxerTest { final String paid = "Paid"; @@ -58,111 +59,94 @@ public class ThreadOutputMuxerTest final String full = "Full"; @Test - public void testSingleThreaded() - throws Exception - { + public void testSingleThreaded() throws Exception { ProjectBuildList src = getProjectBuildList(); - ProjectBuildList projectBuildList = - new ProjectBuildList( Arrays.asList( src.get( 0 ), src.get( 1 ), src.get( 2 ) ) ); + ProjectBuildList projectBuildList = new ProjectBuildList(Arrays.asList(src.get(0), src.get(1), src.get(2))); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - PrintStream systemOut = new PrintStream( byteArrayOutputStream ); - ThreadOutputMuxer threadOutputMuxer = new ThreadOutputMuxer( projectBuildList, systemOut ); + PrintStream systemOut = new PrintStream(byteArrayOutputStream); + ThreadOutputMuxer threadOutputMuxer = new ThreadOutputMuxer(projectBuildList, systemOut); - threadOutputMuxer.associateThreadWithProjectSegment( projectBuildList.get( 0 ) ); - System.out.print( paid ); // No, this does not print to system.out. It's part of the test - assertEquals( paid.length(), byteArrayOutputStream.size() ); - threadOutputMuxer.associateThreadWithProjectSegment( projectBuildList.get( 1 ) ); - System.out.print( in ); // No, this does not print to system.out. It's part of the test - assertEquals( paid.length(), byteArrayOutputStream.size() ); - threadOutputMuxer.associateThreadWithProjectSegment( projectBuildList.get( 2 ) ); - System.out.print( full ); // No, this does not print to system.out. It's part of the test - assertEquals( paid.length(), byteArrayOutputStream.size() ); + threadOutputMuxer.associateThreadWithProjectSegment(projectBuildList.get(0)); + System.out.print(paid); // No, this does not print to system.out. It's part of the test + assertEquals(paid.length(), byteArrayOutputStream.size()); + threadOutputMuxer.associateThreadWithProjectSegment(projectBuildList.get(1)); + System.out.print(in); // No, this does not print to system.out. It's part of the test + assertEquals(paid.length(), byteArrayOutputStream.size()); + threadOutputMuxer.associateThreadWithProjectSegment(projectBuildList.get(2)); + System.out.print(full); // No, this does not print to system.out. It's part of the test + assertEquals(paid.length(), byteArrayOutputStream.size()); - threadOutputMuxer.setThisModuleComplete( projectBuildList.get( 0 ) ); - threadOutputMuxer.setThisModuleComplete( projectBuildList.get( 1 ) ); - threadOutputMuxer.setThisModuleComplete( projectBuildList.get( 2 ) ); + threadOutputMuxer.setThisModuleComplete(projectBuildList.get(0)); + threadOutputMuxer.setThisModuleComplete(projectBuildList.get(1)); + threadOutputMuxer.setThisModuleComplete(projectBuildList.get(2)); threadOutputMuxer.close(); - assertEquals( ( paid + in + full ).length(), byteArrayOutputStream.size() ); + assertEquals((paid + in + full).length(), byteArrayOutputStream.size()); } @Test - public void testMultiThreaded() - throws Exception - { + public void testMultiThreaded() throws Exception { ProjectBuildList projectBuildList = getProjectBuildList(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - PrintStream systemOut = new PrintStream( byteArrayOutputStream ); - final ThreadOutputMuxer threadOutputMuxer = new ThreadOutputMuxer( projectBuildList, systemOut ); + PrintStream systemOut = new PrintStream(byteArrayOutputStream); + final ThreadOutputMuxer threadOutputMuxer = new ThreadOutputMuxer(projectBuildList, systemOut); - final List stringList = - Arrays.asList( "Thinkin", "of", "a", "master", "plan", "Cuz", "ain’t", "nuthin", "but", "sweat", "inside", - "my", "hand" ); + final List stringList = Arrays.asList( + "Thinkin", "of", "a", "master", "plan", "Cuz", "ain’t", "nuthin", "but", "sweat", "inside", "my", + "hand"); Iterator lyrics = stringList.iterator(); - ExecutorService executor = Executors.newFixedThreadPool( 10 ); - CompletionService service = new ExecutorCompletionService<>( executor ); + ExecutorService executor = Executors.newFixedThreadPool(10); + CompletionService service = new ExecutorCompletionService<>(executor); List> futures = new ArrayList<>(); - for ( ProjectSegment projectBuild : projectBuildList ) - { + for (ProjectSegment projectBuild : projectBuildList) { final Future buildFuture = - service.submit( new Outputter( threadOutputMuxer, projectBuild, lyrics.next() ) ); - futures.add( buildFuture ); + service.submit(new Outputter(threadOutputMuxer, projectBuild, lyrics.next())); + futures.add(buildFuture); } - for ( Future future : futures ) - { + for (Future future : futures) { future.get(); } int expectedLength = 0; - for ( int i = 0; i < projectBuildList.size(); i++ ) - { - expectedLength += stringList.get( i ).length(); + for (int i = 0; i < projectBuildList.size(); i++) { + expectedLength += stringList.get(i).length(); } threadOutputMuxer.close(); final byte[] bytes = byteArrayOutputStream.toByteArray(); - String result = new String( bytes ); - assertEquals( expectedLength, bytes.length, result ); - - + String result = new String(bytes); + assertEquals(expectedLength, bytes.length, result); } - class Outputter - implements Callable - { + class Outputter implements Callable { private final ThreadOutputMuxer threadOutputMuxer; private final ProjectSegment item; private final String response; - Outputter( ThreadOutputMuxer threadOutputMuxer, ProjectSegment item, String response ) - { + Outputter(ThreadOutputMuxer threadOutputMuxer, ProjectSegment item, String response) { this.threadOutputMuxer = threadOutputMuxer; this.item = item; this.response = response; } - public ProjectSegment call() - throws Exception - { - threadOutputMuxer.associateThreadWithProjectSegment( item ); - System.out.print( response ); - threadOutputMuxer.setThisModuleComplete( item ); + public ProjectSegment call() throws Exception { + threadOutputMuxer.associateThreadWithProjectSegment(item); + System.out.print(response); + threadOutputMuxer.setThisModuleComplete(item); return item; } } - private ProjectBuildList getProjectBuildList() - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { final MavenSession session = ProjectDependencyGraphStub.getMavenSession(); - return ProjectDependencyGraphStub.getProjectBuildList( session ); + return ProjectDependencyGraphStub.getProjectBuildList(session); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/BuildPluginManagerStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/BuildPluginManagerStub.java index cdb00fc02a..3d6d0fa298 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/BuildPluginManagerStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/BuildPluginManagerStub.java @@ -1,22 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.apache.maven.lifecycle.internal.stub; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - import java.util.List; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.BuildPluginManager; @@ -30,27 +32,21 @@ import org.eclipse.aether.repository.RemoteRepository; /** * @author Kristian Rosenvold */ -public class BuildPluginManagerStub - implements BuildPluginManager -{ +public class BuildPluginManagerStub implements BuildPluginManager { - public PluginDescriptor loadPlugin( Plugin plugin, List repositories, RepositorySystemSession session ) - { + public PluginDescriptor loadPlugin( + Plugin plugin, List repositories, RepositorySystemSession session) { return null; } - public MojoDescriptor getMojoDescriptor( Plugin plugin, String goal, List repositories, - RepositorySystemSession session ) - { - return MojoExecutorStub.createMojoDescriptor( plugin ); + public MojoDescriptor getMojoDescriptor( + Plugin plugin, String goal, List repositories, RepositorySystemSession session) { + return MojoExecutorStub.createMojoDescriptor(plugin); } - public ClassRealm getPluginRealm( MavenSession session, PluginDescriptor pluginDescriptor ) - { + public ClassRealm getPluginRealm(MavenSession session, PluginDescriptor pluginDescriptor) { return null; } - public void executeMojo( MavenSession session, MojoExecution execution ) - { - } + public void executeMojo(MavenSession session, MojoExecution execution) {} } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/CompletionServiceStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/CompletionServiceStub.java index 6c7acea85b..8e673f2519 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/CompletionServiceStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/CompletionServiceStub.java @@ -1,22 +1,23 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; -import org.apache.maven.lifecycle.internal.ProjectSegment; - import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -25,65 +26,51 @@ import java.util.concurrent.CompletionService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; +import org.apache.maven.lifecycle.internal.ProjectSegment; /** * @author Kristian Rosenvold */ -public class CompletionServiceStub - implements CompletionService -{ - List> projectBuildFutureTasks = - Collections.synchronizedList(new ArrayList<>() ); +public class CompletionServiceStub implements CompletionService { + List> projectBuildFutureTasks = Collections.synchronizedList(new ArrayList<>()); final boolean finishImmediately; - - public int size() - { + public int size() { return projectBuildFutureTasks.size(); } - public CompletionServiceStub( boolean finishImmediately ) - { + public CompletionServiceStub(boolean finishImmediately) { this.finishImmediately = finishImmediately; } - public Future submit( Callable task ) - { - FutureTask projectBuildFutureTask = new FutureTask<>( task ); - projectBuildFutureTasks.add( projectBuildFutureTask ); - if ( finishImmediately ) - { + public Future submit(Callable task) { + FutureTask projectBuildFutureTask = new FutureTask<>(task); + projectBuildFutureTasks.add(projectBuildFutureTask); + if (finishImmediately) { projectBuildFutureTask.run(); } return projectBuildFutureTask; } - public Future submit( Runnable task, ProjectSegment result ) - { - FutureTask projectBuildFutureTask = new FutureTask<>( task, result ); - projectBuildFutureTasks.add( projectBuildFutureTask ); - if ( finishImmediately ) - { + public Future submit(Runnable task, ProjectSegment result) { + FutureTask projectBuildFutureTask = new FutureTask<>(task, result); + projectBuildFutureTasks.add(projectBuildFutureTask); + if (finishImmediately) { projectBuildFutureTask.run(); } return projectBuildFutureTask; } - public Future take() - throws InterruptedException - { + public Future take() throws InterruptedException { return null; } - public Future poll() - { + public Future poll() { return null; } - public Future poll( long timeout, TimeUnit unit ) - throws InterruptedException - { + public Future poll(long timeout, TimeUnit unit) throws InterruptedException { return null; } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/DefaultLifecyclesStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/DefaultLifecyclesStub.java index 5d78a6bfa2..6b2d1ba269 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/DefaultLifecyclesStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/DefaultLifecyclesStub.java @@ -1,73 +1,75 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; -import org.apache.maven.lifecycle.DefaultLifecycles; -import org.apache.maven.lifecycle.Lifecycle; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import static org.apache.maven.lifecycle.internal.stub.LifecycleExecutionPlanCalculatorStub.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; - -import static org.apache.maven.lifecycle.internal.stub.LifecycleExecutionPlanCalculatorStub.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.apache.maven.lifecycle.DefaultLifecycles; +import org.apache.maven.lifecycle.Lifecycle; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; /** * @author Kristian Rosenvold */ +public class DefaultLifecyclesStub { + public static DefaultLifecycles createDefaultLifecycles() throws ComponentLookupException { -public class DefaultLifecyclesStub -{ - public static DefaultLifecycles createDefaultLifecycles() - throws ComponentLookupException - { - - List stubDefaultCycle = - Arrays.asList( VALIDATE.getPhase(), INITIALIZE.getPhase(), PROCESS_RESOURCES.getPhase(), COMPILE.getPhase(), - TEST.getPhase(), PROCESS_TEST_RESOURCES.getPhase(), PACKAGE.getPhase(), "BEER", - INSTALL.getPhase() ); + List stubDefaultCycle = Arrays.asList( + VALIDATE.getPhase(), + INITIALIZE.getPhase(), + PROCESS_RESOURCES.getPhase(), + COMPILE.getPhase(), + TEST.getPhase(), + PROCESS_TEST_RESOURCES.getPhase(), + PACKAGE.getPhase(), + "BEER", + INSTALL.getPhase()); // The two phases below are really for future expansion, some would say they lack a drink // The point being that they do not really have to match the "real" stuff, - List stubCleanCycle = Arrays.asList( PRE_CLEAN.getPhase(), CLEAN.getPhase(), POST_CLEAN.getPhase() ); + List stubCleanCycle = Arrays.asList(PRE_CLEAN.getPhase(), CLEAN.getPhase(), POST_CLEAN.getPhase()); List stubSiteCycle = - Arrays.asList( PRE_SITE.getPhase(), SITE.getPhase(), POST_SITE.getPhase(), SITE_DEPLOY.getPhase() ); + Arrays.asList(PRE_SITE.getPhase(), SITE.getPhase(), POST_SITE.getPhase(), SITE_DEPLOY.getPhase()); - List stubWrapperCycle = Arrays.asList( WRAPPER.getPhase() ); + List stubWrapperCycle = Arrays.asList(WRAPPER.getPhase()); - Iterator> lcs = Arrays.asList( stubDefaultCycle, stubCleanCycle, stubSiteCycle, stubWrapperCycle ).iterator(); + Iterator> lcs = Arrays.asList(stubDefaultCycle, stubCleanCycle, stubSiteCycle, stubWrapperCycle) + .iterator(); Map lifeCycles = new HashMap<>(); - for ( String s : DefaultLifecycles.STANDARD_LIFECYCLES ) - { - final Lifecycle lifecycle = new Lifecycle( s, lcs.next(), null ); - lifeCycles.put( s, lifecycle ); - + for (String s : DefaultLifecycles.STANDARD_LIFECYCLES) { + final Lifecycle lifecycle = new Lifecycle(s, lcs.next(), null); + lifeCycles.put(s, lifecycle); } - PlexusContainer mockedContainer = mock( PlexusContainer.class ); - when( mockedContainer.lookupMap( Lifecycle.class ) ).thenReturn( lifeCycles ); + PlexusContainer mockedContainer = mock(PlexusContainer.class); + when(mockedContainer.lookupMap(Lifecycle.class)).thenReturn(lifeCycles); - return new DefaultLifecycles( mockedContainer ); + return new DefaultLifecycles(mockedContainer); } - -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ExecutionEventCatapultStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ExecutionEventCatapultStub.java index e47ec611c0..70156b58c2 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ExecutionEventCatapultStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ExecutionEventCatapultStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.lifecycle.internal.stub; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,25 +16,19 @@ package org.apache.maven.lifecycle.internal.stub; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.lifecycle.internal.stub; -import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ExecutionEvent.Type; +import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.ExecutionEventCatapult; import org.apache.maven.plugin.MojoExecution; /** * @author Benjamin Bentmann */ -public class ExecutionEventCatapultStub - implements ExecutionEventCatapult -{ +public class ExecutionEventCatapultStub implements ExecutionEventCatapult { - public void fire( Type eventType, MavenSession session, MojoExecution mojoExecution ) - { - } - - public void fire( Type eventType, MavenSession session, MojoExecution mojoExecution, Exception exception ) - { - } + public void fire(Type eventType, MavenSession session, MojoExecution mojoExecution) {} + public void fire(Type eventType, MavenSession session, MojoExecution mojoExecution, Exception exception) {} } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifeCyclePluginAnalyzerStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifeCyclePluginAnalyzerStub.java index b067e244a9..72a3285e2f 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifeCyclePluginAnalyzerStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifeCyclePluginAnalyzerStub.java @@ -1,74 +1,67 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; -import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.PluginExecution; - import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; +import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; /** * @author Kristian Rosenvold */ -public class LifeCyclePluginAnalyzerStub - implements LifeCyclePluginAnalyzer -{ - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { +public class LifeCyclePluginAnalyzerStub implements LifeCyclePluginAnalyzer { + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { Set plugins; // NOTE: The upper-case packaging name is intentional, that's a special hinting mode used for certain tests - if ( "JAR".equals( packaging ) ) - { + if ("JAR".equals(packaging)) { plugins = new LinkedHashSet<>(); - plugins.add( newPlugin( "maven-compiler-plugin", "compile", "testCompile" ) ); - plugins.add( newPlugin( "maven-resources-plugin", "resources", "testResources" ) ); - plugins.add( newPlugin( "maven-surefire-plugin", "test" ) ); - plugins.add( newPlugin( "maven-jar-plugin", "jar" ) ); - plugins.add( newPlugin( "maven-install-plugin", "install" ) ); - plugins.add( newPlugin( "maven-deploy-plugin", "deploy" ) ); - } - else - { + plugins.add(newPlugin("maven-compiler-plugin", "compile", "testCompile")); + plugins.add(newPlugin("maven-resources-plugin", "resources", "testResources")); + plugins.add(newPlugin("maven-surefire-plugin", "test")); + plugins.add(newPlugin("maven-jar-plugin", "jar")); + plugins.add(newPlugin("maven-install-plugin", "install")); + plugins.add(newPlugin("maven-deploy-plugin", "deploy")); + } else { plugins = Collections.emptySet(); } return plugins; } - private Plugin newPlugin( String artifactId, String... goals ) - { + private Plugin newPlugin(String artifactId, String... goals) { Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.plugins" ); - plugin.setArtifactId( artifactId ); + plugin.setGroupId("org.apache.maven.plugins"); + plugin.setArtifactId(artifactId); - for ( String goal : goals ) - { + for (String goal : goals) { PluginExecution pluginExecution = new PluginExecution(); - pluginExecution.setId( "default-" + goal ); - pluginExecution.addGoal( goal ); - plugin.addExecution( pluginExecution ); + pluginExecution.setId("default-" + goal); + pluginExecution.addGoal(goal); + plugin.addExecution(pluginExecution); } return plugin; } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleExecutionPlanCalculatorStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleExecutionPlanCalculatorStub.java index 76fe0122e8..12e40529a9 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleExecutionPlanCalculatorStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleExecutionPlanCalculatorStub.java @@ -1,20 +1,28 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.apache.maven.execution.MavenSession; import org.apache.maven.internal.xml.Xpp3Dom; import org.apache.maven.lifecycle.DefaultLifecycles; @@ -42,227 +50,200 @@ import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - /** * @author Kristian Rosenvold */ -public class LifecycleExecutionPlanCalculatorStub - implements LifecycleExecutionPlanCalculator -{ +public class LifecycleExecutionPlanCalculatorStub implements LifecycleExecutionPlanCalculator { // clean - public final static MojoDescriptor PRE_CLEAN = createMojoDescriptor( "pre-clean" ); + public static final MojoDescriptor PRE_CLEAN = createMojoDescriptor("pre-clean"); - public final static MojoDescriptor CLEAN = createMojoDescriptor( "clean" ); + public static final MojoDescriptor CLEAN = createMojoDescriptor("clean"); - public final static MojoDescriptor POST_CLEAN = createMojoDescriptor( "post-clean" ); + public static final MojoDescriptor POST_CLEAN = createMojoDescriptor("post-clean"); // default (or at least some of them) - public final static MojoDescriptor VALIDATE = createMojoDescriptor( "validate" ); + public static final MojoDescriptor VALIDATE = createMojoDescriptor("validate"); - public final static MojoDescriptor INITIALIZE = createMojoDescriptor( "initialize" ); + public static final MojoDescriptor INITIALIZE = createMojoDescriptor("initialize"); - public final static MojoDescriptor TEST_COMPILE = createMojoDescriptor( "test-compile" ); + public static final MojoDescriptor TEST_COMPILE = createMojoDescriptor("test-compile"); - public final static MojoDescriptor PROCESS_TEST_RESOURCES = createMojoDescriptor( "process-test-resources" ); + public static final MojoDescriptor PROCESS_TEST_RESOURCES = createMojoDescriptor("process-test-resources"); - public final static MojoDescriptor PROCESS_RESOURCES = createMojoDescriptor( "process-resources" ); + public static final MojoDescriptor PROCESS_RESOURCES = createMojoDescriptor("process-resources"); - public final static MojoDescriptor COMPILE = createMojoDescriptor( "compile", true ); + public static final MojoDescriptor COMPILE = createMojoDescriptor("compile", true); - public final static MojoDescriptor TEST = createMojoDescriptor( "test" ); + public static final MojoDescriptor TEST = createMojoDescriptor("test"); - public final static MojoDescriptor PACKAGE = createMojoDescriptor( "package" ); + public static final MojoDescriptor PACKAGE = createMojoDescriptor("package"); - public final static MojoDescriptor INSTALL = createMojoDescriptor( "install" ); + public static final MojoDescriptor INSTALL = createMojoDescriptor("install"); // site - public final static MojoDescriptor PRE_SITE = createMojoDescriptor( "pre-site" ); + public static final MojoDescriptor PRE_SITE = createMojoDescriptor("pre-site"); - public final static MojoDescriptor SITE = createMojoDescriptor( "site" ); + public static final MojoDescriptor SITE = createMojoDescriptor("site"); - public final static MojoDescriptor POST_SITE = createMojoDescriptor( "post-site" ); + public static final MojoDescriptor POST_SITE = createMojoDescriptor("post-site"); - public final static MojoDescriptor SITE_DEPLOY = createMojoDescriptor( "site-deploy" ); + public static final MojoDescriptor SITE_DEPLOY = createMojoDescriptor("site-deploy"); // wrapper - public final static MojoDescriptor WRAPPER = createMojoDescriptor( "wrapper" ); + public static final MojoDescriptor WRAPPER = createMojoDescriptor("wrapper"); /** * @deprecated instead use {@link #getNumberOfExecutions(ProjectBuildList)} */ @Deprecated - public int getNumberOfExceutions( ProjectBuildList projectBuildList ) - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + public int getNumberOfExceutions(ProjectBuildList projectBuildList) + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { int result = 0; - for ( ProjectSegment projectBuild : projectBuildList ) - { - MavenExecutionPlan plan = calculateExecutionPlan( projectBuild.getSession(), projectBuild.getProject(), - projectBuild.getTaskSegment().getTasks() ); + for (ProjectSegment projectBuild : projectBuildList) { + MavenExecutionPlan plan = calculateExecutionPlan( + projectBuild.getSession(), + projectBuild.getProject(), + projectBuild.getTaskSegment().getTasks()); result += plan.size(); } return result; } - public int getNumberOfExecutions( ProjectBuildList projectBuildList ) - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { - return getNumberOfExceutions( projectBuildList ); + public int getNumberOfExecutions(ProjectBuildList projectBuildList) + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { + return getNumberOfExceutions(projectBuildList); } - public void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { + public void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) + throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, + PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException { // Maybe do something ? } - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List tasks, - boolean setup ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException - { - if ( project.equals( ProjectDependencyGraphStub.A ) ) - { + public MavenExecutionPlan calculateExecutionPlan( + MavenSession session, MavenProject project, List tasks, boolean setup) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException { + if (project.equals(ProjectDependencyGraphStub.A)) { return getProjectAExecutionPlan(); } - if ( project.equals( ProjectDependencyGraphStub.B ) ) - { + if (project.equals(ProjectDependencyGraphStub.B)) { return getProjectBExecutionPlan(); } // The remaining are basically "for future expansion" List me = new ArrayList<>(); - me.add( createMojoExecution( "resources", "default-resources", PROCESS_RESOURCES ) ); - me.add( createMojoExecution( "compile", "default-compile", COMPILE ) ); - return createExecutionPlan( project, me ); + me.add(createMojoExecution("resources", "default-resources", PROCESS_RESOURCES)); + me.add(createMojoExecution("compile", "default-compile", COMPILE)); + return createExecutionPlan(project, me); } - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List tasks ) - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException - { - return calculateExecutionPlan( session, project, tasks, true ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, MavenProject project, List tasks) + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException { + return calculateExecutionPlan(session, project, tasks, true); } - public void setupMojoExecution( MavenSession session, MavenProject project, MojoExecution mojoExecution, Set alreadyForkedExecutions ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException - { - } + public void setupMojoExecution( + MavenSession session, + MavenProject project, + MojoExecution mojoExecution, + Set alreadyForkedExecutions) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, + LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException {} public static MavenExecutionPlan getProjectAExecutionPlan() - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException - { + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException { List me = new ArrayList<>(); - me.add( createMojoExecution( "initialize", "default-initialize", INITIALIZE ) ); - me.add( createMojoExecution( "resources", "default-resources", PROCESS_RESOURCES ) ); - me.add( createMojoExecution( "compile", "default-compile", COMPILE ) ); - me.add( createMojoExecution( "testResources", "default-testResources", PROCESS_TEST_RESOURCES ) ); - me.add( createMojoExecution( "testCompile", "default-testCompile", TEST_COMPILE ) ); - me.add( createMojoExecution( "test", "default-test", TEST ) ); - me.add( createMojoExecution( "war", "default-war", PACKAGE ) ); - me.add( createMojoExecution( "install", "default-install", INSTALL ) ); - return createExecutionPlan( ProjectDependencyGraphStub.A.getExecutionProject(), me ); + me.add(createMojoExecution("initialize", "default-initialize", INITIALIZE)); + me.add(createMojoExecution("resources", "default-resources", PROCESS_RESOURCES)); + me.add(createMojoExecution("compile", "default-compile", COMPILE)); + me.add(createMojoExecution("testResources", "default-testResources", PROCESS_TEST_RESOURCES)); + me.add(createMojoExecution("testCompile", "default-testCompile", TEST_COMPILE)); + me.add(createMojoExecution("test", "default-test", TEST)); + me.add(createMojoExecution("war", "default-war", PACKAGE)); + me.add(createMojoExecution("install", "default-install", INSTALL)); + return createExecutionPlan(ProjectDependencyGraphStub.A.getExecutionProject(), me); } public static MavenExecutionPlan getProjectBExecutionPlan() - throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, - PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, - NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException - { + throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, + PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, + NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException { List me = new ArrayList<>(); - me.add( createMojoExecution( "enforce", "enforce-versions", VALIDATE ) ); - me.add( createMojoExecution( "resources", "default-resources", PROCESS_RESOURCES ) ); - me.add( createMojoExecution( "compile", "default-compile", COMPILE ) ); - me.add( createMojoExecution( "testResources", "default-testResources", PROCESS_TEST_RESOURCES ) ); - me.add( createMojoExecution( "testCompile", "default-testCompile", TEST_COMPILE ) ); - me.add( createMojoExecution( "test", "default-test", TEST ) ); - return createExecutionPlan( ProjectDependencyGraphStub.B.getExecutionProject(), me ); + me.add(createMojoExecution("enforce", "enforce-versions", VALIDATE)); + me.add(createMojoExecution("resources", "default-resources", PROCESS_RESOURCES)); + me.add(createMojoExecution("compile", "default-compile", COMPILE)); + me.add(createMojoExecution("testResources", "default-testResources", PROCESS_TEST_RESOURCES)); + me.add(createMojoExecution("testCompile", "default-testCompile", TEST_COMPILE)); + me.add(createMojoExecution("test", "default-test", TEST)); + return createExecutionPlan(ProjectDependencyGraphStub.B.getExecutionProject(), me); } - - private static MavenExecutionPlan createExecutionPlan( MavenProject project, List mojoExecutions ) - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + private static MavenExecutionPlan createExecutionPlan(MavenProject project, List mojoExecutions) + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { final List planItemList = - ExecutionPlanItem.createExecutionPlanItems( project, mojoExecutions ); - return new MavenExecutionPlan( planItemList, getDefaultLifecycles()); + ExecutionPlanItem.createExecutionPlanItems(project, mojoExecutions); + return new MavenExecutionPlan(planItemList, getDefaultLifecycles()); } - private static DefaultLifecycles getDefaultLifecycles() - { - try - { + private static DefaultLifecycles getDefaultLifecycles() { + try { return DefaultLifecyclesStub.createDefaultLifecycles(); - } - catch ( ComponentLookupException e ) - { + } catch (ComponentLookupException e) { // ignore return null; } } - private static MojoExecution createMojoExecution( String goal, String executionId, MojoDescriptor mojoDescriptor ) - { + private static MojoExecution createMojoExecution(String goal, String executionId, MojoDescriptor mojoDescriptor) { InputSource defaultBindings = new InputSource(); - defaultBindings.setModelId( DefaultLifecyclePluginAnalyzer.DEFAULTLIFECYCLEBINDINGS_MODELID ); + defaultBindings.setModelId(DefaultLifecyclePluginAnalyzer.DEFAULTLIFECYCLEBINDINGS_MODELID); final Plugin plugin = mojoDescriptor.getPluginDescriptor().getPlugin(); - plugin.setLocation( "version", new InputLocation( 12, 34, defaultBindings ) ); - MojoExecution result = new MojoExecution( plugin, goal, executionId ); - result.setConfiguration( new Xpp3Dom( executionId + "-" + goal ) ); - result.setMojoDescriptor( mojoDescriptor ); - result.setLifecyclePhase( mojoDescriptor.getPhase() ); + plugin.setLocation("version", new InputLocation(12, 34, defaultBindings)); + MojoExecution result = new MojoExecution(plugin, goal, executionId); + result.setConfiguration(new Xpp3Dom(executionId + "-" + goal)); + result.setMojoDescriptor(mojoDescriptor); + result.setLifecyclePhase(mojoDescriptor.getPhase()); return result; - } - public static MojoDescriptor createMojoDescriptor( String phaseName ) - { - return createMojoDescriptor( phaseName, false ); + public static MojoDescriptor createMojoDescriptor(String phaseName) { + return createMojoDescriptor(phaseName, false); } - public static MojoDescriptor createMojoDescriptor( String phaseName, boolean threadSafe ) - { + public static MojoDescriptor createMojoDescriptor(String phaseName, boolean threadSafe) { final MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setPhase( phaseName ); + mojoDescriptor.setPhase(phaseName); final PluginDescriptor descriptor = new PluginDescriptor(); Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.test.MavenExecutionPlan" ); - plugin.setArtifactId( "stub-plugin-" + phaseName ); - descriptor.setPlugin( plugin ); - descriptor.setArtifactId( "artifact." + phaseName ); - mojoDescriptor.setPluginDescriptor( descriptor ); - mojoDescriptor.setThreadSafe( threadSafe ); + plugin.setGroupId("org.apache.maven.test.MavenExecutionPlan"); + plugin.setArtifactId("stub-plugin-" + phaseName); + descriptor.setPlugin(plugin); + descriptor.setArtifactId("artifact." + phaseName); + mojoDescriptor.setPluginDescriptor(descriptor); + mojoDescriptor.setThreadSafe(threadSafe); return mojoDescriptor; } - - public static Set getScopes() - { - return new HashSet<>( Arrays.asList( "compile" ) ); + public static Set getScopes() { + return new HashSet<>(Arrays.asList("compile")); } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleTaskSegmentCalculatorStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleTaskSegmentCalculatorStub.java index 6422235a46..1edcaa3190 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleTaskSegmentCalculatorStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/LifecycleTaskSegmentCalculatorStub.java @@ -1,24 +1,29 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; +import java.util.ArrayList; +import java.util.List; import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalculator; import org.apache.maven.lifecycle.internal.GoalTask; import org.apache.maven.lifecycle.internal.LifecycleTask; -import org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalculator; import org.apache.maven.lifecycle.internal.TaskSegment; import org.apache.maven.plugin.InvalidPluginDescriptorException; import org.apache.maven.plugin.MojoNotFoundException; @@ -28,66 +33,52 @@ import org.apache.maven.plugin.PluginResolutionException; import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; -import java.util.ArrayList; -import java.util.List; - /** * @author Kristian Rosenvold */ -public class LifecycleTaskSegmentCalculatorStub - extends DefaultLifecycleTaskSegmentCalculator -{ +public class LifecycleTaskSegmentCalculatorStub extends DefaultLifecycleTaskSegmentCalculator { public static final String clean = "clean"; public static final String aggr = "aggr"; public static final String install = "install"; - public LifecycleTaskSegmentCalculatorStub() - { - super( null, null ); + public LifecycleTaskSegmentCalculatorStub() { + super(null, null); } - public List calculateTaskSegments(MavenSession session, List tasks ) - throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, - MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, - PluginVersionResolutionException - { - List taskSegments = new ArrayList<>( tasks.size() ); + public List calculateTaskSegments(MavenSession session, List tasks) + throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, + MojoNotFoundException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, + PluginVersionResolutionException { + List taskSegments = new ArrayList<>(tasks.size()); TaskSegment currentSegment = null; - for ( String task : tasks ) - { - if ( aggr.equals( task ) ) - { + for (String task : tasks) { + if (aggr.equals(task)) { boolean aggregating = true; - if ( currentSegment == null || currentSegment.isAggregating() != aggregating ) - { - currentSegment = new TaskSegment( aggregating ); - taskSegments.add( currentSegment ); + if (currentSegment == null || currentSegment.isAggregating() != aggregating) { + currentSegment = new TaskSegment(aggregating); + taskSegments.add(currentSegment); } - currentSegment.getTasks().add( new GoalTask( task ) ); - } - else - { + currentSegment.getTasks().add(new GoalTask(task)); + } else { // lifecycle phase - if ( currentSegment == null || currentSegment.isAggregating() ) - { - currentSegment = new TaskSegment( false ); - taskSegments.add( currentSegment ); + if (currentSegment == null || currentSegment.isAggregating()) { + currentSegment = new TaskSegment(false); + taskSegments.add(currentSegment); } - currentSegment.getTasks().add( new LifecycleTask( task ) ); + currentSegment.getTasks().add(new LifecycleTask(task)); } } return taskSegments; } - public boolean requiresProject( MavenSession session ) - { + public boolean requiresProject(MavenSession session) { return true; } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java index e716645927..2021785c13 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java @@ -1,54 +1,51 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import javax.inject.Provider; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleExecutionException; -import org.apache.maven.lifecycle.internal.DependencyContext; import org.apache.maven.lifecycle.internal.ExecutionEventCatapult; import org.apache.maven.lifecycle.internal.LifecycleDependencyResolver; import org.apache.maven.lifecycle.internal.MojoExecutor; import org.apache.maven.lifecycle.internal.ProjectIndex; +import org.apache.maven.model.Plugin; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MavenPluginManager; -import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojosExecutionStrategy; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.project.MavenProject; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - /** * @author Kristian Rosenvold */ -public class MojoExecutorStub - extends MojoExecutor -{ // This is being lazy instead of making interface +public class MojoExecutorStub extends MojoExecutor { // This is being lazy instead of making interface - public final List executions = Collections.synchronizedList(new ArrayList<>() ); + public final List executions = Collections.synchronizedList(new ArrayList<>()); - public MojoExecutorStub() - { - super( null, null, null, null, null ); + public MojoExecutorStub() { + super(null, null, null, null, null); } public MojoExecutorStub( @@ -56,35 +53,31 @@ public class MojoExecutorStub MavenPluginManager mavenPluginManager, LifecycleDependencyResolver lifeCycleDependencyResolver, ExecutionEventCatapult eventCatapult, - Provider mojosExecutionStrategy ) - { - super( pluginManager, mavenPluginManager, lifeCycleDependencyResolver, eventCatapult, mojosExecutionStrategy ); + Provider mojosExecutionStrategy) { + super(pluginManager, mavenPluginManager, lifeCycleDependencyResolver, eventCatapult, mojosExecutionStrategy); } @Override - public void execute( MavenSession session, List mojoExecutions, ProjectIndex projectIndex ) - throws LifecycleExecutionException - { - executions.addAll( mojoExecutions ); + public void execute(MavenSession session, List mojoExecutions, ProjectIndex projectIndex) + throws LifecycleExecutionException { + executions.addAll(mojoExecutions); } @Override - public List executeForkedExecutions( MojoExecution mojoExecution, MavenSession session, ProjectIndex projectIndex ) throws LifecycleExecutionException - { + public List executeForkedExecutions( + MojoExecution mojoExecution, MavenSession session, ProjectIndex projectIndex) + throws LifecycleExecutionException { return null; } - - public static MojoDescriptor createMojoDescriptor( Plugin plugin ) - { + public static MojoDescriptor createMojoDescriptor(Plugin plugin) { final PluginDescriptor descriptor = new PluginDescriptor(); - descriptor.setGroupId( plugin.getGroupId() ); - descriptor.setArtifactId( plugin.getArtifactId() ); - descriptor.setPlugin( plugin ); - descriptor.setVersion( plugin.getVersion() ); + descriptor.setGroupId(plugin.getGroupId()); + descriptor.setArtifactId(plugin.getArtifactId()); + descriptor.setPlugin(plugin); + descriptor.setVersion(plugin.getVersion()); final MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setPluginDescriptor( descriptor ); + mojoDescriptor.setPluginDescriptor(descriptor); return mojoDescriptor; } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginPrefixResolverStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginPrefixResolverStub.java index a4b54e9814..13bf0f855c 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginPrefixResolverStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginPrefixResolverStub.java @@ -1,18 +1,21 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; @@ -24,27 +27,18 @@ import org.eclipse.aether.repository.ArtifactRepository; /** * @author Kristian Rosenvold */ - -public class PluginPrefixResolverStub - implements PluginPrefixResolver -{ - public PluginPrefixResult resolve( PluginPrefixRequest request ) - throws NoPluginFoundForPrefixException - { - return new PluginPrefixResult() - { - public String getGroupId() - { +public class PluginPrefixResolverStub implements PluginPrefixResolver { + public PluginPrefixResult resolve(PluginPrefixRequest request) throws NoPluginFoundForPrefixException { + return new PluginPrefixResult() { + public String getGroupId() { return "com.foobar"; } - public String getArtifactId() - { + public String getArtifactId() { return "bazbaz"; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return null; } }; diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginVersionResolverStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginVersionResolverStub.java index c79658e8d7..6ce1e3dcbb 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginVersionResolverStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/PluginVersionResolverStub.java @@ -1,18 +1,21 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; import org.apache.maven.plugin.version.PluginVersionRequest; @@ -24,23 +27,15 @@ import org.eclipse.aether.repository.ArtifactRepository; /** * @author Kristian Rosenvold */ +public class PluginVersionResolverStub implements PluginVersionResolver { -public class PluginVersionResolverStub - implements PluginVersionResolver -{ - - public PluginVersionResult resolve( PluginVersionRequest request ) - throws PluginVersionResolutionException - { - return new PluginVersionResult() - { - public String getVersion() - { + public PluginVersionResult resolve(PluginVersionRequest request) throws PluginVersionResolutionException { + return new PluginVersionResult() { + public String getVersion() { return "0.42"; } - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return null; } }; diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependenciesResolverStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependenciesResolverStub.java index 8a557d554f..70e8393e9d 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependenciesResolverStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependenciesResolverStub.java @@ -1,20 +1,28 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.apache.maven.ProjectDependenciesResolver; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; @@ -28,82 +36,68 @@ import org.eclipse.aether.graph.DefaultDependencyNode; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - /** * @author Kristian Rosenvold */ public class ProjectDependenciesResolverStub - implements ProjectDependenciesResolver, org.apache.maven.project.ProjectDependenciesResolver -{ - public Set resolve( MavenProject project, Collection scopesToResolve, MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { + implements ProjectDependenciesResolver, org.apache.maven.project.ProjectDependenciesResolver { + public Set resolve(MavenProject project, Collection scopesToResolve, MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { return new HashSet<>(); } - public Set resolve( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { + public Set resolve( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { return new HashSet<>(); } - public Set resolve( Collection projects, Collection scopes, - MavenSession session ) - throws ArtifactResolutionException, ArtifactNotFoundException - { + public Set resolve( + Collection projects, Collection scopes, MavenSession session) + throws ArtifactResolutionException, ArtifactNotFoundException { return new HashSet<>(); } - public Set resolve( MavenProject project, Collection scopesToCollect, - Collection scopesToResolve, MavenSession session, - Set ignorableArtifacts ) - throws ArtifactResolutionException, ArtifactNotFoundException - { + public Set resolve( + MavenProject project, + Collection scopesToCollect, + Collection scopesToResolve, + MavenSession session, + Set ignorableArtifacts) + throws ArtifactResolutionException, ArtifactNotFoundException { return new HashSet<>(); } - public DependencyResolutionResult resolve( DependencyResolutionRequest request ) - throws DependencyResolutionException - { - return new DependencyResolutionResult() - { + public DependencyResolutionResult resolve(DependencyResolutionRequest request) + throws DependencyResolutionException { + return new DependencyResolutionResult() { - public List getUnresolvedDependencies() - { + public List getUnresolvedDependencies() { return Collections.emptyList(); } - public List getResolvedDependencies() - { + public List getResolvedDependencies() { return Collections.emptyList(); } - public List getResolutionErrors( Dependency dependency ) - { + public List getResolutionErrors(Dependency dependency) { return Collections.emptyList(); } - public DependencyNode getDependencyGraph() - { - return new DefaultDependencyNode( (Dependency) null ); + public DependencyNode getDependencyGraph() { + return new DefaultDependencyNode((Dependency) null); } - public List getDependencies() - { + public List getDependencies() { return Collections.emptyList(); } - public List getCollectionErrors() - { + public List getCollectionErrors() { return Collections.emptyList(); } }; } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStub.java index 961dc7ca8b..7650e017e4 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStub.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStub.java @@ -1,20 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.apache.maven.execution.AbstractExecutionListener; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.DefaultMavenExecutionResult; @@ -36,10 +42,6 @@ import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - /** * A stub dependency graph that is custom-made for testing concurrent build graph evaluations. *

    @@ -54,9 +56,7 @@ import java.util.List; * * @author Kristian Rosenvold */ -public class ProjectDependencyGraphStub - implements ProjectDependencyGraph -{ +public class ProjectDependencyGraphStub implements ProjectDependencyGraph { public static final MavenProject A = new MavenProject(); public static final MavenProject B = new MavenProject(); @@ -71,163 +71,139 @@ public class ProjectDependencyGraphStub public static final MavenProject UNKNOWN = new MavenProject(); - static - { - A.setArtifactId( "A" ); - B.setArtifactId( "B" ); - C.setArtifactId( "C" ); - X.setArtifactId( "X" ); - Y.setArtifactId( "Y" ); - Z.setArtifactId( "Z" ); + static { + A.setArtifactId("A"); + B.setArtifactId("B"); + C.setArtifactId("C"); + X.setArtifactId("X"); + Y.setArtifactId("Y"); + Z.setArtifactId("Z"); } // This should probably be moved to a separate stub - public static ProjectBuildList getProjectBuildList( MavenSession session ) - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { - final List list = getProjectBuilds( session ); - return new ProjectBuildList( list ); - + public static ProjectBuildList getProjectBuildList(MavenSession session) + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { + final List list = getProjectBuilds(session); + return new ProjectBuildList(list); } - public static List getProjectBuilds( MavenSession session ) - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, PluginNotFoundException, MojoNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + public static List getProjectBuilds(MavenSession session) + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, PluginNotFoundException, MojoNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { List projectBuilds = new ArrayList<>(); TaskSegment segment = createTaskSegment(); - projectBuilds.add( createProjectBuild( A, session, segment ) ); - projectBuilds.add( createProjectBuild( B, session, segment ) ); - projectBuilds.add( createProjectBuild( C, session, segment ) ); - projectBuilds.add( createProjectBuild( X, session, segment ) ); - projectBuilds.add( createProjectBuild( Y, session, segment ) ); - projectBuilds.add( createProjectBuild( Z, session, segment ) ); + projectBuilds.add(createProjectBuild(A, session, segment)); + projectBuilds.add(createProjectBuild(B, session, segment)); + projectBuilds.add(createProjectBuild(C, session, segment)); + projectBuilds.add(createProjectBuild(X, session, segment)); + projectBuilds.add(createProjectBuild(Y, session, segment)); + projectBuilds.add(createProjectBuild(Z, session, segment)); return projectBuilds; } - private static ProjectSegment createProjectBuild( MavenProject project, MavenSession session, - TaskSegment taskSegment ) - throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, - NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, PluginResolutionException, - LifecyclePhaseNotFoundException, LifecycleNotFoundException - { + private static ProjectSegment createProjectBuild( + MavenProject project, MavenSession session, TaskSegment taskSegment) + throws InvalidPluginDescriptorException, PluginVersionResolutionException, PluginDescriptorParsingException, + NoPluginFoundForPrefixException, MojoNotFoundException, PluginNotFoundException, + PluginResolutionException, LifecyclePhaseNotFoundException, LifecycleNotFoundException { final MavenSession session1 = session.clone(); - return new ProjectSegment( project, taskSegment, session1 ); + return new ProjectSegment(project, taskSegment, session1); } - - private static TaskSegment createTaskSegment() - { - TaskSegment result = new TaskSegment( false ); - result.getTasks().add( new GoalTask( "t1" ) ); - result.getTasks().add( new GoalTask( "t2" ) ); + private static TaskSegment createTaskSegment() { + TaskSegment result = new TaskSegment(false); + result.getTasks().add(new GoalTask("t1")); + result.getTasks().add(new GoalTask("t2")); return result; } - class Dependency - { + class Dependency { MavenProject dependant; MavenProject dependency; - Dependency( MavenProject dependant, MavenProject dependency ) - { + Dependency(MavenProject dependant, MavenProject dependency) { this.dependant = dependant; this.dependency = dependency; } - void addIfDownstream( MavenProject mavenProject, List result ) - { - if ( dependency == mavenProject ) - { - result.add( dependant ); + void addIfDownstream(MavenProject mavenProject, List result) { + if (dependency == mavenProject) { + result.add(dependant); } } - void addIfUpstreamOf( MavenProject mavenProject, List result ) - { - if ( dependant == mavenProject ) - { - result.add( dependency ); // All projects are the statics from this class + void addIfUpstreamOf(MavenProject mavenProject, List result) { + if (dependant == mavenProject) { + result.add(dependency); // All projects are the statics from this class } } } - private List getDependencies() - { + private List getDependencies() { List dependencies = new ArrayList<>(); - dependencies.add( new Dependency( B, A ) ); - dependencies.add( new Dependency( C, A ) ); - dependencies.add( new Dependency( X, B ) ); - dependencies.add( new Dependency( X, C ) ); - dependencies.add( new Dependency( Y, B ) ); - dependencies.add( new Dependency( Z, C ) ); + dependencies.add(new Dependency(B, A)); + dependencies.add(new Dependency(C, A)); + dependencies.add(new Dependency(X, B)); + dependencies.add(new Dependency(X, C)); + dependencies.add(new Dependency(Y, B)); + dependencies.add(new Dependency(Z, C)); return dependencies; } - public List getAllProjects() - { - return Arrays.asList( A, B, C, X, Y, Z, UNKNOWN ); + public List getAllProjects() { + return Arrays.asList(A, B, C, X, Y, Z, UNKNOWN); } - public List getSortedProjects() - { - return Arrays.asList( A, B, C, X, Y, Z ); // I'm not entirely sure about the order but this should do... + public List getSortedProjects() { + return Arrays.asList(A, B, C, X, Y, Z); // I'm not entirely sure about the order but this should do... } - public List getDownstreamProjects( MavenProject project, boolean transitive ) - { - if ( transitive ) - { - throw new RuntimeException( "Not implemented yet" ); + public List getDownstreamProjects(MavenProject project, boolean transitive) { + if (transitive) { + throw new RuntimeException("Not implemented yet"); } List result = new ArrayList<>(); - for ( Dependency dependency : getDependencies() ) - { - dependency.addIfDownstream( project, result ); + for (Dependency dependency : getDependencies()) { + dependency.addIfDownstream(project, result); } return result; } - public List getUpstreamProjects( MavenProject project, boolean transitive ) - { + public List getUpstreamProjects(MavenProject project, boolean transitive) { /* if ( transitive ) { throw new RuntimeException( "Not implemented yet" ); }*/ List result = new ArrayList<>(); final List dependencies = getDependencies(); - for ( Dependency dependency : dependencies ) - { - dependency.addIfUpstreamOf( project, result ); + for (Dependency dependency : dependencies) { + dependency.addIfUpstreamOf(project, result); } return result; } - public static MavenSession getMavenSession( MavenProject mavenProject ) - { + public static MavenSession getMavenSession(MavenProject mavenProject) { final MavenSession session = getMavenSession(); - session.setCurrentProject( mavenProject ); + session.setCurrentProject(mavenProject); return session; } - public static MavenSession getMavenSession() - { + public static MavenSession getMavenSession() { final DefaultMavenExecutionResult defaultMavenExecutionResult = new DefaultMavenExecutionResult(); MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest(); - mavenExecutionRequest.setExecutionListener( new AbstractExecutionListener() ); - mavenExecutionRequest.setGoals( Arrays.asList( "clean", "aggr", "install" ) ); - mavenExecutionRequest.setDegreeOfConcurrency( 1 ); - final MavenSession session = new MavenSession( null, null, mavenExecutionRequest, defaultMavenExecutionResult ); + mavenExecutionRequest.setExecutionListener(new AbstractExecutionListener()); + mavenExecutionRequest.setGoals(Arrays.asList("clean", "aggr", "install")); + mavenExecutionRequest.setDegreeOfConcurrency(1); + final MavenSession session = new MavenSession(null, null, mavenExecutionRequest, defaultMavenExecutionResult); final ProjectDependencyGraphStub dependencyGraphStub = new ProjectDependencyGraphStub(); - session.setProjectDependencyGraph( dependencyGraphStub ); - session.setProjects( dependencyGraphStub.getSortedProjects() ); + session.setProjectDependencyGraph(dependencyGraphStub); + session.setProjects(dependencyGraphStub.getSortedProjects()); return session; } - } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStubTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStubTest.java index 56283ad94f..4f7b3a56cf 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStubTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/ProjectDependencyGraphStubTest.java @@ -1,67 +1,63 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package org.apache.maven.lifecycle.internal.stub; -import java.util.List; - -import org.apache.maven.project.MavenProject; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; +import org.apache.maven.project.MavenProject; +import org.junit.jupiter.api.Test; + /** * Tests the stub. Yeah, I know. * * @author Kristian Rosenvold */ - -public class ProjectDependencyGraphStubTest -{ +public class ProjectDependencyGraphStubTest { ProjectDependencyGraphStub stub = new ProjectDependencyGraphStub(); @Test - public void testADependencies() - { - final List mavenProjects = stub.getUpstreamProjects( ProjectDependencyGraphStub.A, false ); - assertEquals( 0, mavenProjects.size() ); + public void testADependencies() { + final List mavenProjects = stub.getUpstreamProjects(ProjectDependencyGraphStub.A, false); + assertEquals(0, mavenProjects.size()); } @Test - public void testBDependencies() - { - final List bProjects = stub.getUpstreamProjects( ProjectDependencyGraphStub.B, false ); - assertEquals( 1, bProjects.size() ); - assertTrue( bProjects.contains( ProjectDependencyGraphStub.A ) ); + public void testBDependencies() { + final List bProjects = stub.getUpstreamProjects(ProjectDependencyGraphStub.B, false); + assertEquals(1, bProjects.size()); + assertTrue(bProjects.contains(ProjectDependencyGraphStub.A)); } @Test - public void testCDependencies() - { - final List cProjects = stub.getUpstreamProjects( ProjectDependencyGraphStub.C, false ); - assertEquals( 1, cProjects.size() ); - assertTrue( cProjects.contains( ProjectDependencyGraphStub.A ) ); + public void testCDependencies() { + final List cProjects = stub.getUpstreamProjects(ProjectDependencyGraphStub.C, false); + assertEquals(1, cProjects.size()); + assertTrue(cProjects.contains(ProjectDependencyGraphStub.A)); } @Test - public void testXDependencies() - { - final List cProjects = stub.getUpstreamProjects( ProjectDependencyGraphStub.X, false ); - assertEquals( 2, cProjects.size() ); - assertTrue( cProjects.contains( ProjectDependencyGraphStub.C ) ); - assertTrue( cProjects.contains( ProjectDependencyGraphStub.B ) ); + public void testXDependencies() { + final List cProjects = stub.getUpstreamProjects(ProjectDependencyGraphStub.X, false); + assertEquals(2, cProjects.size()); + assertTrue(cProjects.contains(ProjectDependencyGraphStub.C)); + assertTrue(cProjects.contains(ProjectDependencyGraphStub.B)); } } diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/mapping/LifecyclePhaseTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/mapping/LifecyclePhaseTest.java index 677915f92d..aae92d05e0 100644 --- a/maven-core/src/test/java/org/apache/maven/lifecycle/mapping/LifecyclePhaseTest.java +++ b/maven-core/src/test/java/org/apache/maven/lifecycle/mapping/LifecyclePhaseTest.java @@ -1,73 +1,72 @@ -package org.apache.maven.lifecycle.mapping; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ +package org.apache.maven.lifecycle.mapping; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; /** * @author atanasenko */ -public class LifecyclePhaseTest -{ +public class LifecyclePhaseTest { @Test - public void testToString() - { + public void testToString() { LifecyclePhase phase = new LifecyclePhase(); - assertEquals( "", phase.toString() ); + assertEquals("", phase.toString()); LifecycleMojo mojo1 = new LifecycleMojo(); - mojo1.setGoal( "jar:jar" ); - phase.setMojos( Arrays.asList( mojo1 ) ); - assertEquals( "jar:jar", phase.toString() ); + mojo1.setGoal("jar:jar"); + phase.setMojos(Arrays.asList(mojo1)); + assertEquals("jar:jar", phase.toString()); LifecycleMojo mojo2 = new LifecycleMojo(); - mojo2.setGoal( "war:war" ); - phase.setMojos( Arrays.asList( mojo1, mojo2 ) ); - assertEquals( "jar:jar,war:war", phase.toString() ); + mojo2.setGoal("war:war"); + phase.setMojos(Arrays.asList(mojo1, mojo2)); + assertEquals("jar:jar,war:war", phase.toString()); } @Test - public void testSet() - { + public void testSet() { LifecyclePhase phase = new LifecyclePhase(); - assertNull( phase.getMojos() ); + assertNull(phase.getMojos()); - phase.set( "" ); - assertNotNull( phase.getMojos() ); - assertEquals( 0, phase.getMojos().size() ); + phase.set(""); + assertNotNull(phase.getMojos()); + assertEquals(0, phase.getMojos().size()); - phase.set( "jar:jar, war:war" ); + phase.set("jar:jar, war:war"); List mojos = phase.getMojos(); - assertNotNull( mojos ); - assertEquals( 2, mojos.size() ); + assertNotNull(mojos); + assertEquals(2, mojos.size()); LifecycleMojo mojo1 = mojos.get(0); - assertNotNull( mojo1 ); - assertEquals( "jar:jar", mojo1.getGoal() ); + assertNotNull(mojo1); + assertEquals("jar:jar", mojo1.getGoal()); LifecycleMojo mojo2 = mojos.get(1); - assertNotNull( mojo2 ); - assertEquals( "war:war", mojo2.getGoal() ); + assertNotNull(mojo2); + assertEquals("war:war", mojo2.getGoal()); } } - diff --git a/maven-core/src/test/java/org/apache/maven/plugin/PluginManagerTest.java b/maven-core/src/test/java/org/apache/maven/plugin/PluginManagerTest.java index a688c76999..ab7de39baa 100644 --- a/maven-core/src/test/java/org/apache/maven/plugin/PluginManagerTest.java +++ b/maven-core/src/test/java/org/apache/maven/plugin/PluginManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,14 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.DefaultRepositoryRequest; @@ -34,69 +37,57 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; - -import javax.inject.Inject; - -public class PluginManagerTest - extends AbstractCoreMavenComponentTestCase -{ +public class PluginManagerTest extends AbstractCoreMavenComponentTestCase { @Inject private DefaultBuildPluginManager pluginManager; - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/plugin-manager"; } @Test - public void testPluginLoading() - throws Exception - { - MavenSession session = createMavenSession( null ); + public void testPluginLoading() throws Exception { + MavenSession session = createMavenSession(null); Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.its.plugins" ); - plugin.setArtifactId( "maven-it-plugin" ); - plugin.setVersion( "0.1" ); - PluginDescriptor pluginDescriptor = - pluginManager.loadPlugin( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); - assertNotNull( pluginDescriptor ); + plugin.setGroupId("org.apache.maven.its.plugins"); + plugin.setArtifactId("maven-it-plugin"); + plugin.setVersion("0.1"); + PluginDescriptor pluginDescriptor = pluginManager.loadPlugin( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); + assertNotNull(pluginDescriptor); } @Test - public void testMojoDescriptorRetrieval() - throws Exception - { - MavenSession session = createMavenSession( null ); + public void testMojoDescriptorRetrieval() throws Exception { + MavenSession session = createMavenSession(null); String goal = "it"; Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.its.plugins" ); - plugin.setArtifactId( "maven-it-plugin" ); - plugin.setVersion( "0.1" ); + plugin.setGroupId("org.apache.maven.its.plugins"); + plugin.setArtifactId("maven-it-plugin"); + plugin.setVersion("0.1"); - MojoDescriptor mojoDescriptor = - pluginManager.getMojoDescriptor( plugin, goal, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); - assertNotNull( mojoDescriptor ); - assertEquals( goal, mojoDescriptor.getGoal() ); + MojoDescriptor mojoDescriptor = pluginManager.getMojoDescriptor( + plugin, + goal, + session.getCurrentProject().getRemotePluginRepositories(), + session.getRepositorySession()); + assertNotNull(mojoDescriptor); + assertEquals(goal, mojoDescriptor.getGoal()); // igorf: plugin realm comes later // assertNotNull( mojoDescriptor.getRealm() ); PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); - assertNotNull( pluginDescriptor ); - assertEquals( "org.apache.maven.its.plugins", pluginDescriptor.getGroupId() ); - assertEquals( "maven-it-plugin", pluginDescriptor.getArtifactId() ); - assertEquals( "0.1", pluginDescriptor.getVersion() ); + assertNotNull(pluginDescriptor); + assertEquals("org.apache.maven.its.plugins", pluginDescriptor.getGroupId()); + assertEquals("maven-it-plugin", pluginDescriptor.getArtifactId()); + assertEquals("0.1", pluginDescriptor.getVersion()); } // ----------------------------------------------------------------------------------------------- // Tests which exercise the lifecycle executor when it is dealing with individual goals. // ----------------------------------------------------------------------------------------------- - //TODO These two tests display a lack of symmetry with respect to the input which is a free form string and the + // TODO These two tests display a lack of symmetry with respect to the input which is a free form string and the // mojo descriptor which comes back. All the free form parsing needs to be done somewhere else, this is // really the function of the CLI, and then the pre-processing of that output still needs to be fed into // a hinting process which helps flesh out the full specification of the plugin. The plugin manager should @@ -104,10 +95,8 @@ public class PluginManagerTest // the plugin manager provides. @Test - public void testRemoteResourcesPlugin() - throws Exception - { - //TODO turn an equivalent back on when the RR plugin is released. + public void testRemoteResourcesPlugin() throws Exception { + // TODO turn an equivalent back on when the RR plugin is released. /* @@ -132,10 +121,8 @@ public class PluginManagerTest */ } - //TODO this will be the basis of the customizable lifecycle execution so need to figure this out quickly. - public void testSurefirePlugin() - throws Exception - { + // TODO this will be the basis of the customizable lifecycle execution so need to figure this out quickly. + public void testSurefirePlugin() throws Exception { /* MavenSession session = createMavenSession( getProject( "project-with-inheritance" ) ); String goal = "test"; @@ -158,10 +145,7 @@ public class PluginManagerTest } @Test - public void testMojoConfigurationIsMergedCorrectly() - throws Exception - { - } + public void testMojoConfigurationIsMergedCorrectly() throws Exception {} /** * The case where the user wants to specify an alternate version of the underlying tool. Common case @@ -169,40 +153,28 @@ public class PluginManagerTest * to use a specific version. We need to make sure the version that they specify takes precedence. */ @Test - public void testMojoWhereInternallyStatedDependencyIsOverriddenByProject() - throws Exception - { - } + public void testMojoWhereInternallyStatedDependencyIsOverriddenByProject() throws Exception {} /** * The case where you have a plugin in the current build that you want to be used on projects in * the current build. */ @Test - public void testMojoThatIsPresentInTheCurrentBuild() - throws Exception - { - } + public void testMojoThatIsPresentInTheCurrentBuild() throws Exception {} /** * This is the case where the Mojo wants to execute on every project and then do something at the end * with the results of each project. */ @Test - public void testAggregatorMojo() - throws Exception - { - } + public void testAggregatorMojo() throws Exception {} /** * This is the case where a Mojo needs the lifecycle run to a certain phase before it can do * anything useful. */ @Test - public void testMojoThatRequiresExecutionToAGivenPhaseBeforeExecutingItself() - throws Exception - { - } + public void testMojoThatRequiresExecutionToAGivenPhaseBeforeExecutingItself() throws Exception {} // test that mojo which does not require dependency resolution trigger no downloading of dependencies @@ -211,111 +183,98 @@ public class PluginManagerTest // test a build where projects use different versions of the same plugin @Test - public void testThatPluginDependencyThatHasSystemScopeIsResolved() - throws Exception - { - MavenSession session = createMavenSession( getProject( "project-contributing-system-scope-plugin-dep" ) ); + public void testThatPluginDependencyThatHasSystemScopeIsResolved() throws Exception { + MavenSession session = createMavenSession(getProject("project-contributing-system-scope-plugin-dep")); MavenProject project = session.getCurrentProject(); - Plugin plugin = project.getPlugin( "org.apache.maven.its.plugins:maven-it-plugin" ); + Plugin plugin = project.getPlugin("org.apache.maven.its.plugins:maven-it-plugin"); RepositoryRequest repositoryRequest = new DefaultRepositoryRequest(); - repositoryRequest.setLocalRepository( getLocalRepository() ); - repositoryRequest.setRemoteRepositories( getPluginArtifactRepositories() ); + repositoryRequest.setLocalRepository(getLocalRepository()); + repositoryRequest.setRemoteRepositories(getPluginArtifactRepositories()); - PluginDescriptor pluginDescriptor = - pluginManager.loadPlugin( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); - pluginManager.getPluginRealm( session, pluginDescriptor ); + PluginDescriptor pluginDescriptor = pluginManager.loadPlugin( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); + pluginManager.getPluginRealm(session, pluginDescriptor); List artifacts = pluginDescriptor.getArtifacts(); - for ( Artifact a : artifacts ) - { - if ( a.getGroupId().equals( "org.apache.maven.its.mng3586" ) && a.getArtifactId().equals( "tools" ) ) - { + for (Artifact a : artifacts) { + if (a.getGroupId().equals("org.apache.maven.its.mng3586") + && a.getArtifactId().equals("tools")) { // The system scoped dependencies will be present in the classloader for the plugin return; } } - fail( "Can't find the system scoped dependency in the plugin artifacts." ); + fail("Can't find the system scoped dependency in the plugin artifacts."); } // ----------------------------------------------------------------------------------------------- // Testing help // ----------------------------------------------------------------------------------------------- - protected void assertPluginDescriptor( MojoDescriptor mojoDescriptor, String groupId, String artifactId, String version ) - { - assertNotNull( mojoDescriptor ); + protected void assertPluginDescriptor( + MojoDescriptor mojoDescriptor, String groupId, String artifactId, String version) { + assertNotNull(mojoDescriptor); PluginDescriptor pd = mojoDescriptor.getPluginDescriptor(); - assertNotNull( pd ); - assertEquals( groupId, pd.getGroupId() ); - assertEquals( artifactId, pd.getArtifactId() ); - assertEquals( version, pd.getVersion() ); + assertNotNull(pd); + assertEquals(groupId, pd.getGroupId()); + assertEquals(artifactId, pd.getArtifactId()); + assertEquals(version, pd.getVersion()); } @Test - public void testPluginRealmCache() - throws Exception - { + public void testPluginRealmCache() throws Exception { RepositoryRequest repositoryRequest = new DefaultRepositoryRequest(); - repositoryRequest.setLocalRepository( getLocalRepository() ); - repositoryRequest.setRemoteRepositories( getPluginArtifactRepositories() ); + repositoryRequest.setLocalRepository(getLocalRepository()); + repositoryRequest.setRemoteRepositories(getPluginArtifactRepositories()); // prime realm cache - MavenSession session = createMavenSession( getProject( "project-contributing-system-scope-plugin-dep" ) ); + MavenSession session = createMavenSession(getProject("project-contributing-system-scope-plugin-dep")); MavenProject project = session.getCurrentProject(); - Plugin plugin = project.getPlugin( "org.apache.maven.its.plugins:maven-it-plugin" ); + Plugin plugin = project.getPlugin("org.apache.maven.its.plugins:maven-it-plugin"); - PluginDescriptor pluginDescriptor = - pluginManager.loadPlugin( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); - pluginManager.getPluginRealm( session, pluginDescriptor ); + PluginDescriptor pluginDescriptor = pluginManager.loadPlugin( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); + pluginManager.getPluginRealm(session, pluginDescriptor); - assertEquals( 1, pluginDescriptor.getDependencies().size() ); + assertEquals(1, pluginDescriptor.getDependencies().size()); - for ( ComponentDescriptor descriptor : pluginDescriptor.getComponents() ) - { - assertNotNull( descriptor.getRealm() ); - assertNotNull( descriptor.getImplementationClass() ); + for (ComponentDescriptor descriptor : pluginDescriptor.getComponents()) { + assertNotNull(descriptor.getRealm()); + assertNotNull(descriptor.getImplementationClass()); } // reload plugin realm from cache - session = createMavenSession( getProject( "project-contributing-system-scope-plugin-dep" ) ); + session = createMavenSession(getProject("project-contributing-system-scope-plugin-dep")); project = session.getCurrentProject(); - plugin = project.getPlugin( "org.apache.maven.its.plugins:maven-it-plugin" ); + plugin = project.getPlugin("org.apache.maven.its.plugins:maven-it-plugin"); - pluginDescriptor = - pluginManager.loadPlugin( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); - pluginManager.getPluginRealm( session, pluginDescriptor ); + pluginDescriptor = pluginManager.loadPlugin( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); + pluginManager.getPluginRealm(session, pluginDescriptor); - assertEquals( 1, pluginDescriptor.getDependencies().size() ); + assertEquals(1, pluginDescriptor.getDependencies().size()); - for ( ComponentDescriptor descriptor : pluginDescriptor.getComponents() ) - { - assertNotNull( descriptor.getRealm() ); - assertNotNull( descriptor.getImplementationClass() ); + for (ComponentDescriptor descriptor : pluginDescriptor.getComponents()) { + assertNotNull(descriptor.getRealm()); + assertNotNull(descriptor.getImplementationClass()); } } @Test - public void testBuildExtensionsPluginLoading() - throws Exception - { + public void testBuildExtensionsPluginLoading() throws Exception { RepositoryRequest repositoryRequest = new DefaultRepositoryRequest(); - repositoryRequest.setLocalRepository( getLocalRepository() ); - repositoryRequest.setRemoteRepositories( getPluginArtifactRepositories() ); + repositoryRequest.setLocalRepository(getLocalRepository()); + repositoryRequest.setRemoteRepositories(getPluginArtifactRepositories()); // prime realm cache - MavenSession session = createMavenSession( getProject( "project-with-build-extensions-plugin" ) ); + MavenSession session = createMavenSession(getProject("project-with-build-extensions-plugin")); MavenProject project = session.getCurrentProject(); - Plugin plugin = project.getPlugin( "org.apache.maven.its.plugins:maven-it-plugin" ); + Plugin plugin = project.getPlugin("org.apache.maven.its.plugins:maven-it-plugin"); - PluginDescriptor pluginDescriptor = - pluginManager.loadPlugin( plugin, session.getCurrentProject().getRemotePluginRepositories(), - session.getRepositorySession() ); - ClassRealm pluginRealm = pluginManager.getPluginRealm( session, pluginDescriptor ); + PluginDescriptor pluginDescriptor = pluginManager.loadPlugin( + plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession()); + ClassRealm pluginRealm = pluginManager.getPluginRealm(session, pluginDescriptor); assertEquals(pluginRealm, pluginDescriptor.getComponents().get(0).getRealm()); } diff --git a/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExceptionTest.java b/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExceptionTest.java index d2702938ee..f924e51043 100644 --- a/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExceptionTest.java +++ b/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,152 +16,154 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; - import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * MNG-3131 * * @author Robert Scholte * */ -public class PluginParameterExceptionTest -{ +public class PluginParameterExceptionTest { private final String LS = System.lineSeparator(); @Test - public void testMissingRequiredStringArrayTypeParameter() - { + public void testMissingRequiredStringArrayTypeParameter() { MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setGoal( "goal" ); + mojoDescriptor.setGoal("goal"); PluginDescriptor pluginDescriptor = new PluginDescriptor(); - pluginDescriptor.setGoalPrefix( "goalPrefix" ); - pluginDescriptor.setArtifactId( "artifactId" ); - mojoDescriptor.setPluginDescriptor( pluginDescriptor ); + pluginDescriptor.setGoalPrefix("goalPrefix"); + pluginDescriptor.setArtifactId("artifactId"); + mojoDescriptor.setPluginDescriptor(pluginDescriptor); Parameter parameter = new Parameter(); - parameter.setType( "java.lang.String[]" ); - parameter.setName( "toAddresses" ); + parameter.setType("java.lang.String[]"); + parameter.setName("toAddresses"); - parameter.setRequired( true ); + parameter.setRequired(true); PluginParameterException exception = - new PluginParameterException( mojoDescriptor, Collections.singletonList( parameter ) ); + new PluginParameterException(mojoDescriptor, Collections.singletonList(parameter)); - assertEquals( "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + - LS + LS + - "[0] Inside the definition for plugin 'artifactId', specify the following:" + - LS + LS + - "" + LS + - " ..." + LS + - " " + LS + - " VALUE" + LS + - " " + LS + - "." + LS, exception.buildDiagnosticMessage() ); + assertEquals( + "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + LS + + LS + "[0] Inside the definition for plugin 'artifactId', specify the following:" + + LS + + LS + "" + + LS + " ..." + + LS + " " + + LS + " VALUE" + + LS + " " + + LS + "." + + LS, + exception.buildDiagnosticMessage()); } @Test - public void testMissingRequiredCollectionTypeParameter() - { + public void testMissingRequiredCollectionTypeParameter() { MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setGoal( "goal" ); + mojoDescriptor.setGoal("goal"); PluginDescriptor pluginDescriptor = new PluginDescriptor(); - pluginDescriptor.setGoalPrefix( "goalPrefix" ); - pluginDescriptor.setArtifactId( "artifactId" ); - mojoDescriptor.setPluginDescriptor( pluginDescriptor ); + pluginDescriptor.setGoalPrefix("goalPrefix"); + pluginDescriptor.setArtifactId("artifactId"); + mojoDescriptor.setPluginDescriptor(pluginDescriptor); Parameter parameter = new Parameter(); - parameter.setType( "java.util.List" ); - parameter.setName( "toAddresses" ); + parameter.setType("java.util.List"); + parameter.setName("toAddresses"); - parameter.setRequired( true ); + parameter.setRequired(true); PluginParameterException exception = - new PluginParameterException( mojoDescriptor, Collections.singletonList( parameter ) ); + new PluginParameterException(mojoDescriptor, Collections.singletonList(parameter)); - assertEquals( "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + - LS + LS + - "[0] Inside the definition for plugin 'artifactId', specify the following:" + - LS + LS + - "" + LS + - " ..." + LS + - " " + LS + - " VALUE" + LS + - " " + LS + - "." + LS, exception.buildDiagnosticMessage() ); + assertEquals( + "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + LS + + LS + "[0] Inside the definition for plugin 'artifactId', specify the following:" + + LS + + LS + "" + + LS + " ..." + + LS + " " + + LS + " VALUE" + + LS + " " + + LS + "." + + LS, + exception.buildDiagnosticMessage()); } @Test - public void testMissingRequiredMapTypeParameter() - { + public void testMissingRequiredMapTypeParameter() { MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setGoal( "goal" ); + mojoDescriptor.setGoal("goal"); PluginDescriptor pluginDescriptor = new PluginDescriptor(); - pluginDescriptor.setGoalPrefix( "goalPrefix" ); - pluginDescriptor.setArtifactId( "artifactId" ); - mojoDescriptor.setPluginDescriptor( pluginDescriptor ); + pluginDescriptor.setGoalPrefix("goalPrefix"); + pluginDescriptor.setArtifactId("artifactId"); + mojoDescriptor.setPluginDescriptor(pluginDescriptor); Parameter parameter = new Parameter(); - parameter.setType( "java.util.Map" ); - parameter.setName( "toAddresses" ); + parameter.setType("java.util.Map"); + parameter.setName("toAddresses"); - parameter.setRequired( true ); + parameter.setRequired(true); PluginParameterException exception = - new PluginParameterException( mojoDescriptor, Collections.singletonList( parameter ) ); + new PluginParameterException(mojoDescriptor, Collections.singletonList(parameter)); - assertEquals( "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + - LS + LS + - "[0] Inside the definition for plugin 'artifactId', specify the following:" + - LS + LS + - "" + LS + - " ..." + LS + - " " + LS + - " VALUE" + LS + - " " + LS + - "." + LS, exception.buildDiagnosticMessage() ); + assertEquals( + "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + LS + + LS + "[0] Inside the definition for plugin 'artifactId', specify the following:" + + LS + + LS + "" + + LS + " ..." + + LS + " " + + LS + " VALUE" + + LS + " " + + LS + "." + + LS, + exception.buildDiagnosticMessage()); } @Test - public void testMissingRequiredPropertiesTypeParameter() - { + public void testMissingRequiredPropertiesTypeParameter() { MojoDescriptor mojoDescriptor = new MojoDescriptor(); - mojoDescriptor.setGoal( "goal" ); + mojoDescriptor.setGoal("goal"); PluginDescriptor pluginDescriptor = new PluginDescriptor(); - pluginDescriptor.setGoalPrefix( "goalPrefix" ); - pluginDescriptor.setArtifactId( "artifactId" ); - mojoDescriptor.setPluginDescriptor( pluginDescriptor ); + pluginDescriptor.setGoalPrefix("goalPrefix"); + pluginDescriptor.setArtifactId("artifactId"); + mojoDescriptor.setPluginDescriptor(pluginDescriptor); Parameter parameter = new Parameter(); - parameter.setType( "java.util.Properties" ); - parameter.setName( "toAddresses" ); + parameter.setType("java.util.Properties"); + parameter.setName("toAddresses"); - parameter.setRequired( true ); + parameter.setRequired(true); PluginParameterException exception = - new PluginParameterException( mojoDescriptor, Collections.singletonList( parameter ) ); + new PluginParameterException(mojoDescriptor, Collections.singletonList(parameter)); - assertEquals( "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + - LS + LS + - "[0] Inside the definition for plugin 'artifactId', specify the following:" + - LS + LS + - "" + LS + - " ..." + LS + - " " + LS + - " " + LS + - " KEY" + LS + - " VALUE" + LS + - " " + LS + - " " + LS + - "." + LS, exception.buildDiagnosticMessage() ); + assertEquals( + "One or more required plugin parameters are invalid/missing for 'goalPrefix:goal'" + LS + + LS + "[0] Inside the definition for plugin 'artifactId', specify the following:" + + LS + + LS + "" + + LS + " ..." + + LS + " " + + LS + " " + + LS + " KEY" + + LS + " VALUE" + + LS + " " + + LS + " " + + LS + "." + + LS, + exception.buildDiagnosticMessage()); } - } diff --git a/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorTest.java b/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorTest.java index 16deedd337..4e5ef62fc3 100644 --- a/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorTest.java +++ b/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.plugin; * "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 + * 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 @@ -18,6 +16,13 @@ package org.apache.maven.plugin; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin; + +import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.util.ArrayList; @@ -25,7 +30,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; - +import javax.inject.Inject; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; @@ -48,411 +53,361 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator import org.codehaus.plexus.util.dag.CycleDetectedException; import org.junit.jupiter.api.Test; -import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javax.inject.Inject; - /** * @author Jason van Zyl */ -public class PluginParameterExpressionEvaluatorTest - extends AbstractCoreMavenComponentTestCase -{ +public class PluginParameterExpressionEvaluatorTest extends AbstractCoreMavenComponentTestCase { private static final String FS = File.separator; @Inject private RepositorySystem factory; @Test - public void testPluginDescriptorExpressionReference() - throws Exception - { + public void testPluginDescriptorExpressionReference() throws Exception { MojoExecution exec = newMojoExecution(); MavenSession session = newMavenSession(); - Object result = new PluginParameterExpressionEvaluator( session, exec ).evaluate( "${plugin}" ); + Object result = new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin}"); - System.out.println( "Result: " + result ); + System.out.println("Result: " + result); - assertSame( exec.getMojoDescriptor().getPluginDescriptor(), - result, - "${plugin} expression does not return plugin descriptor." ); + assertSame( + exec.getMojoDescriptor().getPluginDescriptor(), + result, + "${plugin} expression does not return plugin descriptor."); } @Test - public void testPluginArtifactsExpressionReference() - throws Exception - { + public void testPluginArtifactsExpressionReference() throws Exception { MojoExecution exec = newMojoExecution(); - Artifact depArtifact = createArtifact( "group", "artifact", "1" ); + Artifact depArtifact = createArtifact("group", "artifact", "1"); List deps = new ArrayList<>(); - deps.add( depArtifact ); + deps.add(depArtifact); - exec.getMojoDescriptor().getPluginDescriptor().setArtifacts( deps ); + exec.getMojoDescriptor().getPluginDescriptor().setArtifacts(deps); MavenSession session = newMavenSession(); - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") List depResults = - (List) new PluginParameterExpressionEvaluator( session, exec ).evaluate( "${plugin.artifacts}" ); + (List) new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin.artifacts}"); - System.out.println( "Result: " + depResults ); + System.out.println("Result: " + depResults); - assertNotNull( depResults ); - assertEquals( 1, depResults.size() ); - assertSame( depArtifact, depResults.get( 0 ), "dependency artifact is wrong." ); + assertNotNull(depResults); + assertEquals(1, depResults.size()); + assertSame(depArtifact, depResults.get(0), "dependency artifact is wrong."); } @Test - public void testPluginArtifactMapExpressionReference() - throws Exception - { + public void testPluginArtifactMapExpressionReference() throws Exception { MojoExecution exec = newMojoExecution(); - Artifact depArtifact = createArtifact( "group", "artifact", "1" ); + Artifact depArtifact = createArtifact("group", "artifact", "1"); List deps = new ArrayList<>(); - deps.add( depArtifact ); + deps.add(depArtifact); - exec.getMojoDescriptor().getPluginDescriptor().setArtifacts( deps ); + exec.getMojoDescriptor().getPluginDescriptor().setArtifacts(deps); MavenSession session = newMavenSession(); - @SuppressWarnings( "unchecked" ) - Map depResults = - (Map) new PluginParameterExpressionEvaluator( session, exec ).evaluate( "${plugin.artifactMap}" ); + @SuppressWarnings("unchecked") + Map depResults = (Map) + new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin.artifactMap}"); - System.out.println( "Result: " + depResults ); + System.out.println("Result: " + depResults); - assertNotNull( depResults ); - assertEquals( 1, depResults.size() ); - assertSame( depArtifact, - depResults.get( ArtifactUtils.versionlessKey( depArtifact ) ), - "dependency artifact is wrong." ); + assertNotNull(depResults); + assertEquals(1, depResults.size()); + assertSame( + depArtifact, + depResults.get(ArtifactUtils.versionlessKey(depArtifact)), + "dependency artifact is wrong."); } @Test - public void testPluginArtifactIdExpressionReference() - throws Exception - { + public void testPluginArtifactIdExpressionReference() throws Exception { MojoExecution exec = newMojoExecution(); MavenSession session = newMavenSession(); - Object result = new PluginParameterExpressionEvaluator( session, exec ).evaluate( "${plugin.artifactId}" ); + Object result = new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin.artifactId}"); - System.out.println( "Result: " + result ); + System.out.println("Result: " + result); - assertSame( exec.getMojoDescriptor().getPluginDescriptor().getArtifactId(), - result, - "${plugin.artifactId} expression does not return plugin descriptor's artifactId." ); + assertSame( + exec.getMojoDescriptor().getPluginDescriptor().getArtifactId(), + result, + "${plugin.artifactId} expression does not return plugin descriptor's artifactId."); } @Test - public void testValueExtractionWithAPomValueContainingAPath() - throws Exception - { - String expected = getTestFile( "target/test-classes/target/classes" ).getCanonicalPath(); + public void testValueExtractionWithAPomValueContainingAPath() throws Exception { + String expected = getTestFile("target/test-classes/target/classes").getCanonicalPath(); Build build = new Build(); - build.setDirectory( expected.substring( 0, expected.length() - "/classes".length() ) ); + build.setDirectory(expected.substring(0, expected.length() - "/classes".length())); Model model = new Model(); - model.setBuild( build ); + model.setBuild(build); - MavenProject project = new MavenProject( model ); - project.setFile( new File( "pom.xml" ).getCanonicalFile() ); + MavenProject project = new MavenProject(model); + project.setFile(new File("pom.xml").getCanonicalFile()); - ExpressionEvaluator expressionEvaluator = createExpressionEvaluator( project, null, new Properties() ); + ExpressionEvaluator expressionEvaluator = createExpressionEvaluator(project, null, new Properties()); - Object value = expressionEvaluator.evaluate( "${project.build.directory}/classes" ); - String actual = new File( value.toString() ).getCanonicalPath(); + Object value = expressionEvaluator.evaluate("${project.build.directory}/classes"); + String actual = new File(value.toString()).getCanonicalPath(); - assertEquals( expected, actual ); + assertEquals(expected, actual); } @Test - public void testEscapedVariablePassthrough() - throws Exception - { + public void testEscapedVariablePassthrough() throws Exception { String var = "${var}"; Model model = new Model(); - model.setVersion( "1" ); + model.setVersion("1"); - MavenProject project = new MavenProject( model ); + MavenProject project = new MavenProject(model); - ExpressionEvaluator ee = createExpressionEvaluator( project, null, new Properties() ); + ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties()); - Object value = ee.evaluate( "$" + var ); + Object value = ee.evaluate("$" + var); - assertEquals( var, value ); + assertEquals(var, value); } @Test - public void testEscapedVariablePassthroughInLargerExpression() - throws Exception - { + public void testEscapedVariablePassthroughInLargerExpression() throws Exception { String var = "${var}"; String key = var + " with version: ${project.version}"; Model model = new Model(); - model.setVersion( "1" ); + model.setVersion("1"); - MavenProject project = new MavenProject( model ); + MavenProject project = new MavenProject(model); - ExpressionEvaluator ee = createExpressionEvaluator( project, null, new Properties() ); + ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties()); - Object value = ee.evaluate( "$" + key ); + Object value = ee.evaluate("$" + key); - assertEquals( "${var} with version: 1", value ); + assertEquals("${var} with version: 1", value); } @Test - public void testMultipleSubExpressionsInLargerExpression() - throws Exception - { + public void testMultipleSubExpressionsInLargerExpression() throws Exception { String key = "${project.artifactId} with version: ${project.version}"; Model model = new Model(); - model.setArtifactId( "test" ); - model.setVersion( "1" ); + model.setArtifactId("test"); + model.setVersion("1"); - MavenProject project = new MavenProject( model ); + MavenProject project = new MavenProject(model); - ExpressionEvaluator ee = createExpressionEvaluator( project, null, new Properties() ); + ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties()); - Object value = ee.evaluate( key ); + Object value = ee.evaluate(key); - assertEquals( "test with version: 1", value ); + assertEquals("test with version: 1", value); } @Test - public void testMissingPOMPropertyRefInLargerExpression() - throws Exception - { + public void testMissingPOMPropertyRefInLargerExpression() throws Exception { String expr = "/path/to/someproject-${baseVersion}"; - MavenProject project = new MavenProject( new Model() ); + MavenProject project = new MavenProject(new Model()); - ExpressionEvaluator ee = createExpressionEvaluator( project, null, new Properties() ); + ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties()); - Object value = ee.evaluate( expr ); + Object value = ee.evaluate(expr); - assertEquals( expr, value ); + assertEquals(expr, value); } @Test - public void testPOMPropertyExtractionWithMissingProject_WithDotNotation() - throws Exception - { + public void testPOMPropertyExtractionWithMissingProject_WithDotNotation() throws Exception { String key = "m2.name"; String checkValue = "value"; Properties properties = new Properties(); - properties.setProperty( key, checkValue ); + properties.setProperty(key, checkValue); Model model = new Model(); - model.setProperties( properties ); + model.setProperties(properties); - MavenProject project = new MavenProject( model ); + MavenProject project = new MavenProject(model); - ExpressionEvaluator ee = createExpressionEvaluator( project, null, new Properties() ); + ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties()); - Object value = ee.evaluate( "${" + key + "}" ); + Object value = ee.evaluate("${" + key + "}"); - assertEquals( checkValue, value ); + assertEquals(checkValue, value); } @Test - public void testBasedirExtractionWithMissingProject() - throws Exception - { - ExpressionEvaluator ee = createExpressionEvaluator( null, null, new Properties() ); + public void testBasedirExtractionWithMissingProject() throws Exception { + ExpressionEvaluator ee = createExpressionEvaluator(null, null, new Properties()); - Object value = ee.evaluate( "${basedir}" ); + Object value = ee.evaluate("${basedir}"); - assertEquals( System.getProperty( "user.dir" ), value ); + assertEquals(System.getProperty("user.dir"), value); } @Test - public void testValueExtractionFromSystemPropertiesWithMissingProject() - throws Exception - { + public void testValueExtractionFromSystemPropertiesWithMissingProject() throws Exception { String sysprop = "PPEET_sysprop1"; Properties executionProperties = new Properties(); - if ( executionProperties.getProperty( sysprop ) == null ) - { - executionProperties.setProperty( sysprop, "value" ); + if (executionProperties.getProperty(sysprop) == null) { + executionProperties.setProperty(sysprop, "value"); } - ExpressionEvaluator ee = createExpressionEvaluator( null, null, executionProperties ); + ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties); - Object value = ee.evaluate( "${" + sysprop + "}" ); + Object value = ee.evaluate("${" + sysprop + "}"); - assertEquals( "value", value ); + assertEquals("value", value); } @Test - public void testValueExtractionFromSystemPropertiesWithMissingProject_WithDotNotation() - throws Exception - { + public void testValueExtractionFromSystemPropertiesWithMissingProject_WithDotNotation() throws Exception { String sysprop = "PPEET.sysprop2"; Properties executionProperties = new Properties(); - if ( executionProperties.getProperty( sysprop ) == null ) - { - executionProperties.setProperty( sysprop, "value" ); + if (executionProperties.getProperty(sysprop) == null) { + executionProperties.setProperty(sysprop, "value"); } - ExpressionEvaluator ee = createExpressionEvaluator( null, null, executionProperties ); + ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties); - Object value = ee.evaluate( "${" + sysprop + "}" ); + Object value = ee.evaluate("${" + sysprop + "}"); - assertEquals( "value", value ); + assertEquals("value", value); } - @SuppressWarnings( "deprecation" ) - private static MavenSession createSession( PlexusContainer container, ArtifactRepository repo, Properties properties ) - throws CycleDetectedException, DuplicateProjectException - { + @SuppressWarnings("deprecation") + private static MavenSession createSession(PlexusContainer container, ArtifactRepository repo, Properties properties) + throws CycleDetectedException, DuplicateProjectException { MavenExecutionRequest request = new DefaultMavenExecutionRequest() - .setSystemProperties( properties ) - .setGoals( Collections.emptyList() ) - .setBaseDirectory( new File( "" ) ) - .setLocalRepository( repo ); + .setSystemProperties(properties) + .setGoals(Collections.emptyList()) + .setBaseDirectory(new File("")) + .setLocalRepository(repo); - return new MavenSession( container, request, new DefaultMavenExecutionResult(), Collections.emptyList() ); + return new MavenSession( + container, request, new DefaultMavenExecutionResult(), Collections.emptyList()); } @Test - public void testLocalRepositoryExtraction() - throws Exception - { + public void testLocalRepositoryExtraction() throws Exception { ExpressionEvaluator expressionEvaluator = - createExpressionEvaluator( createDefaultProject(), null, new Properties() ); - Object value = expressionEvaluator.evaluate( "${localRepository}" ); + createExpressionEvaluator(createDefaultProject(), null, new Properties()); + Object value = expressionEvaluator.evaluate("${localRepository}"); - assertEquals( "local", ( (ArtifactRepository) value ).getId() ); + assertEquals("local", ((ArtifactRepository) value).getId()); } @Test - public void testTwoExpressions() - throws Exception - { + public void testTwoExpressions() throws Exception { Build build = new Build(); - build.setDirectory( "expected-directory" ); - build.setFinalName( "expected-finalName" ); + build.setDirectory("expected-directory"); + build.setFinalName("expected-finalName"); Model model = new Model(); - model.setBuild( build ); + model.setBuild(build); ExpressionEvaluator expressionEvaluator = - createExpressionEvaluator( new MavenProject( model ), null, new Properties() ); + createExpressionEvaluator(new MavenProject(model), null, new Properties()); - Object value = expressionEvaluator.evaluate( "${project.build.directory}" + FS + "${project.build.finalName}" ); + Object value = expressionEvaluator.evaluate("${project.build.directory}" + FS + "${project.build.finalName}"); - assertEquals( "expected-directory" + File.separatorChar + "expected-finalName", value ); + assertEquals("expected-directory" + File.separatorChar + "expected-finalName", value); } @Test - public void testShouldExtractPluginArtifacts() - throws Exception - { + public void testShouldExtractPluginArtifacts() throws Exception { PluginDescriptor pd = new PluginDescriptor(); - Artifact artifact = createArtifact( "testGroup", "testArtifact", "1.0" ); + Artifact artifact = createArtifact("testGroup", "testArtifact", "1.0"); - pd.setArtifacts( Collections.singletonList( artifact ) ); + pd.setArtifacts(Collections.singletonList(artifact)); - ExpressionEvaluator ee = createExpressionEvaluator( createDefaultProject(), pd, new Properties() ); + ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), pd, new Properties()); - Object value = ee.evaluate( "${plugin.artifacts}" ); + Object value = ee.evaluate("${plugin.artifacts}"); - assertTrue( value instanceof List ); + assertTrue(value instanceof List); - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") List artifacts = (List) value; - assertEquals( 1, artifacts.size() ); + assertEquals(1, artifacts.size()); - Artifact result = artifacts.get( 0 ); + Artifact result = artifacts.get(0); - assertEquals( "testGroup", result.getGroupId() ); + assertEquals("testGroup", result.getGroupId()); } - private MavenProject createDefaultProject() - { - return new MavenProject( new Model() ); + private MavenProject createDefaultProject() { + return new MavenProject(new Model()); } - private ExpressionEvaluator createExpressionEvaluator( MavenProject project, PluginDescriptor pluginDescriptor, Properties executionProperties ) - throws Exception - { + private ExpressionEvaluator createExpressionEvaluator( + MavenProject project, PluginDescriptor pluginDescriptor, Properties executionProperties) throws Exception { ArtifactRepository repo = factory.createDefaultLocalRepository(); MutablePlexusContainer container = (MutablePlexusContainer) getContainer(); - MavenSession session = createSession( container, repo, executionProperties ); - session.setCurrentProject( project ); + MavenSession session = createSession(container, repo, executionProperties); + session.setCurrentProject(project); MojoDescriptor mojo = new MojoDescriptor(); - mojo.setPluginDescriptor( pluginDescriptor ); - mojo.setGoal( "goal" ); + mojo.setPluginDescriptor(pluginDescriptor); + mojo.setGoal("goal"); - MojoExecution mojoExecution = new MojoExecution( mojo ); + MojoExecution mojoExecution = new MojoExecution(mojo); - return new PluginParameterExpressionEvaluator( session, mojoExecution ); + return new PluginParameterExpressionEvaluator(session, mojoExecution); } - protected Artifact createArtifact( String groupId, String artifactId, String version ) - throws Exception - { + protected Artifact createArtifact(String groupId, String artifactId, String version) throws Exception { Dependency dependency = new Dependency(); - dependency.setGroupId( groupId ); - dependency.setArtifactId( artifactId ); - dependency.setVersion( version ); - dependency.setType( "jar" ); - dependency.setScope( "compile" ); + dependency.setGroupId(groupId); + dependency.setArtifactId(artifactId); + dependency.setVersion(version); + dependency.setType("jar"); + dependency.setScope("compile"); - return factory.createDependencyArtifact( dependency ); + return factory.createDependencyArtifact(dependency); } - private MojoExecution newMojoExecution() - { + private MojoExecution newMojoExecution() { PluginDescriptor pd = new PluginDescriptor(); - pd.setArtifactId( "my-plugin" ); - pd.setGroupId( "org.myco.plugins" ); - pd.setVersion( "1" ); + pd.setArtifactId("my-plugin"); + pd.setGroupId("org.myco.plugins"); + pd.setVersion("1"); MojoDescriptor md = new MojoDescriptor(); - md.setPluginDescriptor( pd ); + md.setPluginDescriptor(pd); - pd.addComponentDescriptor( md ); + pd.addComponentDescriptor(md); - return new MojoExecution( md ); + return new MojoExecution(md); } - private MavenSession newMavenSession() - throws Exception - { - return createMavenSession( null ); + private MavenSession newMavenSession() throws Exception { + return createMavenSession(null); } @Override - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { // TODO Auto-generated method stub return null; } - } diff --git a/maven-core/src/test/java/org/apache/maven/plugin/internal/DefaultLegacySupportTest.java b/maven-core/src/test/java/org/apache/maven/plugin/internal/DefaultLegacySupportTest.java index 4cf01cf87d..7b1327aba5 100644 --- a/maven-core/src/test/java/org/apache/maven/plugin/internal/DefaultLegacySupportTest.java +++ b/maven-core/src/test/java/org/apache/maven/plugin/internal/DefaultLegacySupportTest.java @@ -1,4 +1,3 @@ -package org.apache.maven.plugin.internal; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,7 +7,7 @@ package org.apache.maven.plugin.internal; * "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 + * 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 @@ -17,16 +16,16 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; + +import static org.junit.jupiter.api.Assertions.assertNull; import java.util.concurrent.CountDownLatch; - import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNull; - /** * @author Kristian Rosenvold */ @@ -49,21 +48,17 @@ public class DefaultLegacySupportTest { defaultLegacySupport.setSession(m2); latch.countDown(); thread.join(); - assertNull( myRunnable.getSession()); + assertNull(myRunnable.getSession()); } - class MyRunnable implements Runnable { private volatile MavenSession session; public void run() { - try - { + try { latch.await(); - } - catch (InterruptedException ignore) - { + } catch (InterruptedException ignore) { // Test may fail if we get interrupted } session = defaultLegacySupport.getSession(); @@ -73,5 +68,4 @@ public class DefaultLegacySupportTest { return session; } } - } diff --git a/maven-core/src/test/java/org/apache/maven/plugin/internal/MavenPluginValidatorTest.java b/maven-core/src/test/java/org/apache/maven/plugin/internal/MavenPluginValidatorTest.java index 872809647a..d3ffccbc01 100644 --- a/maven-core/src/test/java/org/apache/maven/plugin/internal/MavenPluginValidatorTest.java +++ b/maven-core/src/test/java/org/apache/maven/plugin/internal/MavenPluginValidatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,88 +16,104 @@ package org.apache.maven.plugin.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.internal; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; - +import javax.inject.Inject; import org.apache.maven.AbstractCoreMavenComponentTestCase; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.plugin.internal.MavenPluginValidator; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import javax.inject.Inject; - /** * @author Michael Simacek */ -public class MavenPluginValidatorTest extends AbstractCoreMavenComponentTestCase -{ +public class MavenPluginValidatorTest extends AbstractCoreMavenComponentTestCase { @Inject private MavenPluginValidator mavenPluginValidator; - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/default-maven"; } @Test - public void testValidate() - { - Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", - "jar", null, new DefaultArtifactHandler( "ignore" ) ); + public void testValidate() { + Artifact plugin = new DefaultArtifact( + "org.apache.maven.its.plugins", + "maven-it-plugin", + "0.1", + "compile", + "jar", + null, + new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); - descriptor.setGroupId( "org.apache.maven.its.plugins" ); - descriptor.setArtifactId( "maven-it-plugin" ); - descriptor.setVersion( "0.1" ); + descriptor.setGroupId("org.apache.maven.its.plugins"); + descriptor.setArtifactId("maven-it-plugin"); + descriptor.setVersion("0.1"); List errors = new ArrayList<>(); - mavenPluginValidator.validate( plugin, descriptor, errors ); - assertTrue( errors.isEmpty() ); + mavenPluginValidator.validate(plugin, descriptor, errors); + assertTrue(errors.isEmpty()); } @Test - public void testInvalidGroupId() - { - Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", - "jar", null, new DefaultArtifactHandler( "ignore" ) ); + public void testInvalidGroupId() { + Artifact plugin = new DefaultArtifact( + "org.apache.maven.its.plugins", + "maven-it-plugin", + "0.1", + "compile", + "jar", + null, + new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); - descriptor.setGroupId( "org.apache.maven.its.plugins.invalid" ); - descriptor.setArtifactId( "maven-it-plugin" ); - descriptor.setVersion( "0.1" ); + descriptor.setGroupId("org.apache.maven.its.plugins.invalid"); + descriptor.setArtifactId("maven-it-plugin"); + descriptor.setVersion("0.1"); List errors = new ArrayList<>(); - mavenPluginValidator.validate( plugin, descriptor, errors ); - assertFalse( errors.isEmpty() ); + mavenPluginValidator.validate(plugin, descriptor, errors); + assertFalse(errors.isEmpty()); } @Test - public void testInvalidArtifactId() - { - Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", - "jar", null, new DefaultArtifactHandler( "ignore" ) ); + public void testInvalidArtifactId() { + Artifact plugin = new DefaultArtifact( + "org.apache.maven.its.plugins", + "maven-it-plugin", + "0.1", + "compile", + "jar", + null, + new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); - descriptor.setGroupId( "org.apache.maven.its.plugins" ); - descriptor.setArtifactId( "maven-it-plugin.invalid" ); - descriptor.setVersion( "0.1" ); + descriptor.setGroupId("org.apache.maven.its.plugins"); + descriptor.setArtifactId("maven-it-plugin.invalid"); + descriptor.setVersion("0.1"); List errors = new ArrayList<>(); - mavenPluginValidator.validate( plugin, descriptor, errors ); - assertFalse( errors.isEmpty() ); + mavenPluginValidator.validate(plugin, descriptor, errors); + assertFalse(errors.isEmpty()); } @Test - public void testInvalidVersion() - { - Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", - "jar", null, new DefaultArtifactHandler( "ignore" ) ); + public void testInvalidVersion() { + Artifact plugin = new DefaultArtifact( + "org.apache.maven.its.plugins", + "maven-it-plugin", + "0.1", + "compile", + "jar", + null, + new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); - descriptor.setGroupId( "org.apache.maven.its.plugins" ); - descriptor.setArtifactId( "maven-it-plugin" ); + descriptor.setGroupId("org.apache.maven.its.plugins"); + descriptor.setArtifactId("maven-it-plugin"); List errors = new ArrayList<>(); - mavenPluginValidator.validate( plugin, descriptor, errors ); - assertFalse( errors.isEmpty() ); + mavenPluginValidator.validate(plugin, descriptor, errors); + assertFalse(errors.isEmpty()); } } diff --git a/maven-core/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java b/maven-core/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java index 785958e054..d2d6b41756 100644 --- a/maven-core/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java +++ b/maven-core/src/test/java/org/apache/maven/project/AbstractMavenProjectTestCase.java @@ -1,19 +1,22 @@ -package org.apache.maven.project; - /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ +package org.apache.maven.project; import java.io.File; import java.io.FileNotFoundException; @@ -21,26 +24,23 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; - +import javax.inject.Inject; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.building.ModelBuildingException; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; -import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.eclipse.aether.DefaultRepositoryCache; import org.eclipse.aether.DefaultRepositorySystemSession; import org.junit.jupiter.api.BeforeEach; -import javax.inject.Inject; - /** * @author Jason van Zyl */ @PlexusTest -public abstract class AbstractMavenProjectTestCase -{ +public abstract class AbstractMavenProjectTestCase { protected ProjectBuilder projectBuilder; @Inject @@ -54,22 +54,16 @@ public abstract class AbstractMavenProjectTestCase } @BeforeEach - public void setUp() - throws Exception - { - if ( getContainer().hasComponent( ProjectBuilder.class, "test" ) ) - { - projectBuilder = getContainer().lookup( ProjectBuilder.class, "test" ); - } - else - { + public void setUp() throws Exception { + if (getContainer().hasComponent(ProjectBuilder.class, "test")) { + projectBuilder = getContainer().lookup(ProjectBuilder.class, "test"); + } else { // default over to the main project builder... - projectBuilder = getContainer().lookup( ProjectBuilder.class ); + projectBuilder = getContainer().lookup(ProjectBuilder.class); } } - protected ProjectBuilder getProjectBuilder() - { + protected ProjectBuilder getProjectBuilder() { return projectBuilder; } @@ -77,103 +71,81 @@ public abstract class AbstractMavenProjectTestCase // Local repository // ---------------------------------------------------------------------- - protected File getLocalRepositoryPath() - throws FileNotFoundException, URISyntaxException - { - File markerFile = getFileForClasspathResource( "local-repo/marker.txt" ); + protected File getLocalRepositoryPath() throws FileNotFoundException, URISyntaxException { + File markerFile = getFileForClasspathResource("local-repo/marker.txt"); return markerFile.getAbsoluteFile().getParentFile(); } - protected static File getFileForClasspathResource( String resource ) - throws FileNotFoundException - { + protected static File getFileForClasspathResource(String resource) throws FileNotFoundException { ClassLoader cloader = Thread.currentThread().getContextClassLoader(); - URL resourceUrl = cloader.getResource( resource ); + URL resourceUrl = cloader.getResource(resource); - if ( resourceUrl == null ) - { - throw new FileNotFoundException( "Unable to find: " + resource ); + if (resourceUrl == null) { + throw new FileNotFoundException("Unable to find: " + resource); } - return new File( URI.create( resourceUrl.toString().replaceAll( " ", "%20" ) ) ); + return new File(URI.create(resourceUrl.toString().replaceAll(" ", "%20"))); } - protected ArtifactRepository getLocalRepository() - throws Exception - { - return repositorySystem.createLocalRepository( getLocalRepositoryPath() ); + protected ArtifactRepository getLocalRepository() throws Exception { + return repositorySystem.createLocalRepository(getLocalRepositoryPath()); } // ---------------------------------------------------------------------- // Project building // ---------------------------------------------------------------------- - protected MavenProject getProjectWithDependencies( File pom ) - throws Exception - { + protected MavenProject getProjectWithDependencies(File pom) throws Exception { ProjectBuildingRequest configuration = newBuildingRequest(); - configuration.setRemoteRepositories( Arrays.asList( new ArtifactRepository[] {} ) ); - configuration.setProcessPlugins( false ); - configuration.setResolveDependencies( true ); + configuration.setRemoteRepositories(Arrays.asList(new ArtifactRepository[] {})); + configuration.setProcessPlugins(false); + configuration.setResolveDependencies(true); - try - { - return projectBuilder.build( pom, configuration ).getProject(); - } - catch ( Exception e ) - { + try { + return projectBuilder.build(pom, configuration).getProject(); + } catch (Exception e) { Throwable cause = e.getCause(); - if ( cause instanceof ModelBuildingException ) - { + if (cause instanceof ModelBuildingException) { String message = "In: " + pom + "\n\n"; - for ( ModelProblem problem : ( (ModelBuildingException) cause ).getProblems() ) - { + for (ModelProblem problem : ((ModelBuildingException) cause).getProblems()) { message += problem + "\n"; } - System.out.println( message ); + System.out.println(message); } throw e; } } - protected MavenProject getProject( File pom ) - throws Exception - { + protected MavenProject getProject(File pom) throws Exception { ProjectBuildingRequest configuration = newBuildingRequest(); - return projectBuilder.build( pom, configuration ).getProject(); + return projectBuilder.build(pom, configuration).getProject(); } - protected MavenProject getProjectFromRemoteRepository( final File pom ) - throws Exception - { + protected MavenProject getProjectFromRemoteRepository(final File pom) throws Exception { final ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setLocalRepository( this.getLocalRepository() ); - configuration.setRemoteRepositories( Arrays.asList( this.repositorySystem.createDefaultRemoteRepository() ) ); - initRepoSession( configuration ); + configuration.setLocalRepository(this.getLocalRepository()); + configuration.setRemoteRepositories(Arrays.asList(this.repositorySystem.createDefaultRemoteRepository())); + initRepoSession(configuration); - return projectBuilder.build( pom, configuration ).getProject(); + return projectBuilder.build(pom, configuration).getProject(); } - protected ProjectBuildingRequest newBuildingRequest() - throws Exception - { + protected ProjectBuildingRequest newBuildingRequest() throws Exception { ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setLocalRepository( getLocalRepository() ); - initRepoSession( configuration ); + configuration.setLocalRepository(getLocalRepository()); + initRepoSession(configuration); return configuration; } - protected void initRepoSession( ProjectBuildingRequest request ) - { - File localRepo = new File( request.getLocalRepository().getBasedir() ); + protected void initRepoSession(ProjectBuildingRequest request) { + File localRepo = new File(request.getLocalRepository().getBasedir()); DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession(); - repoSession.setCache( new DefaultRepositoryCache() ); - repoSession.setLocalRepositoryManager( new LegacyLocalRepositoryManager( localRepo ) ); - request.setRepositorySession( repoSession ); + repoSession.setCache(new DefaultRepositoryCache()); + repoSession.setLocalRepositoryManager(new LegacyLocalRepositoryManager(localRepo)); + request.setRepositorySession(repoSession); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java b/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java index 59cab5dac3..f166d0f04c 100644 --- a/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import static org.apache.maven.project.ProjectBuildingResultWithProblemMessageMatcher.projectBuildingResultWithProblemMessage; import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; @@ -38,7 +37,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.List; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.junit.jupiter.api.BeforeEach; @@ -46,9 +44,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -public class DefaultMavenProjectBuilderTest - extends AbstractMavenProjectTestCase -{ +public class DefaultMavenProjectBuilderTest extends AbstractMavenProjectTestCase { @TempDir File localRepoDir; @@ -58,20 +54,16 @@ public class DefaultMavenProjectBuilderTest @Override @BeforeEach - public void setUp() - throws Exception - { - projectBuilder = getContainer().lookup( ProjectBuilder.class ); + public void setUp() throws Exception { + projectBuilder = getContainer().lookup(ProjectBuilder.class); } - protected MavenProject getProject( Artifact pom, boolean allowStub ) - throws Exception - { + protected MavenProject getProject(Artifact pom, boolean allowStub) throws Exception { ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setLocalRepository( getLocalRepository() ); - initRepoSession( configuration ); + configuration.setLocalRepository(getLocalRepository()); + initRepoSession(configuration); - return projectBuilder.build( pom, allowStub, configuration ).getProject(); + return projectBuilder.build(pom, allowStub, configuration).getProject(); } /** @@ -80,122 +72,102 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void testBuildFromMiddlePom() throws Exception - { - File f1 = getTestFile( "src/test/resources/projects/grandchild-check/child/pom.xml"); - File f2 = getTestFile( "src/test/resources/projects/grandchild-check/child/grandchild/pom.xml"); + public void testBuildFromMiddlePom() throws Exception { + File f1 = getTestFile("src/test/resources/projects/grandchild-check/child/pom.xml"); + File f2 = getTestFile("src/test/resources/projects/grandchild-check/child/grandchild/pom.xml"); - getProject( f1 ); + getProject(f1); // it's the building of the grandchild project, having already cached the child project // (but not the parent project), which causes the problem. - getProject( f2 ); + getProject(f2); } - @Disabled( "Maven 4 does not allow duplicate plugin declarations" ) + @Disabled("Maven 4 does not allow duplicate plugin declarations") @Test - public void testDuplicatePluginDefinitionsMerged() - throws Exception - { - File f1 = getTestFile( "src/test/resources/projects/duplicate-plugins-merged-pom.xml" ); + public void testDuplicatePluginDefinitionsMerged() throws Exception { + File f1 = getTestFile("src/test/resources/projects/duplicate-plugins-merged-pom.xml"); - MavenProject project = getProject( f1 ); - assertEquals( 2, project.getBuildPlugins().get( 0 ).getDependencies().size() ); - assertEquals( 2, project.getBuildPlugins().get( 0 ).getExecutions().size() ); - assertEquals( "first", project.getBuildPlugins().get( 0 ).getExecutions().get( 0 ).getId() ); + MavenProject project = getProject(f1); + assertEquals(2, project.getBuildPlugins().get(0).getDependencies().size()); + assertEquals(2, project.getBuildPlugins().get(0).getExecutions().size()); + assertEquals( + "first", project.getBuildPlugins().get(0).getExecutions().get(0).getId()); } @Test - public void testFutureModelVersion() - throws Exception - { - File f1 = getTestFile( "src/test/resources/projects/future-model-version-pom.xml" ); + public void testFutureModelVersion() throws Exception { + File f1 = getTestFile("src/test/resources/projects/future-model-version-pom.xml"); ProjectBuildingException e = assertThrows( - ProjectBuildingException.class, - () -> getProject( f1 ), - "Expected to fail for future versions" ); - assertThat( e.getMessage(), containsString( "Building this project requires a newer version of Maven" ) ); + ProjectBuildingException.class, () -> getProject(f1), "Expected to fail for future versions"); + assertThat(e.getMessage(), containsString("Building this project requires a newer version of Maven")); } @Test - public void testPastModelVersion() - throws Exception - { + public void testPastModelVersion() throws Exception { // a Maven 1.x pom will not even // update the resource if we stop supporting modelVersion 4.0.0 - File f1 = getTestFile( "src/test/resources/projects/past-model-version-pom.xml" ); + File f1 = getTestFile("src/test/resources/projects/past-model-version-pom.xml"); ProjectBuildingException e = assertThrows( - ProjectBuildingException.class, - () -> getProject( f1 ), - "Expected to fail for past versions" ); - assertThat( e.getMessage(), containsString( "Building this project requires an older version of Maven" ) ); + ProjectBuildingException.class, () -> getProject(f1), "Expected to fail for past versions"); + assertThat(e.getMessage(), containsString("Building this project requires an older version of Maven")); } @Test - public void testFutureSchemaModelVersion() - throws Exception - { - File f1 = getTestFile( "src/test/resources/projects/future-schema-model-version-pom.xml" ); + public void testFutureSchemaModelVersion() throws Exception { + File f1 = getTestFile("src/test/resources/projects/future-schema-model-version-pom.xml"); ProjectBuildingException e = assertThrows( - ProjectBuildingException.class, - () -> getProject( f1 ), - "Expected to fail for future versions" ); - assertThat( e.getMessage(), containsString( "Building this project requires a newer version of Maven" ) ); + ProjectBuildingException.class, () -> getProject(f1), "Expected to fail for future versions"); + assertThat(e.getMessage(), containsString("Building this project requires a newer version of Maven")); } @Test - public void testBuildStubModelForMissingRemotePom() - throws Exception - { - Artifact pom = repositorySystem.createProjectArtifact( "org.apache.maven.its", "missing", "0.1" ); - MavenProject project = getProject( pom, true ); + public void testBuildStubModelForMissingRemotePom() throws Exception { + Artifact pom = repositorySystem.createProjectArtifact("org.apache.maven.its", "missing", "0.1"); + MavenProject project = getProject(pom, true); - assertNotNull( project.getArtifactId() ); + assertNotNull(project.getArtifactId()); - assertNotNull( project.getRemoteArtifactRepositories() ); - assertFalse( project.getRemoteArtifactRepositories().isEmpty() ); + assertNotNull(project.getRemoteArtifactRepositories()); + assertFalse(project.getRemoteArtifactRepositories().isEmpty()); - assertNotNull( project.getPluginArtifactRepositories() ); - assertFalse( project.getPluginArtifactRepositories().isEmpty() ); + assertNotNull(project.getPluginArtifactRepositories()); + assertFalse(project.getPluginArtifactRepositories().isEmpty()); - assertNull( project.getParent() ); - assertNull( project.getParentArtifact() ); + assertNull(project.getParent()); + assertNull(project.getParentArtifact()); - assertFalse( project.isExecutionRoot() ); + assertFalse(project.isExecutionRoot()); } @Override - protected ArtifactRepository getLocalRepository() - throws Exception - { - return repositorySystem.createLocalRepository( getLocalRepositoryPath() ); + protected ArtifactRepository getLocalRepository() throws Exception { + return repositorySystem.createLocalRepository(getLocalRepositoryPath()); } @Test - public void testPartialResultUponBadDependencyDeclaration() - throws Exception - { - File pomFile = getTestFile( "src/test/resources/projects/bad-dependency.xml" ); + public void testPartialResultUponBadDependencyDeclaration() throws Exception { + File pomFile = getTestFile("src/test/resources/projects/bad-dependency.xml"); ProjectBuildingRequest request = newBuildingRequest(); - request.setProcessPlugins( false ); - request.setResolveDependencies( true ); + request.setProcessPlugins(false); + request.setResolveDependencies(true); ProjectBuildingException e = assertThrows( ProjectBuildingException.class, - () -> projectBuilder.build( pomFile, request ), - "Project building did not fail despite invalid POM" ); + () -> projectBuilder.build(pomFile, request), + "Project building did not fail despite invalid POM"); List results = e.getResults(); - assertNotNull( results ); - assertEquals( 1, results.size() ); - ProjectBuildingResult result = results.get( 0 ); - assertNotNull( result ); - assertNotNull( result.getProject() ); - assertEquals( 1, result.getProblems().size() ); - assertEquals( 1, result.getProject().getArtifacts().size() ); - assertNotNull( result.getDependencyResolutionResult() ); + assertNotNull(results); + assertEquals(1, results.size()); + ProjectBuildingResult result = results.get(0); + assertNotNull(result); + assertNotNull(result.getProject()); + assertEquals(1, result.getProblems().size()); + assertEquals(1, result.getProject().getArtifacts().size()); + assertNotNull(result.getDependencyResolutionResult()); } /** @@ -204,18 +176,17 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void testBuildValidParentVersionRangeLocally() throws Exception - { - File f1 = getTestFile( "src/test/resources/projects/parent-version-range-local-valid/child/pom.xml" ); + public void testBuildValidParentVersionRangeLocally() throws Exception { + File f1 = getTestFile("src/test/resources/projects/parent-version-range-local-valid/child/pom.xml"); - final MavenProject childProject = getProject( f1 ); + final MavenProject childProject = getProject(f1); - assertNotNull( childProject.getParentArtifact() ); - assertEquals( childProject.getParentArtifact().getVersion(), "1" ); - assertNotNull( childProject.getParent() ); - assertEquals( childProject.getParent().getVersion(), "1" ); - assertNotNull( childProject.getModel().getParent() ); - assertEquals( childProject.getModel().getParent().getVersion(), "[1,10]" ); + assertNotNull(childProject.getParentArtifact()); + assertEquals(childProject.getParentArtifact().getVersion(), "1"); + assertNotNull(childProject.getParent()); + assertEquals(childProject.getParent().getVersion(), "1"); + assertNotNull(childProject.getModel().getParent()); + assertEquals(childProject.getModel().getParent().getVersion(), "[1,10]"); } /** @@ -224,16 +195,15 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void testBuildParentVersionRangeLocallyWithoutChildVersion() throws Exception - { - File f1 = - getTestFile( "src/test/resources/projects/parent-version-range-local-child-without-version/child/pom.xml" ); + public void testBuildParentVersionRangeLocallyWithoutChildVersion() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-local-child-without-version/child/pom.xml"); ProjectBuildingException e = assertThrows( ProjectBuildingException.class, - () -> getProject( f1 ), - "Expected 'ProjectBuildingException' not thrown." ); - assertThat( e.getResults(), contains( projectBuildingResultWithProblemMessage( "Version must be a constant" ) ) ); + () -> getProject(f1), + "Expected 'ProjectBuildingException' not thrown."); + assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant"))); } /** @@ -242,77 +212,47 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void testBuildParentVersionRangeLocallyWithChildProjectVersionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-local-child-project-version-expression/child/pom.xml" ); + public void testBuildParentVersionRangeLocallyWithChildProjectVersionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-local-child-project-version-expression/child/pom.xml"); ProjectBuildingException e = assertThrows( ProjectBuildingException.class, - () -> getProject( f1 ), - "Expected 'ProjectBuildingException' not thrown." ); - assertThat( e.getResults(), contains( projectBuildingResultWithProblemMessage( "Version must be a constant" ) ) ); + () -> getProject(f1), + "Expected 'ProjectBuildingException' not thrown."); + assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant"))); } - + /** * Tests whether local version range parent references are build correctly. * * @throws Exception */ - public void testBuildParentVersionRangeLocallyWithChildProjectParentVersionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-local-child-project-parent-version-expression/child/pom.xml" ); + public void testBuildParentVersionRangeLocallyWithChildProjectParentVersionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-local-child-project-parent-version-expression/child/pom.xml"); - try - { - getProject( f1 ); - fail( "Expected 'ProjectBuildingException' not thrown." ); - } - catch ( final ProjectBuildingException e ) - { - assertNotNull( e.getMessage() ); - assertThat( e.getMessage(), containsString( "Version must be a constant" ) ); + try { + getProject(f1); + fail("Expected 'ProjectBuildingException' not thrown."); + } catch (final ProjectBuildingException e) { + assertNotNull(e.getMessage()); + assertThat(e.getMessage(), containsString("Version must be a constant")); } } - + /** * Tests whether local version range parent references are build correctly. * * @throws Exception */ - public void testBuildParentVersionRangeLocallyWithChildRevisionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-local-child-revision-expression/child/pom.xml" ); + public void testBuildParentVersionRangeLocallyWithChildRevisionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-local-child-revision-expression/child/pom.xml"); + + MavenProject mp = this.getProjectFromRemoteRepository(f1); - MavenProject mp = this.getProjectFromRemoteRepository( f1 ); - assertEquals("1.0-SNAPSHOT", mp.getVersion()); - - } - - /** - * Tests whether external version range parent references are build correctly. - * - * @throws Exception in case of issue - */ - @Test - public void testBuildParentVersionRangeExternally() throws Exception - { - File f1 = getTestFile( "src/test/resources/projects/parent-version-range-external-valid/pom.xml" ); - - final MavenProject childProject = this.getProjectFromRemoteRepository( f1 ); - - assertNotNull( childProject.getParentArtifact() ); - assertEquals( childProject.getParentArtifact().getVersion(), "1" ); - assertNotNull( childProject.getParent() ); - assertEquals( childProject.getParent().getVersion(), "1" ); - assertNotNull( childProject.getModel().getParent() ); - assertEquals( childProject.getModel().getParent().getVersion(), "[1,1]" ); } /** @@ -321,17 +261,34 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void testBuildParentVersionRangeExternallyWithoutChildVersion() throws Exception - { + public void testBuildParentVersionRangeExternally() throws Exception { + File f1 = getTestFile("src/test/resources/projects/parent-version-range-external-valid/pom.xml"); + + final MavenProject childProject = this.getProjectFromRemoteRepository(f1); + + assertNotNull(childProject.getParentArtifact()); + assertEquals(childProject.getParentArtifact().getVersion(), "1"); + assertNotNull(childProject.getParent()); + assertEquals(childProject.getParent().getVersion(), "1"); + assertNotNull(childProject.getModel().getParent()); + assertEquals(childProject.getModel().getParent().getVersion(), "[1,1]"); + } + + /** + * Tests whether external version range parent references are build correctly. + * + * @throws Exception in case of issue + */ + @Test + public void testBuildParentVersionRangeExternallyWithoutChildVersion() throws Exception { File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-external-child-without-version/pom.xml" ); + getTestFile("src/test/resources/projects/parent-version-range-external-child-without-version/pom.xml"); ProjectBuildingException e = assertThrows( ProjectBuildingException.class, - () -> getProjectFromRemoteRepository( f1 ), - "Expected 'ProjectBuildingException' not thrown." ); - assertThat( e.getResults(), contains( projectBuildingResultWithProblemMessage( "Version must be a constant" ) ) ); + () -> getProjectFromRemoteRepository(f1), + "Expected 'ProjectBuildingException' not thrown."); + assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant"))); } /** @@ -340,17 +297,15 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void testBuildParentVersionRangeExternallyWithChildProjectVersionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-external-child-project-version-expression/pom.xml" ); + public void testBuildParentVersionRangeExternallyWithChildProjectVersionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-external-child-project-version-expression/pom.xml"); ProjectBuildingException e = assertThrows( ProjectBuildingException.class, - () -> getProjectFromRemoteRepository( f1 ), - "Expected 'ProjectBuildingException' not thrown." ); - assertThat( e.getResults(), contains( projectBuildingResultWithProblemMessage( "Version must be a constant") ) ); + () -> getProjectFromRemoteRepository(f1), + "Expected 'ProjectBuildingException' not thrown."); + assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant"))); } /** @@ -359,28 +314,26 @@ public class DefaultMavenProjectBuilderTest * @throws Exception in case of issue */ @Test - public void rereadPom_mng7063() throws Exception - { - final Path pom = projectRoot.resolve( "pom.xml" ); + public void rereadPom_mng7063() throws Exception { + final Path pom = projectRoot.resolve("pom.xml"); final ProjectBuildingRequest buildingRequest = newBuildingRequest(); - try ( InputStream pomResource = - DefaultMavenProjectBuilderTest.class.getResourceAsStream( "/projects/reread/pom1.xml" ) ) - { - Files.copy( pomResource, pom, StandardCopyOption.REPLACE_EXISTING ); + try (InputStream pomResource = + DefaultMavenProjectBuilderTest.class.getResourceAsStream("/projects/reread/pom1.xml")) { + Files.copy(pomResource, pom, StandardCopyOption.REPLACE_EXISTING); } - MavenProject project = projectBuilder.build( pom.toFile(), buildingRequest ).getProject(); - assertThat( project.getName(), is( "aid" ) ); // inherited from artifactId + MavenProject project = + projectBuilder.build(pom.toFile(), buildingRequest).getProject(); + assertThat(project.getName(), is("aid")); // inherited from artifactId - try ( InputStream pomResource = - DefaultMavenProjectBuilderTest.class.getResourceAsStream( "/projects/reread/pom2.xml" ) ) - { - Files.copy( pomResource, pom, StandardCopyOption.REPLACE_EXISTING ); + try (InputStream pomResource = + DefaultMavenProjectBuilderTest.class.getResourceAsStream("/projects/reread/pom2.xml")) { + Files.copy(pomResource, pom, StandardCopyOption.REPLACE_EXISTING); } - project = projectBuilder.build( pom.toFile(), buildingRequest ).getProject(); - assertThat( project.getName(), is( "PROJECT NAME" ) ); + project = projectBuilder.build(pom.toFile(), buildingRequest).getProject(); + assertThat(project.getName(), is("PROJECT NAME")); } /** @@ -388,21 +341,16 @@ public class DefaultMavenProjectBuilderTest * * @throws Exception */ - public void testBuildParentVersionRangeExternallyWithChildPomVersionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-external-child-pom-version-expression/pom.xml" ); + public void testBuildParentVersionRangeExternallyWithChildPomVersionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-external-child-pom-version-expression/pom.xml"); - try - { - this.getProjectFromRemoteRepository( f1 ); - fail( "Expected 'ProjectBuildingException' not thrown." ); - } - catch ( final ProjectBuildingException e ) - { - assertNotNull( e.getMessage() ); - assertThat( e.getMessage(), containsString( "Version must be a constant" ) ); + try { + this.getProjectFromRemoteRepository(f1); + fail("Expected 'ProjectBuildingException' not thrown."); + } catch (final ProjectBuildingException e) { + assertNotNull(e.getMessage()); + assertThat(e.getMessage(), containsString("Version must be a constant")); } } @@ -411,21 +359,16 @@ public class DefaultMavenProjectBuilderTest * * @throws Exception */ - public void testBuildParentVersionRangeExternallyWithChildPomParentVersionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-external-child-pom-parent-version-expression/pom.xml" ); + public void testBuildParentVersionRangeExternallyWithChildPomParentVersionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-external-child-pom-parent-version-expression/pom.xml"); - try - { - this.getProjectFromRemoteRepository( f1 ); - fail( "Expected 'ProjectBuildingException' not thrown." ); - } - catch ( final ProjectBuildingException e ) - { - assertNotNull( e.getMessage() ); - assertThat( e.getMessage(), containsString( "Version must be a constant" ) ); + try { + this.getProjectFromRemoteRepository(f1); + fail("Expected 'ProjectBuildingException' not thrown."); + } catch (final ProjectBuildingException e) { + assertNotNull(e.getMessage()); + assertThat(e.getMessage(), containsString("Version must be a constant")); } } @@ -434,40 +377,30 @@ public class DefaultMavenProjectBuilderTest * * @throws Exception */ - public void testBuildParentVersionRangeExternallyWithChildProjectParentVersionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-external-child-project-parent-version-expression/pom.xml" ); + public void testBuildParentVersionRangeExternallyWithChildProjectParentVersionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-external-child-project-parent-version-expression/pom.xml"); - try - { - this.getProjectFromRemoteRepository( f1 ); - fail( "Expected 'ProjectBuildingException' not thrown." ); - } - catch ( final ProjectBuildingException e ) - { - assertNotNull( e.getMessage() ); - assertThat( e.getMessage(), containsString( "Version must be a constant" ) ); + try { + this.getProjectFromRemoteRepository(f1); + fail("Expected 'ProjectBuildingException' not thrown."); + } catch (final ProjectBuildingException e) { + assertNotNull(e.getMessage()); + assertThat(e.getMessage(), containsString("Version must be a constant")); } } - + /** * Tests whether external version range parent references are build correctly. * * @throws Exception */ - public void testBuildParentVersionRangeExternallyWithChildRevisionExpression() throws Exception - { - File f1 = - getTestFile( - "src/test/resources/projects/parent-version-range-external-child-revision-expression/pom.xml" ); + public void testBuildParentVersionRangeExternallyWithChildRevisionExpression() throws Exception { + File f1 = getTestFile( + "src/test/resources/projects/parent-version-range-external-child-revision-expression/pom.xml"); + + MavenProject mp = this.getProjectFromRemoteRepository(f1); - - MavenProject mp = this.getProjectFromRemoteRepository( f1 ); - assertEquals("1.0-SNAPSHOT", mp.getVersion()); - - } } diff --git a/maven-core/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java b/maven-core/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java index da2ae4c8fa..22ed84b9e7 100644 --- a/maven-core/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java +++ b/maven-core/src/test/java/org/apache/maven/project/EmptyLifecycleExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; - import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleExecutor; import org.apache.maven.lifecycle.MavenExecutionPlan; @@ -37,73 +35,57 @@ import org.apache.maven.plugin.MojoExecution; * * @author Benjamin Bentmann */ -public class EmptyLifecycleExecutor - implements LifecycleExecutor -{ +public class EmptyLifecycleExecutor implements LifecycleExecutor { - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, String... tasks ) - { - return new MavenExecutionPlan( null, null ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, String... tasks) { + return new MavenExecutionPlan(null, null); } - public MavenExecutionPlan calculateExecutionPlan( MavenSession session, boolean setup, String... tasks ) - { - return new MavenExecutionPlan( null, null ); + public MavenExecutionPlan calculateExecutionPlan(MavenSession session, boolean setup, String... tasks) { + return new MavenExecutionPlan(null, null); } - public void execute( MavenSession session ) - { - } + public void execute(MavenSession session) {} - public Set getPluginsBoundByDefaultToAllLifecycles( String packaging ) - { + public Set getPluginsBoundByDefaultToAllLifecycles(String packaging) { Set plugins; // NOTE: The upper-case packaging name is intentional, that's a special hinting mode used for certain tests - if ( "JAR".equals( packaging ) ) - { + if ("JAR".equals(packaging)) { plugins = new LinkedHashSet<>(); - plugins.add( newPlugin( "maven-compiler-plugin", "compile", "testCompile" ) ); - plugins.add( newPlugin( "maven-resources-plugin", "resources", "testResources" ) ); - plugins.add( newPlugin( "maven-surefire-plugin", "test" ) ); - plugins.add( newPlugin( "maven-jar-plugin", "jar" ) ); - plugins.add( newPlugin( "maven-install-plugin", "install" ) ); - plugins.add( newPlugin( "maven-deploy-plugin", "deploy" ) ); - } - else - { + plugins.add(newPlugin("maven-compiler-plugin", "compile", "testCompile")); + plugins.add(newPlugin("maven-resources-plugin", "resources", "testResources")); + plugins.add(newPlugin("maven-surefire-plugin", "test")); + plugins.add(newPlugin("maven-jar-plugin", "jar")); + plugins.add(newPlugin("maven-install-plugin", "install")); + plugins.add(newPlugin("maven-deploy-plugin", "deploy")); + } else { plugins = Collections.emptySet(); } return plugins; } - private Plugin newPlugin( String artifactId, String... goals ) - { + private Plugin newPlugin(String artifactId, String... goals) { Plugin plugin = new Plugin(); - plugin.setGroupId( "org.apache.maven.plugins" ); - plugin.setArtifactId( artifactId ); + plugin.setGroupId("org.apache.maven.plugins"); + plugin.setArtifactId(artifactId); - for ( String goal : goals ) - { + for (String goal : goals) { PluginExecution pluginExecution = new PluginExecution(); - pluginExecution.setId( "default-" + goal ); - pluginExecution.setGoals( Collections.singletonList( goal ) ); - plugin.addExecution( pluginExecution ); + pluginExecution.setId("default-" + goal); + pluginExecution.setGoals(Collections.singletonList(goal)); + plugin.addExecution(pluginExecution); } return plugin; } - public void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - { - } + public void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) {} - public List executeForkedExecutions( MojoExecution mojoExecution, MavenSession session ) - { + public List executeForkedExecutions(MojoExecution mojoExecution, MavenSession session) { return Collections.emptyList(); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/EmptyProjectBuildingHelper.java b/maven-core/src/test/java/org/apache/maven/project/EmptyProjectBuildingHelper.java index c843ca722f..384ef0bab2 100644 --- a/maven-core/src/test/java/org/apache/maven/project/EmptyProjectBuildingHelper.java +++ b/maven-core/src/test/java/org/apache/maven/project/EmptyProjectBuildingHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.ArrayList; import java.util.List; - import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Model; import org.apache.maven.model.Repository; @@ -31,32 +29,23 @@ import org.apache.maven.model.Repository; * * @author Benjamin Bentmann */ -public class EmptyProjectBuildingHelper - implements ProjectBuildingHelper -{ +public class EmptyProjectBuildingHelper implements ProjectBuildingHelper { - public List createArtifactRepositories( List pomRepositories, - List externalRepositories, - ProjectBuildingRequest request ) - { - if ( externalRepositories != null ) - { + public List createArtifactRepositories( + List pomRepositories, + List externalRepositories, + ProjectBuildingRequest request) { + if (externalRepositories != null) { return externalRepositories; - } - else - { + } else { return new ArrayList<>(); } } - public ProjectRealmCache.CacheRecord createProjectRealm( MavenProject project, - Model model, ProjectBuildingRequest request ) - { - return new ProjectRealmCache.CacheRecord( null, null ); - } - - public void selectProjectRealm( MavenProject project ) - { + public ProjectRealmCache.CacheRecord createProjectRealm( + MavenProject project, Model model, ProjectBuildingRequest request) { + return new ProjectRealmCache.CacheRecord(null, null); } + public void selectProjectRealm(MavenProject project) {} } diff --git a/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java b/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java index 150eb6a949..1dd591f3b7 100644 --- a/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,82 +16,70 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; - /** * Tests {@link ExtensionDescriptorBuilder}. * * @author Benjamin Bentmann */ -public class ExtensionDescriptorBuilderTest -{ +public class ExtensionDescriptorBuilderTest { private ExtensionDescriptorBuilder builder; @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { builder = new ExtensionDescriptorBuilder(); } @AfterEach - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { builder = null; } - private InputStream toStream( String xml ) - { - return new ByteArrayInputStream( xml.getBytes( StandardCharsets.UTF_8 ) ); + private InputStream toStream(String xml) { + return new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); } @Test - public void testEmptyDescriptor() - throws Exception - { + public void testEmptyDescriptor() throws Exception { String xml = ""; - ExtensionDescriptor ed = builder.build( toStream( xml ) ); + ExtensionDescriptor ed = builder.build(toStream(xml)); - assertNotNull( ed ); - assertNotNull( ed.getExportedPackages() ); - assertThat( ed.getExportedPackages(), is( empty() ) ); - assertNotNull( ed.getExportedArtifacts() ); - assertThat( ed.getExportedArtifacts(), is( empty() ) ); + assertNotNull(ed); + assertNotNull(ed.getExportedPackages()); + assertThat(ed.getExportedPackages(), is(empty())); + assertNotNull(ed.getExportedArtifacts()); + assertThat(ed.getExportedArtifacts(), is(empty())); } @Test - public void testCompleteDescriptor() - throws Exception - { - String xml = - "" + "" + "" + public void testCompleteDescriptor() throws Exception { + String xml = "" + "" + "" + "a" + "b" + "c" + "" + "" + "x" + "y" + " z " + "" + ""; - ExtensionDescriptor ed = builder.build( toStream( xml ) ); + ExtensionDescriptor ed = builder.build(toStream(xml)); - assertNotNull( ed ); - assertEquals( Arrays.asList( "a", "b", "c" ), ed.getExportedPackages() ); - assertEquals( Arrays.asList( "x", "y", "z" ), ed.getExportedArtifacts() ); + assertNotNull(ed); + assertEquals(Arrays.asList("a", "b", "c"), ed.getExportedPackages()); + assertEquals(Arrays.asList("x", "y", "z"), ed.getExportedArtifacts()); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java b/maven-core/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java index a685bc1639..18125fb717 100644 --- a/maven-core/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java +++ b/maven-core/src/test/java/org/apache/maven/project/LegacyLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.io.File; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; @@ -37,124 +35,102 @@ import org.eclipse.aether.repository.RemoteRepository; /** * @author Benjamin Bentmann */ -public class LegacyLocalRepositoryManager - implements LocalRepositoryManager -{ +public class LegacyLocalRepositoryManager implements LocalRepositoryManager { private final LocalRepository repository; - LegacyLocalRepositoryManager( File basedir ) - { - this.repository = new LocalRepository( basedir.getAbsoluteFile(), "legacy" ); + LegacyLocalRepositoryManager(File basedir) { + this.repository = new LocalRepository(basedir.getAbsoluteFile(), "legacy"); } - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return repository; } - public String getPathForLocalArtifact( Artifact artifact ) - { - StringBuilder path = new StringBuilder( 128 ); + public String getPathForLocalArtifact(Artifact artifact) { + StringBuilder path = new StringBuilder(128); - path.append( artifact.getGroupId() ).append( '/' ); + path.append(artifact.getGroupId()).append('/'); - path.append( artifact.getExtension() ).append( "s/" ); + path.append(artifact.getExtension()).append("s/"); - path.append( artifact.getArtifactId() ).append( '-' ).append( artifact.getVersion() ); + path.append(artifact.getArtifactId()).append('-').append(artifact.getVersion()); - if ( artifact.getClassifier().length() > 0 ) - { - path.append( '-' ).append( artifact.getClassifier() ); + if (artifact.getClassifier().length() > 0) { + path.append('-').append(artifact.getClassifier()); } - path.append( '.' ).append( artifact.getExtension() ); + path.append('.').append(artifact.getExtension()); return path.toString(); } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { - return getPathForLocalArtifact( artifact ); + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { + return getPathForLocalArtifact(artifact); } - public String getPathForLocalMetadata( Metadata metadata ) - { - return getPath( metadata, "local" ); + public String getPathForLocalMetadata(Metadata metadata) { + return getPath(metadata, "local"); } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { - return getPath( metadata, getRepositoryKey( repository, context ) ); + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { + return getPath(metadata, getRepositoryKey(repository, context)); } - String getRepositoryKey( RemoteRepository repository, String context ) - { + String getRepositoryKey(RemoteRepository repository, String context) { return repository.getId(); } - private String getPath( Metadata metadata, String repositoryKey ) - { - StringBuilder path = new StringBuilder( 128 ); + private String getPath(Metadata metadata, String repositoryKey) { + StringBuilder path = new StringBuilder(128); - if ( metadata.getGroupId().length() > 0 ) - { - path.append( metadata.getGroupId().replace( '.', '/' ) ).append( '/' ); + if (metadata.getGroupId().length() > 0) { + path.append(metadata.getGroupId().replace('.', '/')).append('/'); - if ( metadata.getArtifactId().length() > 0 ) - { - path.append( metadata.getArtifactId() ).append( '/' ); + if (metadata.getArtifactId().length() > 0) { + path.append(metadata.getArtifactId()).append('/'); - if ( metadata.getVersion().length() > 0 ) - { - path.append( metadata.getVersion() ).append( '/' ); + if (metadata.getVersion().length() > 0) { + path.append(metadata.getVersion()).append('/'); } } } - path.append( insertRepositoryKey( metadata.getType(), repositoryKey ) ); + path.append(insertRepositoryKey(metadata.getType(), repositoryKey)); return path.toString(); } - private String insertRepositoryKey( String filename, String repositoryKey ) - { + private String insertRepositoryKey(String filename, String repositoryKey) { String result; - int idx = filename.indexOf( '.' ); - if ( idx < 0 ) - { + int idx = filename.indexOf('.'); + if (idx < 0) { result = filename + '-' + repositoryKey; - } - else - { - result = filename.substring( 0, idx ) + '-' + repositoryKey + filename.substring( idx ); + } else { + result = filename.substring(0, idx) + '-' + repositoryKey + filename.substring(idx); } return result; } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { - String path = getPathForLocalArtifact( request.getArtifact() ); - File file = new File( getRepository().getBasedir(), path ); + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { + String path = getPathForLocalArtifact(request.getArtifact()); + File file = new File(getRepository().getBasedir(), path); - LocalArtifactResult result = new LocalArtifactResult( request ); - if ( file.isFile() ) - { - result.setFile( file ); - result.setAvailable( true ); + LocalArtifactResult result = new LocalArtifactResult(request); + if (file.isFile()) { + result.setFile(file); + result.setAvailable(true); } return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { // noop } - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - LocalMetadataResult result = new LocalMetadataResult( request ); + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + LocalMetadataResult result = new LocalMetadataResult(request); String path; @@ -162,31 +138,25 @@ public class LegacyLocalRepositoryManager String context = request.getContext(); RemoteRepository remote = request.getRepository(); - if ( remote != null ) - { - path = getPathForRemoteMetadata( metadata, remote, context ); - } - else - { - path = getPathForLocalMetadata( metadata ); + if (remote != null) { + path = getPathForRemoteMetadata(metadata, remote, context); + } else { + path = getPathForLocalMetadata(metadata); } - File file = new File( getRepository().getBasedir(), path ); - if ( file.isFile() ) - { - result.setFile( file ); + File file = new File(getRepository().getBasedir(), path); + if (file.isFile()) { + result.setFile(file); } return result; } - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { + public void add(RepositorySystemSession session, LocalMetadataRegistration request) { // noop } - public String toString() - { - return String.valueOf( getRepository() ); + public String toString() { + return String.valueOf(getRepository()); } } diff --git a/maven-core/src/test/java/org/apache/maven/project/MavenProjectTest.java b/maven-core/src/test/java/org/apache/maven/project/MavenProjectTest.java index d2cba20a41..54d833c780 100644 --- a/maven-core/src/test/java/org/apache/maven/project/MavenProjectTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/MavenProjectTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,17 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import org.apache.maven.model.DependencyManagement; -import org.apache.maven.model.Model; -import org.apache.maven.model.Parent; -import org.apache.maven.model.Profile; -import org.junit.jupiter.api.Test; +package org.apache.maven.project; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -36,201 +24,194 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; -public class MavenProjectTest - extends AbstractMavenProjectTestCase -{ +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import org.apache.maven.model.DependencyManagement; +import org.apache.maven.model.Model; +import org.apache.maven.model.Parent; +import org.apache.maven.model.Profile; +import org.junit.jupiter.api.Test; + +public class MavenProjectTest extends AbstractMavenProjectTestCase { @Test - public void testShouldInterpretChildPathAdjustmentBasedOnModulePaths() - throws IOException - { + public void testShouldInterpretChildPathAdjustmentBasedOnModulePaths() throws IOException { Model parentModel = new Model(); - parentModel.addModule( "../child" ); + parentModel.addModule("../child"); - MavenProject parentProject = new MavenProject( parentModel ); + MavenProject parentProject = new MavenProject(parentModel); Model childModel = new Model(); - childModel.setArtifactId( "artifact" ); + childModel.setArtifactId("artifact"); - MavenProject childProject = new MavenProject( childModel ); + MavenProject childProject = new MavenProject(childModel); - File childFile = - new File( System.getProperty( "java.io.tmpdir" ), "maven-project-tests" + System.currentTimeMillis() - + "/child/pom.xml" ); + File childFile = new File( + System.getProperty("java.io.tmpdir"), + "maven-project-tests" + System.currentTimeMillis() + "/child/pom.xml"); - childProject.setFile( childFile ); + childProject.setFile(childFile); - String adjustment = parentProject.getModulePathAdjustment( childProject ); + String adjustment = parentProject.getModulePathAdjustment(childProject); - assertNotNull( adjustment ); + assertNotNull(adjustment); - assertEquals( "..", adjustment ); + assertEquals("..", adjustment); } @Test - public void testIdentityProtoInheritance() - { + public void testIdentityProtoInheritance() { Parent parent = new Parent(); - parent.setGroupId( "test-group" ); - parent.setVersion( "1000" ); - parent.setArtifactId( "test-artifact" ); + parent.setGroupId("test-group"); + parent.setVersion("1000"); + parent.setArtifactId("test-artifact"); Model model = new Model(); - model.setParent( parent ); - model.setArtifactId( "real-artifact" ); + model.setParent(parent); + model.setArtifactId("real-artifact"); - MavenProject project = new MavenProject( model ); + MavenProject project = new MavenProject(model); - assertEquals( "test-group", project.getGroupId(), "groupId proto-inheritance failed." ); - assertEquals( "real-artifact", project.getArtifactId(), "artifactId is masked." ); - assertEquals( "1000", project.getVersion(), "version proto-inheritance failed." ); + assertEquals("test-group", project.getGroupId(), "groupId proto-inheritance failed."); + assertEquals("real-artifact", project.getArtifactId(), "artifactId is masked."); + assertEquals("1000", project.getVersion(), "version proto-inheritance failed."); // draw the NPE. project.getId(); } @Test - public void testEmptyConstructor() - { + public void testEmptyConstructor() { MavenProject project = new MavenProject(); - assertEquals( MavenProject.EMPTY_PROJECT_GROUP_ID + ":" + MavenProject.EMPTY_PROJECT_ARTIFACT_ID + ":jar:" - + MavenProject.EMPTY_PROJECT_VERSION, project.getId() ); + assertEquals( + MavenProject.EMPTY_PROJECT_GROUP_ID + ":" + MavenProject.EMPTY_PROJECT_ARTIFACT_ID + ":jar:" + + MavenProject.EMPTY_PROJECT_VERSION, + project.getId()); } @Test - public void testClone() - throws Exception - { - File f = getFileForClasspathResource( "canonical-pom.xml" ); - MavenProject projectToClone = getProject( f ); + public void testClone() throws Exception { + File f = getFileForClasspathResource("canonical-pom.xml"); + MavenProject projectToClone = getProject(f); MavenProject clonedProject = projectToClone.clone(); - assertEquals( "maven-core", clonedProject.getArtifactId() ); + assertEquals("maven-core", clonedProject.getArtifactId()); Map clonedMap = clonedProject.getManagedVersionMap(); - assertNotNull( clonedMap, "ManagedVersionMap not copied" ); - assertTrue( clonedMap.isEmpty(), "ManagedVersionMap is not empty" ); + assertNotNull(clonedMap, "ManagedVersionMap not copied"); + assertTrue(clonedMap.isEmpty(), "ManagedVersionMap is not empty"); } @Test - public void testCloneWithDependencyManagement() - throws Exception - { - File f = getFileForClasspathResource( "dependencyManagement-pom.xml" ); - MavenProject projectToClone = getProjectWithDependencies( f ); + public void testCloneWithDependencyManagement() throws Exception { + File f = getFileForClasspathResource("dependencyManagement-pom.xml"); + MavenProject projectToClone = getProjectWithDependencies(f); DependencyManagement dep = projectToClone.getDependencyManagement(); - assertNotNull( dep, "No dependencyManagement" ); + assertNotNull(dep, "No dependencyManagement"); List list = dep.getDependencies(); - assertNotNull( list, "No dependencies" ); - assertTrue( !list.isEmpty(), "Empty dependency list" ); + assertNotNull(list, "No dependencies"); + assertTrue(!list.isEmpty(), "Empty dependency list"); Map map = projectToClone.getManagedVersionMap(); - assertNotNull( map, "No ManagedVersionMap" ); - assertTrue( !map.isEmpty(), "ManagedVersionMap is empty" ); + assertNotNull(map, "No ManagedVersionMap"); + assertTrue(!map.isEmpty(), "ManagedVersionMap is empty"); MavenProject clonedProject = projectToClone.clone(); - assertEquals( "maven-core", clonedProject.getArtifactId() ); + assertEquals("maven-core", clonedProject.getArtifactId()); Map clonedMap = clonedProject.getManagedVersionMap(); - assertNotNull( clonedMap, "ManagedVersionMap not copied" ); - assertTrue( !clonedMap.isEmpty(), "ManagedVersionMap is empty" ); - assertTrue( clonedMap.containsKey( "maven-test:maven-test-b:jar" ), "ManagedVersionMap does not contain test key" ); + assertNotNull(clonedMap, "ManagedVersionMap not copied"); + assertTrue(!clonedMap.isEmpty(), "ManagedVersionMap is empty"); + assertTrue(clonedMap.containsKey("maven-test:maven-test-b:jar"), "ManagedVersionMap does not contain test key"); } @Test - public void testGetModulePathAdjustment() - throws IOException - { + public void testGetModulePathAdjustment() throws IOException { Model moduleModel = new Model(); - MavenProject module = new MavenProject( moduleModel ); - module.setFile( new File( "module-dir/pom.xml" ) ); + MavenProject module = new MavenProject(moduleModel); + module.setFile(new File("module-dir/pom.xml")); Model parentModel = new Model(); - parentModel.addModule( "../module-dir" ); + parentModel.addModule("../module-dir"); - MavenProject parent = new MavenProject( parentModel ); - parent.setFile( new File( "parent-dir/pom.xml" ) ); + MavenProject parent = new MavenProject(parentModel); + parent.setFile(new File("parent-dir/pom.xml")); - String pathAdjustment = parent.getModulePathAdjustment( module ); + String pathAdjustment = parent.getModulePathAdjustment(module); - assertEquals( "..", pathAdjustment ); + assertEquals("..", pathAdjustment); } @Test - public void testCloneWithDistributionManagement() - throws Exception - { + public void testCloneWithDistributionManagement() throws Exception { - File f = getFileForClasspathResource( "distributionManagement-pom.xml" ); - MavenProject projectToClone = getProject( f ); + File f = getFileForClasspathResource("distributionManagement-pom.xml"); + MavenProject projectToClone = getProject(f); MavenProject clonedProject = projectToClone.clone(); - assertNotNull( clonedProject.getDistributionManagementArtifactRepository(), "clonedProject - distributionManagement" ); + assertNotNull( + clonedProject.getDistributionManagementArtifactRepository(), "clonedProject - distributionManagement"); } @Test - public void testCloneWithActiveProfile() - throws Exception - { + public void testCloneWithActiveProfile() throws Exception { - File f = getFileForClasspathResource( "withActiveByDefaultProfile-pom.xml" ); - MavenProject projectToClone = getProject( f ); + File f = getFileForClasspathResource("withActiveByDefaultProfile-pom.xml"); + MavenProject projectToClone = getProject(f); List activeProfilesOrig = projectToClone.getActiveProfiles(); - assertEquals( 1, activeProfilesOrig.size(), "Expecting 1 active profile" ); + assertEquals(1, activeProfilesOrig.size(), "Expecting 1 active profile"); MavenProject clonedProject = projectToClone.clone(); List activeProfilesClone = clonedProject.getActiveProfiles(); - assertEquals( 1, activeProfilesClone.size(), "Expecting 1 active profile" ); + assertEquals(1, activeProfilesClone.size(), "Expecting 1 active profile"); - assertNotSame( activeProfilesOrig, activeProfilesClone, - "The list of active profiles should have been cloned too but is same" ); + assertNotSame( + activeProfilesOrig, + activeProfilesClone, + "The list of active profiles should have been cloned too but is same"); } @Test - public void testCloneWithBaseDir() - throws Exception - { - File f = getFileForClasspathResource( "canonical-pom.xml" ); - MavenProject projectToClone = getProject( f ); - projectToClone.setPomFile( new File( new File( f.getParentFile(), "target" ), "flattened.xml" ) ); + public void testCloneWithBaseDir() throws Exception { + File f = getFileForClasspathResource("canonical-pom.xml"); + MavenProject projectToClone = getProject(f); + projectToClone.setPomFile(new File(new File(f.getParentFile(), "target"), "flattened.xml")); MavenProject clonedProject = projectToClone.clone(); - assertEquals( projectToClone.getFile(), clonedProject.getFile(), "POM file is preserved across clone" ); - assertEquals( projectToClone.getBasedir(), clonedProject.getBasedir(), "Base directory is preserved across clone" ); + assertEquals(projectToClone.getFile(), clonedProject.getFile(), "POM file is preserved across clone"); + assertEquals( + projectToClone.getBasedir(), clonedProject.getBasedir(), "Base directory is preserved across clone"); } @Test - public void testUndefinedOutputDirectory() - throws Exception - { + public void testUndefinedOutputDirectory() throws Exception { MavenProject p = new MavenProject(); - assertNoNulls( p.getCompileClasspathElements() ); - assertNoNulls( p.getSystemClasspathElements() ); - assertNoNulls( p.getRuntimeClasspathElements() ); - assertNoNulls( p.getTestClasspathElements() ); + assertNoNulls(p.getCompileClasspathElements()); + assertNoNulls(p.getSystemClasspathElements()); + assertNoNulls(p.getRuntimeClasspathElements()); + assertNoNulls(p.getTestClasspathElements()); } @Test - public void testAddDotFile() - { + public void testAddDotFile() { MavenProject project = new MavenProject(); - File basedir = new File( System.getProperty( "java.io.tmpdir" ) ); - project.setFile( new File( basedir, "file" ) ); + File basedir = new File(System.getProperty("java.io.tmpdir")); + project.setFile(new File(basedir, "file")); - project.addCompileSourceRoot( basedir.getAbsolutePath() ); - project.addCompileSourceRoot( "." ); + project.addCompileSourceRoot(basedir.getAbsolutePath()); + project.addCompileSourceRoot("."); - assertEquals( 1, project.getCompileSourceRoots().size() ); + assertEquals(1, project.getCompileSourceRoots().size()); } - private void assertNoNulls( List elements ) - { - assertFalse( elements.contains( null ) ); + private void assertNoNulls(List elements) { + assertFalse(elements.contains(null)); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/PomConstructionTest.java b/maven-core/src/test/java/org/apache/maven/project/PomConstructionTest.java index c2ab83cce7..0de6e361b8 100644 --- a/maven-core/src/test/java/org/apache/maven/project/PomConstructionTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/PomConstructionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,29 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.inject.Inject; - -import org.codehaus.plexus.testing.PlexusTest; -import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.PluginExecution; -import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.project.harness.PomTestWrapper; -import org.apache.maven.repository.RepositorySystem; -import org.apache.maven.repository.internal.MavenRepositorySystemUtils; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; -import org.eclipse.aether.repository.LocalRepository; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +package org.apache.maven.project; import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; import static org.hamcrest.MatcherAssert.assertThat; @@ -54,9 +30,29 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import javax.inject.Inject; +import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.model.building.ModelBuildingRequest; +import org.apache.maven.project.harness.PomTestWrapper; +import org.apache.maven.repository.RepositorySystem; +import org.apache.maven.repository.internal.MavenRepositorySystemUtils; +import org.codehaus.plexus.testing.PlexusTest; +import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; +import org.eclipse.aether.repository.LocalRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + @PlexusTest -public class PomConstructionTest -{ +public class PomConstructionTest { private static String BASE_DIR = "src/test"; private static String BASE_POM_DIR = BASE_DIR + "/resources-project-builder"; @@ -72,11 +68,9 @@ public class PomConstructionTest private File testDirectory; @BeforeEach - public void setUp() - throws Exception - { - testDirectory = new File( getBasedir(), BASE_POM_DIR ); - new File( getBasedir(), BASE_MIXIN_DIR ); + public void setUp() throws Exception { + testDirectory = new File(getBasedir(), BASE_POM_DIR); + new File(getBasedir(), BASE_MIXIN_DIR); } /** @@ -85,10 +79,8 @@ public class PomConstructionTest * @throws Exception in case of issue */ @Test - public void testEmptyUrl() - throws Exception - { - buildPom( "empty-distMng-repo-url" ); + public void testEmptyUrl() throws Exception { + buildPom("empty-distMng-repo-url"); } /** @@ -98,16 +90,14 @@ public class PomConstructionTest */ /* MNG-786*/ @Test - public void testProfileModules() - throws Exception - { - PomTestWrapper pom = buildPom( "profile-module", "a" ); - assertEquals( "test-prop", pom.getValue( "properties[1]/b" ) );// verifies profile applied - assertEquals( 4, ( (List) pom.getValue( "modules" ) ).size() ); - assertEquals( "module-2", pom.getValue( "modules[1]" ) ); - assertEquals( "module-1", pom.getValue( "modules[2]" ) ); - assertEquals( "module-3", pom.getValue( "modules[3]" ) ); - assertEquals( "module-4", pom.getValue( "modules[4]" ) ); + public void testProfileModules() throws Exception { + PomTestWrapper pom = buildPom("profile-module", "a"); + assertEquals("test-prop", pom.getValue("properties[1]/b")); // verifies profile applied + assertEquals(4, ((List) pom.getValue("modules")).size()); + assertEquals("module-2", pom.getValue("modules[1]")); + assertEquals("module-1", pom.getValue("modules[2]")); + assertEquals("module-3", pom.getValue("modules[3]")); + assertEquals("module-4", pom.getValue("modules[4]")); } /** @@ -116,52 +106,42 @@ public class PomConstructionTest * @throws Exception in case of issue */ @Test - public void testParentInheritance() - throws Exception - { - buildPom( "parent-inheritance/sub" ); + public void testParentInheritance() throws Exception { + buildPom("parent-inheritance/sub"); } /*MNG-3995*/ @Test - public void testExecutionConfigurationJoin() - throws Exception - { - PomTestWrapper pom = buildPom( "execution-configuration-join" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/fileset[1]" ) ).size() ); + public void testExecutionConfigurationJoin() throws Exception { + PomTestWrapper pom = buildPom("execution-configuration-join"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions[1]/configuration[1]/fileset[1]")).size()); } /*MNG-3803*/ @Test - public void testPluginConfigProperties() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-properties" ); - assertEquals( "my.property", pom.getValue( "build/plugins[1]/configuration[1]/systemProperties[1]/property[1]/name" ) ); + public void testPluginConfigProperties() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-properties"); + assertEquals( + "my.property", pom.getValue("build/plugins[1]/configuration[1]/systemProperties[1]/property[1]/name")); } /*MNG-3900*/ @Test - public void testProfilePropertiesInterpolation() - throws Exception - { - PomTestWrapper pom = buildPom( "profile-properties-interpolation", "interpolation-profile" ); - assertEquals( "PASSED", pom.getValue( "properties[1]/test" ) ); - assertEquals( "PASSED", pom.getValue( "properties[1]/property" ) ); + public void testProfilePropertiesInterpolation() throws Exception { + PomTestWrapper pom = buildPom("profile-properties-interpolation", "interpolation-profile"); + assertEquals("PASSED", pom.getValue("properties[1]/test")); + assertEquals("PASSED", pom.getValue("properties[1]/property")); } - // Some better conventions for the test poms needs to be created and each of these tests // that represent a verification of a specification item needs to be a couple lines at most. // The expressions help a lot, but we need a clean to pick up a directory of POMs, automatically load // them into a resolver, create the expression to extract the data to validate the Model, and the URI // to validate the properties. We also need a way to navigate from the Tex specification documents to // the test in question and vice versa. A little Eclipse plugin would do the trick. - public void testThatExecutionsWithoutIdsAreMergedAndTheChildWins() - throws Exception - { - PomTestWrapper tester = buildPom( "micromailer" ); - assertModelEquals( tester, "child-descriptor", "build/plugins[1]/executions[1]/goals[1]" ); + public void testThatExecutionsWithoutIdsAreMergedAndTheChildWins() throws Exception { + PomTestWrapper tester = buildPom("micromailer"); + assertModelEquals(tester, "child-descriptor", "build/plugins[1]/executions[1]/goals[1]"); } /*MNG- @@ -174,22 +154,16 @@ public class PomConstructionTest /*MNG- 4010*/ @Test - public void testDuplicateExclusionsDependency() - throws Exception - { - PomTestWrapper pom = buildPom( "duplicate-exclusions-dependency/sub" ); - assertEquals( 1, ( (List) pom.getValue( "dependencies[1]/exclusions" ) ).size() ); - + public void testDuplicateExclusionsDependency() throws Exception { + PomTestWrapper pom = buildPom("duplicate-exclusions-dependency/sub"); + assertEquals(1, ((List) pom.getValue("dependencies[1]/exclusions")).size()); } /*MNG- 4008*/ @Test - public void testMultipleFilters() - throws Exception - { - PomTestWrapper pom = buildPom( "multiple-filters" ); - assertEquals( 4, ( (List) pom.getValue( "build/filters" ) ).size() ); - + public void testMultipleFilters() throws Exception { + PomTestWrapper pom = buildPom("multiple-filters"); + assertEquals(4, ((List) pom.getValue("build/filters")).size()); } /* MNG-4005: postponed to 3.1 @@ -254,25 +228,21 @@ public class PomConstructionTest */ @Test - public void testDuplicateDependenciesCauseLastDeclarationToBePickedInLenientMode() - throws Exception - { - PomTestWrapper pom = buildPom( "unique-dependency-key/deps", true, null, null ); - assertEquals( 1, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "0.2", pom.getValue( "dependencies[1]/version" ) ); + public void testDuplicateDependenciesCauseLastDeclarationToBePickedInLenientMode() throws Exception { + PomTestWrapper pom = buildPom("unique-dependency-key/deps", true, null, null); + assertEquals(1, ((List) pom.getValue("dependencies")).size()); + assertEquals("0.2", pom.getValue("dependencies[1]/version")); } /* MNG-3567*/ @Test - public void testParentInterpolation() - throws Exception - { - PomTestWrapper pom = buildPom( "parent-interpolation/sub" ); - pom = new PomTestWrapper( pom.getMavenProject().getParent() ); - assertEquals( "1.3.0-SNAPSHOT", pom.getValue( "build/plugins[1]/version" ) ); + public void testParentInterpolation() throws Exception { + PomTestWrapper pom = buildPom("parent-interpolation/sub"); + pom = new PomTestWrapper(pom.getMavenProject().getParent()); + assertEquals("1.3.0-SNAPSHOT", pom.getValue("build/plugins[1]/version")); } -/* + /* public void testMaven() throws Exception { @@ -288,1653 +258,1450 @@ public class PomConstructionTest /* MNG-3567*/ @Test - public void testPluginManagementInherited() - throws Exception - { - PomTestWrapper pom = buildPom( "pluginmanagement-inherited/sub" ); - assertEquals( "1.0-alpha-21", pom.getValue( "build/plugins[1]/version" ) ); + public void testPluginManagementInherited() throws Exception { + PomTestWrapper pom = buildPom("pluginmanagement-inherited/sub"); + assertEquals("1.0-alpha-21", pom.getValue("build/plugins[1]/version")); } - /* MNG-2174*/ + /* MNG-2174*/ @Test - public void testPluginManagementDependencies() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-management-dependencies/sub", "test" ); - assertEquals( "1.0-alpha-21", pom.getValue( "build/plugins[1]/version" ) ); - assertEquals( "1.0", pom.getValue( "build/plugins[1]/dependencies[1]/version" ) ); + public void testPluginManagementDependencies() throws Exception { + PomTestWrapper pom = buildPom("plugin-management-dependencies/sub", "test"); + assertEquals("1.0-alpha-21", pom.getValue("build/plugins[1]/version")); + assertEquals("1.0", pom.getValue("build/plugins[1]/dependencies[1]/version")); } - /* MNG-3877*/ @Test - public void testReportingInterpolation() - throws Exception - { - PomTestWrapper pom = buildPom( "reporting-interpolation" ); - assertEquals( createPath( Arrays.asList( System.getProperty( "user.dir" ), "src", "test", - "resources-project-builder", "reporting-interpolation", "target", - "site" ) ), pom.getValue( "reporting/outputDirectory" ) ); + public void testReportingInterpolation() throws Exception { + PomTestWrapper pom = buildPom("reporting-interpolation"); + assertEquals( + createPath(Arrays.asList( + System.getProperty("user.dir"), + "src", + "test", + "resources-project-builder", + "reporting-interpolation", + "target", + "site")), + pom.getValue("reporting/outputDirectory")); } @Test - public void testPluginOrder() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-order" ); - assertEquals( "plexus-component-metadata", pom.getValue( "build/plugins[1]/artifactId" ) ); - assertEquals( "maven-surefire-plugin", pom.getValue( "build/plugins[2]/artifactId" ) ); + public void testPluginOrder() throws Exception { + PomTestWrapper pom = buildPom("plugin-order"); + assertEquals("plexus-component-metadata", pom.getValue("build/plugins[1]/artifactId")); + assertEquals("maven-surefire-plugin", pom.getValue("build/plugins[2]/artifactId")); } @Test - public void testErroneousJoiningOfDifferentPluginsWithEqualDependencies() - throws Exception - { - PomTestWrapper pom = buildPom( "equal-plugin-deps" ); - assertEquals( "maven-it-plugin-a", pom.getValue( "build/plugins[1]/artifactId" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/dependencies" ) ).size() ); - assertEquals( "maven-it-plugin-b", pom.getValue( "build/plugins[2]/artifactId" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/dependencies" ) ).size() ); + public void testErroneousJoiningOfDifferentPluginsWithEqualDependencies() throws Exception { + PomTestWrapper pom = buildPom("equal-plugin-deps"); + assertEquals("maven-it-plugin-a", pom.getValue("build/plugins[1]/artifactId")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/dependencies")).size()); + assertEquals("maven-it-plugin-b", pom.getValue("build/plugins[2]/artifactId")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/dependencies")).size()); } /** MNG-3821 */ @Test - public void testErroneousJoiningOfDifferentPluginsWithEqualExecutionIds() - throws Exception - { - PomTestWrapper pom = buildPom( "equal-plugin-exec-ids" ); - assertEquals( "maven-it-plugin-a", pom.getValue( "build/plugins[1]/artifactId" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "maven-it-plugin-b", pom.getValue( "build/plugins[2]/artifactId" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "maven-it-plugin-a", pom.getValue( "reporting/plugins[1]/artifactId" ) ); - assertEquals( 1, ( (List) pom.getValue( "reporting/plugins[1]/reportSets" ) ).size() ); - assertEquals( "maven-it-plugin-b", pom.getValue( "reporting/plugins[2]/artifactId" ) ); - assertEquals( 1, ( (List) pom.getValue( "reporting/plugins[1]/reportSets" ) ).size() ); + public void testErroneousJoiningOfDifferentPluginsWithEqualExecutionIds() throws Exception { + PomTestWrapper pom = buildPom("equal-plugin-exec-ids"); + assertEquals("maven-it-plugin-a", pom.getValue("build/plugins[1]/artifactId")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("maven-it-plugin-b", pom.getValue("build/plugins[2]/artifactId")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("maven-it-plugin-a", pom.getValue("reporting/plugins[1]/artifactId")); + assertEquals(1, ((List) pom.getValue("reporting/plugins[1]/reportSets")).size()); + assertEquals("maven-it-plugin-b", pom.getValue("reporting/plugins[2]/artifactId")); + assertEquals(1, ((List) pom.getValue("reporting/plugins[1]/reportSets")).size()); } - /** MNG-3998 */ + /** MNG-3998 */ @Test - public void testExecutionConfiguration() - throws Exception - { - PomTestWrapper pom = buildPom( "execution-configuration" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "src/main/mdo/nexus.xml", - ( pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/model" ) ) ); - assertEquals( "src/main/mdo/security.xml", - ( pom.getValue( "build/plugins[1]/executions[2]/configuration[1]/model" ) ) ); + public void testExecutionConfiguration() throws Exception { + PomTestWrapper pom = buildPom("execution-configuration"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("src/main/mdo/nexus.xml", (pom.getValue("build/plugins[1]/executions[1]/configuration[1]/model"))); + assertEquals( + "src/main/mdo/security.xml", (pom.getValue("build/plugins[1]/executions[2]/configuration[1]/model"))); } /* - public void testPluginConfigDuplicate() - throws Exception -{ - PomTestWrapper pom = buildPom( "plugin-config-duplicate/dup" ); -} -*/ - @Test - public void testSingleConfigurationInheritance() + public void testPluginConfigDuplicate() throws Exception { - PomTestWrapper pom = buildPom( "single-configuration-inheritance" ); + PomTestWrapper pom = buildPom( "plugin-config-duplicate/dup" ); + } + */ + @Test + public void testSingleConfigurationInheritance() throws Exception { + PomTestWrapper pom = buildPom("single-configuration-inheritance"); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/rules" ) ).size() ); - assertEquals( "2.0.6", - pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/rules[1]/requireMavenVersion[1]/version" ) ); - assertEquals( "[1.4,)", - pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/rules[1]/requireJavaVersion[1]/version" ) ); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions[1]/configuration[1]/rules")).size()); + assertEquals( + "2.0.6", + pom.getValue( + "build/plugins[1]/executions[1]/configuration[1]/rules[1]/requireMavenVersion[1]/version")); + assertEquals( + "[1.4,)", + pom.getValue("build/plugins[1]/executions[1]/configuration[1]/rules[1]/requireJavaVersion[1]/version")); } @Test - public void testConfigWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "config-with-plugin-mng" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "src/main/mdo/security.xml", pom.getValue( "build/plugins[1]/executions[2]/configuration[1]/model" ) ); - assertEquals( "1.0.8", pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/version" ) ); + public void testConfigWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("config-with-plugin-mng"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals( + "src/main/mdo/security.xml", pom.getValue("build/plugins[1]/executions[2]/configuration[1]/model")); + assertEquals("1.0.8", pom.getValue("build/plugins[1]/executions[1]/configuration[1]/version")); } /** MNG-3965 */ @Test - public void testExecutionConfigurationSubcollections() - throws Exception - { - PomTestWrapper pom = buildPom( "execution-configuration-subcollections" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions[1]/configuration[1]/rules[1]/bannedDependencies" ) ).size() ); + public void testExecutionConfigurationSubcollections() throws Exception { + PomTestWrapper pom = buildPom("execution-configuration-subcollections"); + assertEquals( + 2, + ((List) pom.getValue("build/plugins[1]/executions[1]/configuration[1]/rules[1]/bannedDependencies")) + .size()); } /** MNG-3985 */ @Test - public void testMultipleRepositories() - throws Exception - { - PomTestWrapper pom = buildPom( "multiple-repos/sub" ); - assertEquals( 3, ( (List) pom.getValue( "repositories" ) ).size() ); + public void testMultipleRepositories() throws Exception { + PomTestWrapper pom = buildPom("multiple-repos/sub"); + assertEquals(3, ((List) pom.getValue("repositories")).size()); } /** MNG-3965 */ @Test - public void testMultipleExecutionIds() - throws Exception - { - PomTestWrapper pom = buildPom( "dual-execution-ids/sub" ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); + public void testMultipleExecutionIds() throws Exception { + PomTestWrapper pom = buildPom("dual-execution-ids/sub"); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/executions")).size()); } /** MNG-3997 */ @Test - public void testConsecutiveEmptyElements() - throws Exception - { - buildPom( "consecutive_empty_elements" ); + public void testConsecutiveEmptyElements() throws Exception { + buildPom("consecutive_empty_elements"); } @Test - public void testOrderOfGoalsFromPluginExecutionWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-goals-order/wo-plugin-mgmt" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions[1]/goals" ) ).size() ); - assertEquals( "b", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "a", pom.getValue( "build/plugins[1]/executions[1]/goals[2]" ) ); - assertEquals( "d", pom.getValue( "build/plugins[1]/executions[1]/goals[3]" ) ); - assertEquals( "c", pom.getValue( "build/plugins[1]/executions[1]/goals[4]" ) ); - assertEquals( "e", pom.getValue( "build/plugins[1]/executions[1]/goals[5]" ) ); + public void testOrderOfGoalsFromPluginExecutionWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-goals-order/wo-plugin-mgmt"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions[1]/goals")).size()); + assertEquals("b", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("a", pom.getValue("build/plugins[1]/executions[1]/goals[2]")); + assertEquals("d", pom.getValue("build/plugins[1]/executions[1]/goals[3]")); + assertEquals("c", pom.getValue("build/plugins[1]/executions[1]/goals[4]")); + assertEquals("e", pom.getValue("build/plugins[1]/executions[1]/goals[5]")); } /* MNG-3886*/ @Test - public void testOrderOfGoalsFromPluginExecutionWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-goals-order/w-plugin-mgmt" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions[1]/goals" ) ).size() ); - assertEquals( "b", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "a", pom.getValue( "build/plugins[1]/executions[1]/goals[2]" ) ); - assertEquals( "d", pom.getValue( "build/plugins[1]/executions[1]/goals[3]" ) ); - assertEquals( "c", pom.getValue( "build/plugins[1]/executions[1]/goals[4]" ) ); - assertEquals( "e", pom.getValue( "build/plugins[1]/executions[1]/goals[5]" ) ); + public void testOrderOfGoalsFromPluginExecutionWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-goals-order/w-plugin-mgmt"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions[1]/goals")).size()); + assertEquals("b", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("a", pom.getValue("build/plugins[1]/executions[1]/goals[2]")); + assertEquals("d", pom.getValue("build/plugins[1]/executions[1]/goals[3]")); + assertEquals("c", pom.getValue("build/plugins[1]/executions[1]/goals[4]")); + assertEquals("e", pom.getValue("build/plugins[1]/executions[1]/goals[5]")); } @Test - public void testOrderOfPluginExecutionsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-order/wo-plugin-mgmt" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "b", pom.getValue( "build/plugins[1]/executions[1]/id" ) ); - assertEquals( "a", pom.getValue( "build/plugins[1]/executions[2]/id" ) ); - assertEquals( "d", pom.getValue( "build/plugins[1]/executions[3]/id" ) ); - assertEquals( "c", pom.getValue( "build/plugins[1]/executions[4]/id" ) ); - assertEquals( "e", pom.getValue( "build/plugins[1]/executions[5]/id" ) ); + public void testOrderOfPluginExecutionsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-order/wo-plugin-mgmt"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("b", pom.getValue("build/plugins[1]/executions[1]/id")); + assertEquals("a", pom.getValue("build/plugins[1]/executions[2]/id")); + assertEquals("d", pom.getValue("build/plugins[1]/executions[3]/id")); + assertEquals("c", pom.getValue("build/plugins[1]/executions[4]/id")); + assertEquals("e", pom.getValue("build/plugins[1]/executions[5]/id")); } /* MNG-3887 */ @Test - public void testOrderOfPluginExecutionsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-order/w-plugin-mgmt" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "b", pom.getValue( "build/plugins[1]/executions[1]/id" ) ); - assertEquals( "a", pom.getValue( "build/plugins[1]/executions[2]/id" ) ); - assertEquals( "d", pom.getValue( "build/plugins[1]/executions[3]/id" ) ); - assertEquals( "c", pom.getValue( "build/plugins[1]/executions[4]/id" ) ); - assertEquals( "e", pom.getValue( "build/plugins[1]/executions[5]/id" ) ); + public void testOrderOfPluginExecutionsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-order/w-plugin-mgmt"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("b", pom.getValue("build/plugins[1]/executions[1]/id")); + assertEquals("a", pom.getValue("build/plugins[1]/executions[2]/id")); + assertEquals("d", pom.getValue("build/plugins[1]/executions[3]/id")); + assertEquals("c", pom.getValue("build/plugins[1]/executions[4]/id")); + assertEquals("e", pom.getValue("build/plugins[1]/executions[5]/id")); } @Test - public void testMergeOfPluginExecutionsWhenChildInheritsPluginVersion() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-merging-wo-version/sub" ); - assertEquals( 4, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); + public void testMergeOfPluginExecutionsWhenChildInheritsPluginVersion() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-merging-wo-version/sub"); + assertEquals(4, ((List) pom.getValue("build/plugins[1]/executions")).size()); } /* MNG-3943*/ @Test - public void testMergeOfPluginExecutionsWhenChildAndParentUseDifferentPluginVersions() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-merging-version-insensitive/sub" ); - assertEquals( 4, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); + public void testMergeOfPluginExecutionsWhenChildAndParentUseDifferentPluginVersions() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-merging-version-insensitive/sub"); + assertEquals(4, ((List) pom.getValue("build/plugins[1]/executions")).size()); } - @Test - public void testInterpolationWithXmlMarkup() - throws Exception - { - PomTestWrapper pom = buildPom( "xml-markup-interpolation" ); - assertEquals( "Tom&Jerry", pom.getValue( "properties/xmlTest" ) ); + public void testInterpolationWithXmlMarkup() throws Exception { + PomTestWrapper pom = buildPom("xml-markup-interpolation"); + assertEquals("Tom&Jerry", pom.getValue("properties/xmlTest")); } /* MNG-3925 */ @Test - public void testOrderOfMergedPluginExecutionsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-plugin-exec-order/wo-plugin-mgmt/sub" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "parent-1", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "parent-2", pom.getValue( "build/plugins[1]/executions[2]/goals[1]" ) ); - assertEquals( "child-default", pom.getValue( "build/plugins[1]/executions[3]/goals[1]" ) ); - assertEquals( "child-1", pom.getValue( "build/plugins[1]/executions[4]/goals[1]" ) ); - assertEquals( "child-2", pom.getValue( "build/plugins[1]/executions[5]/goals[1]" ) ); + public void testOrderOfMergedPluginExecutionsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("merged-plugin-exec-order/wo-plugin-mgmt/sub"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("parent-1", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("parent-2", pom.getValue("build/plugins[1]/executions[2]/goals[1]")); + assertEquals("child-default", pom.getValue("build/plugins[1]/executions[3]/goals[1]")); + assertEquals("child-1", pom.getValue("build/plugins[1]/executions[4]/goals[1]")); + assertEquals("child-2", pom.getValue("build/plugins[1]/executions[5]/goals[1]")); } @Test - public void testOrderOfMergedPluginExecutionsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-plugin-exec-order/w-plugin-mgmt/sub" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "parent-1", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "parent-2", pom.getValue( "build/plugins[1]/executions[2]/goals[1]" ) ); - assertEquals( "child-default", pom.getValue( "build/plugins[1]/executions[3]/goals[1]" ) ); - assertEquals( "child-1", pom.getValue( "build/plugins[1]/executions[4]/goals[1]" ) ); - assertEquals( "child-2", pom.getValue( "build/plugins[1]/executions[5]/goals[1]" ) ); + public void testOrderOfMergedPluginExecutionsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("merged-plugin-exec-order/w-plugin-mgmt/sub"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("parent-1", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("parent-2", pom.getValue("build/plugins[1]/executions[2]/goals[1]")); + assertEquals("child-default", pom.getValue("build/plugins[1]/executions[3]/goals[1]")); + assertEquals("child-1", pom.getValue("build/plugins[1]/executions[4]/goals[1]")); + assertEquals("child-2", pom.getValue("build/plugins[1]/executions[5]/goals[1]")); } /* MNG-3984*/ @Test - public void testDifferentContainersWithSameId() - throws Exception - { - PomTestWrapper pom = buildPom( "join-different-containers-same-id" ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/executions[1]/goals" ) ).size() ); - assertEquals( 1, ( (List) pom.getValue( "build/pluginManagement/plugins[@artifactId='maven-it-plugin-b']/executions[1]/goals" ) ).size() ); + public void testDifferentContainersWithSameId() throws Exception { + PomTestWrapper pom = buildPom("join-different-containers-same-id"); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/executions[1]/goals")).size()); + assertEquals( + 1, + ((List) pom.getValue( + "build/pluginManagement/plugins[@artifactId='maven-it-plugin-b']/executions[1]/goals")) + .size()); } /* MNG-3937*/ @Test - public void testOrderOfMergedPluginExecutionGoalsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-plugin-exec-goals-order/wo-plugin-mgmt/sub" ); + public void testOrderOfMergedPluginExecutionGoalsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("merged-plugin-exec-goals-order/wo-plugin-mgmt/sub"); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions[1]/goals" ) ).size() ); - assertEquals( "child-a", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "merged", pom.getValue( "build/plugins[1]/executions[1]/goals[2]" ) ); - assertEquals( "child-b", pom.getValue( "build/plugins[1]/executions[1]/goals[3]" ) ); - assertEquals( "parent-b", pom.getValue( "build/plugins[1]/executions[1]/goals[4]" ) ); - assertEquals( "parent-a", pom.getValue( "build/plugins[1]/executions[1]/goals[5]" ) ); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions[1]/goals")).size()); + assertEquals("child-a", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("merged", pom.getValue("build/plugins[1]/executions[1]/goals[2]")); + assertEquals("child-b", pom.getValue("build/plugins[1]/executions[1]/goals[3]")); + assertEquals("parent-b", pom.getValue("build/plugins[1]/executions[1]/goals[4]")); + assertEquals("parent-a", pom.getValue("build/plugins[1]/executions[1]/goals[5]")); } @Test - public void testOrderOfMergedPluginExecutionGoalsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-plugin-exec-goals-order/w-plugin-mgmt/sub" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/executions[1]/goals" ) ).size() ); - assertEquals( "child-a", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "merged", pom.getValue( "build/plugins[1]/executions[1]/goals[2]" ) ); - assertEquals( "child-b", pom.getValue( "build/plugins[1]/executions[1]/goals[3]" ) ); - assertEquals( "parent-b", pom.getValue( "build/plugins[1]/executions[1]/goals[4]" ) ); - assertEquals( "parent-a", pom.getValue( "build/plugins[1]/executions[1]/goals[5]" ) ); + public void testOrderOfMergedPluginExecutionGoalsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("merged-plugin-exec-goals-order/w-plugin-mgmt/sub"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/executions[1]/goals")).size()); + assertEquals("child-a", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("merged", pom.getValue("build/plugins[1]/executions[1]/goals[2]")); + assertEquals("child-b", pom.getValue("build/plugins[1]/executions[1]/goals[3]")); + assertEquals("parent-b", pom.getValue("build/plugins[1]/executions[1]/goals[4]")); + assertEquals("parent-a", pom.getValue("build/plugins[1]/executions[1]/goals[5]")); } /*MNG-3938*/ @Test - public void testOverridingOfInheritedPluginExecutionsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-merging/wo-plugin-mgmt/sub" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "child-default", pom.getValue( "build/plugins[1]/executions[@id='default']/phase" ) ); - assertEquals( "child-non-default", pom.getValue( "build/plugins[1]/executions[@id='non-default']/phase" ) ); + public void testOverridingOfInheritedPluginExecutionsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-merging/wo-plugin-mgmt/sub"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("child-default", pom.getValue("build/plugins[1]/executions[@id='default']/phase")); + assertEquals("child-non-default", pom.getValue("build/plugins[1]/executions[@id='non-default']/phase")); } /* MNG-3938 */ @Test - public void testOverridingOfInheritedPluginExecutionsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-merging/w-plugin-mgmt/sub" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "child-default", pom.getValue( "build/plugins[1]/executions[@id='default']/phase" ) ); - assertEquals( "child-non-default", pom.getValue( "build/plugins[1]/executions[@id='non-default']/phase" ) ); + public void testOverridingOfInheritedPluginExecutionsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-merging/w-plugin-mgmt/sub"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("child-default", pom.getValue("build/plugins[1]/executions[@id='default']/phase")); + assertEquals("child-non-default", pom.getValue("build/plugins[1]/executions[@id='non-default']/phase")); } - /* MNG-3906*/ @Test - public void testOrderOfMergedPluginDependenciesWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-plugin-class-path-order/wo-plugin-mgmt/sub" ); + public void testOrderOfMergedPluginDependenciesWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("merged-plugin-class-path-order/wo-plugin-mgmt/sub"); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/dependencies" ) ).size() ); - assertNotNull( pom.getValue( "build/plugins[1]/dependencies[1]" ) ); - assertEquals( "c", pom.getValue( "build/plugins[1]/dependencies[1]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[1]/version" ) ); - assertEquals( "a", pom.getValue( "build/plugins[1]/dependencies[2]/artifactId" ) ); - assertEquals( "2", pom.getValue( "build/plugins[1]/dependencies[2]/version" ) ); - assertEquals( "b", pom.getValue( "build/plugins[1]/dependencies[3]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[3]/version" ) ); - assertEquals( "e", pom.getValue( "build/plugins[1]/dependencies[4]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[4]/version" ) ); - assertEquals( "d", pom.getValue( "build/plugins[1]/dependencies[5]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[5]/version" ) ); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/dependencies")).size()); + assertNotNull(pom.getValue("build/plugins[1]/dependencies[1]")); + assertEquals("c", pom.getValue("build/plugins[1]/dependencies[1]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[1]/version")); + assertEquals("a", pom.getValue("build/plugins[1]/dependencies[2]/artifactId")); + assertEquals("2", pom.getValue("build/plugins[1]/dependencies[2]/version")); + assertEquals("b", pom.getValue("build/plugins[1]/dependencies[3]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[3]/version")); + assertEquals("e", pom.getValue("build/plugins[1]/dependencies[4]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[4]/version")); + assertEquals("d", pom.getValue("build/plugins[1]/dependencies[5]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[5]/version")); } @Test - public void testOrderOfMergedPluginDependenciesWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-plugin-class-path-order/w-plugin-mgmt/sub" ); - assertEquals( 5, ( (List) pom.getValue( "build/plugins[1]/dependencies" ) ).size() ); - assertEquals( "c", pom.getValue( "build/plugins[1]/dependencies[1]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[1]/version" ) ); - assertEquals( "a", pom.getValue( "build/plugins[1]/dependencies[2]/artifactId" ) ); - assertEquals( "2", pom.getValue( "build/plugins[1]/dependencies[2]/version" ) ); - assertEquals( "b", pom.getValue( "build/plugins[1]/dependencies[3]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[3]/version" ) ); - assertEquals( "e", pom.getValue( "build/plugins[1]/dependencies[4]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[4]/version" ) ); - assertEquals( "d", pom.getValue( "build/plugins[1]/dependencies[5]/artifactId" ) ); - assertEquals( "1", pom.getValue( "build/plugins[1]/dependencies[5]/version" ) ); + public void testOrderOfMergedPluginDependenciesWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("merged-plugin-class-path-order/w-plugin-mgmt/sub"); + assertEquals(5, ((List) pom.getValue("build/plugins[1]/dependencies")).size()); + assertEquals("c", pom.getValue("build/plugins[1]/dependencies[1]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[1]/version")); + assertEquals("a", pom.getValue("build/plugins[1]/dependencies[2]/artifactId")); + assertEquals("2", pom.getValue("build/plugins[1]/dependencies[2]/version")); + assertEquals("b", pom.getValue("build/plugins[1]/dependencies[3]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[3]/version")); + assertEquals("e", pom.getValue("build/plugins[1]/dependencies[4]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[4]/version")); + assertEquals("d", pom.getValue("build/plugins[1]/dependencies[5]/artifactId")); + assertEquals("1", pom.getValue("build/plugins[1]/dependencies[5]/version")); } @Test - public void testInterpolationOfNestedBuildDirectories() - throws Exception - { - PomTestWrapper pom = buildPom( "nested-build-dir-interpolation" ); - assertEquals( new File( pom.getBasedir(), "target/classes/dir0" ), - new File( (String) pom.getValue( "properties/dir0" ) ) ); - assertEquals( new File( pom.getBasedir(), "src/test/dir1" ), - new File( (String) pom.getValue( "properties/dir1" ) ) ); - assertEquals( new File( pom.getBasedir(), "target/site/dir2" ), - new File( (String) pom.getValue( "properties/dir2" ) ) ); + public void testInterpolationOfNestedBuildDirectories() throws Exception { + PomTestWrapper pom = buildPom("nested-build-dir-interpolation"); + assertEquals( + new File(pom.getBasedir(), "target/classes/dir0"), new File((String) pom.getValue("properties/dir0"))); + assertEquals(new File(pom.getBasedir(), "src/test/dir1"), new File((String) pom.getValue("properties/dir1"))); + assertEquals( + new File(pom.getBasedir(), "target/site/dir2"), new File((String) pom.getValue("properties/dir2"))); } @Test - public void testAppendArtifactIdOfChildToInheritedUrls() - throws Exception - { - PomTestWrapper pom = buildPom( "url-inheritance/sub" ); - assertEquals( "https://parent.url/child", pom.getValue( "url" ) ); - assertEquals( "https://parent.url/org", pom.getValue( "organization/url" ) ); - assertEquals( "https://parent.url/license.txt", pom.getValue( "licenses[1]/url" ) ); - assertEquals( "https://parent.url/viewvc/child", pom.getValue( "scm/url" ) ); - assertEquals( "https://parent.url/scm/child", pom.getValue( "scm/connection" ) ); - assertEquals( "https://parent.url/scm/child", pom.getValue( "scm/developerConnection" ) ); - assertEquals( "https://parent.url/issues", pom.getValue( "issueManagement/url" ) ); - assertEquals( "https://parent.url/ci", pom.getValue( "ciManagement/url" ) ); - assertEquals( "https://parent.url/dist", pom.getValue( "distributionManagement/repository/url" ) ); - assertEquals( "https://parent.url/snaps", pom.getValue( "distributionManagement/snapshotRepository/url" ) ); - assertEquals( "https://parent.url/site/child", pom.getValue( "distributionManagement/site/url" ) ); - assertEquals( "https://parent.url/download", pom.getValue( "distributionManagement/downloadUrl" ) ); + public void testAppendArtifactIdOfChildToInheritedUrls() throws Exception { + PomTestWrapper pom = buildPom("url-inheritance/sub"); + assertEquals("https://parent.url/child", pom.getValue("url")); + assertEquals("https://parent.url/org", pom.getValue("organization/url")); + assertEquals("https://parent.url/license.txt", pom.getValue("licenses[1]/url")); + assertEquals("https://parent.url/viewvc/child", pom.getValue("scm/url")); + assertEquals("https://parent.url/scm/child", pom.getValue("scm/connection")); + assertEquals("https://parent.url/scm/child", pom.getValue("scm/developerConnection")); + assertEquals("https://parent.url/issues", pom.getValue("issueManagement/url")); + assertEquals("https://parent.url/ci", pom.getValue("ciManagement/url")); + assertEquals("https://parent.url/dist", pom.getValue("distributionManagement/repository/url")); + assertEquals("https://parent.url/snaps", pom.getValue("distributionManagement/snapshotRepository/url")); + assertEquals("https://parent.url/site/child", pom.getValue("distributionManagement/site/url")); + assertEquals("https://parent.url/download", pom.getValue("distributionManagement/downloadUrl")); } /* MNG-3846*/ @Test - public void testAppendArtifactIdOfParentAndChildToInheritedUrls() - throws Exception - { - PomTestWrapper pom = buildPom( "url-inheritance/another-parent/sub" ); - assertEquals( "https://parent.url/ap/child", pom.getValue( "url" ) ); - assertEquals( "https://parent.url/org", pom.getValue( "organization/url" ) ); - assertEquals( "https://parent.url/license.txt", pom.getValue( "licenses[1]/url" ) ); - assertEquals( "https://parent.url/viewvc/ap/child", pom.getValue( "scm/url" ) ); - assertEquals( "https://parent.url/scm/ap/child", pom.getValue( "scm/connection" ) ); - assertEquals( "https://parent.url/scm/ap/child", pom.getValue( "scm/developerConnection" ) ); - assertEquals( "https://parent.url/issues", pom.getValue( "issueManagement/url" ) ); - assertEquals( "https://parent.url/ci", pom.getValue( "ciManagement/url" ) ); - assertEquals( "https://parent.url/dist", pom.getValue( "distributionManagement/repository/url" ) ); - assertEquals( "https://parent.url/snaps", pom.getValue( "distributionManagement/snapshotRepository/url" ) ); - assertEquals( "https://parent.url/site/ap/child", pom.getValue( "distributionManagement/site/url" ) ); - assertEquals( "https://parent.url/download", pom.getValue( "distributionManagement/downloadUrl" ) ); + public void testAppendArtifactIdOfParentAndChildToInheritedUrls() throws Exception { + PomTestWrapper pom = buildPom("url-inheritance/another-parent/sub"); + assertEquals("https://parent.url/ap/child", pom.getValue("url")); + assertEquals("https://parent.url/org", pom.getValue("organization/url")); + assertEquals("https://parent.url/license.txt", pom.getValue("licenses[1]/url")); + assertEquals("https://parent.url/viewvc/ap/child", pom.getValue("scm/url")); + assertEquals("https://parent.url/scm/ap/child", pom.getValue("scm/connection")); + assertEquals("https://parent.url/scm/ap/child", pom.getValue("scm/developerConnection")); + assertEquals("https://parent.url/issues", pom.getValue("issueManagement/url")); + assertEquals("https://parent.url/ci", pom.getValue("ciManagement/url")); + assertEquals("https://parent.url/dist", pom.getValue("distributionManagement/repository/url")); + assertEquals("https://parent.url/snaps", pom.getValue("distributionManagement/snapshotRepository/url")); + assertEquals("https://parent.url/site/ap/child", pom.getValue("distributionManagement/site/url")); + assertEquals("https://parent.url/download", pom.getValue("distributionManagement/downloadUrl")); } @Test - public void testNonInheritedElementsInSubtreesOverriddenByChild() - throws Exception - { - PomTestWrapper pom = buildPom( "limited-inheritance/child" ); - assertNull( pom.getValue( "organization/url" ) ); - assertNull( pom.getValue( "issueManagement/system" ) ); - assertEquals( 0, ( (List) pom.getValue( "ciManagement/notifiers" ) ).size() ); - assertEquals( "child-distros", pom.getValue( "distributionManagement/repository/id" ) ); - assertEquals( "ssh://child.url/distros", pom.getValue( "distributionManagement/repository/url" ) ); - assertNull( pom.getValue( "distributionManagement/repository/name" ) ); - assertEquals( true, pom.getValue( "distributionManagement/repository/uniqueVersion" ) ); - assertEquals( "default", pom.getValue( "distributionManagement/repository/layout" ) ); - assertEquals( "child-snaps", pom.getValue( "distributionManagement/snapshotRepository/id" ) ); - assertEquals( "ssh://child.url/snaps", pom.getValue( "distributionManagement/snapshotRepository/url" ) ); - assertNull( pom.getValue( "distributionManagement/snapshotRepository/name" ) ); - assertEquals( true, pom.getValue( "distributionManagement/snapshotRepository/uniqueVersion" ) ); - assertEquals( "default", pom.getValue( "distributionManagement/snapshotRepository/layout" ) ); - assertEquals( "child-site", pom.getValue( "distributionManagement/site/id" ) ); - assertEquals( "scp://child.url/site", pom.getValue( "distributionManagement/site/url" ) ); - assertNull( pom.getValue( "distributionManagement/site/name" ) ); + public void testNonInheritedElementsInSubtreesOverriddenByChild() throws Exception { + PomTestWrapper pom = buildPom("limited-inheritance/child"); + assertNull(pom.getValue("organization/url")); + assertNull(pom.getValue("issueManagement/system")); + assertEquals(0, ((List) pom.getValue("ciManagement/notifiers")).size()); + assertEquals("child-distros", pom.getValue("distributionManagement/repository/id")); + assertEquals("ssh://child.url/distros", pom.getValue("distributionManagement/repository/url")); + assertNull(pom.getValue("distributionManagement/repository/name")); + assertEquals(true, pom.getValue("distributionManagement/repository/uniqueVersion")); + assertEquals("default", pom.getValue("distributionManagement/repository/layout")); + assertEquals("child-snaps", pom.getValue("distributionManagement/snapshotRepository/id")); + assertEquals("ssh://child.url/snaps", pom.getValue("distributionManagement/snapshotRepository/url")); + assertNull(pom.getValue("distributionManagement/snapshotRepository/name")); + assertEquals(true, pom.getValue("distributionManagement/snapshotRepository/uniqueVersion")); + assertEquals("default", pom.getValue("distributionManagement/snapshotRepository/layout")); + assertEquals("child-site", pom.getValue("distributionManagement/site/id")); + assertEquals("scp://child.url/site", pom.getValue("distributionManagement/site/url")); + assertNull(pom.getValue("distributionManagement/site/name")); } @Test - public void testXmlTextCoalescing() - throws Exception - { - PomTestWrapper pom = buildPom( "xml-coalesce-text" ); - assertEquals( "A Test Project Property", pom.getValue( "properties/prop0" ) ); - assertEquals( "That's a test!", pom.getValue( "properties/prop1" ) ); - assertEquals( 32 * 1024, - pom.getValue( "properties/prop2" ).toString().trim().replaceAll( "[\n\r]", "" ).length() ); + public void testXmlTextCoalescing() throws Exception { + PomTestWrapper pom = buildPom("xml-coalesce-text"); + assertEquals("A Test Project Property", pom.getValue("properties/prop0")); + assertEquals("That's a test!", pom.getValue("properties/prop1")); + assertEquals( + 32 * 1024, + pom.getValue("properties/prop2") + .toString() + .trim() + .replaceAll("[\n\r]", "") + .length()); } @Test - public void testFullInterpolationOfNestedExpressions() - throws Exception - { - PomTestWrapper pom = buildPom( "full-interpolation" ); - for ( int i = 0; i < 24; i++ ) - { - String index = ( ( i < 10 ) ? "0" : "" ) + i; - assertEquals( "PASSED", pom.getValue( "properties/property" + index ) ); + public void testFullInterpolationOfNestedExpressions() throws Exception { + PomTestWrapper pom = buildPom("full-interpolation"); + for (int i = 0; i < 24; i++) { + String index = ((i < 10) ? "0" : "") + i; + assertEquals("PASSED", pom.getValue("properties/property" + index)); } } - @Test - public void testInterpolationWithBasedirAlignedDirectories() - throws Exception - { - PomTestWrapper pom = buildPom( "basedir-aligned-interpolation" ); - assertEquals( new File( pom.getBasedir(), "src/main/java" ), - new File( pom.getValue( "properties/buildMainSrc" ).toString() ) ); - assertEquals( new File( pom.getBasedir(), "src/test/java" ), - new File( pom.getValue( "properties/buildTestSrc" ).toString() ) ); - assertEquals( new File( pom.getBasedir(), "src/main/scripts" ), - new File( pom.getValue( "properties/buildScriptSrc" ).toString() ) ); - assertEquals( new File( pom.getBasedir(), "target" ), - new File( pom.getValue( "properties/buildOut" ).toString() ) ); - assertEquals( new File( pom.getBasedir(), "target/classes" ), - new File( pom.getValue( "properties/buildMainOut" ).toString() ) ); - assertEquals( new File( pom.getBasedir(), "target/test-classes" ), - new File( pom.getValue( "properties/buildTestOut" ).toString() ) ); - assertEquals( new File( pom.getBasedir(), "target/site" ), - new File( pom.getValue( "properties/siteOut" ).toString() ) ); + public void testInterpolationWithBasedirAlignedDirectories() throws Exception { + PomTestWrapper pom = buildPom("basedir-aligned-interpolation"); + assertEquals( + new File(pom.getBasedir(), "src/main/java"), + new File(pom.getValue("properties/buildMainSrc").toString())); + assertEquals( + new File(pom.getBasedir(), "src/test/java"), + new File(pom.getValue("properties/buildTestSrc").toString())); + assertEquals( + new File(pom.getBasedir(), "src/main/scripts"), + new File(pom.getValue("properties/buildScriptSrc").toString())); + assertEquals( + new File(pom.getBasedir(), "target"), + new File(pom.getValue("properties/buildOut").toString())); + assertEquals( + new File(pom.getBasedir(), "target/classes"), + new File(pom.getValue("properties/buildMainOut").toString())); + assertEquals( + new File(pom.getBasedir(), "target/test-classes"), + new File(pom.getValue("properties/buildTestOut").toString())); + assertEquals( + new File(pom.getBasedir(), "target/site"), + new File(pom.getValue("properties/siteOut").toString())); } /* MNG-3944*/ @Test - public void testInterpolationOfBasedirInPomWithUnusualName() - throws Exception - { - PomTestWrapper pom = buildPom( "basedir-interpolation/pom-with-unusual-name.xml" ); - assertEquals( pom.getBasedir(), new File( pom.getValue( "properties/prop0" ).toString() ) ); - assertEquals( pom.getBasedir(), new File( pom.getValue( "properties/prop1" ).toString() ) ); + public void testInterpolationOfBasedirInPomWithUnusualName() throws Exception { + PomTestWrapper pom = buildPom("basedir-interpolation/pom-with-unusual-name.xml"); + assertEquals(pom.getBasedir(), new File(pom.getValue("properties/prop0").toString())); + assertEquals(pom.getBasedir(), new File(pom.getValue("properties/prop1").toString())); } /* MNG-3979 */ @Test - public void testJoiningOfContainersWhenChildHasEmptyElements() - throws Exception - { - PomTestWrapper pom = buildPom( "id-container-joining-with-empty-elements/sub" ); - assertNotNull( pom ); + public void testJoiningOfContainersWhenChildHasEmptyElements() throws Exception { + PomTestWrapper pom = buildPom("id-container-joining-with-empty-elements/sub"); + assertNotNull(pom); } @Test - public void testOrderOfPluginConfigurationElementsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-order/wo-plugin-mgmt" ); - assertEquals( "one", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[1]" ) ); - assertEquals( "two", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[2]" ) ); - assertEquals( "three", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[3]" ) ); - assertEquals( "four", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[4]" ) ); + public void testOrderOfPluginConfigurationElementsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-order/wo-plugin-mgmt"); + assertEquals("one", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[1]")); + assertEquals("two", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[2]")); + assertEquals("three", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[3]")); + assertEquals("four", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[4]")); } /* MNG-3827*/ @Test - public void testOrderOfPluginConfigurationElementsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-order/w-plugin-mgmt" ); - assertEquals( "one", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[1]" ) ); - assertEquals( "two", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[2]" ) ); - assertEquals( "three", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[3]" ) ); - assertEquals( "four", pom.getValue( "build/plugins[1]/configuration/stringParams/stringParam[4]" ) ); + public void testOrderOfPluginConfigurationElementsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-order/w-plugin-mgmt"); + assertEquals("one", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[1]")); + assertEquals("two", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[2]")); + assertEquals("three", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[3]")); + assertEquals("four", pom.getValue("build/plugins[1]/configuration/stringParams/stringParam[4]")); } @Test - public void testOrderOfPluginExecutionConfigurationElementsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-config-order/wo-plugin-mgmt" ); + public void testOrderOfPluginExecutionConfigurationElementsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-config-order/wo-plugin-mgmt"); String prefix = "build/plugins[1]/executions[1]/configuration/"; - assertEquals( "one", pom.getValue( prefix + "stringParams/stringParam[1]" ) ); - assertEquals( "two", pom.getValue( prefix + "stringParams/stringParam[2]" ) ); - assertEquals( "three", pom.getValue( prefix + "stringParams/stringParam[3]" ) ); - assertEquals( "four", pom.getValue( prefix + "stringParams/stringParam[4]" ) ); - assertEquals( "key1", pom.getValue( prefix + "propertiesParam/property[1]/name" ) ); - assertEquals( "key2", pom.getValue( prefix + "propertiesParam/property[2]/name" ) ); + assertEquals("one", pom.getValue(prefix + "stringParams/stringParam[1]")); + assertEquals("two", pom.getValue(prefix + "stringParams/stringParam[2]")); + assertEquals("three", pom.getValue(prefix + "stringParams/stringParam[3]")); + assertEquals("four", pom.getValue(prefix + "stringParams/stringParam[4]")); + assertEquals("key1", pom.getValue(prefix + "propertiesParam/property[1]/name")); + assertEquals("key2", pom.getValue(prefix + "propertiesParam/property[2]/name")); } /* MNG-3864*/ @Test - public void testOrderOfPluginExecutionConfigurationElementsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-config-order/w-plugin-mgmt" ); + public void testOrderOfPluginExecutionConfigurationElementsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-config-order/w-plugin-mgmt"); String prefix = "build/plugins[1]/executions[1]/configuration/"; - assertEquals( "one", pom.getValue( prefix + "stringParams/stringParam[1]" ) ); - assertEquals( "two", pom.getValue( prefix + "stringParams/stringParam[2]" ) ); - assertEquals( "three", pom.getValue( prefix + "stringParams/stringParam[3]" ) ); - assertEquals( "four", pom.getValue( prefix + "stringParams/stringParam[4]" ) ); - assertEquals( "key1", pom.getValue( prefix + "propertiesParam/property[1]/name" ) ); - assertEquals( "key2", pom.getValue( prefix + "propertiesParam/property[2]/name" ) ); + assertEquals("one", pom.getValue(prefix + "stringParams/stringParam[1]")); + assertEquals("two", pom.getValue(prefix + "stringParams/stringParam[2]")); + assertEquals("three", pom.getValue(prefix + "stringParams/stringParam[3]")); + assertEquals("four", pom.getValue(prefix + "stringParams/stringParam[4]")); + assertEquals("key1", pom.getValue(prefix + "propertiesParam/property[1]/name")); + assertEquals("key2", pom.getValue(prefix + "propertiesParam/property[2]/name")); } /* MNG-3836*/ @Test - public void testMergeOfInheritedPluginConfiguration() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-merging/child" ); + public void testMergeOfInheritedPluginConfiguration() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-merging/child"); String prefix = "build/plugins[1]/configuration/"; - assertEquals( "PASSED", pom.getValue( prefix + "propertiesFile" ) ); - assertEquals( "PASSED", pom.getValue( prefix + "parent" ) ); - assertEquals( "PASSED-1", pom.getValue( prefix + "stringParams/stringParam[1]" ) ); - assertEquals( "PASSED-3", pom.getValue( prefix + "stringParams/stringParam[2]" ) ); - assertEquals( "PASSED-2", pom.getValue( prefix + "stringParams/stringParam[3]" ) ); - assertEquals( "PASSED-4", pom.getValue( prefix + "stringParams/stringParam[4]" ) ); - assertEquals( "PASSED-1", pom.getValue( prefix + "listParam/listParam[1]" ) ); - assertEquals( "PASSED-3", pom.getValue( prefix + "listParam/listParam[2]" ) ); - assertEquals( "PASSED-2", pom.getValue( prefix + "listParam/listParam[3]" ) ); - assertEquals( "PASSED-4", pom.getValue( prefix + "listParam/listParam[4]" ) ); + assertEquals("PASSED", pom.getValue(prefix + "propertiesFile")); + assertEquals("PASSED", pom.getValue(prefix + "parent")); + assertEquals("PASSED-1", pom.getValue(prefix + "stringParams/stringParam[1]")); + assertEquals("PASSED-3", pom.getValue(prefix + "stringParams/stringParam[2]")); + assertEquals("PASSED-2", pom.getValue(prefix + "stringParams/stringParam[3]")); + assertEquals("PASSED-4", pom.getValue(prefix + "stringParams/stringParam[4]")); + assertEquals("PASSED-1", pom.getValue(prefix + "listParam/listParam[1]")); + assertEquals("PASSED-3", pom.getValue(prefix + "listParam/listParam[2]")); + assertEquals("PASSED-2", pom.getValue(prefix + "listParam/listParam[3]")); + assertEquals("PASSED-4", pom.getValue(prefix + "listParam/listParam[4]")); } /* MNG-2591 */ @Test - public void testAppendOfInheritedPluginConfigurationWithNoProfile() - throws Exception - { - testAppendOfInheritedPluginConfiguration( "no-profile" ); + public void testAppendOfInheritedPluginConfigurationWithNoProfile() throws Exception { + testAppendOfInheritedPluginConfiguration("no-profile"); } /* MNG-2591*/ @Test - public void testAppendOfInheritedPluginConfigurationWithActiveProfile() - throws Exception - { - testAppendOfInheritedPluginConfiguration( "with-profile" ); + public void testAppendOfInheritedPluginConfigurationWithActiveProfile() throws Exception { + testAppendOfInheritedPluginConfiguration("with-profile"); } - private void testAppendOfInheritedPluginConfiguration( String test ) - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-append/" + test + "/subproject" ); + private void testAppendOfInheritedPluginConfiguration(String test) throws Exception { + PomTestWrapper pom = buildPom("plugin-config-append/" + test + "/subproject"); String prefix = "build/plugins[1]/configuration/"; - assertEquals( "PARENT-1", pom.getValue( prefix + "stringParams/stringParam[1]" ) ); - assertEquals( "PARENT-3", pom.getValue( prefix + "stringParams/stringParam[2]" ) ); - assertEquals( "PARENT-2", pom.getValue( prefix + "stringParams/stringParam[3]" ) ); - assertEquals( "PARENT-4", pom.getValue( prefix + "stringParams/stringParam[4]" ) ); - assertEquals( "CHILD-1", pom.getValue( prefix + "stringParams/stringParam[5]" ) ); - assertEquals( "CHILD-3", pom.getValue( prefix + "stringParams/stringParam[6]" ) ); - assertEquals( "CHILD-2", pom.getValue( prefix + "stringParams/stringParam[7]" ) ); - assertEquals( "CHILD-4", pom.getValue( prefix + "stringParams/stringParam[8]" ) ); - assertNull( pom.getValue( prefix + "stringParams/stringParam[9]" ) ); - assertEquals( "PARENT-1", pom.getValue( prefix + "listParam/listParam[1]" ) ); - assertEquals( "PARENT-3", pom.getValue( prefix + "listParam/listParam[2]" ) ); - assertEquals( "PARENT-2", pom.getValue( prefix + "listParam/listParam[3]" ) ); - assertEquals( "PARENT-4", pom.getValue( prefix + "listParam/listParam[4]" ) ); - assertEquals( "CHILD-1", pom.getValue( prefix + "listParam/listParam[5]" ) ); - assertEquals( "CHILD-3", pom.getValue( prefix + "listParam/listParam[6]" ) ); - assertEquals( "CHILD-2", pom.getValue( prefix + "listParam/listParam[7]" ) ); - assertEquals( "CHILD-4", pom.getValue( prefix + "listParam/listParam[8]" ) ); - assertNull( pom.getValue( prefix + "listParam/listParam[9]" ) ); + assertEquals("PARENT-1", pom.getValue(prefix + "stringParams/stringParam[1]")); + assertEquals("PARENT-3", pom.getValue(prefix + "stringParams/stringParam[2]")); + assertEquals("PARENT-2", pom.getValue(prefix + "stringParams/stringParam[3]")); + assertEquals("PARENT-4", pom.getValue(prefix + "stringParams/stringParam[4]")); + assertEquals("CHILD-1", pom.getValue(prefix + "stringParams/stringParam[5]")); + assertEquals("CHILD-3", pom.getValue(prefix + "stringParams/stringParam[6]")); + assertEquals("CHILD-2", pom.getValue(prefix + "stringParams/stringParam[7]")); + assertEquals("CHILD-4", pom.getValue(prefix + "stringParams/stringParam[8]")); + assertNull(pom.getValue(prefix + "stringParams/stringParam[9]")); + assertEquals("PARENT-1", pom.getValue(prefix + "listParam/listParam[1]")); + assertEquals("PARENT-3", pom.getValue(prefix + "listParam/listParam[2]")); + assertEquals("PARENT-2", pom.getValue(prefix + "listParam/listParam[3]")); + assertEquals("PARENT-4", pom.getValue(prefix + "listParam/listParam[4]")); + assertEquals("CHILD-1", pom.getValue(prefix + "listParam/listParam[5]")); + assertEquals("CHILD-3", pom.getValue(prefix + "listParam/listParam[6]")); + assertEquals("CHILD-2", pom.getValue(prefix + "listParam/listParam[7]")); + assertEquals("CHILD-4", pom.getValue(prefix + "listParam/listParam[8]")); + assertNull(pom.getValue(prefix + "listParam/listParam[9]")); } /* MNG-4000 */ @Test - public void testMultiplePluginExecutionsWithAndWithoutIdsWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-w-and-wo-id/wo-plugin-mgmt" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "log-string", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "log-string", pom.getValue( "build/plugins[1]/executions[2]/goals[1]" ) ); + public void testMultiplePluginExecutionsWithAndWithoutIdsWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-w-and-wo-id/wo-plugin-mgmt"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("log-string", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("log-string", pom.getValue("build/plugins[1]/executions[2]/goals[1]")); } @Test - public void testMultiplePluginExecutionsWithAndWithoutIdsWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-w-and-wo-id/w-plugin-mgmt" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "log-string", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( "log-string", pom.getValue( "build/plugins[1]/executions[2]/goals[1]" ) ); + public void testMultiplePluginExecutionsWithAndWithoutIdsWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-w-and-wo-id/w-plugin-mgmt"); + assertEquals(2, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("log-string", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals("log-string", pom.getValue("build/plugins[1]/executions[2]/goals[1]")); } @Test - public void testDependencyOrderWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "dependency-order/wo-plugin-mgmt" ); - assertEquals( 4, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "a", pom.getValue( "dependencies[1]/artifactId" ) ); - assertEquals( "c", pom.getValue( "dependencies[2]/artifactId" ) ); - assertEquals( "b", pom.getValue( "dependencies[3]/artifactId" ) ); - assertEquals( "d", pom.getValue( "dependencies[4]/artifactId" ) ); + public void testDependencyOrderWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("dependency-order/wo-plugin-mgmt"); + assertEquals(4, ((List) pom.getValue("dependencies")).size()); + assertEquals("a", pom.getValue("dependencies[1]/artifactId")); + assertEquals("c", pom.getValue("dependencies[2]/artifactId")); + assertEquals("b", pom.getValue("dependencies[3]/artifactId")); + assertEquals("d", pom.getValue("dependencies[4]/artifactId")); } @Test - public void testDependencyOrderWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "dependency-order/w-plugin-mgmt" ); - assertEquals( 4, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "a", pom.getValue( "dependencies[1]/artifactId" ) ); - assertEquals( "c", pom.getValue( "dependencies[2]/artifactId" ) ); - assertEquals( "b", pom.getValue( "dependencies[3]/artifactId" ) ); - assertEquals( "d", pom.getValue( "dependencies[4]/artifactId" ) ); + public void testDependencyOrderWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("dependency-order/w-plugin-mgmt"); + assertEquals(4, ((List) pom.getValue("dependencies")).size()); + assertEquals("a", pom.getValue("dependencies[1]/artifactId")); + assertEquals("c", pom.getValue("dependencies[2]/artifactId")); + assertEquals("b", pom.getValue("dependencies[3]/artifactId")); + assertEquals("d", pom.getValue("dependencies[4]/artifactId")); } @Test - public void testBuildDirectoriesUsePlatformSpecificFileSeparator() - throws Exception - { - PomTestWrapper pom = buildPom( "platform-file-separator" ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/directory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/outputDirectory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/testOutputDirectory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/sourceDirectory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/testSourceDirectory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/resources[1]/directory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/testResources[1]/directory" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "build/filters[1]" ) ); - assertPathWithNormalizedFileSeparators( pom.getValue( "reporting/outputDirectory" ) ); + public void testBuildDirectoriesUsePlatformSpecificFileSeparator() throws Exception { + PomTestWrapper pom = buildPom("platform-file-separator"); + assertPathWithNormalizedFileSeparators(pom.getValue("build/directory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/outputDirectory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/testOutputDirectory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/sourceDirectory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/testSourceDirectory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/resources[1]/directory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/testResources[1]/directory")); + assertPathWithNormalizedFileSeparators(pom.getValue("build/filters[1]")); + assertPathWithNormalizedFileSeparators(pom.getValue("reporting/outputDirectory")); } /* MNG-4008 */ @Test - public void testMergedFilterOrder() - throws Exception - { - PomTestWrapper pom = buildPom( "merged-filter-order/sub" ); + public void testMergedFilterOrder() throws Exception { + PomTestWrapper pom = buildPom("merged-filter-order/sub"); - assertEquals( 7, ( (List) pom.getValue( "build/filters" ) ).size() ); - assertThat( pom.getValue( "build/filters[1]" ).toString(), endsWith( "child-a.properties" ) ); - assertThat( pom.getValue( "build/filters[2]" ).toString(), endsWith( "child-c.properties" ) ); - assertThat( pom.getValue( "build/filters[3]" ).toString(), endsWith( "child-b.properties" ) ); - assertThat( pom.getValue( "build/filters[4]" ).toString(), endsWith( "child-d.properties" ) ); - assertThat( pom.getValue( "build/filters[5]" ).toString(), endsWith( "parent-c.properties" ) ); - assertThat( pom.getValue( "build/filters[6]" ).toString(), endsWith( "parent-b.properties" ) ); - assertThat( pom.getValue( "build/filters[7]" ).toString(), endsWith( "parent-d.properties" ) ); + assertEquals(7, ((List) pom.getValue("build/filters")).size()); + assertThat(pom.getValue("build/filters[1]").toString(), endsWith("child-a.properties")); + assertThat(pom.getValue("build/filters[2]").toString(), endsWith("child-c.properties")); + assertThat(pom.getValue("build/filters[3]").toString(), endsWith("child-b.properties")); + assertThat(pom.getValue("build/filters[4]").toString(), endsWith("child-d.properties")); + assertThat(pom.getValue("build/filters[5]").toString(), endsWith("parent-c.properties")); + assertThat(pom.getValue("build/filters[6]").toString(), endsWith("parent-b.properties")); + assertThat(pom.getValue("build/filters[7]").toString(), endsWith("parent-d.properties")); } /** MNG-4027*/ @Test - public void testProfileInjectedDependencies() - throws Exception - { - PomTestWrapper pom = buildPom( "profile-injected-dependencies" ); - assertEquals( 4, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "a", pom.getValue( "dependencies[1]/artifactId" ) ); - assertEquals( "c", pom.getValue( "dependencies[2]/artifactId" ) ); - assertEquals( "b", pom.getValue( "dependencies[3]/artifactId" ) ); - assertEquals( "d", pom.getValue( "dependencies[4]/artifactId" ) ); + public void testProfileInjectedDependencies() throws Exception { + PomTestWrapper pom = buildPom("profile-injected-dependencies"); + assertEquals(4, ((List) pom.getValue("dependencies")).size()); + assertEquals("a", pom.getValue("dependencies[1]/artifactId")); + assertEquals("c", pom.getValue("dependencies[2]/artifactId")); + assertEquals("b", pom.getValue("dependencies[3]/artifactId")); + assertEquals("d", pom.getValue("dependencies[4]/artifactId")); } /** IT-0021*/ @Test - public void testProfileDependenciesMultipleProfiles() - throws Exception - { - PomTestWrapper pom = buildPom( "profile-dependencies-multiple-profiles", "profile-1", "profile-2" ); - assertEquals(2, ( (List) pom.getValue( "dependencies" ) ).size() ); + public void testProfileDependenciesMultipleProfiles() throws Exception { + PomTestWrapper pom = buildPom("profile-dependencies-multiple-profiles", "profile-1", "profile-2"); + assertEquals(2, ((List) pom.getValue("dependencies")).size()); } @Test - public void testDependencyInheritance() - throws Exception - { - PomTestWrapper pom = buildPom( "dependency-inheritance/sub" ); - assertEquals( 1, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "4.13.1", pom.getValue( "dependencies[1]/version" ) ); + public void testDependencyInheritance() throws Exception { + PomTestWrapper pom = buildPom("dependency-inheritance/sub"); + assertEquals(1, ((List) pom.getValue("dependencies")).size()); + assertEquals("4.13.1", pom.getValue("dependencies[1]/version")); } /** MNG-4034 */ @Test - public void testManagedProfileDependency() - throws Exception - { - PomTestWrapper pom = this.buildPom( "managed-profile-dependency/sub", "maven-core-it" ); - assertEquals( 1, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "org.apache.maven.its", pom.getValue( "dependencies[1]/groupId" ) ); - assertEquals( "maven-core-it-support", pom.getValue( "dependencies[1]/artifactId" ) ); - assertEquals( "1.3", pom.getValue( "dependencies[1]/version" ) ); - assertEquals( "runtime", pom.getValue( "dependencies[1]/scope" ) ); - assertEquals( 1, ( (List) pom.getValue( "dependencies[1]/exclusions" ) ).size() ); - assertEquals( "commons-lang", pom.getValue( "dependencies[1]/exclusions[1]/groupId" ) ); + public void testManagedProfileDependency() throws Exception { + PomTestWrapper pom = this.buildPom("managed-profile-dependency/sub", "maven-core-it"); + assertEquals(1, ((List) pom.getValue("dependencies")).size()); + assertEquals("org.apache.maven.its", pom.getValue("dependencies[1]/groupId")); + assertEquals("maven-core-it-support", pom.getValue("dependencies[1]/artifactId")); + assertEquals("1.3", pom.getValue("dependencies[1]/version")); + assertEquals("runtime", pom.getValue("dependencies[1]/scope")); + assertEquals(1, ((List) pom.getValue("dependencies[1]/exclusions")).size()); + assertEquals("commons-lang", pom.getValue("dependencies[1]/exclusions[1]/groupId")); } /** MNG-4040 */ @Test - public void testProfileModuleInheritance() - throws Exception - { - PomTestWrapper pom = this.buildPom( "profile-module-inheritance/sub", "dist" ); - assertEquals( 0, ( (List) pom.getValue( "modules" ) ).size() ); + public void testProfileModuleInheritance() throws Exception { + PomTestWrapper pom = this.buildPom("profile-module-inheritance/sub", "dist"); + assertEquals(0, ((List) pom.getValue("modules")).size()); } /** MNG-3621 */ @Test - public void testUncPath() - throws Exception - { - PomTestWrapper pom = this.buildPom( "unc-path/sub" ); - assertEquals( "file:////host/site/test-child", pom.getValue( "distributionManagement/site/url" ) ); + public void testUncPath() throws Exception { + PomTestWrapper pom = this.buildPom("unc-path/sub"); + assertEquals("file:////host/site/test-child", pom.getValue("distributionManagement/site/url")); } /** MNG-2006 */ @Test - public void testUrlAppendWithChildPathAdjustment() - throws Exception - { - PomTestWrapper pom = this.buildPom( "url-append/child" ); - assertEquals( "https://project.url/child", pom.getValue( "url" ) ); - assertEquals( "https://viewvc.project.url/child", pom.getValue( "scm/url" ) ); - assertEquals( "https://scm.project.url/child", pom.getValue( "scm/connection" ) ); - assertEquals( "https://scm.project.url/child", pom.getValue( "scm/developerConnection" ) ); - assertEquals( "https://site.project.url/child", pom.getValue( "distributionManagement/site/url" ) ); + public void testUrlAppendWithChildPathAdjustment() throws Exception { + PomTestWrapper pom = this.buildPom("url-append/child"); + assertEquals("https://project.url/child", pom.getValue("url")); + assertEquals("https://viewvc.project.url/child", pom.getValue("scm/url")); + assertEquals("https://scm.project.url/child", pom.getValue("scm/connection")); + assertEquals("https://scm.project.url/child", pom.getValue("scm/developerConnection")); + assertEquals("https://site.project.url/child", pom.getValue("distributionManagement/site/url")); } /** MNG-0479 */ @Test - public void testRepoInheritance() - throws Exception - { - PomTestWrapper pom = this.buildPom( "repo-inheritance" ); - assertEquals( 1, ( (List) pom.getValue( "repositories" ) ).size() ); - assertEquals( "it0043", pom.getValue( "repositories[1]/name" ) ); + public void testRepoInheritance() throws Exception { + PomTestWrapper pom = this.buildPom("repo-inheritance"); + assertEquals(1, ((List) pom.getValue("repositories")).size()); + assertEquals("it0043", pom.getValue("repositories[1]/name")); } @Test - public void testEmptyScm() - throws Exception - { - PomTestWrapper pom = this.buildPom( "empty-scm" ); - assertNull( pom.getValue( "scm" ) ); + public void testEmptyScm() throws Exception { + PomTestWrapper pom = this.buildPom("empty-scm"); + assertNull(pom.getValue("scm")); } @Test - public void testPluginConfigurationUsingAttributesWithoutPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-attributes/wo-plugin-mgmt" ); - assertEquals( "src", pom.getValue( "build/plugins[1]/configuration/domParam/copy/@todir" ) ); - assertEquals( "true", pom.getValue( "build/plugins[1]/configuration/domParam/copy/@overwrite" ) ); - assertEquals( "target", pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@dir" ) ); - assertNull( pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@todir" ) ); - assertNull( pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@overwrite" ) ); + public void testPluginConfigurationUsingAttributesWithoutPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-attributes/wo-plugin-mgmt"); + assertEquals("src", pom.getValue("build/plugins[1]/configuration/domParam/copy/@todir")); + assertEquals("true", pom.getValue("build/plugins[1]/configuration/domParam/copy/@overwrite")); + assertEquals("target", pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@dir")); + assertNull(pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@todir")); + assertNull(pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@overwrite")); } /** MNG-4053*/ @Test - public void testPluginConfigurationUsingAttributesWithPluginManagement() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-attributes/w-plugin-mgmt" ); - assertEquals( "src", pom.getValue( "build/plugins[1]/configuration/domParam/copy/@todir" ) ); - assertEquals( "true", pom.getValue( "build/plugins[1]/configuration/domParam/copy/@overwrite" ) ); - assertEquals( "target", pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@dir" ) ); - assertNull( pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@todir" ) ); - assertNull( pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@overwrite" ) ); + public void testPluginConfigurationUsingAttributesWithPluginManagement() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-attributes/w-plugin-mgmt"); + assertEquals("src", pom.getValue("build/plugins[1]/configuration/domParam/copy/@todir")); + assertEquals("true", pom.getValue("build/plugins[1]/configuration/domParam/copy/@overwrite")); + assertEquals("target", pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@dir")); + assertNull(pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@todir")); + assertNull(pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@overwrite")); } @Test - public void testPluginConfigurationUsingAttributesWithPluginManagementAndProfile() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-config-attributes/w-profile", "maven-core-it" ); - assertEquals( "src", pom.getValue( "build/plugins[1]/configuration/domParam/copy/@todir" ) ); - assertEquals( "true", pom.getValue( "build/plugins[1]/configuration/domParam/copy/@overwrite" ) ); - assertEquals( "target", pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@dir" ) ); - assertNull( pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@todir" ) ); - assertNull( pom.getValue( "build/plugins[1]/configuration/domParam/copy/fileset/@overwrite" ) ); + public void testPluginConfigurationUsingAttributesWithPluginManagementAndProfile() throws Exception { + PomTestWrapper pom = buildPom("plugin-config-attributes/w-profile", "maven-core-it"); + assertEquals("src", pom.getValue("build/plugins[1]/configuration/domParam/copy/@todir")); + assertEquals("true", pom.getValue("build/plugins[1]/configuration/domParam/copy/@overwrite")); + assertEquals("target", pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@dir")); + assertNull(pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@todir")); + assertNull(pom.getValue("build/plugins[1]/configuration/domParam/copy/fileset/@overwrite")); } @Test - public void testPomEncoding() - throws Exception - { - PomTestWrapper pom = buildPom( "pom-encoding/utf-8" ); - assertEquals( "TEST-CHARS: \u00DF\u0131\u03A3\u042F\u05D0\u20AC", pom.getValue( "description" ) ); - pom = buildPom( "pom-encoding/latin-1" ); - assertEquals( "TEST-CHARS: \u00C4\u00D6\u00DC\u00E4\u00F6\u00FC\u00DF", pom.getValue( "description" ) ); + public void testPomEncoding() throws Exception { + PomTestWrapper pom = buildPom("pom-encoding/utf-8"); + assertEquals("TEST-CHARS: \u00DF\u0131\u03A3\u042F\u05D0\u20AC", pom.getValue("description")); + pom = buildPom("pom-encoding/latin-1"); + assertEquals("TEST-CHARS: \u00C4\u00D6\u00DC\u00E4\u00F6\u00FC\u00DF", pom.getValue("description")); } /* MNG-4070 */ @Test - public void testXmlWhitespaceHandling() - throws Exception - { - PomTestWrapper pom = buildPom( "xml-whitespace/sub" ); - assertEquals( "org.apache.maven.its.mng4070", pom.getValue( "groupId" ) ); + public void testXmlWhitespaceHandling() throws Exception { + PomTestWrapper pom = buildPom("xml-whitespace/sub"); + assertEquals("org.apache.maven.its.mng4070", pom.getValue("groupId")); } /* MNG-3760*/ @Test - public void testInterpolationOfBaseUri() - throws Exception - { - PomTestWrapper pom = buildPom( "baseuri-interpolation/pom.xml" ); - assertNotEquals( pom.getBasedir().toURI().toString(), pom.getValue( "properties/prop1" ).toString() ); + public void testInterpolationOfBaseUri() throws Exception { + PomTestWrapper pom = buildPom("baseuri-interpolation/pom.xml"); + assertNotEquals( + pom.getBasedir().toURI().toString(), + pom.getValue("properties/prop1").toString()); } /* MNG-6386 */ @Test - public void testInterpolationOfRfc3986BaseUri() - throws Exception - { - PomTestWrapper pom = buildPom( "baseuri-interpolation/pom.xml" ); - String prop1 = pom.getValue( "properties/prop1" ).toString(); - assertEquals( pom.getBasedir().toPath().toUri().toASCIIString(), prop1 ); - assertThat( prop1, startsWith( "file:///" ) ); + public void testInterpolationOfRfc3986BaseUri() throws Exception { + PomTestWrapper pom = buildPom("baseuri-interpolation/pom.xml"); + String prop1 = pom.getValue("properties/prop1").toString(); + assertEquals(pom.getBasedir().toPath().toUri().toASCIIString(), prop1); + assertThat(prop1, startsWith("file:///")); } /* MNG-3811*/ @Test - public void testReportingPluginConfig() - throws Exception - { - PomTestWrapper pom = buildPom( "reporting-plugin-config/sub" ); + public void testReportingPluginConfig() throws Exception { + PomTestWrapper pom = buildPom("reporting-plugin-config/sub"); - assertEquals( 3, ( (List) pom.getValue( "reporting/plugins[1]/configuration/stringParams" ) ).size() ); - assertEquals( "parentParam", pom.getValue( "reporting/plugins[1]/configuration/stringParams[1]/stringParam[1]" ) ); - assertEquals( "childParam", pom.getValue( "reporting/plugins[1]/configuration/stringParams[1]/stringParam[2]" ) ); - assertEquals( " preserve space ", pom.getValue( "reporting/plugins[1]/configuration/stringParams[1]/stringParam[3]" ) ); - assertEquals( "true", pom.getValue( "reporting/plugins[1]/configuration/booleanParam" ) ); + assertEquals(3, ((List) pom.getValue("reporting/plugins[1]/configuration/stringParams")).size()); + assertEquals("parentParam", pom.getValue("reporting/plugins[1]/configuration/stringParams[1]/stringParam[1]")); + assertEquals("childParam", pom.getValue("reporting/plugins[1]/configuration/stringParams[1]/stringParam[2]")); + assertEquals( + " preserve space ", + pom.getValue("reporting/plugins[1]/configuration/stringParams[1]/stringParam[3]")); + assertEquals("true", pom.getValue("reporting/plugins[1]/configuration/booleanParam")); } @Test - public void testPropertiesNoDuplication() - throws Exception - { - PomTestWrapper pom = buildPom( "properties-no-duplication/sub" ); - assertEquals( 1, ( (Properties) pom.getValue( "properties" ) ).size() ); - assertEquals( "child", pom.getValue( "properties/pomProfile" ) ); + public void testPropertiesNoDuplication() throws Exception { + PomTestWrapper pom = buildPom("properties-no-duplication/sub"); + assertEquals(1, ((Properties) pom.getValue("properties")).size()); + assertEquals("child", pom.getValue("properties/pomProfile")); } @Test - public void testPomInheritance() - throws Exception - { - PomTestWrapper pom = buildPom( "pom-inheritance/sub" ); - assertEquals( "parent-description", pom.getValue( "description" ) ); - assertEquals( "jar", pom.getValue( "packaging" ) ); + public void testPomInheritance() throws Exception { + PomTestWrapper pom = buildPom("pom-inheritance/sub"); + assertEquals("parent-description", pom.getValue("description")); + assertEquals("jar", pom.getValue("packaging")); } @Test - public void testCompleteModelWithoutParent() - throws Exception - { - PomTestWrapper pom = buildPom( "complete-model/wo-parent" ); + public void testCompleteModelWithoutParent() throws Exception { + PomTestWrapper pom = buildPom("complete-model/wo-parent"); - testCompleteModel( pom ); + testCompleteModel(pom); } @Test - public void testCompleteModelWithParent() - throws Exception - { - PomTestWrapper pom = buildPom( "complete-model/w-parent/sub" ); + public void testCompleteModelWithParent() throws Exception { + PomTestWrapper pom = buildPom("complete-model/w-parent/sub"); - testCompleteModel( pom ); + testCompleteModel(pom); } - private void testCompleteModel( PomTestWrapper pom ) - throws Exception - { - assertEquals( "4.0.0", pom.getValue( "modelVersion" ) ); + private void testCompleteModel(PomTestWrapper pom) throws Exception { + assertEquals("4.0.0", pom.getValue("modelVersion")); - assertEquals( "org.apache.maven.its.mng", pom.getValue( "groupId" ) ); - assertEquals( "test", pom.getValue( "artifactId" ) ); - assertEquals( "0.2", pom.getValue( "version" ) ); - assertEquals( "pom", pom.getValue( "packaging" ) ); + assertEquals("org.apache.maven.its.mng", pom.getValue("groupId")); + assertEquals("test", pom.getValue("artifactId")); + assertEquals("0.2", pom.getValue("version")); + assertEquals("pom", pom.getValue("packaging")); - assertEquals( "project-name", pom.getValue( "name" ) ); - assertEquals( "project-description", pom.getValue( "description" ) ); - assertEquals( "https://project.url/", pom.getValue( "url" ) ); - assertEquals( "2009", pom.getValue( "inceptionYear" ) ); + assertEquals("project-name", pom.getValue("name")); + assertEquals("project-description", pom.getValue("description")); + assertEquals("https://project.url/", pom.getValue("url")); + assertEquals("2009", pom.getValue("inceptionYear")); - assertEquals( "project-org", pom.getValue( "organization/name" ) ); - assertEquals( "https://project-org.url/", pom.getValue( "organization/url" ) ); + assertEquals("project-org", pom.getValue("organization/name")); + assertEquals("https://project-org.url/", pom.getValue("organization/url")); - assertEquals( 1, ( (List) pom.getValue( "licenses" ) ).size() ); - assertEquals( "project-license", pom.getValue( "licenses[1]/name" ) ); - assertEquals( "https://project.url/license", pom.getValue( "licenses[1]/url" ) ); - assertEquals( "repo", pom.getValue( "licenses[1]/distribution" ) ); - assertEquals( "free", pom.getValue( "licenses[1]/comments" ) ); + assertEquals(1, ((List) pom.getValue("licenses")).size()); + assertEquals("project-license", pom.getValue("licenses[1]/name")); + assertEquals("https://project.url/license", pom.getValue("licenses[1]/url")); + assertEquals("repo", pom.getValue("licenses[1]/distribution")); + assertEquals("free", pom.getValue("licenses[1]/comments")); - assertEquals( 1, ( (List) pom.getValue( "developers" ) ).size() ); - assertEquals( "dev", pom.getValue( "developers[1]/id" ) ); - assertEquals( "project-developer", pom.getValue( "developers[1]/name" ) ); - assertEquals( "developer@", pom.getValue( "developers[1]/email" ) ); - assertEquals( "https://developer", pom.getValue( "developers[1]/url" ) ); - assertEquals( "developer", pom.getValue( "developers[1]/organization" ) ); - assertEquals( "https://devel.org", pom.getValue( "developers[1]/organizationUrl" ) ); - assertEquals( "-1", pom.getValue( "developers[1]/timezone" ) ); - assertEquals( "yes", pom.getValue( "developers[1]/properties/developer" ) ); - assertEquals( 1, ( (List) pom.getValue( "developers[1]/roles" ) ).size() ); - assertEquals( "devel", pom.getValue( "developers[1]/roles[1]" ) ); + assertEquals(1, ((List) pom.getValue("developers")).size()); + assertEquals("dev", pom.getValue("developers[1]/id")); + assertEquals("project-developer", pom.getValue("developers[1]/name")); + assertEquals("developer@", pom.getValue("developers[1]/email")); + assertEquals("https://developer", pom.getValue("developers[1]/url")); + assertEquals("developer", pom.getValue("developers[1]/organization")); + assertEquals("https://devel.org", pom.getValue("developers[1]/organizationUrl")); + assertEquals("-1", pom.getValue("developers[1]/timezone")); + assertEquals("yes", pom.getValue("developers[1]/properties/developer")); + assertEquals(1, ((List) pom.getValue("developers[1]/roles")).size()); + assertEquals("devel", pom.getValue("developers[1]/roles[1]")); - assertEquals( 1, ( (List) pom.getValue( "contributors" ) ).size() ); - assertEquals( "project-contributor", pom.getValue( "contributors[1]/name" ) ); - assertEquals( "contributor@", pom.getValue( "contributors[1]/email" ) ); - assertEquals( "https://contributor", pom.getValue( "contributors[1]/url" ) ); - assertEquals( "contributor", pom.getValue( "contributors[1]/organization" ) ); - assertEquals( "https://contrib.org", pom.getValue( "contributors[1]/organizationUrl" ) ); - assertEquals( "+1", pom.getValue( "contributors[1]/timezone" ) ); - assertEquals( "yes", pom.getValue( "contributors[1]/properties/contributor" ) ); - assertEquals( 1, ( (List) pom.getValue( "contributors[1]/roles" ) ).size() ); - assertEquals( "contrib", pom.getValue( "contributors[1]/roles[1]" ) ); + assertEquals(1, ((List) pom.getValue("contributors")).size()); + assertEquals("project-contributor", pom.getValue("contributors[1]/name")); + assertEquals("contributor@", pom.getValue("contributors[1]/email")); + assertEquals("https://contributor", pom.getValue("contributors[1]/url")); + assertEquals("contributor", pom.getValue("contributors[1]/organization")); + assertEquals("https://contrib.org", pom.getValue("contributors[1]/organizationUrl")); + assertEquals("+1", pom.getValue("contributors[1]/timezone")); + assertEquals("yes", pom.getValue("contributors[1]/properties/contributor")); + assertEquals(1, ((List) pom.getValue("contributors[1]/roles")).size()); + assertEquals("contrib", pom.getValue("contributors[1]/roles[1]")); - assertEquals( 1, ( (List) pom.getValue( "mailingLists" ) ).size() ); - assertEquals( "project-mailing-list", pom.getValue( "mailingLists[1]/name" ) ); - assertEquals( "subscribe@", pom.getValue( "mailingLists[1]/subscribe" ) ); - assertEquals( "unsubscribe@", pom.getValue( "mailingLists[1]/unsubscribe" ) ); - assertEquals( "post@", pom.getValue( "mailingLists[1]/post" ) ); - assertEquals( "mail-archive", pom.getValue( "mailingLists[1]/archive" ) ); - assertEquals( 1, ( (List) pom.getValue( "mailingLists[1]/otherArchives" ) ).size() ); - assertEquals( "other-archive", pom.getValue( "mailingLists[1]/otherArchives[1]" ) ); + assertEquals(1, ((List) pom.getValue("mailingLists")).size()); + assertEquals("project-mailing-list", pom.getValue("mailingLists[1]/name")); + assertEquals("subscribe@", pom.getValue("mailingLists[1]/subscribe")); + assertEquals("unsubscribe@", pom.getValue("mailingLists[1]/unsubscribe")); + assertEquals("post@", pom.getValue("mailingLists[1]/post")); + assertEquals("mail-archive", pom.getValue("mailingLists[1]/archive")); + assertEquals(1, ((List) pom.getValue("mailingLists[1]/otherArchives")).size()); + assertEquals("other-archive", pom.getValue("mailingLists[1]/otherArchives[1]")); - assertEquals( "2.0.1", pom.getValue( "prerequisites/maven" ) ); + assertEquals("2.0.1", pom.getValue("prerequisites/maven")); - assertEquals( "https://project.url/trunk", pom.getValue( "scm/url" ) ); - assertEquals( "https://project.url/scm", pom.getValue( "scm/connection" ) ); - assertEquals( "https://project.url/scm", pom.getValue( "scm/developerConnection" ) ); - assertEquals( "TAG", pom.getValue( "scm/tag" ) ); + assertEquals("https://project.url/trunk", pom.getValue("scm/url")); + assertEquals("https://project.url/scm", pom.getValue("scm/connection")); + assertEquals("https://project.url/scm", pom.getValue("scm/developerConnection")); + assertEquals("TAG", pom.getValue("scm/tag")); - assertEquals( "issues", pom.getValue( "issueManagement/system" ) ); - assertEquals( "https://project.url/issues", pom.getValue( "issueManagement/url" ) ); + assertEquals("issues", pom.getValue("issueManagement/system")); + assertEquals("https://project.url/issues", pom.getValue("issueManagement/url")); - assertEquals( "ci", pom.getValue( "ciManagement/system" ) ); - assertEquals( "https://project.url/ci", pom.getValue( "ciManagement/url" ) ); - assertEquals( 1, ( (List) pom.getValue( "ciManagement/notifiers" ) ).size() ); - assertEquals( "irc", pom.getValue( "ciManagement/notifiers[1]/type" ) ); - assertEquals( "ci@", pom.getValue( "ciManagement/notifiers[1]/address" ) ); - assertEquals( Boolean.TRUE, pom.getValue( "ciManagement/notifiers[1]/sendOnError" ) ); - assertEquals( Boolean.FALSE, pom.getValue( "ciManagement/notifiers[1]/sendOnFailure" ) ); - assertEquals( Boolean.FALSE, pom.getValue( "ciManagement/notifiers[1]/sendOnWarning" ) ); - assertEquals( Boolean.FALSE, pom.getValue( "ciManagement/notifiers[1]/sendOnSuccess" ) ); - assertEquals( "ci", pom.getValue( "ciManagement/notifiers[1]/configuration/ciProp" ) ); + assertEquals("ci", pom.getValue("ciManagement/system")); + assertEquals("https://project.url/ci", pom.getValue("ciManagement/url")); + assertEquals(1, ((List) pom.getValue("ciManagement/notifiers")).size()); + assertEquals("irc", pom.getValue("ciManagement/notifiers[1]/type")); + assertEquals("ci@", pom.getValue("ciManagement/notifiers[1]/address")); + assertEquals(Boolean.TRUE, pom.getValue("ciManagement/notifiers[1]/sendOnError")); + assertEquals(Boolean.FALSE, pom.getValue("ciManagement/notifiers[1]/sendOnFailure")); + assertEquals(Boolean.FALSE, pom.getValue("ciManagement/notifiers[1]/sendOnWarning")); + assertEquals(Boolean.FALSE, pom.getValue("ciManagement/notifiers[1]/sendOnSuccess")); + assertEquals("ci", pom.getValue("ciManagement/notifiers[1]/configuration/ciProp")); - assertEquals( "project.distros", pom.getValue( "distributionManagement/repository/id" ) ); - assertEquals( "distros", pom.getValue( "distributionManagement/repository/name" ) ); - assertEquals( "https://project.url/dist", pom.getValue( "distributionManagement/repository/url" ) ); - assertEquals( Boolean.TRUE, pom.getValue( "distributionManagement/repository/uniqueVersion" ) ); + assertEquals("project.distros", pom.getValue("distributionManagement/repository/id")); + assertEquals("distros", pom.getValue("distributionManagement/repository/name")); + assertEquals("https://project.url/dist", pom.getValue("distributionManagement/repository/url")); + assertEquals(Boolean.TRUE, pom.getValue("distributionManagement/repository/uniqueVersion")); - assertEquals( "project.snaps", pom.getValue( "distributionManagement/snapshotRepository/id" ) ); - assertEquals( "snaps", pom.getValue( "distributionManagement/snapshotRepository/name" ) ); - assertEquals( "https://project.url/snaps", pom.getValue( "distributionManagement/snapshotRepository/url" ) ); - assertEquals( Boolean.FALSE, pom.getValue( "distributionManagement/snapshotRepository/uniqueVersion" ) ); + assertEquals("project.snaps", pom.getValue("distributionManagement/snapshotRepository/id")); + assertEquals("snaps", pom.getValue("distributionManagement/snapshotRepository/name")); + assertEquals("https://project.url/snaps", pom.getValue("distributionManagement/snapshotRepository/url")); + assertEquals(Boolean.FALSE, pom.getValue("distributionManagement/snapshotRepository/uniqueVersion")); - assertEquals( "project.site", pom.getValue( "distributionManagement/site/id" ) ); - assertEquals( "docs", pom.getValue( "distributionManagement/site/name" ) ); - assertEquals( "https://project.url/site", pom.getValue( "distributionManagement/site/url" ) ); + assertEquals("project.site", pom.getValue("distributionManagement/site/id")); + assertEquals("docs", pom.getValue("distributionManagement/site/name")); + assertEquals("https://project.url/site", pom.getValue("distributionManagement/site/url")); - assertEquals( "https://project.url/download", pom.getValue( "distributionManagement/downloadUrl" ) ); - assertEquals( "reloc-gid", pom.getValue( "distributionManagement/relocation/groupId" ) ); - assertEquals( "reloc-aid", pom.getValue( "distributionManagement/relocation/artifactId" ) ); - assertEquals( "reloc-version", pom.getValue( "distributionManagement/relocation/version" ) ); - assertEquals( "project-reloc-msg", pom.getValue( "distributionManagement/relocation/message" ) ); + assertEquals("https://project.url/download", pom.getValue("distributionManagement/downloadUrl")); + assertEquals("reloc-gid", pom.getValue("distributionManagement/relocation/groupId")); + assertEquals("reloc-aid", pom.getValue("distributionManagement/relocation/artifactId")); + assertEquals("reloc-version", pom.getValue("distributionManagement/relocation/version")); + assertEquals("project-reloc-msg", pom.getValue("distributionManagement/relocation/message")); - assertEquals( 1, ( (List) pom.getValue( "modules" ) ).size() ); - assertEquals( "sub", pom.getValue( "modules[1]" ) ); + assertEquals(1, ((List) pom.getValue("modules")).size()); + assertEquals("sub", pom.getValue("modules[1]")); - assertEquals( 1, ( (Map) pom.getValue( "properties" ) ).size() ); - assertEquals( "project-property", pom.getValue( "properties[1]/itProperty" ) ); + assertEquals(1, ((Map) pom.getValue("properties")).size()); + assertEquals("project-property", pom.getValue("properties[1]/itProperty")); - assertEquals( 1, ( (List) pom.getValue( "dependencyManagement/dependencies" ) ).size() ); - assertEquals( "org.apache.maven.its", pom.getValue( "dependencyManagement/dependencies[1]/groupId" ) ); - assertEquals( "managed-dep", pom.getValue( "dependencyManagement/dependencies[1]/artifactId" ) ); - assertEquals( "0.1", pom.getValue( "dependencyManagement/dependencies[1]/version" ) ); - assertEquals( "war", pom.getValue( "dependencyManagement/dependencies[1]/type" ) ); - assertEquals( "runtime", pom.getValue( "dependencyManagement/dependencies[1]/scope" ) ); - assertEquals( Boolean.FALSE, pom.getValue( "dependencyManagement/dependencies[1]/optional" ) ); - assertEquals( 1, ( (List) pom.getValue( "dependencyManagement/dependencies[1]/exclusions" ) ).size() ); - assertEquals( "org.apache.maven.its", - pom.getValue( "dependencyManagement/dependencies[1]/exclusions[1]/groupId" ) ); - assertEquals( "excluded-managed-dep", - pom.getValue( "dependencyManagement/dependencies[1]/exclusions[1]/artifactId" ) ); + assertEquals(1, ((List) pom.getValue("dependencyManagement/dependencies")).size()); + assertEquals("org.apache.maven.its", pom.getValue("dependencyManagement/dependencies[1]/groupId")); + assertEquals("managed-dep", pom.getValue("dependencyManagement/dependencies[1]/artifactId")); + assertEquals("0.1", pom.getValue("dependencyManagement/dependencies[1]/version")); + assertEquals("war", pom.getValue("dependencyManagement/dependencies[1]/type")); + assertEquals("runtime", pom.getValue("dependencyManagement/dependencies[1]/scope")); + assertEquals(Boolean.FALSE, pom.getValue("dependencyManagement/dependencies[1]/optional")); + assertEquals(1, ((List) pom.getValue("dependencyManagement/dependencies[1]/exclusions")).size()); + assertEquals( + "org.apache.maven.its", pom.getValue("dependencyManagement/dependencies[1]/exclusions[1]/groupId")); + assertEquals( + "excluded-managed-dep", pom.getValue("dependencyManagement/dependencies[1]/exclusions[1]/artifactId")); - assertEquals( 1, ( (List) pom.getValue( "dependencies" ) ).size() ); - assertEquals( "org.apache.maven.its", pom.getValue( "dependencies[1]/groupId" ) ); - assertEquals( "dep", pom.getValue( "dependencies[1]/artifactId" ) ); - assertEquals( "0.2", pom.getValue( "dependencies[1]/version" ) ); - assertEquals( "ejb", pom.getValue( "dependencies[1]/type" ) ); - assertEquals( "test", pom.getValue( "dependencies[1]/scope" ) ); - assertEquals( Boolean.TRUE, pom.getValue( "dependencies[1]/optional" ) ); - assertEquals( 1, ( (List) pom.getValue( "dependencies[1]/exclusions" ) ).size() ); - assertEquals( "org.apache.maven.its", pom.getValue( "dependencies[1]/exclusions[1]/groupId" ) ); - assertEquals( "excluded-dep", pom.getValue( "dependencies[1]/exclusions[1]/artifactId" ) ); + assertEquals(1, ((List) pom.getValue("dependencies")).size()); + assertEquals("org.apache.maven.its", pom.getValue("dependencies[1]/groupId")); + assertEquals("dep", pom.getValue("dependencies[1]/artifactId")); + assertEquals("0.2", pom.getValue("dependencies[1]/version")); + assertEquals("ejb", pom.getValue("dependencies[1]/type")); + assertEquals("test", pom.getValue("dependencies[1]/scope")); + assertEquals(Boolean.TRUE, pom.getValue("dependencies[1]/optional")); + assertEquals(1, ((List) pom.getValue("dependencies[1]/exclusions")).size()); + assertEquals("org.apache.maven.its", pom.getValue("dependencies[1]/exclusions[1]/groupId")); + assertEquals("excluded-dep", pom.getValue("dependencies[1]/exclusions[1]/artifactId")); - assertEquals( 2, ( (List) pom.getValue( "repositories" ) ).size() ); - assertEquals( "project-remote-repo", pom.getValue( "repositories[1]/id" ) ); - assertEquals( "https://project.url/remote", pom.getValue( "repositories[1]/url" ) ); - assertEquals( "repo", pom.getValue( "repositories[1]/name" ) ); - assertEquals( RepositorySystem.DEFAULT_REMOTE_REPO_ID, pom.getValue( "repositories[2]/id" ) ); - assertEquals( RepositorySystem.DEFAULT_REMOTE_REPO_URL, pom.getValue( "repositories[2]/url" ) ); + assertEquals(2, ((List) pom.getValue("repositories")).size()); + assertEquals("project-remote-repo", pom.getValue("repositories[1]/id")); + assertEquals("https://project.url/remote", pom.getValue("repositories[1]/url")); + assertEquals("repo", pom.getValue("repositories[1]/name")); + assertEquals(RepositorySystem.DEFAULT_REMOTE_REPO_ID, pom.getValue("repositories[2]/id")); + assertEquals(RepositorySystem.DEFAULT_REMOTE_REPO_URL, pom.getValue("repositories[2]/url")); - assertEquals( "test", pom.getValue( "build/defaultGoal" ) ); - assertEquals( "coreit", pom.getValue( "build/finalName" ) ); + assertEquals("test", pom.getValue("build/defaultGoal")); + assertEquals("coreit", pom.getValue("build/finalName")); - assertPathSuffixEquals( "build", pom.getValue( "build/directory" ) ); - assertPathSuffixEquals( "build/main", pom.getValue( "build/outputDirectory" ) ); - assertPathSuffixEquals( "build/test", pom.getValue( "build/testOutputDirectory" ) ); - assertPathSuffixEquals( "sources/main", pom.getValue( "build/sourceDirectory" ) ); - assertPathSuffixEquals( "sources/test", pom.getValue( "build/testSourceDirectory" ) ); - assertPathSuffixEquals( "sources/scripts", pom.getValue( "build/scriptSourceDirectory" ) ); + assertPathSuffixEquals("build", pom.getValue("build/directory")); + assertPathSuffixEquals("build/main", pom.getValue("build/outputDirectory")); + assertPathSuffixEquals("build/test", pom.getValue("build/testOutputDirectory")); + assertPathSuffixEquals("sources/main", pom.getValue("build/sourceDirectory")); + assertPathSuffixEquals("sources/test", pom.getValue("build/testSourceDirectory")); + assertPathSuffixEquals("sources/scripts", pom.getValue("build/scriptSourceDirectory")); - assertEquals( 1, ( (List) pom.getValue( "build/filters" ) ).size() ); - assertPathSuffixEquals( "src/main/filter/it.properties", pom.getValue( "build/filters[1]" ) ); + assertEquals(1, ((List) pom.getValue("build/filters")).size()); + assertPathSuffixEquals("src/main/filter/it.properties", pom.getValue("build/filters[1]")); - assertEquals( 1, ( (List) pom.getValue( "build/resources" ) ).size() ); - assertPathSuffixEquals( "res/main", pom.getValue( "build/resources[1]/directory" ) ); - assertPathSuffixEquals( "main", pom.getValue( "build/resources[1]/targetPath" ) ); - assertEquals( Boolean.TRUE, pom.getValue( "build/resources[1]/filtering" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/resources[1]/includes" ) ).size() ); - assertPathSuffixEquals( "main.included", pom.getValue( "build/resources[1]/includes[1]" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/resources[1]/excludes" ) ).size() ); - assertPathSuffixEquals( "main.excluded", pom.getValue( "build/resources[1]/excludes[1]" ) ); + assertEquals(1, ((List) pom.getValue("build/resources")).size()); + assertPathSuffixEquals("res/main", pom.getValue("build/resources[1]/directory")); + assertPathSuffixEquals("main", pom.getValue("build/resources[1]/targetPath")); + assertEquals(Boolean.TRUE, pom.getValue("build/resources[1]/filtering")); + assertEquals(1, ((List) pom.getValue("build/resources[1]/includes")).size()); + assertPathSuffixEquals("main.included", pom.getValue("build/resources[1]/includes[1]")); + assertEquals(1, ((List) pom.getValue("build/resources[1]/excludes")).size()); + assertPathSuffixEquals("main.excluded", pom.getValue("build/resources[1]/excludes[1]")); - assertEquals( 1, ( (List) pom.getValue( "build/testResources" ) ).size() ); - assertPathSuffixEquals( "res/test", pom.getValue( "build/testResources[1]/directory" ) ); - assertPathSuffixEquals( "test", pom.getValue( "build/testResources[1]/targetPath" ) ); - assertEquals( Boolean.TRUE, pom.getValue( "build/testResources[1]/filtering" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/testResources[1]/includes" ) ).size() ); - assertPathSuffixEquals( "test.included", pom.getValue( "build/testResources[1]/includes[1]" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/testResources[1]/excludes" ) ).size() ); - assertPathSuffixEquals( "test.excluded", pom.getValue( "build/testResources[1]/excludes[1]" ) ); + assertEquals(1, ((List) pom.getValue("build/testResources")).size()); + assertPathSuffixEquals("res/test", pom.getValue("build/testResources[1]/directory")); + assertPathSuffixEquals("test", pom.getValue("build/testResources[1]/targetPath")); + assertEquals(Boolean.TRUE, pom.getValue("build/testResources[1]/filtering")); + assertEquals(1, ((List) pom.getValue("build/testResources[1]/includes")).size()); + assertPathSuffixEquals("test.included", pom.getValue("build/testResources[1]/includes[1]")); + assertEquals(1, ((List) pom.getValue("build/testResources[1]/excludes")).size()); + assertPathSuffixEquals("test.excluded", pom.getValue("build/testResources[1]/excludes[1]")); - assertEquals( 1, ( (List) pom.getValue( "build/extensions" ) ).size() ); - assertEquals( "org.apache.maven.its.ext", pom.getValue( "build/extensions[1]/groupId" ) ); - assertEquals( "ext", pom.getValue( "build/extensions[1]/artifactId" ) ); - assertEquals( "3.0", pom.getValue( "build/extensions[1]/version" ) ); + assertEquals(1, ((List) pom.getValue("build/extensions")).size()); + assertEquals("org.apache.maven.its.ext", pom.getValue("build/extensions[1]/groupId")); + assertEquals("ext", pom.getValue("build/extensions[1]/artifactId")); + assertEquals("3.0", pom.getValue("build/extensions[1]/version")); - assertEquals( 1, ( (List) pom.getValue( "build/plugins" ) ).size() ); - assertEquals( "org.apache.maven.its.plugins", pom.getValue( "build/plugins[1]/groupId" ) ); - assertEquals( "maven-it-plugin-build", pom.getValue( "build/plugins[1]/artifactId" ) ); - assertEquals( "2.1-SNAPSHOT", pom.getValue( "build/plugins[1]/version" ) ); - assertEquals( "test.properties", pom.getValue( "build/plugins[1]/configuration/outputFile" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/executions" ) ).size() ); - assertEquals( "test", pom.getValue( "build/plugins[1]/executions[1]/id" ) ); - assertEquals( "validate", pom.getValue( "build/plugins[1]/executions[1]/phase" ) ); - assertEquals( "pom.properties", pom.getValue( "build/plugins[1]/executions[1]/configuration/outputFile" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/executions[1]/goals" ) ).size() ); - assertEquals( "eval", pom.getValue( "build/plugins[1]/executions[1]/goals[1]" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/dependencies" ) ).size() ); - assertEquals( "org.apache.maven.its", pom.getValue( "build/plugins[1]/dependencies[1]/groupId" ) ); - assertEquals( "build-plugin-dep", pom.getValue( "build/plugins[1]/dependencies[1]/artifactId" ) ); - assertEquals( "0.3", pom.getValue( "build/plugins[1]/dependencies[1]/version" ) ); - assertEquals( "zip", pom.getValue( "build/plugins[1]/dependencies[1]/type" ) ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins[1]/dependencies[1]/exclusions" ) ).size() ); - assertEquals( "org.apache.maven.its", pom.getValue( "build/plugins[1]/dependencies[1]/exclusions[1]/groupId" ) ); - assertEquals( "excluded-build-plugin-dep", - pom.getValue( "build/plugins[1]/dependencies[1]/exclusions[1]/artifactId" ) ); + assertEquals(1, ((List) pom.getValue("build/plugins")).size()); + assertEquals("org.apache.maven.its.plugins", pom.getValue("build/plugins[1]/groupId")); + assertEquals("maven-it-plugin-build", pom.getValue("build/plugins[1]/artifactId")); + assertEquals("2.1-SNAPSHOT", pom.getValue("build/plugins[1]/version")); + assertEquals("test.properties", pom.getValue("build/plugins[1]/configuration/outputFile")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/executions")).size()); + assertEquals("test", pom.getValue("build/plugins[1]/executions[1]/id")); + assertEquals("validate", pom.getValue("build/plugins[1]/executions[1]/phase")); + assertEquals("pom.properties", pom.getValue("build/plugins[1]/executions[1]/configuration/outputFile")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/executions[1]/goals")).size()); + assertEquals("eval", pom.getValue("build/plugins[1]/executions[1]/goals[1]")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/dependencies")).size()); + assertEquals("org.apache.maven.its", pom.getValue("build/plugins[1]/dependencies[1]/groupId")); + assertEquals("build-plugin-dep", pom.getValue("build/plugins[1]/dependencies[1]/artifactId")); + assertEquals("0.3", pom.getValue("build/plugins[1]/dependencies[1]/version")); + assertEquals("zip", pom.getValue("build/plugins[1]/dependencies[1]/type")); + assertEquals(1, ((List) pom.getValue("build/plugins[1]/dependencies[1]/exclusions")).size()); + assertEquals("org.apache.maven.its", pom.getValue("build/plugins[1]/dependencies[1]/exclusions[1]/groupId")); + assertEquals( + "excluded-build-plugin-dep", pom.getValue("build/plugins[1]/dependencies[1]/exclusions[1]/artifactId")); - assertEquals( Boolean.TRUE, pom.getValue( "reporting/excludeDefaults" ) ); - assertPathSuffixEquals( "docs", pom.getValue( "reporting/outputDirectory" ) ); + assertEquals(Boolean.TRUE, pom.getValue("reporting/excludeDefaults")); + assertPathSuffixEquals("docs", pom.getValue("reporting/outputDirectory")); - assertEquals( 1, ( (List) pom.getValue( "reporting/plugins" ) ).size() ); - assertEquals( "org.apache.maven.its.plugins", pom.getValue( "reporting/plugins[1]/groupId" ) ); - assertEquals( "maven-it-plugin-reporting", pom.getValue( "reporting/plugins[1]/artifactId" ) ); - assertEquals( "2.0-SNAPSHOT", pom.getValue( "reporting/plugins[1]/version" ) ); - assertEquals( "test.html", pom.getValue( "reporting/plugins[1]/configuration/outputFile" ) ); - assertEquals( 1, ( (List) pom.getValue( "reporting/plugins[1]/reportSets" ) ).size() ); - assertEquals( "it", pom.getValue( "reporting/plugins[1]/reportSets[1]/id" ) ); - assertEquals( "index.html", pom.getValue( "reporting/plugins[1]/reportSets[1]/configuration/outputFile" ) ); - assertEquals( 1, ( (List) pom.getValue( "reporting/plugins[1]/reportSets[1]/reports" ) ).size() ); - assertEquals( "run", pom.getValue( "reporting/plugins[1]/reportSets[1]/reports[1]" ) ); + assertEquals(1, ((List) pom.getValue("reporting/plugins")).size()); + assertEquals("org.apache.maven.its.plugins", pom.getValue("reporting/plugins[1]/groupId")); + assertEquals("maven-it-plugin-reporting", pom.getValue("reporting/plugins[1]/artifactId")); + assertEquals("2.0-SNAPSHOT", pom.getValue("reporting/plugins[1]/version")); + assertEquals("test.html", pom.getValue("reporting/plugins[1]/configuration/outputFile")); + assertEquals(1, ((List) pom.getValue("reporting/plugins[1]/reportSets")).size()); + assertEquals("it", pom.getValue("reporting/plugins[1]/reportSets[1]/id")); + assertEquals("index.html", pom.getValue("reporting/plugins[1]/reportSets[1]/configuration/outputFile")); + assertEquals(1, ((List) pom.getValue("reporting/plugins[1]/reportSets[1]/reports")).size()); + assertEquals("run", pom.getValue("reporting/plugins[1]/reportSets[1]/reports[1]")); } /* MNG-2309*/ @Test - public void testProfileInjectionOrder() - throws Exception - { - PomTestWrapper pom = - buildPom( "profile-injection-order", "pom-a", "pom-b", "pom-e", "pom-c", "pom-d" ); - assertEquals( "e", pom.getValue( "properties[1]/pomProperty" ) ); + public void testProfileInjectionOrder() throws Exception { + PomTestWrapper pom = buildPom("profile-injection-order", "pom-a", "pom-b", "pom-e", "pom-c", "pom-d"); + assertEquals("e", pom.getValue("properties[1]/pomProperty")); } @Test - public void testPropertiesInheritance() - throws Exception - { - PomTestWrapper pom = buildPom( "properties-inheritance/sub" ); - assertEquals( "parent-property", pom.getValue( "properties/parentProperty" ) ); - assertEquals( "child-property", pom.getValue( "properties/childProperty" ) ); - assertEquals( "child-override", pom.getValue( "properties/overriddenProperty" ) ); + public void testPropertiesInheritance() throws Exception { + PomTestWrapper pom = buildPom("properties-inheritance/sub"); + assertEquals("parent-property", pom.getValue("properties/parentProperty")); + assertEquals("child-property", pom.getValue("properties/childProperty")); + assertEquals("child-override", pom.getValue("properties/overriddenProperty")); } /* MNG-4102*/ @Test - public void testInheritedPropertiesInterpolatedWithValuesFromChildWithoutProfiles() - throws Exception - { - PomTestWrapper pom = buildPom( "inherited-properties-interpolation/no-profile/sub" ); + public void testInheritedPropertiesInterpolatedWithValuesFromChildWithoutProfiles() throws Exception { + PomTestWrapper pom = buildPom("inherited-properties-interpolation/no-profile/sub"); - assertEquals( "CHILD", pom.getValue( "properties/overridden" ) ); - assertEquals( "CHILD", pom.getValue( "properties/interpolated" ) ); + assertEquals("CHILD", pom.getValue("properties/overridden")); + assertEquals("CHILD", pom.getValue("properties/interpolated")); } /* MNG-4102 */ @Test - public void testInheritedPropertiesInterpolatedWithValuesFromChildWithActiveProfiles() - throws Exception - { - PomTestWrapper pom = buildPom( "inherited-properties-interpolation/active-profile/sub" ); + public void testInheritedPropertiesInterpolatedWithValuesFromChildWithActiveProfiles() throws Exception { + PomTestWrapper pom = buildPom("inherited-properties-interpolation/active-profile/sub"); - assertEquals( 1, pom.getMavenProject().getModel().getProfiles().size() ); + assertEquals(1, pom.getMavenProject().getModel().getProfiles().size()); - buildPom( "inherited-properties-interpolation/active-profile/sub", "it-parent", "it-child" ); - assertEquals( "CHILD", pom.getValue( "properties/overridden" ) ); - assertEquals( "CHILD", pom.getValue( "properties/interpolated" ) ); + buildPom("inherited-properties-interpolation/active-profile/sub", "it-parent", "it-child"); + assertEquals("CHILD", pom.getValue("properties/overridden")); + assertEquals("CHILD", pom.getValue("properties/interpolated")); } /* MNG-3545 */ @Test - public void testProfileDefaultActivation() - throws Exception - { - PomTestWrapper pom = buildPom( "profile-default-deactivation", "profile4" ); - assertEquals( 1, pom.getMavenProject().getActiveProfiles().size() ); - assertEquals( 1, ( (List) pom.getValue( "build/plugins" ) ).size() ); - assertEquals( "2.1", pom.getValue( "build/plugins[1]/version" ) ); + public void testProfileDefaultActivation() throws Exception { + PomTestWrapper pom = buildPom("profile-default-deactivation", "profile4"); + assertEquals(1, pom.getMavenProject().getActiveProfiles().size()); + assertEquals(1, ((List) pom.getValue("build/plugins")).size()); + assertEquals("2.1", pom.getValue("build/plugins[1]/version")); } /* MNG-1995 */ @Test - public void testBooleanInterpolation() - throws Exception - { - PomTestWrapper pom = buildPom( "boolean-interpolation" ); - assertEquals(true, pom.getValue( "repositories[1]/releases/enabled" ) ); - assertEquals(true, pom.getValue( "build/resources[1]/filtering" ) ); + public void testBooleanInterpolation() throws Exception { + PomTestWrapper pom = buildPom("boolean-interpolation"); + assertEquals(true, pom.getValue("repositories[1]/releases/enabled")); + assertEquals(true, pom.getValue("build/resources[1]/filtering")); } - /* MNG-3899 */ @Test - public void testBuildExtensionInheritance() - throws Exception - { - PomTestWrapper pom = buildPom( "build-extension-inheritance/sub" ); - assertEquals( 3, ( (List) pom.getValue( "build/extensions" ) ).size() ); - assertEquals( "b", pom.getValue( "build/extensions[1]/artifactId" ) ); - assertEquals( "a", pom.getValue( "build/extensions[2]/artifactId" ) ); - assertEquals( "0.2", pom.getValue( "build/extensions[2]/version" ) ); - assertEquals( "c", pom.getValue( "build/extensions[3]/artifactId" ) ); + public void testBuildExtensionInheritance() throws Exception { + PomTestWrapper pom = buildPom("build-extension-inheritance/sub"); + assertEquals(3, ((List) pom.getValue("build/extensions")).size()); + assertEquals("b", pom.getValue("build/extensions[1]/artifactId")); + assertEquals("a", pom.getValue("build/extensions[2]/artifactId")); + assertEquals("0.2", pom.getValue("build/extensions[2]/version")); + assertEquals("c", pom.getValue("build/extensions[3]/artifactId")); } /*MNG-1957*/ @Test - public void testJdkActivation() - throws Exception - { + public void testJdkActivation() throws Exception { Properties props = new Properties(); - props.put( "java.version", "1.5.0_15" ); + props.put("java.version", "1.5.0_15"); - PomTestWrapper pom = buildPom( "jdk-activation", props, null ); - assertEquals( 3, pom.getMavenProject().getActiveProfiles().size() ); - assertEquals( "PASSED", pom.getValue( "properties/jdkProperty3" ) ); - assertEquals( "PASSED", pom.getValue( "properties/jdkProperty2" ) ); - assertEquals( "PASSED", pom.getValue( "properties/jdkProperty1" ) ); + PomTestWrapper pom = buildPom("jdk-activation", props, null); + assertEquals(3, pom.getMavenProject().getActiveProfiles().size()); + assertEquals("PASSED", pom.getValue("properties/jdkProperty3")); + assertEquals("PASSED", pom.getValue("properties/jdkProperty2")); + assertEquals("PASSED", pom.getValue("properties/jdkProperty1")); } /* MNG-2174 */ @Test - public void testProfilePluginMngDependencies() - throws Exception - { - PomTestWrapper pom = buildPom( "profile-plugin-mng-dependencies/sub", "maven-core-it" ); - assertEquals( "a", pom.getValue( "build/plugins[1]/dependencies[1]/artifactId" ) ); + public void testProfilePluginMngDependencies() throws Exception { + PomTestWrapper pom = buildPom("profile-plugin-mng-dependencies/sub", "maven-core-it"); + assertEquals("a", pom.getValue("build/plugins[1]/dependencies[1]/artifactId")); } /** MNG-4116 */ @Test - public void testPercentEncodedUrlsMustNotBeDecoded() - throws Exception - { - PomTestWrapper pom = this.buildPom( "url-no-decoding" ); - assertEquals( "https://maven.apache.org/spacy%20path", pom.getValue( "url" ) ); - assertEquals( "https://svn.apache.org/viewvc/spacy%20path", pom.getValue( "scm/url" ) ); - assertEquals( "scm:svn:svn+ssh://svn.apache.org/spacy%20path", pom.getValue( "scm/connection" ) ); - assertEquals( "scm:svn:svn+ssh://svn.apache.org/spacy%20path", pom.getValue( "scm/developerConnection" ) ); - assertEquals( "https://issues.apache.org/spacy%20path", pom.getValue( "issueManagement/url" ) ); - assertEquals( "https://ci.apache.org/spacy%20path", pom.getValue( "ciManagement/url" ) ); - assertEquals( "scm:svn:svn+ssh://dist.apache.org/spacy%20path", - pom.getValue( "distributionManagement/repository/url" ) ); - assertEquals( "scm:svn:svn+ssh://snap.apache.org/spacy%20path", - pom.getValue( "distributionManagement/snapshotRepository/url" ) ); - assertEquals( "scm:svn:svn+ssh://site.apache.org/spacy%20path", - pom.getValue( "distributionManagement/site/url" ) ); + public void testPercentEncodedUrlsMustNotBeDecoded() throws Exception { + PomTestWrapper pom = this.buildPom("url-no-decoding"); + assertEquals("https://maven.apache.org/spacy%20path", pom.getValue("url")); + assertEquals("https://svn.apache.org/viewvc/spacy%20path", pom.getValue("scm/url")); + assertEquals("scm:svn:svn+ssh://svn.apache.org/spacy%20path", pom.getValue("scm/connection")); + assertEquals("scm:svn:svn+ssh://svn.apache.org/spacy%20path", pom.getValue("scm/developerConnection")); + assertEquals("https://issues.apache.org/spacy%20path", pom.getValue("issueManagement/url")); + assertEquals("https://ci.apache.org/spacy%20path", pom.getValue("ciManagement/url")); + assertEquals( + "scm:svn:svn+ssh://dist.apache.org/spacy%20path", + pom.getValue("distributionManagement/repository/url")); + assertEquals( + "scm:svn:svn+ssh://snap.apache.org/spacy%20path", + pom.getValue("distributionManagement/snapshotRepository/url")); + assertEquals("scm:svn:svn+ssh://site.apache.org/spacy%20path", pom.getValue("distributionManagement/site/url")); } @Test - public void testPluginManagementInheritance() - throws Exception - { - PomTestWrapper pom = this.buildPom( "plugin-management-inheritance" ); - assertEquals( "0.1-stub-SNAPSHOT", - pom.getValue( "build/pluginManagement/plugins[@artifactId='maven-compiler-plugin']/version" ) ); + public void testPluginManagementInheritance() throws Exception { + PomTestWrapper pom = this.buildPom("plugin-management-inheritance"); + assertEquals( + "0.1-stub-SNAPSHOT", + pom.getValue("build/pluginManagement/plugins[@artifactId='maven-compiler-plugin']/version")); } @Test - public void testProfilePlugins() - throws Exception - { - PomTestWrapper pom = this.buildPom( "profile-plugins", "standard" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins" ) ).size() ); - assertEquals( "maven-assembly2-plugin", pom.getValue( "build/plugins[2]/artifactId" ) ); + public void testProfilePlugins() throws Exception { + PomTestWrapper pom = this.buildPom("profile-plugins", "standard"); + assertEquals(2, ((List) pom.getValue("build/plugins")).size()); + assertEquals("maven-assembly2-plugin", pom.getValue("build/plugins[2]/artifactId")); } @Test - public void testPluginInheritanceSimple() - throws Exception - { - PomTestWrapper pom = this.buildPom( "plugin-inheritance-simple/sub" ); - assertEquals( 2, ( (List) pom.getValue( "build/plugins" ) ).size() ); + public void testPluginInheritanceSimple() throws Exception { + PomTestWrapper pom = this.buildPom("plugin-inheritance-simple/sub"); + assertEquals(2, ((List) pom.getValue("build/plugins")).size()); } @Test - public void testPluginManagementDuplicate() - throws Exception - { - PomTestWrapper pom = this.buildPom( "plugin-management-duplicate/sub" ); - assertEquals( 8, ( (List) pom.getValue( "build/pluginManagement/plugins" ) ).size() ); + public void testPluginManagementDuplicate() throws Exception { + PomTestWrapper pom = this.buildPom("plugin-management-duplicate/sub"); + assertEquals(8, ((List) pom.getValue("build/pluginManagement/plugins")).size()); } @Test - public void testDistributionManagement() - throws Exception - { - PomTestWrapper pom = this.buildPom( "distribution-management" ); - assertEquals( "legacy", pom.getValue( "distributionManagement/repository/layout" ) ); + public void testDistributionManagement() throws Exception { + PomTestWrapper pom = this.buildPom("distribution-management"); + assertEquals("legacy", pom.getValue("distributionManagement/repository/layout")); } @Test - public void testDependencyScopeInheritance() - throws Exception - { - PomTestWrapper pom = buildPom( "dependency-scope-inheritance/sub" ); - String scope = (String) pom.getValue( "dependencies[1]/scope" ); - assertEquals( "compile", scope ); + public void testDependencyScopeInheritance() throws Exception { + PomTestWrapper pom = buildPom("dependency-scope-inheritance/sub"); + String scope = (String) pom.getValue("dependencies[1]/scope"); + assertEquals("compile", scope); } @Test - public void testDependencyScope() - throws Exception - { - buildPom( "dependency-scope/sub" ); + public void testDependencyScope() throws Exception { + buildPom("dependency-scope/sub"); } - //This will fail on a validation error if incorrect - public void testDependencyManagementWithInterpolation() - throws Exception - { - buildPom( "dependency-management-with-interpolation/sub" ); + // This will fail on a validation error if incorrect + public void testDependencyManagementWithInterpolation() throws Exception { + buildPom("dependency-management-with-interpolation/sub"); } @Test - public void testInterpolationWithSystemProperty() - throws Exception - { + public void testInterpolationWithSystemProperty() throws Exception { Properties sysProps = new Properties(); - sysProps.setProperty( "system.property", "PASSED" ); - PomTestWrapper pom = buildPom( "system-property-interpolation", sysProps, null ); - assertEquals( "PASSED", pom.getValue( "name" ) ); + sysProps.setProperty("system.property", "PASSED"); + PomTestWrapper pom = buildPom("system-property-interpolation", sysProps, null); + assertEquals("PASSED", pom.getValue("name")); } /* MNG-4129 */ @Test - public void testPluginExecutionInheritanceWhenChildDoesNotDeclarePlugin() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-inheritance/wo-merge" ); - @SuppressWarnings( "unchecked" ) - List executions = - (List) pom.getValue( "build/pluginsAsMap[@name='org.apache.maven.its.plugins:maven-it-plugin-log-file']/executions" ); - assertEquals( 1, executions.size() ); - assertEquals( "inherited-execution", executions.get( 0 ).getId() ); + public void testPluginExecutionInheritanceWhenChildDoesNotDeclarePlugin() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-inheritance/wo-merge"); + @SuppressWarnings("unchecked") + List executions = (List) pom.getValue( + "build/pluginsAsMap[@name='org.apache.maven.its.plugins:maven-it-plugin-log-file']/executions"); + assertEquals(1, executions.size()); + assertEquals("inherited-execution", executions.get(0).getId()); } @Test - public void testPluginExecutionInheritanceWhenChildDoesDeclarePluginAsWell() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-inheritance/w-merge" ); - @SuppressWarnings( "unchecked" ) - List executions = - (List) pom.getValue( "build/pluginsAsMap[@name='org.apache.maven.its.plugins:maven-it-plugin-log-file']/executions" ); - assertEquals( 1, executions.size() ); - assertEquals( "inherited-execution", executions.get( 0 ).getId() ); + public void testPluginExecutionInheritanceWhenChildDoesDeclarePluginAsWell() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-inheritance/w-merge"); + @SuppressWarnings("unchecked") + List executions = (List) pom.getValue( + "build/pluginsAsMap[@name='org.apache.maven.its.plugins:maven-it-plugin-log-file']/executions"); + assertEquals(1, executions.size()); + assertEquals("inherited-execution", executions.get(0).getId()); } /* MNG-4193 */ @Test - public void testValidationErrorUponNonUniqueArtifactRepositoryId() - throws Exception - { + public void testValidationErrorUponNonUniqueArtifactRepositoryId() throws Exception { assertThrows( ProjectBuildingException.class, - () -> buildPom( "unique-repo-id/artifact-repo" ), - "Non-unique repository ids did not cause validation error" ); + () -> buildPom("unique-repo-id/artifact-repo"), + "Non-unique repository ids did not cause validation error"); } /* MNG-4193 */ @Test - public void testValidationErrorUponNonUniquePluginRepositoryId() - throws Exception - { + public void testValidationErrorUponNonUniquePluginRepositoryId() throws Exception { assertThrows( ProjectBuildingException.class, - () -> buildPom( "unique-repo-id/plugin-repo" ), - "Non-unique repository ids did not cause validation error" ); + () -> buildPom("unique-repo-id/plugin-repo"), + "Non-unique repository ids did not cause validation error"); } /* MNG-4193 */ @Test - public void testValidationErrorUponNonUniqueArtifactRepositoryIdInProfile() - throws Exception - { + public void testValidationErrorUponNonUniqueArtifactRepositoryIdInProfile() throws Exception { assertThrows( ProjectBuildingException.class, - () -> buildPom( "unique-repo-id/artifact-repo-in-profile" ), - "Non-unique repository ids did not cause validation error" ); + () -> buildPom("unique-repo-id/artifact-repo-in-profile"), + "Non-unique repository ids did not cause validation error"); } /* MNG-4193 */ @Test - public void testValidationErrorUponNonUniquePluginRepositoryIdInProfile() - throws Exception - { + public void testValidationErrorUponNonUniquePluginRepositoryIdInProfile() throws Exception { assertThrows( ProjectBuildingException.class, - () -> buildPom( "unique-repo-id/plugin-repo-in-profile" ), - "Non-unique repository ids did not cause validation error" ); + () -> buildPom("unique-repo-id/plugin-repo-in-profile"), + "Non-unique repository ids did not cause validation error"); } /** MNG-3843 */ @Test - public void testPrerequisitesAreNotInherited() - throws Exception - { - PomTestWrapper pom = buildPom( "prerequisites-inheritance/child" ); - assertSame( null, pom.getValue( "prerequisites" ) ); + public void testPrerequisitesAreNotInherited() throws Exception { + PomTestWrapper pom = buildPom("prerequisites-inheritance/child"); + assertSame(null, pom.getValue("prerequisites")); } @Test - public void testLicensesAreInheritedButNotAggregated() - throws Exception - { - PomTestWrapper pom = buildPom( "licenses-inheritance/child-2" ); - assertEquals( 1, ( (List) pom.getValue( "licenses" ) ).size() ); - assertEquals( "child-license", pom.getValue( "licenses[1]/name" ) ); - assertEquals( "https://child.url/license", pom.getValue( "licenses[1]/url" ) ); + public void testLicensesAreInheritedButNotAggregated() throws Exception { + PomTestWrapper pom = buildPom("licenses-inheritance/child-2"); + assertEquals(1, ((List) pom.getValue("licenses")).size()); + assertEquals("child-license", pom.getValue("licenses[1]/name")); + assertEquals("https://child.url/license", pom.getValue("licenses[1]/url")); } @Test - public void testDevelopersAreInheritedButNotAggregated() - throws Exception - { - PomTestWrapper pom = buildPom( "developers-inheritance/child-2" ); - assertEquals( 1, ( (List) pom.getValue( "developers" ) ).size() ); - assertEquals( "child-developer", pom.getValue( "developers[1]/name" ) ); + public void testDevelopersAreInheritedButNotAggregated() throws Exception { + PomTestWrapper pom = buildPom("developers-inheritance/child-2"); + assertEquals(1, ((List) pom.getValue("developers")).size()); + assertEquals("child-developer", pom.getValue("developers[1]/name")); } @Test - public void testContributorsAreInheritedButNotAggregated() - throws Exception - { - PomTestWrapper pom = buildPom( "contributors-inheritance/child-2" ); - assertEquals( 1, ( (List) pom.getValue( "contributors" ) ).size() ); - assertEquals( "child-contributor", pom.getValue( "contributors[1]/name" ) ); + public void testContributorsAreInheritedButNotAggregated() throws Exception { + PomTestWrapper pom = buildPom("contributors-inheritance/child-2"); + assertEquals(1, ((List) pom.getValue("contributors")).size()); + assertEquals("child-contributor", pom.getValue("contributors[1]/name")); } @Test - public void testMailingListsAreInheritedButNotAggregated() - throws Exception - { - PomTestWrapper pom = buildPom( "mailing-lists-inheritance/child-2" ); - assertEquals( 1, ( (List) pom.getValue( "mailingLists" ) ).size() ); - assertEquals( "child-mailing-list", pom.getValue( "mailingLists[1]/name" ) ); + public void testMailingListsAreInheritedButNotAggregated() throws Exception { + PomTestWrapper pom = buildPom("mailing-lists-inheritance/child-2"); + assertEquals(1, ((List) pom.getValue("mailingLists")).size()); + assertEquals("child-mailing-list", pom.getValue("mailingLists[1]/name")); } @Test - public void testPluginInheritanceOrder() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-inheritance-order/child" ); + public void testPluginInheritanceOrder() throws Exception { + PomTestWrapper pom = buildPom("plugin-inheritance-order/child"); - assertEquals( "maven-it-plugin-log-file", pom.getValue( "build/plugins[1]/artifactId" ) ); - assertEquals( "maven-it-plugin-expression", pom.getValue( "build/plugins[2]/artifactId" ) ); - assertEquals( "maven-it-plugin-configuration", pom.getValue( "build/plugins[3]/artifactId" ) ); + assertEquals("maven-it-plugin-log-file", pom.getValue("build/plugins[1]/artifactId")); + assertEquals("maven-it-plugin-expression", pom.getValue("build/plugins[2]/artifactId")); + assertEquals("maven-it-plugin-configuration", pom.getValue("build/plugins[3]/artifactId")); - assertEquals( "maven-it-plugin-log-file", pom.getValue( "reporting/plugins[1]/artifactId" ) ); - assertEquals( "maven-it-plugin-expression", pom.getValue( "reporting/plugins[2]/artifactId" ) ); - assertEquals( "maven-it-plugin-configuration", pom.getValue( "reporting/plugins[3]/artifactId" ) ); + assertEquals("maven-it-plugin-log-file", pom.getValue("reporting/plugins[1]/artifactId")); + assertEquals("maven-it-plugin-expression", pom.getValue("reporting/plugins[2]/artifactId")); + assertEquals("maven-it-plugin-configuration", pom.getValue("reporting/plugins[3]/artifactId")); } @Test - public void testCliPropsDominateProjectPropsDuringInterpolation() - throws Exception - { + public void testCliPropsDominateProjectPropsDuringInterpolation() throws Exception { Properties props = new Properties(); - props.setProperty( "testProperty", "PASSED" ); - PomTestWrapper pom = buildPom( "interpolation-cli-wins", null, props ); + props.setProperty("testProperty", "PASSED"); + PomTestWrapper pom = buildPom("interpolation-cli-wins", null, props); - assertEquals( "PASSED", pom.getValue( "properties/interpolatedProperty" ) ); + assertEquals("PASSED", pom.getValue("properties/interpolatedProperty")); } @Test - public void testParentPomPackagingMustBePom() - throws Exception - { + public void testParentPomPackagingMustBePom() throws Exception { assertThrows( ProjectBuildingException.class, - () -> buildPom( "parent-pom-packaging/sub" ), - "Wrong packaging of parent POM was not rejected" ); + () -> buildPom("parent-pom-packaging/sub"), + "Wrong packaging of parent POM was not rejected"); } /** MNG-522, MNG-3018 */ @Test - public void testManagedPluginConfigurationAppliesToImplicitPluginsIntroducedByPackaging() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-management-for-implicit-plugin/child" ); - assertEquals( "passed.txt", - pom.getValue( "build/plugins[@artifactId='maven-resources-plugin']/configuration/pathname" ) ); - assertEquals( "passed.txt", - pom.getValue( "build/plugins[@artifactId='maven-it-plugin-log-file']/configuration/logFile" ) ); + public void testManagedPluginConfigurationAppliesToImplicitPluginsIntroducedByPackaging() throws Exception { + PomTestWrapper pom = buildPom("plugin-management-for-implicit-plugin/child"); + assertEquals( + "passed.txt", + pom.getValue("build/plugins[@artifactId='maven-resources-plugin']/configuration/pathname")); + assertEquals( + "passed.txt", + pom.getValue("build/plugins[@artifactId='maven-it-plugin-log-file']/configuration/logFile")); } @Test - public void testDefaultPluginsExecutionContributedByPackagingExecuteBeforeUserDefinedExecutions() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-order-and-default-exec" ); - @SuppressWarnings( "unchecked" ) + public void testDefaultPluginsExecutionContributedByPackagingExecuteBeforeUserDefinedExecutions() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-order-and-default-exec"); + @SuppressWarnings("unchecked") List executions = - (List) pom.getValue( "build/plugins[@artifactId='maven-resources-plugin']/executions" ); - assertNotNull( executions ); - assertEquals( 4, executions.size() ); - assertEquals( "default-resources", executions.get( 0 ).getId() ); - assertEquals( "default-testResources", executions.get( 1 ).getId() ); - assertEquals( "test-1", executions.get( 2 ).getId() ); - assertEquals( "test-2", executions.get( 3 ).getId() ); + (List) pom.getValue("build/plugins[@artifactId='maven-resources-plugin']/executions"); + assertNotNull(executions); + assertEquals(4, executions.size()); + assertEquals("default-resources", executions.get(0).getId()); + assertEquals("default-testResources", executions.get(1).getId()); + assertEquals("test-1", executions.get(2).getId()); + assertEquals("test-2", executions.get(3).getId()); } @Test - public void testPluginDeclarationsRetainPomOrderAfterInjectionOfDefaultPlugins() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-exec-order-with-lifecycle" ); - @SuppressWarnings( "unchecked" ) - List plugins = (List) pom.getValue( "build/plugins" ); + public void testPluginDeclarationsRetainPomOrderAfterInjectionOfDefaultPlugins() throws Exception { + PomTestWrapper pom = buildPom("plugin-exec-order-with-lifecycle"); + @SuppressWarnings("unchecked") + List plugins = (List) pom.getValue("build/plugins"); int resourcesPlugin = -1; int customPlugin = -1; - for ( int i = 0; i < plugins.size(); i++ ) - { - Plugin plugin = plugins.get( i ); - if ( "maven-resources-plugin".equals( plugin.getArtifactId() ) ) - { - assertThat( resourcesPlugin, lessThan( 0 ) ); + for (int i = 0; i < plugins.size(); i++) { + Plugin plugin = plugins.get(i); + if ("maven-resources-plugin".equals(plugin.getArtifactId())) { + assertThat(resourcesPlugin, lessThan(0)); resourcesPlugin = i; - } - else if ( "maven-it-plugin-log-file".equals( plugin.getArtifactId() ) ) - { - assertThat( customPlugin, lessThan( 0 ) ); + } else if ("maven-it-plugin-log-file".equals(plugin.getArtifactId())) { + assertThat(customPlugin, lessThan(0)); customPlugin = i; } } - assertEquals( customPlugin, resourcesPlugin - 1, plugins.toString() ); + assertEquals(customPlugin, resourcesPlugin - 1, plugins.toString()); } /** MNG-4415 */ @Test - public void testPluginOrderAfterMergingWithInheritedPlugins() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-inheritance-merge-order/sub" ); + public void testPluginOrderAfterMergingWithInheritedPlugins() throws Exception { + PomTestWrapper pom = buildPom("plugin-inheritance-merge-order/sub"); List expected = new ArrayList<>(); - expected.add( "maven-it-plugin-error" ); - expected.add( "maven-it-plugin-configuration" ); - expected.add( "maven-it-plugin-dependency-resolution" ); - expected.add( "maven-it-plugin-packaging" ); - expected.add( "maven-it-plugin-log-file" ); - expected.add( "maven-it-plugin-expression" ); - expected.add( "maven-it-plugin-fork" ); - expected.add( "maven-it-plugin-touch" ); + expected.add("maven-it-plugin-error"); + expected.add("maven-it-plugin-configuration"); + expected.add("maven-it-plugin-dependency-resolution"); + expected.add("maven-it-plugin-packaging"); + expected.add("maven-it-plugin-log-file"); + expected.add("maven-it-plugin-expression"); + expected.add("maven-it-plugin-fork"); + expected.add("maven-it-plugin-touch"); List actual = new ArrayList<>(); - @SuppressWarnings( "unchecked" ) - List plugins = (List) pom.getValue( "build/plugins" ); - for ( Plugin plugin : plugins ) - { - actual.add( plugin.getArtifactId() ); + @SuppressWarnings("unchecked") + List plugins = (List) pom.getValue("build/plugins"); + for (Plugin plugin : plugins) { + actual.add(plugin.getArtifactId()); } - actual.retainAll( expected ); + actual.retainAll(expected); - assertEquals( actual, expected ); + assertEquals(actual, expected); } /** MNG-4416 */ @Test - public void testPluginOrderAfterMergingWithInjectedPlugins() - throws Exception - { - PomTestWrapper pom = buildPom( "plugin-injection-merge-order" ); + public void testPluginOrderAfterMergingWithInjectedPlugins() throws Exception { + PomTestWrapper pom = buildPom("plugin-injection-merge-order"); List expected = new ArrayList<>(); - expected.add( "maven-it-plugin-error" ); - expected.add( "maven-it-plugin-configuration" ); - expected.add( "maven-it-plugin-dependency-resolution" ); - expected.add( "maven-it-plugin-packaging" ); - expected.add( "maven-it-plugin-log-file" ); - expected.add( "maven-it-plugin-expression" ); - expected.add( "maven-it-plugin-fork" ); - expected.add( "maven-it-plugin-touch" ); + expected.add("maven-it-plugin-error"); + expected.add("maven-it-plugin-configuration"); + expected.add("maven-it-plugin-dependency-resolution"); + expected.add("maven-it-plugin-packaging"); + expected.add("maven-it-plugin-log-file"); + expected.add("maven-it-plugin-expression"); + expected.add("maven-it-plugin-fork"); + expected.add("maven-it-plugin-touch"); List actual = new ArrayList<>(); - @SuppressWarnings( "unchecked" ) - List plugins = (List) pom.getValue( "build/plugins" ); - for ( Plugin plugin : plugins ) - { - actual.add( plugin.getArtifactId() ); + @SuppressWarnings("unchecked") + List plugins = (List) pom.getValue("build/plugins"); + for (Plugin plugin : plugins) { + actual.add(plugin.getArtifactId()); } - actual.retainAll( expected ); + actual.retainAll(expected); - assertEquals( actual, expected ); + assertEquals(actual, expected); } @Test - public void testProjectArtifactIdIsNotInheritedButMandatory() - throws Exception - { + public void testProjectArtifactIdIsNotInheritedButMandatory() throws Exception { assertThrows( ProjectBuildingException.class, - () -> buildPom( "artifact-id-inheritance/child" ), - "Missing artifactId did not cause validation error" ); + () -> buildPom("artifact-id-inheritance/child"), + "Missing artifactId did not cause validation error"); } - private void assertPathSuffixEquals( String expected, Object actual ) - { + private void assertPathSuffixEquals(String expected, Object actual) { String a = actual.toString(); - a = a.substring( a.length() - expected.length() ).replace( '\\', '/' ); - assertEquals( expected, a ); + a = a.substring(a.length() - expected.length()).replace('\\', '/'); + assertEquals(expected, a); } - private void assertPathWithNormalizedFileSeparators( Object value ) - { - assertEquals( new File( value.toString() ).getPath(), value.toString() ); + private void assertPathWithNormalizedFileSeparators(Object value) { + assertEquals(new File(value.toString()).getPath(), value.toString()); } - private PomTestWrapper buildPom( String pomPath, String... profileIds ) - throws Exception - { - return buildPom( pomPath, null, null, profileIds ); + private PomTestWrapper buildPom(String pomPath, String... profileIds) throws Exception { + return buildPom(pomPath, null, null, profileIds); } - private PomTestWrapper buildPom( String pomPath, Properties systemProperties, Properties userProperties, String... profileIds ) - throws Exception - { - return buildPom( pomPath, false, systemProperties, userProperties, profileIds ); + private PomTestWrapper buildPom( + String pomPath, Properties systemProperties, Properties userProperties, String... profileIds) + throws Exception { + return buildPom(pomPath, false, systemProperties, userProperties, profileIds); } - private PomTestWrapper buildPom( String pomPath, boolean lenientValidation, Properties systemProperties, - Properties userProperties, String... profileIds ) - throws Exception - { - File pomFile = new File( testDirectory, pomPath ); - if ( pomFile.isDirectory() ) - { - pomFile = new File( pomFile, "pom.xml" ); + private PomTestWrapper buildPom( + String pomPath, + boolean lenientValidation, + Properties systemProperties, + Properties userProperties, + String... profileIds) + throws Exception { + File pomFile = new File(testDirectory, pomPath); + if (pomFile.isDirectory()) { + pomFile = new File(pomFile, "pom.xml"); } ProjectBuildingRequest config = new DefaultProjectBuildingRequest(); String localRepoUrl = - System.getProperty( "maven.repo.local", System.getProperty( "user.home" ) + "/.m2/repository" ); + System.getProperty("maven.repo.local", System.getProperty("user.home") + "/.m2/repository"); localRepoUrl = "file://" + localRepoUrl; - config.setLocalRepository( repositorySystem.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(), null, null ) ); - config.setActiveProfileIds( Arrays.asList( profileIds ) ); - config.setSystemProperties( systemProperties ); - config.setUserProperties( userProperties ); - config.setValidationLevel( lenientValidation ? ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 - : ModelBuildingRequest.VALIDATION_LEVEL_STRICT ); + config.setLocalRepository(repositorySystem.createArtifactRepository( + "local", localRepoUrl, new DefaultRepositoryLayout(), null, null)); + config.setActiveProfileIds(Arrays.asList(profileIds)); + config.setSystemProperties(systemProperties); + config.setUserProperties(userProperties); + config.setValidationLevel( + lenientValidation + ? ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 + : ModelBuildingRequest.VALIDATION_LEVEL_STRICT); DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession(); - LocalRepository localRepo = new LocalRepository( config.getLocalRepository().getBasedir() ); - repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repoSession, localRepo ) ); - config.setRepositorySession( repoSession ); + LocalRepository localRepo = + new LocalRepository(config.getLocalRepository().getBasedir()); + repoSession.setLocalRepositoryManager( + new SimpleLocalRepositoryManagerFactory().newInstance(repoSession, localRepo)); + config.setRepositorySession(repoSession); - return new PomTestWrapper( pomFile, projectBuilder.build( pomFile, config ).getProject() ); + return new PomTestWrapper(pomFile, projectBuilder.build(pomFile, config).getProject()); } - protected void assertModelEquals( PomTestWrapper pom, Object expected, String expression ) - { - assertEquals( expected, pom.getValue( expression ) ); + protected void assertModelEquals(PomTestWrapper pom, Object expected, String expression) { + assertEquals(expected, pom.getValue(expression)); } - private static String createPath( List elements ) - { - StringBuilder buffer = new StringBuilder( 256 ); - for ( String s : elements ) - { - buffer.append( s ).append( File.separator ); + private static String createPath(List elements) { + StringBuilder buffer = new StringBuilder(256); + for (String s : elements) { + buffer.append(s).append(File.separator); } - return buffer.toString().substring( 0, buffer.toString().length() - 1 ); + return buffer.toString().substring(0, buffer.toString().length() - 1); } } diff --git a/maven-core/src/test/java/org/apache/maven/project/ProjectBuilderTest.java b/maven-core/src/test/java/org/apache/maven/project/ProjectBuilderTest.java index 8cc47a8530..542cf80e6c 100644 --- a/maven-core/src/test/java/org/apache/maven/project/ProjectBuilderTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/ProjectBuilderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,25 +16,7 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.commons.io.FileUtils; -import org.apache.maven.AbstractCoreMavenComponentTestCase; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.building.FileModelSource; -import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.model.building.ModelProblem; -import org.apache.maven.model.building.ModelSource; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; +package org.apache.maven.project; import static org.apache.maven.project.ProjectBuildingResultWithLocationMatcher.projectBuildingResultWithLocation; import static org.apache.maven.project.ProjectBuildingResultWithProblemMessageMatcher.projectBuildingResultWithProblemMessage; @@ -52,26 +32,38 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.commons.io.FileUtils; +import org.apache.maven.AbstractCoreMavenComponentTestCase; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.building.FileModelSource; +import org.apache.maven.model.building.ModelBuildingRequest; +import org.apache.maven.model.building.ModelProblem; +import org.apache.maven.model.building.ModelSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class ProjectBuilderTest - extends AbstractCoreMavenComponentTestCase -{ +public class ProjectBuilderTest extends AbstractCoreMavenComponentTestCase { @Override - protected String getProjectsDirectory() - { + protected String getProjectsDirectory() { return "src/test/projects/project-builder"; } @Test - public void testSystemScopeDependencyIsPresentInTheCompileClasspathElements() - throws Exception - { - File pom = getProject( "it0063" ); + public void testSystemScopeDependencyIsPresentInTheCompileClasspathElements() throws Exception { + File pom = getProject("it0063"); Properties eps = new Properties(); - eps.setProperty( "jre.home", new File( pom.getParentFile(), "jdk/jre" ).getPath() ); + eps.setProperty("jre.home", new File(pom.getParentFile(), "jdk/jre").getPath()); - MavenSession session = createMavenSession( pom, eps ); + MavenSession session = createMavenSession(pom, eps); MavenProject project = session.getCurrentProject(); // Here we will actually not have any artifacts because the ProjectDependenciesResolver is not involved here. So @@ -81,56 +73,56 @@ public class ProjectBuilderTest } @Test - public void testBuildFromModelSource() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/modelsource/module01/pom.xml" ); - MavenSession mavenSession = createMavenSession( pomFile ); + public void testBuildFromModelSource() throws Exception { + File pomFile = new File("src/test/resources/projects/modelsource/module01/pom.xml"); + MavenSession mavenSession = createMavenSession(pomFile); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); - ModelSource modelSource = new FileModelSource( pomFile ); - ProjectBuildingResult result = - getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( modelSource, configuration ); + configuration.setRepositorySession(mavenSession.getRepositorySession()); + ModelSource modelSource = new FileModelSource(pomFile); + ProjectBuildingResult result = getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(modelSource, configuration); - assertNotNull( result.getProject().getParentFile() ); + assertNotNull(result.getProject().getParentFile()); } @Test - public void testVersionlessManagedDependency() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/versionless-managed-dependency.xml" ); - MavenSession mavenSession = createMavenSession( null ); + public void testVersionlessManagedDependency() throws Exception { + File pomFile = new File("src/test/resources/projects/versionless-managed-dependency.xml"); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); + configuration.setRepositorySession(mavenSession.getRepositorySession()); - ProjectBuildingException e = assertThrows( ProjectBuildingException.class, - () -> getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( pomFile, configuration ) ); - assertThat( e.getResults(), contains( projectBuildingResultWithProblemMessage( - "'dependencies.dependency.version' for org.apache.maven.its:a:jar is missing" ) ) ); - assertThat( e.getResults(), contains( projectBuildingResultWithLocation( 17, 9 ) ) ); + ProjectBuildingException e = assertThrows(ProjectBuildingException.class, () -> getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(pomFile, configuration)); + assertThat( + e.getResults(), + contains(projectBuildingResultWithProblemMessage( + "'dependencies.dependency.version' for org.apache.maven.its:a:jar is missing"))); + assertThat(e.getResults(), contains(projectBuildingResultWithLocation(17, 9))); } @Test - public void testResolveDependencies() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/basic-resolveDependencies.xml" ); - MavenSession mavenSession = createMavenSession( null ); + public void testResolveDependencies() throws Exception { + File pomFile = new File("src/test/resources/projects/basic-resolveDependencies.xml"); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); - configuration.setResolveDependencies( true ); + configuration.setRepositorySession(mavenSession.getRepositorySession()); + configuration.setResolveDependencies(true); // single project build entry point - ProjectBuildingResult result = getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( pomFile, configuration ); - assertEquals( 1, result.getProject().getArtifacts().size() ); + ProjectBuildingResult result = getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(pomFile, configuration); + assertEquals(1, result.getProject().getArtifacts().size()); // multi projects build entry point - List results = - getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( Collections.singletonList( pomFile ), false, - configuration ); - assertEquals( 1, results.size() ); - MavenProject mavenProject = results.get( 0 ).getProject(); - assertEquals( 1, mavenProject.getArtifacts().size() ); + List results = getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(Collections.singletonList(pomFile), false, configuration); + assertEquals(1, results.size()); + MavenProject mavenProject = results.get(0).getProject(); + assertEquals(1, mavenProject.getArtifacts().size()); final MavenProject project = mavenProject; final AtomicInteger artifactsResultInAnotherThread = new AtomicInteger(); @@ -142,228 +134,216 @@ public class ProjectBuilderTest }); t.start(); t.join(); - assertEquals( project.getArtifacts().size(), artifactsResultInAnotherThread.get() ); + assertEquals(project.getArtifacts().size(), artifactsResultInAnotherThread.get()); } @Test - public void testDontResolveDependencies() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/basic-resolveDependencies.xml" ); - MavenSession mavenSession = createMavenSession( null ); + public void testDontResolveDependencies() throws Exception { + File pomFile = new File("src/test/resources/projects/basic-resolveDependencies.xml"); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); - configuration.setResolveDependencies( false ); + configuration.setRepositorySession(mavenSession.getRepositorySession()); + configuration.setResolveDependencies(false); // single project build entry point - ProjectBuildingResult result = getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( pomFile, configuration ); - assertEquals( 0, result.getProject().getArtifacts().size() ); + ProjectBuildingResult result = getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(pomFile, configuration); + assertEquals(0, result.getProject().getArtifacts().size()); // multi projects build entry point - List results = getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( Collections.singletonList( pomFile ), false, configuration ); - assertEquals( 1, results.size() ); - MavenProject mavenProject = results.get( 0 ).getProject(); - assertEquals( 0, mavenProject.getArtifacts().size() ); + List results = getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(Collections.singletonList(pomFile), false, configuration); + assertEquals(1, results.size()); + MavenProject mavenProject = results.get(0).getProject(); + assertEquals(0, mavenProject.getArtifacts().size()); } @Test - public void testReadModifiedPoms( @TempDir Path tempDir ) throws Exception { + public void testReadModifiedPoms(@TempDir Path tempDir) throws Exception { // TODO a similar test should be created to test the dependency management (basically all usages // of DefaultModelBuilder.getCache() are affected by MNG-6530 - FileUtils.copyDirectory( new File( "src/test/resources/projects/grandchild-check" ), tempDir.toFile() ); - MavenSession mavenSession = createMavenSession( null ); + FileUtils.copyDirectory(new File("src/test/resources/projects/grandchild-check"), tempDir.toFile()); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); - org.apache.maven.project.ProjectBuilder projectBuilder = getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ); - File child = new File( tempDir.toFile(), "child/pom.xml" ); + configuration.setRepositorySession(mavenSession.getRepositorySession()); + org.apache.maven.project.ProjectBuilder projectBuilder = + getContainer().lookup(org.apache.maven.project.ProjectBuilder.class); + File child = new File(tempDir.toFile(), "child/pom.xml"); // build project once - projectBuilder.build( child, configuration ); + projectBuilder.build(child, configuration); // modify parent - File parent = new File( tempDir.toFile(), "pom.xml" ); - String parentContent = FileUtils.readFileToString( parent, "UTF-8" ); - parentContent = parentContent.replaceAll( "pom", - "pomaddedValue" ); - FileUtils.write( parent, parentContent, "UTF-8" ); + File parent = new File(tempDir.toFile(), "pom.xml"); + String parentContent = FileUtils.readFileToString(parent, "UTF-8"); + parentContent = parentContent.replaceAll( + "pom", + "pomaddedValue"); + FileUtils.write(parent, parentContent, "UTF-8"); // re-build pom with modified parent - ProjectBuildingResult result = projectBuilder.build( child, configuration ); - assertThat( result.getProject().getProperties(), hasKey( (Object) "addedProperty" ) ); + ProjectBuildingResult result = projectBuilder.build(child, configuration); + assertThat(result.getProject().getProperties(), hasKey((Object) "addedProperty")); } @Test - public void testReadErroneousMavenProjectContainsReference() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/artifactMissingVersion.xml" ).getAbsoluteFile(); - MavenSession mavenSession = createMavenSession( null ); + public void testReadErroneousMavenProjectContainsReference() throws Exception { + File pomFile = new File("src/test/resources/projects/artifactMissingVersion.xml").getAbsoluteFile(); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); + configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); + configuration.setRepositorySession(mavenSession.getRepositorySession()); org.apache.maven.project.ProjectBuilder projectBuilder = - getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ); + getContainer().lookup(org.apache.maven.project.ProjectBuilder.class); // single project build entry point ProjectBuildingException ex1 = - assertThrows( ProjectBuildingException.class, () -> projectBuilder.build( pomFile, configuration ) ); + assertThrows(ProjectBuildingException.class, () -> projectBuilder.build(pomFile, configuration)); - assertEquals( 1, ex1.getResults().size() ); - MavenProject project1 = ex1.getResults().get( 0 ).getProject(); - assertNotNull( project1 ); - assertEquals( "testArtifactMissingVersion", project1.getArtifactId() ); - assertEquals( pomFile, project1.getFile() ); + assertEquals(1, ex1.getResults().size()); + MavenProject project1 = ex1.getResults().get(0).getProject(); + assertNotNull(project1); + assertEquals("testArtifactMissingVersion", project1.getArtifactId()); + assertEquals(pomFile, project1.getFile()); // multi projects build entry point - ProjectBuildingException ex2 = - assertThrows( ProjectBuildingException.class, - () -> projectBuilder.build( Collections.singletonList( pomFile ), false, configuration ) ); + ProjectBuildingException ex2 = assertThrows( + ProjectBuildingException.class, + () -> projectBuilder.build(Collections.singletonList(pomFile), false, configuration)); - assertEquals( 1, ex2.getResults().size() ); - MavenProject project2 = ex2.getResults().get( 0 ).getProject(); - assertNotNull( project2 ); - assertEquals( "testArtifactMissingVersion", project2.getArtifactId() ); - assertEquals( pomFile, project2.getFile() ); + assertEquals(1, ex2.getResults().size()); + MavenProject project2 = ex2.getResults().get(0).getProject(); + assertNotNull(project2); + assertEquals("testArtifactMissingVersion", project2.getArtifactId()); + assertEquals(pomFile, project2.getFile()); } @Test - public void testReadInvalidPom() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/badPom.xml" ).getAbsoluteFile(); - MavenSession mavenSession = createMavenSession( null ); + public void testReadInvalidPom() throws Exception { + File pomFile = new File("src/test/resources/projects/badPom.xml").getAbsoluteFile(); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); + configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); + configuration.setRepositorySession(mavenSession.getRepositorySession()); org.apache.maven.project.ProjectBuilder projectBuilder = - getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ); + getContainer().lookup(org.apache.maven.project.ProjectBuilder.class); // single project build entry point - Exception ex = assertThrows( Exception.class, () -> projectBuilder.build( pomFile, configuration ) ); - assertThat( ex.getMessage(), containsString( "expected START_TAG or END_TAG not TEXT" ) ); + Exception ex = assertThrows(Exception.class, () -> projectBuilder.build(pomFile, configuration)); + assertThat(ex.getMessage(), containsString("expected START_TAG or END_TAG not TEXT")); // multi projects build entry point - ProjectBuildingException pex = - assertThrows( ProjectBuildingException.class, - () -> projectBuilder.build( Collections.singletonList( pomFile ), false, configuration ) ); - assertEquals( 1, pex.getResults().size() ); - assertNotNull( pex.getResults().get( 0 ).getPomFile() ); - assertThat( pex.getResults().get( 0 ).getProblems().size(), greaterThan( 0 ) ); - assertThat( pex.getResults(), contains( projectBuildingResultWithProblemMessage( "expected START_TAG or END_TAG not TEXT" ) ) ); + ProjectBuildingException pex = assertThrows( + ProjectBuildingException.class, + () -> projectBuilder.build(Collections.singletonList(pomFile), false, configuration)); + assertEquals(1, pex.getResults().size()); + assertNotNull(pex.getResults().get(0).getPomFile()); + assertThat(pex.getResults().get(0).getProblems().size(), greaterThan(0)); + assertThat( + pex.getResults(), + contains(projectBuildingResultWithProblemMessage("expected START_TAG or END_TAG not TEXT"))); } @Test - public void testReadParentAndChildWithRegularVersionSetParentFile() - throws Exception - { - List toRead = new ArrayList<>( 2 ); - File parentPom = getProject( "MNG-6723" ); - toRead.add( parentPom ); - toRead.add( new File( parentPom.getParentFile(), "child/pom.xml" ) ); - MavenSession mavenSession = createMavenSession( null ); + public void testReadParentAndChildWithRegularVersionSetParentFile() throws Exception { + List toRead = new ArrayList<>(2); + File parentPom = getProject("MNG-6723"); + toRead.add(parentPom); + toRead.add(new File(parentPom.getParentFile(), "child/pom.xml")); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); + configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); + configuration.setRepositorySession(mavenSession.getRepositorySession()); org.apache.maven.project.ProjectBuilder projectBuilder = - getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ); + getContainer().lookup(org.apache.maven.project.ProjectBuilder.class); // read poms separately boolean parentFileWasFoundOnChild = false; - for ( File file : toRead ) - { - List results = projectBuilder.build( Collections.singletonList( file ), false, configuration ); - assertResultShowNoError( results ); - MavenProject project = findChildProject( results ); - if ( project != null ) - { - assertEquals( parentPom, project.getParentFile() ); + for (File file : toRead) { + List results = + projectBuilder.build(Collections.singletonList(file), false, configuration); + assertResultShowNoError(results); + MavenProject project = findChildProject(results); + if (project != null) { + assertEquals(parentPom, project.getParentFile()); parentFileWasFoundOnChild = true; } } - assertTrue( parentFileWasFoundOnChild ); + assertTrue(parentFileWasFoundOnChild); // read projects together - List results = projectBuilder.build( toRead, false, configuration ); - assertResultShowNoError( results ); - assertEquals( parentPom, findChildProject( results ).getParentFile() ); - Collections.reverse( toRead ); - results = projectBuilder.build( toRead, false, configuration ); - assertResultShowNoError( results ); - assertEquals( parentPom, findChildProject( results ).getParentFile() ); + List results = projectBuilder.build(toRead, false, configuration); + assertResultShowNoError(results); + assertEquals(parentPom, findChildProject(results).getParentFile()); + Collections.reverse(toRead); + results = projectBuilder.build(toRead, false, configuration); + assertResultShowNoError(results); + assertEquals(parentPom, findChildProject(results).getParentFile()); } - private MavenProject findChildProject( List results ) - { - for ( ProjectBuildingResult result : results ) - { - if ( result.getPomFile().getParentFile().getName().equals( "child" ) ) - { + private MavenProject findChildProject(List results) { + for (ProjectBuildingResult result : results) { + if (result.getPomFile().getParentFile().getName().equals("child")) { return result.getProject(); } } return null; } - private void assertResultShowNoError( List results ) - { - for ( ProjectBuildingResult result : results ) - { - assertThat( result.getProblems(), is( empty() ) ); - assertNotNull( result.getProject() ); + private void assertResultShowNoError(List results) { + for (ProjectBuildingResult result : results) { + assertThat(result.getProblems(), is(empty())); + assertNotNull(result.getProject()); } } @Test - public void testBuildProperties() - throws Exception - { - File file = new File( getProject( "MNG-6716" ).getParentFile(), "project/pom.xml" ); - MavenSession mavenSession = createMavenSession( null ); + public void testBuildProperties() throws Exception { + File file = new File(getProject("MNG-6716").getParentFile(), "project/pom.xml"); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); - configuration.setResolveDependencies( true ); - List result = projectBuilder.build( Collections.singletonList( file ), true, configuration ); - MavenProject project = result.get( 0 ).getProject(); + configuration.setRepositorySession(mavenSession.getRepositorySession()); + configuration.setResolveDependencies(true); + List result = projectBuilder.build(Collections.singletonList(file), true, configuration); + MavenProject project = result.get(0).getProject(); // verify a few typical parameters are not duplicated - assertEquals( 1, project.getTestCompileSourceRoots().size() ); - assertEquals( 1, project.getCompileSourceRoots().size() ); - assertEquals( 1, project.getMailingLists().size() ); - assertEquals( 1, project.getResources().size() ); + assertEquals(1, project.getTestCompileSourceRoots().size()); + assertEquals(1, project.getCompileSourceRoots().size()); + assertEquals(1, project.getMailingLists().size()); + assertEquals(1, project.getResources().size()); } @Test - public void testPropertyInPluginManagementGroupId() - throws Exception - { - File pom = getProject( "MNG-6983" ); + public void testPropertyInPluginManagementGroupId() throws Exception { + File pom = getProject("MNG-6983"); - MavenSession session = createMavenSession( pom ); + MavenSession session = createMavenSession(pom); MavenProject project = session.getCurrentProject(); for (Plugin buildPlugin : project.getBuildPlugins()) { - assertNotNull( "Missing version for build plugin " + buildPlugin.getKey(), buildPlugin.getVersion() ); + assertNotNull("Missing version for build plugin " + buildPlugin.getKey(), buildPlugin.getVersion()); } } @Test - public void testBuildFromModelSourceResolvesBasedir() - throws Exception - { - File pomFile = new File( "src/test/resources/projects/modelsourcebasedir/pom.xml" ); - MavenSession mavenSession = createMavenSession( null ); + public void testBuildFromModelSourceResolvesBasedir() throws Exception { + File pomFile = new File("src/test/resources/projects/modelsourcebasedir/pom.xml"); + MavenSession mavenSession = createMavenSession(null); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); - configuration.setRepositorySession( mavenSession.getRepositorySession() ); - ModelSource modelSource = new FileModelSource( pomFile ); - ProjectBuildingResult result = - getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( modelSource, configuration ); + configuration.setRepositorySession(mavenSession.getRepositorySession()); + ModelSource modelSource = new FileModelSource(pomFile); + ProjectBuildingResult result = getContainer() + .lookup(org.apache.maven.project.ProjectBuilder.class) + .build(modelSource, configuration); - assertEquals( pomFile.getAbsoluteFile(), result.getProject().getModel().getPomFile().getAbsoluteFile() ); + assertEquals( + pomFile.getAbsoluteFile(), + result.getProject().getModel().getPomFile().getAbsoluteFile()); int errors = 0; - for ( ModelProblem p : result.getProblems() ) - { - if ( p.getSeverity() == ModelProblem.Severity.ERROR ) - { + for (ModelProblem p : result.getProblems()) { + if (p.getSeverity() == ModelProblem.Severity.ERROR) { errors++; } } - assertEquals( 0, errors ); + assertEquals(0, errors); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithLocationMatcher.java b/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithLocationMatcher.java index fafcb42d7c..329da1d830 100644 --- a/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithLocationMatcher.java +++ b/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithLocationMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,74 +16,64 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; + +import static java.util.stream.Collectors.joining; -import org.apache.maven.model.building.ModelProblem; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; -import static java.util.stream.Collectors.joining; - /** * Hamcrest matcher to help create fluent assertions about {@link ProjectBuildingResult} instances. */ -class ProjectBuildingResultWithLocationMatcher extends BaseMatcher -{ +class ProjectBuildingResultWithLocationMatcher extends BaseMatcher { private final int columnNumber; private final int lineNumber; - ProjectBuildingResultWithLocationMatcher( int columnNumber, int lineNumber ) - { + ProjectBuildingResultWithLocationMatcher(int columnNumber, int lineNumber) { this.columnNumber = columnNumber; this.lineNumber = lineNumber; } @Override - public boolean matches( Object o ) - { - if ( !( o instanceof ProjectBuildingResult ) ) - { + public boolean matches(Object o) { + if (!(o instanceof ProjectBuildingResult)) { return false; } final ProjectBuildingResult r = (ProjectBuildingResult) o; return r.getProblems().stream() - .anyMatch( p -> p.getLineNumber() == lineNumber && p.getColumnNumber() == columnNumber ); + .anyMatch(p -> p.getLineNumber() == lineNumber && p.getColumnNumber() == columnNumber); } @Override - public void describeTo( Description description ) - { - description.appendText( "a ProjectBuildingResult with location " ) - .appendText( formatLocation( columnNumber, lineNumber ) ); + public void describeTo(Description description) { + description + .appendText("a ProjectBuildingResult with location ") + .appendText(formatLocation(columnNumber, lineNumber)); } - private String formatLocation( int columnNumber, int lineNumber ) - { - return String.format( "line %d, column %d", lineNumber, columnNumber ); + private String formatLocation(int columnNumber, int lineNumber) { + return String.format("line %d, column %d", lineNumber, columnNumber); } @Override - public void describeMismatch(final Object o, final Description description) - { - if ( !( o instanceof ProjectBuildingResult ) ) - { - super.describeMismatch( o, description ); - } - else - { + public void describeMismatch(final Object o, final Description description) { + if (!(o instanceof ProjectBuildingResult)) { + super.describeMismatch(o, description); + } else { final ProjectBuildingResult r = (ProjectBuildingResult) o; - description.appendText( "was a ProjectBuildingResult with locations " ); + description.appendText("was a ProjectBuildingResult with locations "); String messages = r.getProblems().stream() - .map( p -> formatLocation( p.getColumnNumber(), p.getLineNumber() ) ) - .collect( joining( ", ") ); - description.appendText( messages ); + .map(p -> formatLocation(p.getColumnNumber(), p.getLineNumber())) + .collect(joining(", ")); + description.appendText(messages); } } - static Matcher projectBuildingResultWithLocation( int columnNumber, int lineNumber ) - { - return new ProjectBuildingResultWithLocationMatcher( columnNumber, lineNumber ); + static Matcher projectBuildingResultWithLocation(int columnNumber, int lineNumber) { + return new ProjectBuildingResultWithLocationMatcher(columnNumber, lineNumber); } } diff --git a/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithProblemMessageMatcher.java b/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithProblemMessageMatcher.java index 0ae052a030..20befb8efa 100644 --- a/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithProblemMessageMatcher.java +++ b/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithProblemMessageMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,67 +16,57 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; + +import static java.util.stream.Collectors.joining; import org.apache.maven.model.building.ModelProblem; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; -import static java.util.stream.Collectors.joining; - /** * Hamcrest matcher to help create fluent assertions about {@link ProjectBuildingResult} instances. */ -class ProjectBuildingResultWithProblemMessageMatcher extends BaseMatcher -{ +class ProjectBuildingResultWithProblemMessageMatcher extends BaseMatcher { private final String problemMessage; - ProjectBuildingResultWithProblemMessageMatcher( String problemMessage ) { + ProjectBuildingResultWithProblemMessageMatcher(String problemMessage) { this.problemMessage = problemMessage; } @Override - public boolean matches( Object o ) - { - if ( !( o instanceof ProjectBuildingResult ) ) - { + public boolean matches(Object o) { + if (!(o instanceof ProjectBuildingResult)) { return false; } final ProjectBuildingResult r = (ProjectBuildingResult) o; - return r.getProblems().stream() - .anyMatch( p -> p.getMessage().contains( problemMessage ) ); + return r.getProblems().stream().anyMatch(p -> p.getMessage().contains(problemMessage)); } @Override - public void describeTo( Description description ) - { - description.appendText( "a ProjectBuildingResult with message " ) - .appendValue(problemMessage); + public void describeTo(Description description) { + description.appendText("a ProjectBuildingResult with message ").appendValue(problemMessage); } @Override - public void describeMismatch(final Object o, final Description description) - { - if ( !( o instanceof ProjectBuildingResult ) ) - { - super.describeMismatch( o, description ); - } - else - { + public void describeMismatch(final Object o, final Description description) { + if (!(o instanceof ProjectBuildingResult)) { + super.describeMismatch(o, description); + } else { final ProjectBuildingResult r = (ProjectBuildingResult) o; - description.appendText( "was a ProjectBuildingResult with messages " ); + description.appendText("was a ProjectBuildingResult with messages "); String messages = r.getProblems().stream() - .map( ModelProblem::getMessage ) - .map( m -> "\"" + m + "\"" + System.lineSeparator() ) - .collect( joining( ", ") ); - description.appendText( messages ); + .map(ModelProblem::getMessage) + .map(m -> "\"" + m + "\"" + System.lineSeparator()) + .collect(joining(", ")); + description.appendText(messages); } } - static Matcher projectBuildingResultWithProblemMessage( String message ) - { - return new ProjectBuildingResultWithProblemMessageMatcher( message ); + static Matcher projectBuildingResultWithProblemMessage(String message) { + return new ProjectBuildingResultWithProblemMessageMatcher(message); } } diff --git a/maven-core/src/test/java/org/apache/maven/project/ProjectModelResolverTest.java b/maven-core/src/test/java/org/apache/maven/project/ProjectModelResolverTest.java index f0ef5585e8..a786c0569a 100644 --- a/maven-core/src/test/java/org/apache/maven/project/ProjectModelResolverTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/ProjectModelResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,19 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; + +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; - import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.model.Dependency; import org.apache.maven.model.Parent; @@ -36,198 +41,177 @@ import org.eclipse.aether.impl.RemoteRepositoryManager; import org.eclipse.aether.repository.RemoteRepository; import org.junit.jupiter.api.Test; -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - /** * Test cases for the project {@code ModelResolver} implementation. * * @author Christian Schulte * @since 3.5.0 */ -public class ProjectModelResolverTest extends AbstractMavenProjectTestCase -{ +public class ProjectModelResolverTest extends AbstractMavenProjectTestCase { /** * Creates a new {@code ProjectModelResolverTest} instance. */ - public ProjectModelResolverTest() - { + public ProjectModelResolverTest() { super(); } @Test - public void testResolveParentThrowsUnresolvableModelExceptionWhenNotFound() throws Exception - { + public void testResolveParentThrowsUnresolvableModelExceptionWhenNotFound() throws Exception { final Parent parent = new Parent(); - parent.setGroupId( "org.apache" ); - parent.setArtifactId( "apache" ); - parent.setVersion( "0" ); + parent.setGroupId("org.apache"); + parent.setArtifactId("apache"); + parent.setVersion("0"); UnresolvableModelException e = assertThrows( UnresolvableModelException.class, - () -> newModelResolver().resolveModel( parent.getDelegate(), new AtomicReference<>() ), - "Expected 'UnresolvableModelException' not thrown." ); - assertNotNull( e.getMessage() ); - assertThat( e.getMessage(), startsWith( "Could not find artifact org.apache:apache:pom:0 in central" ) ); + () -> newModelResolver().resolveModel(parent.getDelegate(), new AtomicReference<>()), + "Expected 'UnresolvableModelException' not thrown."); + assertNotNull(e.getMessage()); + assertThat(e.getMessage(), startsWith("Could not find artifact org.apache:apache:pom:0 in central")); } @Test - public void testResolveParentThrowsUnresolvableModelExceptionWhenNoMatchingVersionFound() throws Exception - { + public void testResolveParentThrowsUnresolvableModelExceptionWhenNoMatchingVersionFound() throws Exception { final Parent parent = new Parent(); - parent.setGroupId( "org.apache" ); - parent.setArtifactId( "apache" ); - parent.setVersion( "[2.0,2.1)" ); + parent.setGroupId("org.apache"); + parent.setArtifactId("apache"); + parent.setVersion("[2.0,2.1)"); UnresolvableModelException e = assertThrows( UnresolvableModelException.class, - () -> newModelResolver().resolveModel( parent.getDelegate(), new AtomicReference<>() ), - "Expected 'UnresolvableModelException' not thrown." ); - assertEquals( "No versions matched the requested parent version range '[2.0,2.1)'", - e.getMessage() ); + () -> newModelResolver().resolveModel(parent.getDelegate(), new AtomicReference<>()), + "Expected 'UnresolvableModelException' not thrown."); + assertEquals("No versions matched the requested parent version range '[2.0,2.1)'", e.getMessage()); } @Test - public void testResolveParentThrowsUnresolvableModelExceptionWhenUsingRangesWithoutUpperBound() throws Exception - { + public void testResolveParentThrowsUnresolvableModelExceptionWhenUsingRangesWithoutUpperBound() throws Exception { final Parent parent = new Parent(); - parent.setGroupId( "org.apache" ); - parent.setArtifactId( "apache" ); - parent.setVersion( "[1,)" ); + parent.setGroupId("org.apache"); + parent.setArtifactId("apache"); + parent.setVersion("[1,)"); UnresolvableModelException e = assertThrows( UnresolvableModelException.class, - () -> newModelResolver().resolveModel( parent.getDelegate(), new AtomicReference<>() ), - "Expected 'UnresolvableModelException' not thrown." ); - assertEquals( "The requested parent version range '[1,)' does not specify an upper bound", - e.getMessage() ); + () -> newModelResolver().resolveModel(parent.getDelegate(), new AtomicReference<>()), + "Expected 'UnresolvableModelException' not thrown."); + assertEquals("The requested parent version range '[1,)' does not specify an upper bound", e.getMessage()); } @Test - public void testResolveParentSuccessfullyResolvesExistingParentWithoutRange() throws Exception - { + public void testResolveParentSuccessfullyResolvesExistingParentWithoutRange() throws Exception { final Parent parent = new Parent(); - parent.setGroupId( "org.apache" ); - parent.setArtifactId( "apache" ); - parent.setVersion( "1" ); + parent.setGroupId("org.apache"); + parent.setArtifactId("apache"); + parent.setVersion("1"); - assertNotNull( this.newModelResolver().resolveModel( parent.getDelegate(), new AtomicReference<>() ) ); - assertEquals( "1", parent.getVersion() ); + assertNotNull(this.newModelResolver().resolveModel(parent.getDelegate(), new AtomicReference<>())); + assertEquals("1", parent.getVersion()); } @Test - public void testResolveParentSuccessfullyResolvesExistingParentUsingHighestVersion() throws Exception - { + public void testResolveParentSuccessfullyResolvesExistingParentUsingHighestVersion() throws Exception { final Parent parent = new Parent(); - parent.setGroupId( "org.apache" ); - parent.setArtifactId( "apache" ); - parent.setVersion( "(,2.0)" ); + parent.setGroupId("org.apache"); + parent.setArtifactId("apache"); + parent.setVersion("(,2.0)"); AtomicReference modified = new AtomicReference<>(); - assertNotNull( this.newModelResolver().resolveModel( parent.getDelegate(), modified ) ); - assertEquals( "1", modified.get().getVersion() ); + assertNotNull(this.newModelResolver().resolveModel(parent.getDelegate(), modified)); + assertEquals("1", modified.get().getVersion()); } @Test - public void testResolveDependencyThrowsUnresolvableModelExceptionWhenNotFound() throws Exception - { + public void testResolveDependencyThrowsUnresolvableModelExceptionWhenNotFound() throws Exception { final Dependency dependency = new Dependency(); - dependency.setGroupId( "org.apache" ); - dependency.setArtifactId( "apache" ); - dependency.setVersion( "0" ); + dependency.setGroupId("org.apache"); + dependency.setArtifactId("apache"); + dependency.setVersion("0"); UnresolvableModelException e = assertThrows( UnresolvableModelException.class, - () -> newModelResolver().resolveModel( dependency.getDelegate(), new AtomicReference<>() ), - "Expected 'UnresolvableModelException' not thrown." ); - assertNotNull( e.getMessage() ); - assertThat( e.getMessage(), startsWith( "Could not find artifact org.apache:apache:pom:0 in central" ) ); + () -> newModelResolver().resolveModel(dependency.getDelegate(), new AtomicReference<>()), + "Expected 'UnresolvableModelException' not thrown."); + assertNotNull(e.getMessage()); + assertThat(e.getMessage(), startsWith("Could not find artifact org.apache:apache:pom:0 in central")); } @Test - public void testResolveDependencyThrowsUnresolvableModelExceptionWhenNoMatchingVersionFound() throws Exception - { + public void testResolveDependencyThrowsUnresolvableModelExceptionWhenNoMatchingVersionFound() throws Exception { final Dependency dependency = new Dependency(); - dependency.setGroupId( "org.apache" ); - dependency.setArtifactId( "apache" ); - dependency.setVersion( "[2.0,2.1)" ); + dependency.setGroupId("org.apache"); + dependency.setArtifactId("apache"); + dependency.setVersion("[2.0,2.1)"); UnresolvableModelException e = assertThrows( UnresolvableModelException.class, - () -> newModelResolver().resolveModel( dependency.getDelegate(), new AtomicReference<>() ), - "Expected 'UnresolvableModelException' not thrown." ); - assertEquals( "No versions matched the requested dependency version range '[2.0,2.1)'", - e.getMessage() ); + () -> newModelResolver().resolveModel(dependency.getDelegate(), new AtomicReference<>()), + "Expected 'UnresolvableModelException' not thrown."); + assertEquals("No versions matched the requested dependency version range '[2.0,2.1)'", e.getMessage()); } @Test - public void testResolveDependencyThrowsUnresolvableModelExceptionWhenUsingRangesWithoutUpperBound() throws Exception - { + public void testResolveDependencyThrowsUnresolvableModelExceptionWhenUsingRangesWithoutUpperBound() + throws Exception { final Dependency dependency = new Dependency(); - dependency.setGroupId( "org.apache" ); - dependency.setArtifactId( "apache" ); - dependency.setVersion( "[1,)" ); + dependency.setGroupId("org.apache"); + dependency.setArtifactId("apache"); + dependency.setVersion("[1,)"); UnresolvableModelException e = assertThrows( UnresolvableModelException.class, - () -> newModelResolver().resolveModel( dependency.getDelegate(), new AtomicReference<>() ), - "Expected 'UnresolvableModelException' not thrown." ); - assertEquals( "The requested dependency version range '[1,)' does not specify an upper bound", - e.getMessage() ); + () -> newModelResolver().resolveModel(dependency.getDelegate(), new AtomicReference<>()), + "Expected 'UnresolvableModelException' not thrown."); + assertEquals("The requested dependency version range '[1,)' does not specify an upper bound", e.getMessage()); } @Test - public void testResolveDependencySuccessfullyResolvesExistingDependencyWithoutRange() throws Exception - { + public void testResolveDependencySuccessfullyResolvesExistingDependencyWithoutRange() throws Exception { final Dependency dependency = new Dependency(); - dependency.setGroupId( "org.apache" ); - dependency.setArtifactId( "apache" ); - dependency.setVersion( "1" ); + dependency.setGroupId("org.apache"); + dependency.setArtifactId("apache"); + dependency.setVersion("1"); - assertNotNull( this.newModelResolver().resolveModel( dependency.getDelegate(), new AtomicReference<>() ) ); - assertEquals( "1", dependency.getVersion() ); + assertNotNull(this.newModelResolver().resolveModel(dependency.getDelegate(), new AtomicReference<>())); + assertEquals("1", dependency.getVersion()); } @Test - public void testResolveDependencySuccessfullyResolvesExistingDependencyUsingHighestVersion() throws Exception - { + public void testResolveDependencySuccessfullyResolvesExistingDependencyUsingHighestVersion() throws Exception { final Dependency dependency = new Dependency(); - dependency.setGroupId( "org.apache" ); - dependency.setArtifactId( "apache" ); - dependency.setVersion( "(,2.0)" ); + dependency.setGroupId("org.apache"); + dependency.setArtifactId("apache"); + dependency.setVersion("(,2.0)"); AtomicReference modified = new AtomicReference<>(); - assertNotNull( this.newModelResolver().resolveModel( dependency.getDelegate(), modified ) ); - assertEquals( "1", modified.get().getVersion() ); + assertNotNull(this.newModelResolver().resolveModel(dependency.getDelegate(), modified)); + assertEquals("1", modified.get().getVersion()); } - private ModelResolver newModelResolver() throws Exception - { - final File localRepo = new File( this.getLocalRepository().getBasedir() ); + private ModelResolver newModelResolver() throws Exception { + final File localRepo = new File(this.getLocalRepository().getBasedir()); final DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession(); - repoSession.setLocalRepositoryManager( new LegacyLocalRepositoryManager( localRepo ) ); - - return new ProjectModelResolver( repoSession, null, getContainer().lookup( RepositorySystem.class ), - getContainer().lookup( RemoteRepositoryManager.class ), - this.getRemoteRepositories(), - ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT, null ); + repoSession.setLocalRepositoryManager(new LegacyLocalRepositoryManager(localRepo)); + return new ProjectModelResolver( + repoSession, + null, + getContainer().lookup(RepositorySystem.class), + getContainer().lookup(RemoteRepositoryManager.class), + this.getRemoteRepositories(), + ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT, + null); } - private List getRemoteRepositories() - throws InvalidRepositoryException - { - final File repoDir = new File( getBasedir(), "src/test/remote-repo" ).getAbsoluteFile(); - final RemoteRepository remoteRepository = - new RemoteRepository.Builder( org.apache.maven.repository.RepositorySystem.DEFAULT_REMOTE_REPO_ID, - "default", repoDir.toURI().toASCIIString() ).build(); + private List getRemoteRepositories() throws InvalidRepositoryException { + final File repoDir = new File(getBasedir(), "src/test/remote-repo").getAbsoluteFile(); + final RemoteRepository remoteRepository = new RemoteRepository.Builder( + org.apache.maven.repository.RepositorySystem.DEFAULT_REMOTE_REPO_ID, + "default", + repoDir.toURI().toASCIIString()) + .build(); - return Collections.singletonList( remoteRepository ); + return Collections.singletonList(remoteRepository); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/ProjectSorterTest.java b/maven-core/src/test/java/org/apache/maven/project/ProjectSorterTest.java index 621cf5fb94..a85255175b 100644 --- a/maven-core/src/test/java/org/apache/maven/project/ProjectSorterTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/ProjectSorterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project; * "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 + * 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 @@ -18,16 +16,16 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; import org.apache.maven.model.Extension; @@ -42,329 +40,295 @@ import org.junit.jupiter.api.Test; * * @author Brett Porter */ -public class ProjectSorterTest -{ - private Parent createParent( MavenProject project ) - { - return createParent( project.getGroupId(), project.getArtifactId(), project.getVersion() ); +public class ProjectSorterTest { + private Parent createParent(MavenProject project) { + return createParent(project.getGroupId(), project.getArtifactId(), project.getVersion()); } - private Parent createParent( String groupId, String artifactId, String version ) - { + private Parent createParent(String groupId, String artifactId, String version) { Parent plugin = new Parent(); - plugin.setGroupId( groupId ); - plugin.setArtifactId( artifactId ); - plugin.setVersion( version ); + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); + plugin.setVersion(version); return plugin; } - private Dependency createDependency( MavenProject project ) - { - return createDependency( project.getGroupId(), project.getArtifactId(), project.getVersion() ); + private Dependency createDependency(MavenProject project) { + return createDependency(project.getGroupId(), project.getArtifactId(), project.getVersion()); } - private Dependency createDependency( String groupId, String artifactId, String version ) - { + private Dependency createDependency(String groupId, String artifactId, String version) { Dependency dependency = new Dependency(); - dependency.setGroupId( groupId ); - dependency.setArtifactId( artifactId ); - dependency.setVersion( version ); + dependency.setGroupId(groupId); + dependency.setArtifactId(artifactId); + dependency.setVersion(version); return dependency; } - private Plugin createPlugin( MavenProject project ) - { - return createPlugin( project.getGroupId(), project.getArtifactId(), project.getVersion() ); + private Plugin createPlugin(MavenProject project) { + return createPlugin(project.getGroupId(), project.getArtifactId(), project.getVersion()); } - private Plugin createPlugin( String groupId, String artifactId, String version ) - { + private Plugin createPlugin(String groupId, String artifactId, String version) { Plugin plugin = new Plugin(); - plugin.setGroupId( groupId ); - plugin.setArtifactId( artifactId ); - plugin.setVersion( version ); + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); + plugin.setVersion(version); return plugin; } - private Extension createExtension( String groupId, String artifactId, String version ) - { + private Extension createExtension(String groupId, String artifactId, String version) { Extension extension = new Extension(); - extension.setGroupId( groupId ); - extension.setArtifactId( artifactId ); - extension.setVersion( version ); + extension.setGroupId(groupId); + extension.setArtifactId(artifactId); + extension.setVersion(version); return extension; } - private static MavenProject createProject( String groupId, String artifactId, String version ) - { + private static MavenProject createProject(String groupId, String artifactId, String version) { Model model = new Model(); - model.setGroupId( groupId ); - model.setArtifactId( artifactId ); - model.setVersion( version ); - model.setBuild( new Build() ); - return new MavenProject( model ); + model.setGroupId(groupId); + model.setArtifactId(artifactId); + model.setVersion(version); + model.setBuild(new Build()); + return new MavenProject(model); } @Test - public void testShouldNotFailWhenPluginDepReferencesCurrentProject() - throws Exception - { - MavenProject project = createProject( "group", "artifact", "1.0" ); + public void testShouldNotFailWhenPluginDepReferencesCurrentProject() throws Exception { + MavenProject project = createProject("group", "artifact", "1.0"); Build build = project.getModel().getBuild(); - Plugin plugin = createPlugin( "other.group", "other-artifact", "1.0" ); + Plugin plugin = createPlugin("other.group", "other-artifact", "1.0"); - Dependency dep = createDependency( "group", "artifact", "1.0" ); + Dependency dep = createDependency("group", "artifact", "1.0"); - plugin.addDependency( dep ); + plugin.addDependency(dep); - build.addPlugin( plugin ); + build.addPlugin(plugin); - new ProjectSorter( Collections.singletonList( project ) ); + new ProjectSorter(Collections.singletonList(project)); } @Test - public void testShouldNotFailWhenManagedPluginDepReferencesCurrentProject() - throws Exception - { - MavenProject project = createProject( "group", "artifact", "1.0" ); + public void testShouldNotFailWhenManagedPluginDepReferencesCurrentProject() throws Exception { + MavenProject project = createProject("group", "artifact", "1.0"); Build build = project.getModel().getBuild(); PluginManagement pMgmt = new PluginManagement(); - Plugin plugin = createPlugin( "other.group", "other-artifact", "1.0" ); + Plugin plugin = createPlugin("other.group", "other-artifact", "1.0"); - Dependency dep = createDependency( "group", "artifact", "1.0" ); + Dependency dep = createDependency("group", "artifact", "1.0"); - plugin.addDependency( dep ); + plugin.addDependency(dep); - pMgmt.addPlugin( plugin ); + pMgmt.addPlugin(plugin); - build.setPluginManagement( pMgmt ); + build.setPluginManagement(pMgmt); - new ProjectSorter( Collections.singletonList( project ) ); + new ProjectSorter(Collections.singletonList(project)); } @Test - public void testShouldNotFailWhenProjectReferencesNonExistentProject() - throws Exception - { - MavenProject project = createProject( "group", "artifact", "1.0" ); + public void testShouldNotFailWhenProjectReferencesNonExistentProject() throws Exception { + MavenProject project = createProject("group", "artifact", "1.0"); Build build = project.getModel().getBuild(); - Extension extension = createExtension( "other.group", "other-artifact", "1.0" ); + Extension extension = createExtension("other.group", "other-artifact", "1.0"); - build.addExtension( extension ); + build.addExtension(extension); - new ProjectSorter( Collections.singletonList( project ) ); + new ProjectSorter(Collections.singletonList(project)); } @Test - public void testMatchingArtifactIdsDifferentGroupIds() - throws Exception - { + public void testMatchingArtifactIdsDifferentGroupIds() throws Exception { List projects = new ArrayList<>(); - MavenProject project1 = createProject( "groupId1", "artifactId", "1.0" ); - projects.add( project1 ); - MavenProject project2 = createProject( "groupId2", "artifactId", "1.0" ); - projects.add( project2 ); - project1.getDependencies().add( createDependency( project2 ) ); + MavenProject project1 = createProject("groupId1", "artifactId", "1.0"); + projects.add(project1); + MavenProject project2 = createProject("groupId2", "artifactId", "1.0"); + projects.add(project2); + project1.getDependencies().add(createDependency(project2)); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertEquals( project2, projects.get( 0 ) ); - assertEquals( project1, projects.get( 1 ) ); + assertEquals(project2, projects.get(0)); + assertEquals(project1, projects.get(1)); } @Test - public void testMatchingGroupIdsDifferentArtifactIds() - throws Exception - { + public void testMatchingGroupIdsDifferentArtifactIds() throws Exception { List projects = new ArrayList<>(); - MavenProject project1 = createProject( "groupId", "artifactId1", "1.0" ); - projects.add( project1 ); - MavenProject project2 = createProject( "groupId", "artifactId2", "1.0" ); - projects.add( project2 ); - project1.getDependencies().add( createDependency( project2 ) ); + MavenProject project1 = createProject("groupId", "artifactId1", "1.0"); + projects.add(project1); + MavenProject project2 = createProject("groupId", "artifactId2", "1.0"); + projects.add(project2); + project1.getDependencies().add(createDependency(project2)); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertEquals( project2, projects.get( 0 ) ); - assertEquals( project1, projects.get( 1 ) ); + assertEquals(project2, projects.get(0)); + assertEquals(project1, projects.get(1)); } @Test - public void testMatchingIdsAndVersions() - throws Exception - { + public void testMatchingIdsAndVersions() throws Exception { List projects = new ArrayList<>(); - MavenProject project1 = createProject( "groupId", "artifactId", "1.0" ); - projects.add( project1 ); - MavenProject project2 = createProject( "groupId", "artifactId", "1.0" ); - projects.add( project2 ); + MavenProject project1 = createProject("groupId", "artifactId", "1.0"); + projects.add(project1); + MavenProject project2 = createProject("groupId", "artifactId", "1.0"); + projects.add(project2); assertThrows( DuplicateProjectException.class, - () -> new ProjectSorter( projects ).getSortedProjects(), - "Duplicate projects should fail" ); + () -> new ProjectSorter(projects).getSortedProjects(), + "Duplicate projects should fail"); } @Test - public void testMatchingIdsAndDifferentVersions() - throws Exception - { + public void testMatchingIdsAndDifferentVersions() throws Exception { List projects = new ArrayList<>(); - MavenProject project1 = createProject( "groupId", "artifactId", "1.0" ); - projects.add( project1 ); - MavenProject project2 = createProject( "groupId", "artifactId", "2.0" ); - projects.add( project2 ); + MavenProject project1 = createProject("groupId", "artifactId", "1.0"); + projects.add(project1); + MavenProject project2 = createProject("groupId", "artifactId", "2.0"); + projects.add(project2); - projects = new ProjectSorter( projects ).getSortedProjects(); - assertEquals( project1, projects.get( 0 ) ); - assertEquals( project2, projects.get( 1 ) ); + projects = new ProjectSorter(projects).getSortedProjects(); + assertEquals(project1, projects.get(0)); + assertEquals(project2, projects.get(1)); } @Test - public void testPluginDependenciesInfluenceSorting() - throws Exception - { + public void testPluginDependenciesInfluenceSorting() throws Exception { List projects = new ArrayList<>(); - MavenProject parentProject = createProject( "groupId", "parent", "1.0" ); - projects.add( parentProject ); + MavenProject parentProject = createProject("groupId", "parent", "1.0"); + projects.add(parentProject); - MavenProject declaringProject = createProject( "groupId", "declarer", "1.0" ); - declaringProject.setParent( parentProject ); - declaringProject.getModel().setParent( createParent( parentProject ) ); - projects.add( declaringProject ); + MavenProject declaringProject = createProject("groupId", "declarer", "1.0"); + declaringProject.setParent(parentProject); + declaringProject.getModel().setParent(createParent(parentProject)); + projects.add(declaringProject); - MavenProject pluginLevelDepProject = createProject( "groupId", "plugin-level-dep", "1.0" ); - pluginLevelDepProject.setParent( parentProject ); - pluginLevelDepProject.getModel().setParent( createParent( parentProject ) ); - projects.add( pluginLevelDepProject ); + MavenProject pluginLevelDepProject = createProject("groupId", "plugin-level-dep", "1.0"); + pluginLevelDepProject.setParent(parentProject); + pluginLevelDepProject.getModel().setParent(createParent(parentProject)); + projects.add(pluginLevelDepProject); - MavenProject pluginProject = createProject( "groupId", "plugin", "1.0" ); - pluginProject.setParent( parentProject ); - pluginProject.getModel().setParent( createParent( parentProject ) ); - projects.add( pluginProject ); + MavenProject pluginProject = createProject("groupId", "plugin", "1.0"); + pluginProject.setParent(parentProject); + pluginProject.getModel().setParent(createParent(parentProject)); + projects.add(pluginProject); - Plugin plugin = createPlugin( pluginProject ); + Plugin plugin = createPlugin(pluginProject); - plugin.addDependency( createDependency( pluginLevelDepProject ) ); + plugin.addDependency(createDependency(pluginLevelDepProject)); Build build = declaringProject.getModel().getBuild(); - build.addPlugin( plugin ); + build.addPlugin(plugin); - declaringProject.getModel().setBuild( build ); + declaringProject.getModel().setBuild(build); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertEquals( parentProject, projects.get( 0 ) ); + assertEquals(parentProject, projects.get(0)); // the order of these two is non-deterministic, based on when they're added to the reactor. - assertThat( projects, hasItem( pluginProject ) ); - assertThat( projects, hasItem( pluginLevelDepProject ) ); + assertThat(projects, hasItem(pluginProject)); + assertThat(projects, hasItem(pluginLevelDepProject)); // the declaring project MUST be listed after the plugin and its plugin-level dep, though. - assertEquals( declaringProject, projects.get( 3 ) ); + assertEquals(declaringProject, projects.get(3)); } @Test - public void testPluginDependenciesInfluenceSorting_DeclarationInParent() - throws Exception - { + public void testPluginDependenciesInfluenceSorting_DeclarationInParent() throws Exception { List projects = new ArrayList<>(); - MavenProject parentProject = createProject( "groupId", "parent-declarer", "1.0" ); - projects.add( parentProject ); + MavenProject parentProject = createProject("groupId", "parent-declarer", "1.0"); + projects.add(parentProject); - MavenProject pluginProject = createProject( "groupId", "plugin", "1.0" ); - pluginProject.setParent( parentProject ); - pluginProject.getModel().setParent( createParent( parentProject ) ); - projects.add( pluginProject ); + MavenProject pluginProject = createProject("groupId", "plugin", "1.0"); + pluginProject.setParent(parentProject); + pluginProject.getModel().setParent(createParent(parentProject)); + projects.add(pluginProject); - MavenProject pluginLevelDepProject = createProject( "groupId", "plugin-level-dep", "1.0" ); - pluginLevelDepProject.setParent( parentProject ); - pluginLevelDepProject.getModel().setParent( createParent( parentProject ) ); - projects.add( pluginLevelDepProject ); + MavenProject pluginLevelDepProject = createProject("groupId", "plugin-level-dep", "1.0"); + pluginLevelDepProject.setParent(parentProject); + pluginLevelDepProject.getModel().setParent(createParent(parentProject)); + projects.add(pluginLevelDepProject); - Plugin plugin = createPlugin( pluginProject ); + Plugin plugin = createPlugin(pluginProject); - plugin.addDependency( createDependency( pluginLevelDepProject ) ); + plugin.addDependency(createDependency(pluginLevelDepProject)); Build build = parentProject.getModel().getBuild(); - build.addPlugin( plugin ); + build.addPlugin(plugin); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertEquals( parentProject, projects.get( 0 ) ); + assertEquals(parentProject, projects.get(0)); // the order of these two is non-deterministic, based on when they're added to the reactor. - assertThat( projects, hasItem( pluginProject ) ); - assertThat( projects, hasItem( pluginLevelDepProject ) ); + assertThat(projects, hasItem(pluginProject)); + assertThat(projects, hasItem(pluginLevelDepProject)); } @Test - public void testPluginVersionsAreConsidered() - throws Exception - { + public void testPluginVersionsAreConsidered() throws Exception { List projects = new ArrayList<>(); - MavenProject pluginProjectA = createProject( "group", "plugin-a", "2.0-SNAPSHOT" ); - projects.add( pluginProjectA ); - pluginProjectA.getModel().getBuild().addPlugin( createPlugin( "group", "plugin-b", "1.0" ) ); + MavenProject pluginProjectA = createProject("group", "plugin-a", "2.0-SNAPSHOT"); + projects.add(pluginProjectA); + pluginProjectA.getModel().getBuild().addPlugin(createPlugin("group", "plugin-b", "1.0")); - MavenProject pluginProjectB = createProject( "group", "plugin-b", "2.0-SNAPSHOT" ); - projects.add( pluginProjectB ); - pluginProjectB.getModel().getBuild().addPlugin( createPlugin( "group", "plugin-a", "1.0" ) ); + MavenProject pluginProjectB = createProject("group", "plugin-b", "2.0-SNAPSHOT"); + projects.add(pluginProjectB); + pluginProjectB.getModel().getBuild().addPlugin(createPlugin("group", "plugin-a", "1.0")); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertThat( projects, hasItem( pluginProjectA ) ); - assertThat( projects, hasItem( pluginProjectB ) ); + assertThat(projects, hasItem(pluginProjectA)); + assertThat(projects, hasItem(pluginProjectB)); } @Test - public void testDependencyPrecedesProjectThatUsesSpecificDependencyVersion() - throws Exception - { + public void testDependencyPrecedesProjectThatUsesSpecificDependencyVersion() throws Exception { List projects = new ArrayList<>(); - MavenProject usingProject = createProject( "group", "project", "1.0" ); - projects.add( usingProject ); - usingProject.getModel().addDependency( createDependency( "group", "dependency", "1.0" ) ); + MavenProject usingProject = createProject("group", "project", "1.0"); + projects.add(usingProject); + usingProject.getModel().addDependency(createDependency("group", "dependency", "1.0")); - MavenProject pluginProject = createProject( "group", "dependency", "1.0" ); - projects.add( pluginProject ); + MavenProject pluginProject = createProject("group", "dependency", "1.0"); + projects.add(pluginProject); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertEquals( pluginProject, projects.get( 0 ) ); - assertEquals( usingProject, projects.get( 1 ) ); + assertEquals(pluginProject, projects.get(0)); + assertEquals(usingProject, projects.get(1)); } @Test - public void testDependencyPrecedesProjectThatUsesUnresolvedDependencyVersion() - throws Exception - { + public void testDependencyPrecedesProjectThatUsesUnresolvedDependencyVersion() throws Exception { List projects = new ArrayList<>(); - MavenProject usingProject = createProject( "group", "project", "1.0" ); - projects.add( usingProject ); - usingProject.getModel().addDependency( createDependency( "group", "dependency", "[1.0,)" ) ); + MavenProject usingProject = createProject("group", "project", "1.0"); + projects.add(usingProject); + usingProject.getModel().addDependency(createDependency("group", "dependency", "[1.0,)")); - MavenProject pluginProject = createProject( "group", "dependency", "1.0" ); - projects.add( pluginProject ); + MavenProject pluginProject = createProject("group", "dependency", "1.0"); + projects.add(pluginProject); - projects = new ProjectSorter( projects ).getSortedProjects(); + projects = new ProjectSorter(projects).getSortedProjects(); - assertEquals( pluginProject, projects.get( 0 ) ); - assertEquals( usingProject, projects.get( 1 ) ); + assertEquals(pluginProject, projects.get(0)); + assertEquals(usingProject, projects.get(1)); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/TestMetadataSource.java b/maven-core/src/test/java/org/apache/maven/project/TestMetadataSource.java index 17fca107b0..28b25607bf 100644 --- a/maven-core/src/test/java/org/apache/maven/project/TestMetadataSource.java +++ b/maven-core/src/test/java/org/apache/maven/project/TestMetadataSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.project; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,11 @@ package org.apache.maven.project; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project; import java.util.List; - import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; @@ -34,27 +31,28 @@ import org.apache.maven.plugin.LegacySupport; import org.apache.maven.project.artifact.MavenMetadataCache; import org.apache.maven.project.artifact.MavenMetadataSource; -@SuppressWarnings( "deprecation" ) -@Named( "classpath" ) +@SuppressWarnings("deprecation") +@Named("classpath") @Singleton -public class TestMetadataSource - extends MavenMetadataSource -{ +public class TestMetadataSource extends MavenMetadataSource { - public TestMetadataSource( RepositoryMetadataManager repositoryMetadataManager, ArtifactFactory repositorySystem, ProjectBuilder projectBuilder, MavenMetadataCache cache, LegacySupport legacySupport) { - super( repositoryMetadataManager, repositorySystem, projectBuilder, cache, legacySupport ); + public TestMetadataSource( + RepositoryMetadataManager repositoryMetadataManager, + ArtifactFactory repositorySystem, + ProjectBuilder projectBuilder, + MavenMetadataCache cache, + LegacySupport legacySupport) { + super(repositoryMetadataManager, repositorySystem, projectBuilder, cache, legacySupport); } @Override - public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, - List remoteRepositories ) - throws ArtifactMetadataRetrievalException - { - ResolutionGroup rg = super.retrieve( artifact, localRepository, remoteRepositories ); + public ResolutionGroup retrieve( + Artifact artifact, ArtifactRepository localRepository, List remoteRepositories) + throws ArtifactMetadataRetrievalException { + ResolutionGroup rg = super.retrieve(artifact, localRepository, remoteRepositories); - for ( Artifact a : rg.getArtifacts() ) - { - a.setResolved( true ); + for (Artifact a : rg.getArtifacts()) { + a.setResolved(true); } return rg; diff --git a/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultMavenMetadataCacheTest.java b/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultMavenMetadataCacheTest.java index 2d5c1baa7f..c3eb1ce528 100644 --- a/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultMavenMetadataCacheTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultMavenMetadataCacheTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,13 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; import java.util.Arrays; import java.util.Collections; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter; @@ -30,56 +31,46 @@ import org.apache.maven.repository.DelegatingLocalArtifactRepository; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.repository.TestRepositorySystem; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; +import org.junit.jupiter.api.Test; /** * @author Igor Fedorenko */ -public class DefaultMavenMetadataCacheTest -{ +public class DefaultMavenMetadataCacheTest { private RepositorySystem repositorySystem; @BeforeEach - public void setUp() - throws Exception - { - repositorySystem = new TestRepositorySystem( null, null ); + public void setUp() throws Exception { + repositorySystem = new TestRepositorySystem(null, null); } @AfterEach - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { repositorySystem = null; } @Test - public void testCacheKey() - throws Exception - { - Artifact a1 = repositorySystem.createArtifact( "testGroup", "testArtifact", "1.2.3", "jar" ); - @SuppressWarnings( "deprecation" ) - ArtifactRepository lr1 = new DelegatingLocalArtifactRepository( repositorySystem.createDefaultLocalRepository() ); + public void testCacheKey() throws Exception { + Artifact a1 = repositorySystem.createArtifact("testGroup", "testArtifact", "1.2.3", "jar"); + @SuppressWarnings("deprecation") + ArtifactRepository lr1 = new DelegatingLocalArtifactRepository(repositorySystem.createDefaultLocalRepository()); ArtifactRepository rr1 = repositorySystem.createDefaultRemoteRepository(); - a1.setDependencyFilter( new ExcludesArtifactFilter( Arrays.asList( "foo" ) ) ); + a1.setDependencyFilter(new ExcludesArtifactFilter(Arrays.asList("foo"))); - Artifact a2 = repositorySystem.createArtifact( "testGroup", "testArtifact", "1.2.3", "jar" ); - @SuppressWarnings( "deprecation" ) - ArtifactRepository lr2 = new DelegatingLocalArtifactRepository( repositorySystem.createDefaultLocalRepository() ); + Artifact a2 = repositorySystem.createArtifact("testGroup", "testArtifact", "1.2.3", "jar"); + @SuppressWarnings("deprecation") + ArtifactRepository lr2 = new DelegatingLocalArtifactRepository(repositorySystem.createDefaultLocalRepository()); ArtifactRepository rr2 = repositorySystem.createDefaultRemoteRepository(); - a2.setDependencyFilter( new ExcludesArtifactFilter( Arrays.asList( "foo" ) ) ); + a2.setDependencyFilter(new ExcludesArtifactFilter(Arrays.asList("foo"))); // sanity checks - assertNotSame( a1, a2 ); - assertNotSame( lr1, lr2 ); - assertNotSame( rr1, rr2 ); + assertNotSame(a1, a2); + assertNotSame(lr1, lr2); + assertNotSame(rr1, rr2); - CacheKey k1 = new CacheKey( a1, false, lr1, Collections.singletonList( rr1 ) ); - CacheKey k2 = new CacheKey( a2, false, lr2, Collections.singletonList( rr2 ) ); + CacheKey k1 = new CacheKey(a1, false, lr1, Collections.singletonList(rr1)); + CacheKey k2 = new CacheKey(a2, false, lr2, Collections.singletonList(rr2)); assertEquals(k1.hashCode(), k2.hashCode()); } diff --git a/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCacheTest.java b/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCacheTest.java index 16317ff62e..c738c947b9 100644 --- a/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCacheTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCacheTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,55 +16,54 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.LinkedHashSet; import java.util.Set; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class DefaultProjectArtifactsCacheTest -{ +public class DefaultProjectArtifactsCacheTest { private ProjectArtifactsCache cache; @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { cache = new DefaultProjectArtifactsCache(); } @Test - public void testProjectDependencyOrder() throws Exception - { - ProjectArtifactsCache.Key project1 = new ProjectArtifactsCache.Key(){}; + public void testProjectDependencyOrder() throws Exception { + ProjectArtifactsCache.Key project1 = new ProjectArtifactsCache.Key() {}; - Set artifacts = new LinkedHashSet<>( 4 ); - artifacts.add( new DefaultArtifact( "g", "a1", "v", "compile", "jar", "", null ) ); - artifacts.add( new DefaultArtifact( "g", "a2", "v", "compile", "jar", "", null ) ); - artifacts.add( new DefaultArtifact( "g", "a3", "v", "compile", "jar", "", null ) ); - artifacts.add( new DefaultArtifact( "g", "a4", "v", "compile", "jar", "", null ) ); + Set artifacts = new LinkedHashSet<>(4); + artifacts.add(new DefaultArtifact("g", "a1", "v", "compile", "jar", "", null)); + artifacts.add(new DefaultArtifact("g", "a2", "v", "compile", "jar", "", null)); + artifacts.add(new DefaultArtifact("g", "a3", "v", "compile", "jar", "", null)); + artifacts.add(new DefaultArtifact("g", "a4", "v", "compile", "jar", "", null)); - cache.put( project1, artifacts ); + cache.put(project1, artifacts); - assertArrayEquals( artifacts.toArray( new Artifact[0] ), - cache.get( project1 ).getArtifacts().toArray( new Artifact[0] ) ); + assertArrayEquals( + artifacts.toArray(new Artifact[0]), + cache.get(project1).getArtifacts().toArray(new Artifact[0])); - ProjectArtifactsCache.Key project2 = new ProjectArtifactsCache.Key(){}; + ProjectArtifactsCache.Key project2 = new ProjectArtifactsCache.Key() {}; - Set reversedArtifacts = new LinkedHashSet<>( 4 ); - artifacts.add( new DefaultArtifact( "g", "a4", "v", "compile", "jar", "", null ) ); - artifacts.add( new DefaultArtifact( "g", "a3", "v", "compile", "jar", "", null ) ); - artifacts.add( new DefaultArtifact( "g", "a2", "v", "compile", "jar", "", null ) ); - artifacts.add( new DefaultArtifact( "g", "a1", "v", "compile", "jar", "", null ) ); + Set reversedArtifacts = new LinkedHashSet<>(4); + artifacts.add(new DefaultArtifact("g", "a4", "v", "compile", "jar", "", null)); + artifacts.add(new DefaultArtifact("g", "a3", "v", "compile", "jar", "", null)); + artifacts.add(new DefaultArtifact("g", "a2", "v", "compile", "jar", "", null)); + artifacts.add(new DefaultArtifact("g", "a1", "v", "compile", "jar", "", null)); - cache.put( project2, reversedArtifacts ); + cache.put(project2, reversedArtifacts); - assertArrayEquals( reversedArtifacts.toArray( new Artifact[0] ), - cache.get( project2 ).getArtifacts().toArray( new Artifact[0] ) ); + assertArrayEquals( + reversedArtifacts.toArray(new Artifact[0]), + cache.get(project2).getArtifacts().toArray(new Artifact[0])); } } diff --git a/maven-core/src/test/java/org/apache/maven/project/artifact/MavenMetadataSourceTest.java b/maven-core/src/test/java/org/apache/maven/project/artifact/MavenMetadataSourceTest.java index 7d5150d4d6..2ab7959899 100644 --- a/maven-core/src/test/java/org/apache/maven/project/artifact/MavenMetadataSourceTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/artifact/MavenMetadataSourceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.artifact; * "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 + * 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 @@ -18,18 +16,17 @@ package org.apache.maven.project.artifact; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.artifact; import javax.inject.Inject; - import org.apache.maven.repository.RepositorySystem; -import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @PlexusTest -public class MavenMetadataSourceTest -{ +public class MavenMetadataSourceTest { @Inject private RepositorySystem repositorySystem; @@ -38,9 +35,7 @@ public class MavenMetadataSourceTest @Test @Disabled - public void testShouldNotCarryExclusionsOverFromDependencyToDependency() - throws Exception - { + public void testShouldNotCarryExclusionsOverFromDependencyToDependency() throws Exception { /* Dependency dep1 = new Dependency(); dep1.setGroupId( "test" ); @@ -88,9 +83,7 @@ public class MavenMetadataSourceTest @Test @Disabled("TODO restore these if it makes sense") - public void testShouldUseCompileScopeIfDependencyScopeEmpty() - throws Exception - { + public void testShouldUseCompileScopeIfDependencyScopeEmpty() throws Exception { /* String groupId = "org.apache.maven"; String artifactId = "maven-model"; @@ -128,9 +121,7 @@ public class MavenMetadataSourceTest @Test @Disabled - public void testShouldUseInjectedTestScopeFromDependencyManagement() - throws Exception - { + public void testShouldUseInjectedTestScopeFromDependencyManagement() throws Exception { /* String groupId = "org.apache.maven"; String artifactId = "maven-model"; @@ -180,5 +171,4 @@ public class MavenMetadataSourceTest assertEquals( "default scope NOT back-propagated to dependency.", Artifact.SCOPE_TEST, dep.getScope() ); */ } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/canonical/CanonicalProjectBuilderTest.java b/maven-core/src/test/java/org/apache/maven/project/canonical/CanonicalProjectBuilderTest.java index 8330c3c294..63794acc43 100644 --- a/maven-core/src/test/java/org/apache/maven/project/canonical/CanonicalProjectBuilderTest.java +++ b/maven-core/src/test/java/org/apache/maven/project/canonical/CanonicalProjectBuilderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.canonical; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.canonical; * "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 + * 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 @@ -18,40 +16,35 @@ package org.apache.maven.project.canonical; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.canonical; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.util.List; - import org.apache.maven.api.xml.Dom; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.project.AbstractMavenProjectTestCase; import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * @author Jason van Zyl */ -public class CanonicalProjectBuilderTest - extends AbstractMavenProjectTestCase -{ +public class CanonicalProjectBuilderTest extends AbstractMavenProjectTestCase { @Test - public void testProjectBuilder() - throws Exception - { - File f = getFileForClasspathResource( "canonical-pom.xml" ); + public void testProjectBuilder() throws Exception { + File f = getFileForClasspathResource("canonical-pom.xml"); - MavenProject project = getProject( f ); + MavenProject project = getProject(f); // ---------------------------------------------------------------------- // Top-level elements // ---------------------------------------------------------------------- - assertEquals( "4.0.0", project.getModelVersion() ); + assertEquals("4.0.0", project.getModelVersion()); // ---------------------------------------------------------------------- // Plugins @@ -64,27 +57,29 @@ public class CanonicalProjectBuilderTest String key = "org.apache.maven.plugins:maven-plexus-plugin"; Plugin plugin = null; - for ( Plugin check : plugins ) - { - if ( key.equals( check.getKey() ) ) - { + for (Plugin check : plugins) { + if (key.equals(check.getKey())) { plugin = check; break; } } - assertNotNull( plugin ); + assertNotNull(plugin); - assertEquals( "1.0", plugin.getVersion() ); + assertEquals("1.0", plugin.getVersion()); Dom configuration = plugin.getDelegate().getConfiguration(); - assertEquals( "src/conf/plexus.conf", configuration.getChild( "plexusConfiguration" ).getValue() ); + assertEquals( + "src/conf/plexus.conf", + configuration.getChild("plexusConfiguration").getValue()); - assertEquals( "src/conf/plexus.properties", - configuration.getChild( "plexusConfigurationPropertiesFile" ).getValue() ); + assertEquals( + "src/conf/plexus.properties", + configuration.getChild("plexusConfigurationPropertiesFile").getValue()); - assertEquals( "Continuum", configuration.getChild( "plexusApplicationName" ).getValue() ); + assertEquals( + "Continuum", configuration.getChild("plexusApplicationName").getValue()); // ---------------------------------------------------------------------- // Goal specific configuration @@ -92,15 +87,16 @@ public class CanonicalProjectBuilderTest List executions = plugin.getExecutions(); - PluginExecution execution = executions.get( 0 ); + PluginExecution execution = executions.get(0); - String g0 = execution.getGoals().get( 0 ); + String g0 = execution.getGoals().get(0); - assertEquals( "plexus:runtime", g0 ); + assertEquals("plexus:runtime", g0); configuration = execution.getDelegate().getConfiguration(); - assertEquals( "ContinuumPro", configuration.getChild( "plexusApplicationName" ).getValue() ); + assertEquals( + "ContinuumPro", configuration.getChild("plexusApplicationName").getValue()); // Plugin1 [antlr] } diff --git a/maven-core/src/test/java/org/apache/maven/project/harness/PomTestWrapper.java b/maven-core/src/test/java/org/apache/maven/project/harness/PomTestWrapper.java index aa203e9e82..cc25189364 100644 --- a/maven-core/src/test/java/org/apache/maven/project/harness/PomTestWrapper.java +++ b/maven-core/src/test/java/org/apache/maven/project/harness/PomTestWrapper.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.harness; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.harness; * "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 + * 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 @@ -18,18 +16,17 @@ package org.apache.maven.project.harness; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.harness; import java.io.File; import java.util.Iterator; import java.util.Objects; - import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathNotFoundException; import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl; import org.apache.maven.project.MavenProject; -public class PomTestWrapper -{ +public class PomTestWrapper { private File pomFile; @@ -37,37 +34,31 @@ public class PomTestWrapper private MavenProject mavenProject; - static - { - JXPathContextReferenceImpl.addNodePointerFactory( new Xpp3DomPointerFactory() ); + static { + JXPathContextReferenceImpl.addNodePointerFactory(new Xpp3DomPointerFactory()); } - public PomTestWrapper( File pomFile, MavenProject mavenProject ) - { - this.mavenProject = Objects.requireNonNull( mavenProject, "mavenProject cannot be null" ); + public PomTestWrapper(File pomFile, MavenProject mavenProject) { + this.mavenProject = Objects.requireNonNull(mavenProject, "mavenProject cannot be null"); this.pomFile = pomFile; - context = JXPathContext.newContext( mavenProject.getModel() ); + context = JXPathContext.newContext(mavenProject.getModel()); } - public PomTestWrapper( MavenProject mavenProject ) - { - this.mavenProject = Objects.requireNonNull( mavenProject, "mavenProject cannot be null" ); - context = JXPathContext.newContext( mavenProject.getModel() ); + public PomTestWrapper(MavenProject mavenProject) { + this.mavenProject = Objects.requireNonNull(mavenProject, "mavenProject cannot be null"); + context = JXPathContext.newContext(mavenProject.getModel()); } - public MavenProject getMavenProject() - { + public MavenProject getMavenProject() { return mavenProject; } - public File getBasedir() - { - return ( pomFile != null ) ? pomFile.getParentFile() : null; + public File getBasedir() { + return (pomFile != null) ? pomFile.getParentFile() : null; } - public void setValueOnModel( String expression, Object value ) - { - context.setValue( expression, value ); + public void setValueOnModel(String expression, Object value) { + context.setValue(expression, value); } /* @@ -81,31 +72,24 @@ public class PomTestWrapper } */ - public Iterator getIteratorForXPathExpression( String expression ) - { - return context.iterate( expression ); + public Iterator getIteratorForXPathExpression(String expression) { + return context.iterate(expression); } - public boolean containsXPathExpression( String expression ) - { - return context.getValue( expression ) != null; + public boolean containsXPathExpression(String expression) { + return context.getValue(expression) != null; } - public Object getValue( String expression ) - { - try - { - return context.getValue( expression ); - } - catch ( JXPathNotFoundException e ) - { + public Object getValue(String expression) { + try { + return context.getValue(expression); + } catch (JXPathNotFoundException e) { return null; } } - public boolean xPathExpressionEqualsValue( String expression, String value ) - { - return context.getValue( expression ) != null && context.getValue( expression ).equals( value ); + public boolean xPathExpressionEqualsValue(String expression, String value) { + return context.getValue(expression) != null + && context.getValue(expression).equals(value); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributeIterator.java b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributeIterator.java index c596a06d3c..6e6f039d91 100644 --- a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributeIterator.java +++ b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributeIterator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.harness; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.harness; * "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 + * 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 @@ -18,11 +16,11 @@ package org.apache.maven.project.harness; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.harness; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.model.NodeIterator; import org.apache.commons.jxpath.ri.model.NodePointer; @@ -33,9 +31,7 @@ import org.apache.maven.internal.xml.Xpp3Dom; * * @author Benjamin Bentmann */ -class Xpp3DomAttributeIterator - implements NodeIterator -{ +class Xpp3DomAttributeIterator implements NodeIterator { private NodePointer parent; @@ -47,35 +43,29 @@ class Xpp3DomAttributeIterator private int position; - public Xpp3DomAttributeIterator( NodePointer parent, QName qname ) - { + public Xpp3DomAttributeIterator(NodePointer parent, QName qname) { this.parent = parent; this.node = (Xpp3Dom) parent.getNode(); this.attributes = this.node.getAttributes().entrySet().stream() - .filter( a -> a.getKey().equals( qname.getName() ) || "*".equals( qname.getName() ) ) - .collect( Collectors.toList() ); + .filter(a -> a.getKey().equals(qname.getName()) || "*".equals(qname.getName())) + .collect(Collectors.toList()); } - public NodePointer getNodePointer() - { - if ( position == 0 ) - { - setPosition( 1 ); + public NodePointer getNodePointer() { + if (position == 0) { + setPosition(1); } - return ( attribute == null ) ? null : new Xpp3DomAttributePointer( parent, attribute ); + return (attribute == null) ? null : new Xpp3DomAttributePointer(parent, attribute); } - public int getPosition() - { + public int getPosition() { return position; } - public boolean setPosition( int position ) - { + public boolean setPosition(int position) { this.position = position; - attribute = ( position > 0 && position <= attributes.size() ) ? attributes.get( position - 1 ) : null; + attribute = (position > 0 && position <= attributes.size()) ? attributes.get(position - 1) : null; return attribute != null; } - -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributePointer.java b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributePointer.java index 04514b186c..cab4d31952 100644 --- a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributePointer.java +++ b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomAttributePointer.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.harness; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.harness; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.project.harness; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.harness; import java.util.Map; - import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.model.NodePointer; @@ -29,77 +27,63 @@ import org.apache.commons.jxpath.ri.model.NodePointer; * * @author Benjamin Bentmann */ -class Xpp3DomAttributePointer - extends NodePointer -{ +class Xpp3DomAttributePointer extends NodePointer { private Map.Entry attrib; - public Xpp3DomAttributePointer( NodePointer parent, Map.Entry attrib ) - { - super( parent ); + public Xpp3DomAttributePointer(NodePointer parent, Map.Entry attrib) { + super(parent); this.attrib = attrib; } @Override - public int compareChildNodePointers( NodePointer pointer1, NodePointer pointer2 ) - { + public int compareChildNodePointers(NodePointer pointer1, NodePointer pointer2) { // should never happen because attributes have no children return 0; } @Override - public Object getValue() - { + public Object getValue() { return attrib.getValue(); } @Override - public Object getBaseValue() - { + public Object getBaseValue() { return attrib; } @Override - public Object getImmediateNode() - { + public Object getImmediateNode() { return attrib; } @Override - public int getLength() - { + public int getLength() { return 1; } @Override - public QName getName() - { - return new QName( null, attrib.getKey() ); + public QName getName() { + return new QName(null, attrib.getKey()); } @Override - public boolean isActual() - { + public boolean isActual() { return true; } @Override - public boolean isCollection() - { + public boolean isCollection() { return false; } @Override - public boolean isLeaf() - { + public boolean isLeaf() { return true; } @Override - public void setValue( Object value ) - { + public void setValue(Object value) { throw new UnsupportedOperationException(); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodeIterator.java b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodeIterator.java index 6890cc77dd..4181064397 100644 --- a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodeIterator.java +++ b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodeIterator.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.harness; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.harness; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project.harness; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.harness; import java.util.ArrayList; import java.util.List; - import org.apache.commons.jxpath.ri.Compiler; import org.apache.commons.jxpath.ri.compiler.NodeNameTest; import org.apache.commons.jxpath.ri.compiler.NodeTest; @@ -37,9 +35,7 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; * * @author Benjamin Bentmann */ -class Xpp3DomNodeIterator - implements NodeIterator -{ +class Xpp3DomNodeIterator implements NodeIterator { private NodePointer parent; @@ -57,75 +53,59 @@ class Xpp3DomNodeIterator private int position; - public Xpp3DomNodeIterator( NodePointer parent, NodeTest test, boolean reverse, NodePointer startWith ) - { + public Xpp3DomNodeIterator(NodePointer parent, NodeTest test, boolean reverse, NodePointer startWith) { this.parent = parent; this.node = (Dom) parent.getNode(); this.children = this.node.getChildren(); - if ( startWith != null ) - { + if (startWith != null) { Xpp3Dom startWithNode = (Xpp3Dom) startWith.getNode(); - for ( ; filteredIndex < children.size(); filteredIndex++ ) - { - if ( startWithNode.equals( children.get(filteredIndex) ) ) - { + for (; filteredIndex < children.size(); filteredIndex++) { + if (startWithNode.equals(children.get(filteredIndex))) { filteredIndex++; break; } } } this.test = test; - if ( reverse ) - { + if (reverse) { throw new UnsupportedOperationException(); } } - public NodePointer getNodePointer() - { - if ( position == 0 ) - { - setPosition( 1 ); + public NodePointer getNodePointer() { + if (position == 0) { + setPosition(1); } - return ( child == null ) ? null : new Xpp3DomNodePointer( parent, child ); + return (child == null) ? null : new Xpp3DomNodePointer(parent, child); } - public int getPosition() - { + public int getPosition() { return position; } - public boolean setPosition( int position ) - { + public boolean setPosition(int position) { this.position = position; - filterChildren( position ); - child = ( position > 0 && position <= filteredChildren.size() ) ? filteredChildren.get( position - 1 ) : null; + filterChildren(position); + child = (position > 0 && position <= filteredChildren.size()) ? filteredChildren.get(position - 1) : null; return child != null; } - private void filterChildren( int position ) - { - for ( ; position > filteredChildren.size() && filteredIndex < children.size(); filteredIndex++ ) - { + private void filterChildren(int position) { + for (; position > filteredChildren.size() && filteredIndex < children.size(); filteredIndex++) { Dom child = children.get(filteredIndex); - if ( testNode( child ) ) - { - filteredChildren.add( child ); + if (testNode(child)) { + filteredChildren.add(child); } } } - private boolean testNode( Dom node ) - { - if ( test == null ) - { + private boolean testNode(Dom node) { + if (test == null) { return true; } - if ( test instanceof NodeNameTest ) - { + if (test instanceof NodeNameTest) { String nodeName = node.getName(); - if ( StringUtils.isEmpty( nodeName ) ) - { + if (StringUtils.isEmpty(nodeName)) { return false; } @@ -134,20 +114,16 @@ class Xpp3DomNodeIterator boolean wildcard = nodeNameTest.isWildcard(); String testName = nodeNameTest.getNodeName().getName(); String testPrefix = nodeNameTest.getNodeName().getPrefix(); - if ( wildcard && testPrefix == null ) - { + if (wildcard && testPrefix == null) { return true; } - if ( wildcard || testName.equals( nodeName ) ) - { - return StringUtils.isEmpty( namespaceURI ) || StringUtils.isEmpty( testPrefix ); + if (wildcard || testName.equals(nodeName)) { + return StringUtils.isEmpty(namespaceURI) || StringUtils.isEmpty(testPrefix); } return false; } - if ( test instanceof NodeTypeTest ) - { - switch ( ( (NodeTypeTest) test ).getNodeType() ) - { + if (test instanceof NodeTypeTest) { + switch (((NodeTypeTest) test).getNodeType()) { case Compiler.NODE_TYPE_NODE: return true; case Compiler.NODE_TYPE_TEXT: @@ -158,5 +134,4 @@ class Xpp3DomNodeIterator } return false; } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodePointer.java b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodePointer.java index 81060b08da..f147d3e392 100644 --- a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodePointer.java +++ b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomNodePointer.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.harness; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.harness; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.project.harness; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.harness; import java.util.ArrayList; import java.util.List; - import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.compiler.NodeTest; import org.apache.commons.jxpath.ri.model.NodeIterator; @@ -33,41 +31,32 @@ import org.apache.maven.api.xml.Dom; * * @author Benjamin Bentmann */ -class Xpp3DomNodePointer - extends NodePointer -{ +class Xpp3DomNodePointer extends NodePointer { private Dom node; - public Xpp3DomNodePointer( Dom node ) - { - super( null ); + public Xpp3DomNodePointer(Dom node) { + super(null); this.node = node; } - public Xpp3DomNodePointer( NodePointer parent, Dom node ) - { - super( parent ); + public Xpp3DomNodePointer(NodePointer parent, Dom node) { + super(parent); this.node = node; } @Override - public int compareChildNodePointers( NodePointer pointer1, NodePointer pointer2 ) - { + public int compareChildNodePointers(NodePointer pointer1, NodePointer pointer2) { Dom node1 = (Dom) pointer1.getBaseValue(); Dom node2 = (Dom) pointer2.getBaseValue(); - if ( node1 == node2 ) - { + if (node1 == node2) { return 0; } - for ( Dom child : node.getChildren() ) - { - if ( child == node1 ) - { + for (Dom child : node.getChildren()) { + if (child == node1) { return -1; } - if ( child == node2 ) - { + if (child == node2) { return 1; } } @@ -75,80 +64,64 @@ class Xpp3DomNodePointer } @Override - public Object getValue() - { - return getValue( node ); + public Object getValue() { + return getValue(node); } - private static Object getValue( Dom node ) - { - if ( node.getValue() != null ) - { + private static Object getValue(Dom node) { + if (node.getValue() != null) { return node.getValue(); - } - else - { + } else { List children = new ArrayList<>(); - for ( Dom child : node.getChildren() ) - { - children.add( getValue( child ) ); + for (Dom child : node.getChildren()) { + children.add(getValue(child)); } return children; } } @Override - public Object getBaseValue() - { + public Object getBaseValue() { return node; } @Override - public Object getImmediateNode() - { + public Object getImmediateNode() { return node; } @Override - public int getLength() - { + public int getLength() { return 1; } @Override - public QName getName() - { - return new QName( null, node.getName() ); + public QName getName() { + return new QName(null, node.getName()); } @Override - public boolean isCollection() - { + public boolean isCollection() { return false; } @Override - public boolean isLeaf() - { + public boolean isLeaf() { return node.getChildren().isEmpty(); } @Override - public void setValue( Object value ) - { + public void setValue(Object value) { throw new UnsupportedOperationException(); } @Override - public NodeIterator childIterator( NodeTest test, boolean reverse, NodePointer startWith ) - { - return new Xpp3DomNodeIterator( this, test, reverse, startWith ); + public NodeIterator childIterator(NodeTest test, boolean reverse, NodePointer startWith) { + return new Xpp3DomNodeIterator(this, test, reverse, startWith); } @Override - public NodeIterator attributeIterator( QName qname ) - { - return new Xpp3DomAttributeIterator( this, qname ); + public NodeIterator attributeIterator(QName qname) { + return new Xpp3DomAttributeIterator(this, qname); } - } diff --git a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomPointerFactory.java b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomPointerFactory.java index 24aab57dcc..73e8c0129d 100644 --- a/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomPointerFactory.java +++ b/maven-core/src/test/java/org/apache/maven/project/harness/Xpp3DomPointerFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.project.harness; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.project.harness; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.project.harness; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.project.harness; import java.util.Locale; - import org.apache.commons.jxpath.ri.QName; import org.apache.commons.jxpath.ri.model.NodePointer; import org.apache.commons.jxpath.ri.model.NodePointerFactory; @@ -31,39 +29,29 @@ import org.apache.maven.api.xml.Dom; * * @author Benjamin Bentmann */ -public class Xpp3DomPointerFactory - implements NodePointerFactory -{ +public class Xpp3DomPointerFactory implements NodePointerFactory { - public int getOrder() - { + public int getOrder() { return 200; } - public NodePointer createNodePointer( QName name, Object object, Locale locale ) - { - if ( object instanceof org.codehaus.plexus.util.xml.Xpp3Dom ) - { - object = ( ( org.codehaus.plexus.util.xml.Xpp3Dom ) object ).getDom(); + public NodePointer createNodePointer(QName name, Object object, Locale locale) { + if (object instanceof org.codehaus.plexus.util.xml.Xpp3Dom) { + object = ((org.codehaus.plexus.util.xml.Xpp3Dom) object).getDom(); } - if ( object instanceof Dom ) - { - return new Xpp3DomNodePointer( (Dom) object ); + if (object instanceof Dom) { + return new Xpp3DomNodePointer((Dom) object); } return null; } - public NodePointer createNodePointer( NodePointer parent, QName name, Object object ) - { - if ( object instanceof org.codehaus.plexus.util.xml.Xpp3Dom ) - { - object = ( ( org.codehaus.plexus.util.xml.Xpp3Dom ) object ).getDom(); + public NodePointer createNodePointer(NodePointer parent, QName name, Object object) { + if (object instanceof org.codehaus.plexus.util.xml.Xpp3Dom) { + object = ((org.codehaus.plexus.util.xml.Xpp3Dom) object).getDom(); } - if ( object instanceof Dom ) - { - return new Xpp3DomNodePointer( parent, (Dom) object ); + if (object instanceof Dom) { + return new Xpp3DomNodePointer(parent, (Dom) object); } return null; } - } diff --git a/maven-core/src/test/java/org/apache/maven/repository/TestArtifactHandler.java b/maven-core/src/test/java/org/apache/maven/repository/TestArtifactHandler.java index db1fecb5b4..818b52ce9d 100644 --- a/maven-core/src/test/java/org/apache/maven/repository/TestArtifactHandler.java +++ b/maven-core/src/test/java/org/apache/maven/repository/TestArtifactHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import org.apache.maven.artifact.handler.ArtifactHandler; @@ -26,58 +25,46 @@ import org.apache.maven.artifact.handler.ArtifactHandler; * * @author Benjamin Bentmann */ -class TestArtifactHandler - implements ArtifactHandler -{ +class TestArtifactHandler implements ArtifactHandler { private String type; private String extension; - public TestArtifactHandler( String type ) - { - this( type, type ); + public TestArtifactHandler(String type) { + this(type, type); } - public TestArtifactHandler( String type, String extension ) - { + public TestArtifactHandler(String type, String extension) { this.type = type; this.extension = extension; } - public String getClassifier() - { + public String getClassifier() { return null; } - public String getDirectory() - { + public String getDirectory() { return getPackaging() + "s"; } - public String getExtension() - { + public String getExtension() { return extension; } - public String getLanguage() - { + public String getLanguage() { return "java"; } - public String getPackaging() - { + public String getPackaging() { return type; } - public boolean isAddedToClasspath() - { + public boolean isAddedToClasspath() { return true; } - public boolean isIncludesDependencies() - { + public boolean isIncludesDependencies() { return false; } - } diff --git a/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnector.java b/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnector.java index cb1243ced5..84d30435b1 100644 --- a/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnector.java +++ b/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnector.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; - import org.codehaus.plexus.util.FileUtils; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; @@ -42,120 +40,92 @@ import org.eclipse.aether.transfer.MetadataTransferException; /** * @author Benjamin Bentmann */ -public class TestRepositoryConnector - implements RepositoryConnector -{ +public class TestRepositoryConnector implements RepositoryConnector { private RemoteRepository repository; private File basedir; - public TestRepositoryConnector( RemoteRepository repository ) - { + public TestRepositoryConnector(RemoteRepository repository) { this.repository = repository; - try - { - basedir = FileUtils.toFile( new URL( repository.getUrl() ) ); - } - catch ( MalformedURLException e ) - { - throw new IllegalStateException( e ); + try { + basedir = FileUtils.toFile(new URL(repository.getUrl())); + } catch (MalformedURLException e) { + throw new IllegalStateException(e); } } - public void close() - { - } + public void close() {} - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - if ( artifactDownloads != null ) - { - for ( ArtifactDownload download : artifactDownloads ) - { - File remoteFile = new File( basedir, path( download.getArtifact() ) ); - try - { - FileUtils.copyFile( remoteFile, download.getFile() ); - } - catch ( IOException e ) - { - if ( !remoteFile.exists() ) - { - download.setException( new ArtifactNotFoundException( download.getArtifact(), repository ) ); - } - else - { - download.setException( new ArtifactTransferException( download.getArtifact(), repository, e ) ); + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + if (artifactDownloads != null) { + for (ArtifactDownload download : artifactDownloads) { + File remoteFile = new File(basedir, path(download.getArtifact())); + try { + FileUtils.copyFile(remoteFile, download.getFile()); + } catch (IOException e) { + if (!remoteFile.exists()) { + download.setException(new ArtifactNotFoundException(download.getArtifact(), repository)); + } else { + download.setException(new ArtifactTransferException(download.getArtifact(), repository, e)); } } } } - if ( metadataDownloads != null ) - { - for ( final MetadataDownload download : metadataDownloads ) - { - File remoteFile = new File( basedir, path( download.getMetadata() ) ); - try - { - FileUtils.copyFile( remoteFile, download.getFile() ); - } - catch ( IOException e ) - { - if ( !remoteFile.exists() ) - { - download.setException( new MetadataNotFoundException( download.getMetadata(), repository ) ); - } - else - { - download.setException( new MetadataTransferException( download.getMetadata(), repository, e ) ); + if (metadataDownloads != null) { + for (final MetadataDownload download : metadataDownloads) { + File remoteFile = new File(basedir, path(download.getMetadata())); + try { + FileUtils.copyFile(remoteFile, download.getFile()); + } catch (IOException e) { + if (!remoteFile.exists()) { + download.setException(new MetadataNotFoundException(download.getMetadata(), repository)); + } else { + download.setException(new MetadataTransferException(download.getMetadata(), repository, e)); } } } } } - private String path( Artifact artifact ) - { - StringBuilder path = new StringBuilder( 128 ); + private String path(Artifact artifact) { + StringBuilder path = new StringBuilder(128); - path.append( artifact.getGroupId().replace( '.', '/' ) ).append( '/' ); + path.append(artifact.getGroupId().replace('.', '/')).append('/'); - path.append( artifact.getArtifactId() ).append( '/' ); + path.append(artifact.getArtifactId()).append('/'); - path.append( artifact.getBaseVersion() ).append( '/' ); + path.append(artifact.getBaseVersion()).append('/'); - path.append( artifact.getArtifactId() ).append( '-' ).append( artifact.getVersion() ); + path.append(artifact.getArtifactId()).append('-').append(artifact.getVersion()); - if ( artifact.getClassifier().length() > 0 ) - { - path.append( '-' ).append( artifact.getClassifier() ); + if (artifact.getClassifier().length() > 0) { + path.append('-').append(artifact.getClassifier()); } - path.append( '.' ).append( artifact.getExtension() ); + path.append('.').append(artifact.getExtension()); return path.toString(); } - private String path( Metadata metadata ) - { - StringBuilder path = new StringBuilder( 128 ); + private String path(Metadata metadata) { + StringBuilder path = new StringBuilder(128); - path.append( metadata.getGroupId().replace( '.', '/' ) ).append( '/' ); + path.append(metadata.getGroupId().replace('.', '/')).append('/'); - path.append( metadata.getArtifactId() ).append( '/' ); + path.append(metadata.getArtifactId()).append('/'); - path.append( "maven-metadata.xml" ); + path.append("maven-metadata.xml"); return path.toString(); } - public void put( Collection artifactUploads, - Collection metadataUploads ) - { + public void put( + Collection artifactUploads, + Collection metadataUploads) { // TODO Auto-generated method stub } - } diff --git a/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnectorFactory.java b/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnectorFactory.java index 1f41e09e1a..8a38321684 100644 --- a/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnectorFactory.java +++ b/maven-core/src/test/java/org/apache/maven/repository/TestRepositoryConnectorFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import javax.inject.Named; import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.RepositoryConnector; @@ -31,21 +29,16 @@ import org.eclipse.aether.transfer.NoRepositoryConnectorException; /** * @author Benjamin Bentmann */ -@Named( "test" ) +@Named("test") @Singleton -public class TestRepositoryConnectorFactory - implements RepositoryConnectorFactory -{ +public class TestRepositoryConnectorFactory implements RepositoryConnectorFactory { - public RepositoryConnector newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryConnectorException - { - return new TestRepositoryConnector( repository ); + public RepositoryConnector newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryConnectorException { + return new TestRepositoryConnector(repository); } - public float getPriority() - { + public float getPriority() { return 0; } - } diff --git a/maven-core/src/test/java/org/apache/maven/repository/TestRepositorySystem.java b/maven-core/src/test/java/org/apache/maven/repository/TestRepositorySystem.java index cec73d273e..d3f62bff0d 100644 --- a/maven-core/src/test/java/org/apache/maven/repository/TestRepositorySystem.java +++ b/maven-core/src/test/java/org/apache/maven/repository/TestRepositorySystem.java @@ -1,5 +1,3 @@ -package org.apache.maven.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.repository; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.repository; import java.io.File; import java.io.IOException; @@ -26,11 +25,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; - +import org.apache.maven.api.model.Model; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.InvalidRepositoryException; @@ -45,7 +43,6 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Dependency; -import org.apache.maven.api.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.Repository; import org.apache.maven.model.io.ModelReader; @@ -62,221 +59,191 @@ import org.eclipse.aether.RepositorySystemSession; */ @Named @Singleton -public class TestRepositorySystem - implements RepositorySystem -{ +public class TestRepositorySystem implements RepositorySystem { private final ModelReader modelReader; private final ArtifactFactory artifactFactory; @Inject - public TestRepositorySystem( ModelReader modelReader, ArtifactFactory artifactFactory ) - { + public TestRepositorySystem(ModelReader modelReader, ArtifactFactory artifactFactory) { this.modelReader = modelReader; this.artifactFactory = artifactFactory; } - public ArtifactRepository buildArtifactRepository( Repository repository ) - throws InvalidRepositoryException - { - return new MavenArtifactRepository( repository.getId(), repository.getUrl(), new DefaultRepositoryLayout(), - new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy() ); + public ArtifactRepository buildArtifactRepository(Repository repository) throws InvalidRepositoryException { + return new MavenArtifactRepository( + repository.getId(), + repository.getUrl(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - public Artifact createArtifact( String groupId, String artifactId, String version, String packaging ) - { - return createArtifact( groupId, artifactId, version, null, packaging ); + public Artifact createArtifact(String groupId, String artifactId, String version, String packaging) { + return createArtifact(groupId, artifactId, version, null, packaging); } - public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ) - { - return new DefaultArtifact( groupId, artifactId, version, scope, type, null, new TestArtifactHandler( type ) ); + public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) { + return new DefaultArtifact(groupId, artifactId, version, scope, type, null, new TestArtifactHandler(type)); } - public ArtifactRepository createArtifactRepository( String id, String url, - ArtifactRepositoryLayout repositoryLayout, - ArtifactRepositoryPolicy snapshots, - ArtifactRepositoryPolicy releases ) - { - return new MavenArtifactRepository( id, url, repositoryLayout, snapshots, releases ); + public ArtifactRepository createArtifactRepository( + String id, + String url, + ArtifactRepositoryLayout repositoryLayout, + ArtifactRepositoryPolicy snapshots, + ArtifactRepositoryPolicy releases) { + return new MavenArtifactRepository(id, url, repositoryLayout, snapshots, releases); } - public Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, - String classifier ) - { - return new DefaultArtifact( groupId, artifactId, version, null, type, classifier, - new TestArtifactHandler( type ) ); + public Artifact createArtifactWithClassifier( + String groupId, String artifactId, String version, String type, String classifier) { + return new DefaultArtifact(groupId, artifactId, version, null, type, classifier, new TestArtifactHandler(type)); } - public ArtifactRepository createDefaultLocalRepository() - throws InvalidRepositoryException - { - return createLocalRepository( new File( System.getProperty( "basedir", "." ), "target/local-repo" ).getAbsoluteFile() ); + public ArtifactRepository createDefaultLocalRepository() throws InvalidRepositoryException { + return createLocalRepository( + new File(System.getProperty("basedir", "."), "target/local-repo").getAbsoluteFile()); } - public ArtifactRepository createDefaultRemoteRepository() - throws InvalidRepositoryException - { - return new MavenArtifactRepository( DEFAULT_REMOTE_REPO_ID, "file://" - + new File( System.getProperty( "basedir", "." ), "src/test/remote-repo" ).getAbsoluteFile().toURI().getPath(), - new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + public ArtifactRepository createDefaultRemoteRepository() throws InvalidRepositoryException { + return new MavenArtifactRepository( + DEFAULT_REMOTE_REPO_ID, + "file://" + + new File(System.getProperty("basedir", "."), "src/test/remote-repo") + .getAbsoluteFile() + .toURI() + .getPath(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - public Artifact createDependencyArtifact( Dependency dependency ) - { - Artifact artifact = - new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), - dependency.getScope(), dependency.getType(), dependency.getClassifier(), - new TestArtifactHandler( dependency.getType() ) ); + public Artifact createDependencyArtifact(Dependency dependency) { + Artifact artifact = new DefaultArtifact( + dependency.getGroupId(), + dependency.getArtifactId(), + dependency.getVersion(), + dependency.getScope(), + dependency.getType(), + dependency.getClassifier(), + new TestArtifactHandler(dependency.getType())); - if ( Artifact.SCOPE_SYSTEM.equals( dependency.getScope() ) ) - { - artifact.setFile( new File( dependency.getSystemPath() ) ); - artifact.setResolved( true ); + if (Artifact.SCOPE_SYSTEM.equals(dependency.getScope())) { + artifact.setFile(new File(dependency.getSystemPath())); + artifact.setResolved(true); } return artifact; } - public ArtifactRepository createLocalRepository( File localRepository ) - throws InvalidRepositoryException - { - return new MavenArtifactRepository( DEFAULT_LOCAL_REPO_ID, "file://" + localRepository.toURI().getPath(), - new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + public ArtifactRepository createLocalRepository(File localRepository) throws InvalidRepositoryException { + return new MavenArtifactRepository( + DEFAULT_LOCAL_REPO_ID, + "file://" + localRepository.toURI().getPath(), + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); } - public Artifact createPluginArtifact( Plugin plugin ) - { + public Artifact createPluginArtifact(Plugin plugin) { VersionRange versionRange; - try - { + try { String version = plugin.getVersion(); - if ( StringUtils.isEmpty( version ) ) - { + if (StringUtils.isEmpty(version)) { version = "RELEASE"; } - versionRange = VersionRange.createFromVersionSpec( version ); - } - catch ( InvalidVersionSpecificationException e ) - { + versionRange = VersionRange.createFromVersionSpec(version); + } catch (InvalidVersionSpecificationException e) { return null; } - return artifactFactory.createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange ); + return artifactFactory.createPluginArtifact(plugin.getGroupId(), plugin.getArtifactId(), versionRange); } - public Artifact createProjectArtifact( String groupId, String artifactId, String version ) - { - return createArtifact( groupId, artifactId, version, "pom" ); + public Artifact createProjectArtifact(String groupId, String artifactId, String version) { + return createArtifact(groupId, artifactId, version, "pom"); } - public List getEffectiveRepositories( List repositories ) - { + public List getEffectiveRepositories(List repositories) { return repositories; } - public Mirror getMirror( ArtifactRepository repository, List mirrors ) - { + public Mirror getMirror(ArtifactRepository repository, List mirrors) { return null; } - public void injectAuthentication( List repositories, List servers ) - { - } + public void injectAuthentication(List repositories, List servers) {} - public void injectMirror( List repositories, List mirrors ) - { - } + public void injectMirror(List repositories, List mirrors) {} - public void injectProxy( List repositories, List proxies ) - { - } + public void injectProxy(List repositories, List proxies) {} - public void publish( ArtifactRepository repository, File source, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException - { + public void publish( + ArtifactRepository repository, File source, String remotePath, ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException { // TODO Auto-generated method stub } - public ArtifactResolutionResult resolve( ArtifactResolutionRequest request ) - { + public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) { ArtifactResolutionResult result = new ArtifactResolutionResult(); - if ( request.isResolveRoot() ) - { - try - { - resolve( request.getArtifact(), request ); - result.addArtifact( request.getArtifact() ); - } - catch ( IOException e ) - { - result.addMissingArtifact( request.getArtifact() ); + if (request.isResolveRoot()) { + try { + resolve(request.getArtifact(), request); + result.addArtifact(request.getArtifact()); + } catch (IOException e) { + result.addMissingArtifact(request.getArtifact()); } } - if ( request.isResolveTransitively() ) - { + if (request.isResolveTransitively()) { Map artifacts = new LinkedHashMap<>(); - if ( request.getArtifactDependencies() != null ) - { - for ( Artifact artifact : request.getArtifactDependencies() ) - { - artifacts.put( artifact.getDependencyConflictId(), artifact ); + if (request.getArtifactDependencies() != null) { + for (Artifact artifact : request.getArtifactDependencies()) { + artifacts.put(artifact.getDependencyConflictId(), artifact); } } List dependencies = new ArrayList<>(); - if ( request.getArtifact() instanceof ArtifactWithDependencies ) - { - dependencies = ( (ArtifactWithDependencies) request.getArtifact() ).getDependencies(); - } - else - { - Artifact pomArtifact = - createProjectArtifact( request.getArtifact().getGroupId(), request.getArtifact().getArtifactId(), - request.getArtifact().getVersion() ); - File pomFile = - new File( request.getLocalRepository().getBasedir(), - request.getLocalRepository().pathOf( pomArtifact ) ); + if (request.getArtifact() instanceof ArtifactWithDependencies) { + dependencies = ((ArtifactWithDependencies) request.getArtifact()).getDependencies(); + } else { + Artifact pomArtifact = createProjectArtifact( + request.getArtifact().getGroupId(), + request.getArtifact().getArtifactId(), + request.getArtifact().getVersion()); + File pomFile = new File( + request.getLocalRepository().getBasedir(), + request.getLocalRepository().pathOf(pomArtifact)); - try - { - Model model = modelReader.read( pomFile, null ).getDelegate(); + try { + Model model = modelReader.read(pomFile, null).getDelegate(); - dependencies = model.getDependencies().stream().map( Dependency::new ).collect( Collectors.toList() ); - } - catch ( IOException e ) - { + dependencies = model.getDependencies().stream() + .map(Dependency::new) + .collect(Collectors.toList()); + } catch (IOException e) { e.printStackTrace(); } } - for ( Dependency dependency : dependencies ) - { - Artifact artifact = createDependencyArtifact( dependency ); - if ( !artifacts.containsKey( artifact.getDependencyConflictId() ) ) - { - artifacts.put( artifact.getDependencyConflictId(), artifact ); + for (Dependency dependency : dependencies) { + Artifact artifact = createDependencyArtifact(dependency); + if (!artifacts.containsKey(artifact.getDependencyConflictId())) { + artifacts.put(artifact.getDependencyConflictId(), artifact); } } - for ( Artifact artifact : artifacts.values() ) - { - try - { - resolve( artifact, request ); - result.addArtifact( artifact ); - } - catch ( IOException e ) - { - result.addMissingArtifact( artifact ); + for (Artifact artifact : artifacts.values()) { + try { + resolve(artifact, request); + result.addArtifact(artifact); + } catch (IOException e) { + result.addMissingArtifact(artifact); } } } @@ -284,55 +251,45 @@ public class TestRepositorySystem return result; } - private void resolve( Artifact artifact, ArtifactResolutionRequest request ) - throws IOException - { - if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) - { + private void resolve(Artifact artifact, ArtifactResolutionRequest request) throws IOException { + if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { return; } ArtifactRepository localRepo = request.getLocalRepository(); - File localFile = new File( localRepo.getBasedir(), localRepo.pathOf( artifact ) ); + File localFile = new File(localRepo.getBasedir(), localRepo.pathOf(artifact)); - artifact.setFile( localFile ); + artifact.setFile(localFile); - if ( !localFile.exists() ) - { - if ( request.getRemoteRepositories().isEmpty() ) - { - throw new IOException( localFile + " does not exist and no remote repositories are configured" ); + if (!localFile.exists()) { + if (request.getRemoteRepositories().isEmpty()) { + throw new IOException(localFile + " does not exist and no remote repositories are configured"); } - ArtifactRepository remoteRepo = request.getRemoteRepositories().get( 0 ); + ArtifactRepository remoteRepo = request.getRemoteRepositories().get(0); - File remoteFile = new File( remoteRepo.getBasedir(), remoteRepo.pathOf( artifact ) ); + File remoteFile = new File(remoteRepo.getBasedir(), remoteRepo.pathOf(artifact)); - FileUtils.copyFile( remoteFile, localFile ); + FileUtils.copyFile(remoteFile, localFile); } - artifact.setResolved( true ); + artifact.setResolved(true); } - public void retrieve( ArtifactRepository repository, File destination, String remotePath, - ArtifactTransferListener transferListener ) - throws ArtifactTransferFailedException, ArtifactDoesNotExistException - { + public void retrieve( + ArtifactRepository repository, + File destination, + String remotePath, + ArtifactTransferListener transferListener) + throws ArtifactTransferFailedException, ArtifactDoesNotExistException { // TODO Auto-generated method stub } - public void injectMirror( RepositorySystemSession session, List repositories ) - { - } + public void injectMirror(RepositorySystemSession session, List repositories) {} - public void injectProxy( RepositorySystemSession session, List repositories ) - { - } - - public void injectAuthentication( RepositorySystemSession session, List repositories ) - { - } + public void injectProxy(RepositorySystemSession session, List repositories) {} + public void injectAuthentication(RepositorySystemSession session, List repositories) {} } diff --git a/maven-core/src/test/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformationTest.java b/maven-core/src/test/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformationTest.java index b6e987e2f6..5c0e80625f 100644 --- a/maven-core/src/test/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformationTest.java +++ b/maven-core/src/test/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.rtinfo.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,7 @@ package org.apache.maven.rtinfo.internal; * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.rtinfo.RuntimeInformation; -import org.codehaus.plexus.testing.PlexusTest; -import org.junit.jupiter.api.Test; +package org.apache.maven.rtinfo.internal; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -29,44 +24,39 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import javax.inject.Inject; +import org.apache.maven.rtinfo.RuntimeInformation; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.Test; @PlexusTest -public class DefaultRuntimeInformationTest -{ +public class DefaultRuntimeInformationTest { @Inject RuntimeInformation rtInfo; @Test - public void testGetMavenVersion() - { + public void testGetMavenVersion() { String mavenVersion = rtInfo.getMavenVersion(); - assertNotNull( mavenVersion ); - assertTrue( mavenVersion.length() > 0 ); + assertNotNull(mavenVersion); + assertTrue(mavenVersion.length() > 0); } @Test - public void testIsMavenVersion() - { - assertTrue( rtInfo.isMavenVersion( "2.0" ) ); - assertFalse( rtInfo.isMavenVersion( "9.9" ) ); + public void testIsMavenVersion() { + assertTrue(rtInfo.isMavenVersion("2.0")); + assertFalse(rtInfo.isMavenVersion("9.9")); - assertTrue( rtInfo.isMavenVersion( "[2.0.11,2.1.0),[3.0,)" ) ); - assertFalse( rtInfo.isMavenVersion( "[9.0,)" ) ); + assertTrue(rtInfo.isMavenVersion("[2.0.11,2.1.0),[3.0,)")); + assertFalse(rtInfo.isMavenVersion("[9.0,)")); assertThrows( IllegalArgumentException.class, - () -> rtInfo.isMavenVersion( "[3.0," ), - "Bad version range wasn't rejected" ); + () -> rtInfo.isMavenVersion("[3.0,"), + "Bad version range wasn't rejected"); assertThrows( - IllegalArgumentException.class, - () -> rtInfo.isMavenVersion( "" ), - "Bad version range wasn't rejected" ); + IllegalArgumentException.class, () -> rtInfo.isMavenVersion(""), "Bad version range wasn't rejected"); assertThrows( - NullPointerException.class, - () -> rtInfo.isMavenVersion( null ), - "Bad version range wasn't rejected" ); + NullPointerException.class, () -> rtInfo.isMavenVersion(null), "Bad version range wasn't rejected"); } - } diff --git a/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java b/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java index 9b16403e5b..8af4ff2a44 100644 --- a/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java +++ b/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.settings; * "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 + * 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 @@ -18,11 +16,15 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; + +import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; import java.io.Reader; - +import javax.inject.Inject; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.model.Profile; import org.apache.maven.project.DefaultProjectBuilder; @@ -41,14 +43,8 @@ import org.eclipse.aether.repository.LocalRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.inject.Inject; - -import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.junit.jupiter.api.Assertions.assertEquals; - @PlexusTest -public class PomConstructionWithSettingsTest -{ +public class PomConstructionWithSettingsTest { private static final String BASE_DIR = "src/test"; private static final String BASE_POM_DIR = BASE_DIR + "/resources-settings"; @@ -62,87 +58,73 @@ public class PomConstructionWithSettingsTest private File testDirectory; @BeforeEach - public void setUp() - throws Exception - { - testDirectory = new File( getBasedir(), BASE_POM_DIR ); + public void setUp() throws Exception { + testDirectory = new File(getBasedir(), BASE_POM_DIR); } @Test - public void testSettingsNoPom() - throws Exception - { - PomTestWrapper pom = buildPom( "settings-no-pom" ); - assertEquals( "local-profile-prop-value", pom.getValue( "properties/local-profile-prop" ) ); + public void testSettingsNoPom() throws Exception { + PomTestWrapper pom = buildPom("settings-no-pom"); + assertEquals("local-profile-prop-value", pom.getValue("properties/local-profile-prop")); } /** * MNG-4107 */ @Test - public void testPomAndSettingsInterpolation() - throws Exception - { - PomTestWrapper pom = buildPom( "test-pom-and-settings-interpolation" ); - assertEquals( "applied", pom.getValue( "properties/settingsProfile" ) ); - assertEquals( "applied", pom.getValue( "properties/pomProfile" ) ); - assertEquals( "settings", pom.getValue( "properties/pomVsSettings" ) ); - assertEquals( "settings", pom.getValue( "properties/pomVsSettingsInterpolated" ) ); + public void testPomAndSettingsInterpolation() throws Exception { + PomTestWrapper pom = buildPom("test-pom-and-settings-interpolation"); + assertEquals("applied", pom.getValue("properties/settingsProfile")); + assertEquals("applied", pom.getValue("properties/pomProfile")); + assertEquals("settings", pom.getValue("properties/pomVsSettings")); + assertEquals("settings", pom.getValue("properties/pomVsSettingsInterpolated")); } /** * MNG-4107 */ @Test - public void testRepositories() - throws Exception - { - PomTestWrapper pom = buildPom( "repositories" ); - assertEquals( "maven-core-it-0", pom.getValue( "repositories[1]/id" ) ); + public void testRepositories() throws Exception { + PomTestWrapper pom = buildPom("repositories"); + assertEquals("maven-core-it-0", pom.getValue("repositories[1]/id")); } - private PomTestWrapper buildPom( String pomPath ) - throws Exception - { - File pomFile = new File( testDirectory + File.separator + pomPath, "pom.xml" ); - File settingsFile = new File( testDirectory + File.separator + pomPath, "settings.xml" ); - Settings settings = readSettingsFile( settingsFile ); + private PomTestWrapper buildPom(String pomPath) throws Exception { + File pomFile = new File(testDirectory + File.separator + pomPath, "pom.xml"); + File settingsFile = new File(testDirectory + File.separator + pomPath, "settings.xml"); + Settings settings = readSettingsFile(settingsFile); ProjectBuildingRequest config = new DefaultProjectBuildingRequest(); - for ( org.apache.maven.settings.Profile rawProfile : settings.getProfiles() ) - { - Profile profile = SettingsUtils.convertFromSettingsProfile( rawProfile.getDelegate() ); - config.addProfile( profile ); + for (org.apache.maven.settings.Profile rawProfile : settings.getProfiles()) { + Profile profile = SettingsUtils.convertFromSettingsProfile(rawProfile.getDelegate()); + config.addProfile(profile); } String localRepoUrl = - System.getProperty( "maven.repo.local", System.getProperty( "user.home" ) + "/.m2/repository" ); + System.getProperty("maven.repo.local", System.getProperty("user.home") + "/.m2/repository"); localRepoUrl = "file://" + localRepoUrl; - config.setLocalRepository( - repositorySystem.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(), null, - null ) ); - config.setActiveProfileIds( settings.getActiveProfiles() ); + config.setLocalRepository(repositorySystem.createArtifactRepository( + "local", localRepoUrl, new DefaultRepositoryLayout(), null, null)); + config.setActiveProfileIds(settings.getActiveProfiles()); DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession(); - LocalRepository localRepo = new LocalRepository( config.getLocalRepository().getBasedir() ); + LocalRepository localRepo = + new LocalRepository(config.getLocalRepository().getBasedir()); repoSession.setLocalRepositoryManager( - new SimpleLocalRepositoryManagerFactory().newInstance( repoSession, localRepo ) ); - config.setRepositorySession( repoSession ); + new SimpleLocalRepositoryManagerFactory().newInstance(repoSession, localRepo)); + config.setRepositorySession(repoSession); - return new PomTestWrapper( pomFile, projectBuilder.build( pomFile, config ).getProject() ); + return new PomTestWrapper(pomFile, projectBuilder.build(pomFile, config).getProject()); } - private static Settings readSettingsFile( File settingsFile ) - throws IOException, XmlPullParserException - { + private static Settings readSettingsFile(File settingsFile) throws IOException, XmlPullParserException { Settings settings = null; - try ( Reader reader = ReaderFactory.newXmlReader( settingsFile ) ) - { + try (Reader reader = ReaderFactory.newXmlReader(settingsFile)) { SettingsXpp3Reader modelReader = new SettingsXpp3Reader(); - settings = modelReader.read( reader ); + settings = modelReader.read(reader); } return settings; } diff --git a/maven-core/src/test/java/org/apache/maven/settings/SettingsUtilsTest.java b/maven-core/src/test/java/org/apache/maven/settings/SettingsUtilsTest.java index 6f59c3c352..9e0d2d9d15 100644 --- a/maven-core/src/test/java/org/apache/maven/settings/SettingsUtilsTest.java +++ b/maven-core/src/test/java/org/apache/maven/settings/SettingsUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.settings; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.settings; * "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 + * 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 @@ -18,15 +16,17 @@ package org.apache.maven.settings; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.settings; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.Random; - import org.apache.maven.api.settings.Activation; import org.apache.maven.api.settings.ActivationFile; import org.apache.maven.api.settings.ActivationOS; @@ -36,113 +36,119 @@ import org.apache.maven.api.settings.Repository; import org.apache.maven.api.settings.Settings; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class SettingsUtilsTest -{ +public class SettingsUtilsTest { @Test - public void testShouldAppendRecessivePluginGroupIds() - { + public void testShouldAppendRecessivePluginGroupIds() { Settings dominant = Settings.newBuilder() - .pluginGroups( Arrays.asList( "org.apache.maven.plugins", "org.codehaus.modello" ) ) + .pluginGroups(Arrays.asList("org.apache.maven.plugins", "org.codehaus.modello")) .build(); Settings recessive = Settings.newBuilder() - .pluginGroups( Arrays.asList( "org.codehaus.plexus" ) ) + .pluginGroups(Arrays.asList("org.codehaus.plexus")) .build(); - Settings merged = SettingsUtils.merge( dominant, recessive, Settings.GLOBAL_LEVEL ); + Settings merged = SettingsUtils.merge(dominant, recessive, Settings.GLOBAL_LEVEL); List pluginGroups = merged.getPluginGroups(); - assertNotNull( pluginGroups ); - assertEquals( 3, pluginGroups.size() ); - assertEquals( "org.apache.maven.plugins", pluginGroups.get( 0 ) ); - assertEquals( "org.codehaus.modello", pluginGroups.get( 1 ) ); - assertEquals( "org.codehaus.plexus", pluginGroups.get( 2 ) ); + assertNotNull(pluginGroups); + assertEquals(3, pluginGroups.size()); + assertEquals("org.apache.maven.plugins", pluginGroups.get(0)); + assertEquals("org.codehaus.modello", pluginGroups.get(1)); + assertEquals("org.codehaus.plexus", pluginGroups.get(2)); } @Test - public void testRoundTripProfiles() - { + public void testRoundTripProfiles() { Random entropy = new Random(); ActivationFile af = ActivationFile.newBuilder() - .exists( "exists" + Long.toHexString( entropy.nextLong() ) ) - .missing( "missing" + Long.toHexString( entropy.nextLong() ) ) + .exists("exists" + Long.toHexString(entropy.nextLong())) + .missing("missing" + Long.toHexString(entropy.nextLong())) .build(); ActivationProperty ap = ActivationProperty.newBuilder() - .name( "name" + Long.toHexString( entropy.nextLong() ) ) - .value( "value" + Long.toHexString( entropy.nextLong() ) ) + .name("name" + Long.toHexString(entropy.nextLong())) + .value("value" + Long.toHexString(entropy.nextLong())) .build(); ActivationOS ao = ActivationOS.newBuilder() - .arch( "arch" + Long.toHexString( entropy.nextLong() ) ) - .family( "family" + Long.toHexString( entropy.nextLong() ) ) - .name( "name" + Long.toHexString( entropy.nextLong() ) ) - .version( "version" + Long.toHexString( entropy.nextLong() ) ) + .arch("arch" + Long.toHexString(entropy.nextLong())) + .family("family" + Long.toHexString(entropy.nextLong())) + .name("name" + Long.toHexString(entropy.nextLong())) + .version("version" + Long.toHexString(entropy.nextLong())) .build(); Activation a = Activation.newBuilder() - .activeByDefault( entropy.nextBoolean() ) - .jdk( "jdk" + Long.toHexString( entropy.nextLong() ) ) - .file( af ) - .property( ap ) - .os( ao ) + .activeByDefault(entropy.nextBoolean()) + .jdk("jdk" + Long.toHexString(entropy.nextLong())) + .file(af) + .property(ap) + .os(ao) .build(); Map props = new HashMap<>(); - int count = entropy.nextInt( 10 ); - for ( int i = 0; i < count; i++ ) - { - props.put( "name" + Long.toHexString( entropy.nextLong() ), - "value" + Long.toHexString( entropy.nextLong() ) ); + int count = entropy.nextInt(10); + for (int i = 0; i < count; i++) { + props.put("name" + Long.toHexString(entropy.nextLong()), "value" + Long.toHexString(entropy.nextLong())); } - count = entropy.nextInt( 3 ); + count = entropy.nextInt(3); List repos = new ArrayList<>(); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { Repository r = Repository.newBuilder() - .id( "id" + Long.toHexString( entropy.nextLong() ) ) - .name( "name" + Long.toHexString( entropy.nextLong() ) ) - .url( "url" + Long.toHexString( entropy.nextLong() ) ) + .id("id" + Long.toHexString(entropy.nextLong())) + .name("name" + Long.toHexString(entropy.nextLong())) + .url("url" + Long.toHexString(entropy.nextLong())) .build(); - repos.add( r ); + repos.add(r); } - count = entropy.nextInt( 3 ); + count = entropy.nextInt(3); List pluginRepos = new ArrayList<>(); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { Repository r = Repository.newBuilder() - .id( "id" + Long.toHexString( entropy.nextLong() ) ) - .name( "name" + Long.toHexString( entropy.nextLong() ) ) - .url( "url" + Long.toHexString( entropy.nextLong() ) ) + .id("id" + Long.toHexString(entropy.nextLong())) + .name("name" + Long.toHexString(entropy.nextLong())) + .url("url" + Long.toHexString(entropy.nextLong())) .build(); - pluginRepos.add( r ); + pluginRepos.add(r); } Profile p = Profile.newBuilder() - .id( "id" + Long.toHexString( entropy.nextLong() ) ) - .activation( a ) - .properties( props ) - .repositories( repos ) - .pluginRepositories( pluginRepos ) + .id("id" + Long.toHexString(entropy.nextLong())) + .activation(a) + .properties(props) + .repositories(repos) + .pluginRepositories(pluginRepos) .build(); - Profile clone = SettingsUtils.convertToSettingsProfile( SettingsUtils.convertFromSettingsProfile( p ) ); + Profile clone = SettingsUtils.convertToSettingsProfile(SettingsUtils.convertFromSettingsProfile(p)); - assertEquals( p.getId(), clone.getId() ); - assertEquals( p.getActivation().getJdk(), clone.getActivation().getJdk() ); - assertEquals( p.getActivation().getFile().getExists(), clone.getActivation().getFile().getExists() ); - assertEquals( p.getActivation().getFile().getMissing(), clone.getActivation().getFile().getMissing() ); - assertEquals( p.getActivation().getProperty().getName(), clone.getActivation().getProperty().getName() ); - assertEquals( p.getActivation().getProperty().getValue(), clone.getActivation().getProperty().getValue() ); - assertEquals( p.getActivation().getOs().getArch(), clone.getActivation().getOs().getArch() ); - assertEquals( p.getActivation().getOs().getFamily(), clone.getActivation().getOs().getFamily() ); - assertEquals( p.getActivation().getOs().getName(), clone.getActivation().getOs().getName() ); - assertEquals( p.getActivation().getOs().getVersion(), clone.getActivation().getOs().getVersion() ); - assertEquals( p.getProperties(), clone.getProperties() ); - assertEquals( p.getRepositories().size(), clone.getRepositories().size() ); + assertEquals(p.getId(), clone.getId()); + assertEquals(p.getActivation().getJdk(), clone.getActivation().getJdk()); + assertEquals( + p.getActivation().getFile().getExists(), + clone.getActivation().getFile().getExists()); + assertEquals( + p.getActivation().getFile().getMissing(), + clone.getActivation().getFile().getMissing()); + assertEquals( + p.getActivation().getProperty().getName(), + clone.getActivation().getProperty().getName()); + assertEquals( + p.getActivation().getProperty().getValue(), + clone.getActivation().getProperty().getValue()); + assertEquals( + p.getActivation().getOs().getArch(), + clone.getActivation().getOs().getArch()); + assertEquals( + p.getActivation().getOs().getFamily(), + clone.getActivation().getOs().getFamily()); + assertEquals( + p.getActivation().getOs().getName(), + clone.getActivation().getOs().getName()); + assertEquals( + p.getActivation().getOs().getVersion(), + clone.getActivation().getOs().getVersion()); + assertEquals(p.getProperties(), clone.getProperties()); + assertEquals(p.getRepositories().size(), clone.getRepositories().size()); // TODO deep compare the lists - assertEquals( p.getPluginRepositories().size(), clone.getPluginRepositories().size() ); + assertEquals( + p.getPluginRepositories().size(), clone.getPluginRepositories().size()); // TODO deep compare the lists } - -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivateTest.java b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivateTest.java index 04ab6f19df..a8a531d94d 100644 --- a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivateTest.java +++ b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivateTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; @@ -30,7 +29,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; @@ -42,8 +40,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; -public class DefaultToolchainManagerPrivateTest -{ +public class DefaultToolchainManagerPrivateTest { // Mocks to inject into toolchainManager @Mock private Logger logger; @@ -58,106 +55,97 @@ public class DefaultToolchainManagerPrivateTest private ToolchainFactory toolchainFactory_rareType; @BeforeEach - public void setUp() - { + public void setUp() { - MockitoAnnotations.initMocks( this ); + MockitoAnnotations.initMocks(this); Map factories = new HashMap<>(); - factories.put( "basic", toolchainFactory_basicType ); - factories.put( "rare", toolchainFactory_rareType ); - toolchainManager = new DefaultToolchainManagerPrivate( factories, logger ); + factories.put("basic", toolchainFactory_basicType); + factories.put("rare", toolchainFactory_rareType); + toolchainManager = new DefaultToolchainManagerPrivate(factories, logger); } @Test - public void testToolchainsForAvailableType() - throws Exception - { + public void testToolchainsForAvailableType() throws Exception { // prepare - MavenSession session = mock( MavenSession.class ); + MavenSession session = mock(MavenSession.class); MavenExecutionRequest req = new DefaultMavenExecutionRequest(); - when( session.getRequest() ).thenReturn( req ); + when(session.getRequest()).thenReturn(req); - ToolchainPrivate basicToolchain = mock( ToolchainPrivate.class ); - when( toolchainFactory_basicType.createDefaultToolchain() ).thenReturn( basicToolchain ); - ToolchainPrivate rareToolchain = mock( ToolchainPrivate.class ); - when( toolchainFactory_rareType.createDefaultToolchain() ).thenReturn( rareToolchain ); + ToolchainPrivate basicToolchain = mock(ToolchainPrivate.class); + when(toolchainFactory_basicType.createDefaultToolchain()).thenReturn(basicToolchain); + ToolchainPrivate rareToolchain = mock(ToolchainPrivate.class); + when(toolchainFactory_rareType.createDefaultToolchain()).thenReturn(rareToolchain); // execute - ToolchainPrivate[] toolchains = toolchainManager.getToolchainsForType( "basic", session ); + ToolchainPrivate[] toolchains = toolchainManager.getToolchainsForType("basic", session); // verify - verify( logger, never() ).error( anyString() ); - assertEquals( 1, toolchains.length ); + verify(logger, never()).error(anyString()); + assertEquals(1, toolchains.length); } @Test - public void testToolchainsForUnknownType() - throws Exception - { + public void testToolchainsForUnknownType() throws Exception { // prepare - MavenSession session = mock( MavenSession.class ); + MavenSession session = mock(MavenSession.class); MavenExecutionRequest req = new DefaultMavenExecutionRequest(); - when( session.getRequest() ).thenReturn( req ); + when(session.getRequest()).thenReturn(req); - ToolchainPrivate basicToolchain = mock( ToolchainPrivate.class ); - when( toolchainFactory_basicType.createDefaultToolchain() ).thenReturn( basicToolchain ); - ToolchainPrivate rareToolchain = mock( ToolchainPrivate.class ); - when( toolchainFactory_rareType.createDefaultToolchain() ).thenReturn( rareToolchain ); + ToolchainPrivate basicToolchain = mock(ToolchainPrivate.class); + when(toolchainFactory_basicType.createDefaultToolchain()).thenReturn(basicToolchain); + ToolchainPrivate rareToolchain = mock(ToolchainPrivate.class); + when(toolchainFactory_rareType.createDefaultToolchain()).thenReturn(rareToolchain); // execute - ToolchainPrivate[] toolchains = toolchainManager.getToolchainsForType( "unknown", session ); + ToolchainPrivate[] toolchains = toolchainManager.getToolchainsForType("unknown", session); // verify - verify( logger ).error( "Missing toolchain factory for type: unknown. Possibly caused by misconfigured project." ); - assertEquals( 0, toolchains.length ); + verify(logger).error("Missing toolchain factory for type: unknown. Possibly caused by misconfigured project."); + assertEquals(0, toolchains.length); } @Test - public void testToolchainsForConfiguredType() - throws Exception - { + public void testToolchainsForConfiguredType() throws Exception { // prepare - MavenSession session = mock( MavenSession.class ); + MavenSession session = mock(MavenSession.class); MavenExecutionRequest req = new DefaultMavenExecutionRequest(); - when( session.getRequest() ).thenReturn( req ); + when(session.getRequest()).thenReturn(req); Map> groupedToolchains = new HashMap<>(); - req.setToolchains( groupedToolchains ); + req.setToolchains(groupedToolchains); List basicToolchains = new ArrayList<>(); ToolchainModel basicToolchainModel = new ToolchainModel(); - basicToolchainModel.setType( "basic" ); - basicToolchains.add( basicToolchainModel ); - basicToolchains.add( basicToolchainModel ); - groupedToolchains.put( "basic", basicToolchains ); + basicToolchainModel.setType("basic"); + basicToolchains.add(basicToolchainModel); + basicToolchains.add(basicToolchainModel); + groupedToolchains.put("basic", basicToolchains); List rareToolchains = new ArrayList<>(); ToolchainModel rareToolchainModel = new ToolchainModel(); - rareToolchainModel.setType( "rare" ); - rareToolchains.add( rareToolchainModel ); - groupedToolchains.put( "rare", rareToolchains ); + rareToolchainModel.setType("rare"); + rareToolchains.add(rareToolchainModel); + groupedToolchains.put("rare", rareToolchains); // execute - ToolchainPrivate[] toolchains = toolchainManager.getToolchainsForType( "basic", session ); + ToolchainPrivate[] toolchains = toolchainManager.getToolchainsForType("basic", session); // verify - verify( logger, never() ).error( anyString() ); - assertEquals( 2, toolchains.length ); + verify(logger, never()).error(anyString()); + assertEquals(2, toolchains.length); } @Test - public void testMisconfiguredToolchain() - throws Exception - { + public void testMisconfiguredToolchain() throws Exception { // prepare - MavenSession session = mock( MavenSession.class ); + MavenSession session = mock(MavenSession.class); MavenExecutionRequest req = new DefaultMavenExecutionRequest(); - when( session.getRequest() ).thenReturn( req ); + when(session.getRequest()).thenReturn(req); // execute ToolchainPrivate[] basics = toolchainManager.getToolchainsForType("basic", session); // verify - assertEquals( 0, basics.length ); + assertEquals(0, basics.length); } } diff --git a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerTest.java b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerTest.java index 893f55f044..b3c5a839f1 100644 --- a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerTest.java +++ b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.isA; @@ -30,7 +29,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; @@ -43,8 +41,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; -public class DefaultToolchainManagerTest -{ +public class DefaultToolchainManagerTest { // Mocks to inject into toolchainManager @Mock private Logger logger; @@ -59,94 +56,90 @@ public class DefaultToolchainManagerTest private ToolchainFactory toolchainFactory_rareType; @BeforeEach - public void onSetup() throws Exception - { - MockitoAnnotations.initMocks( this ); + public void onSetup() throws Exception { + MockitoAnnotations.initMocks(this); Map factories = new HashMap<>(); - factories.put( "basic", toolchainFactory_basicType ); - factories.put( "rare", toolchainFactory_rareType ); - toolchainManager = new DefaultToolchainManager( factories, logger ); + factories.put("basic", toolchainFactory_basicType); + factories.put("rare", toolchainFactory_rareType); + toolchainManager = new DefaultToolchainManager(factories, logger); } @Test - public void testNoModels() - { - MavenSession session = mock( MavenSession.class ); + public void testNoModels() { + MavenSession session = mock(MavenSession.class); MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); - when( session.getRequest() ).thenReturn( executionRequest ); + when(session.getRequest()).thenReturn(executionRequest); - List toolchains = toolchainManager.getToolchains( session, "unknown", null ); + List toolchains = toolchainManager.getToolchains(session, "unknown", null); - assertEquals( 0, toolchains.size() ); + assertEquals(0, toolchains.size()); } @Test - public void testModelNoFactory() - { - MavenSession session = mock( MavenSession.class ); + public void testModelNoFactory() { + MavenSession session = mock(MavenSession.class); MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); Map> toolchainModels = new HashMap<>(); - toolchainModels.put( "unknown", Collections.singletonList( new ToolchainModel() ) ); - executionRequest.setToolchains( toolchainModels ); - when( session.getRequest() ).thenReturn( executionRequest ); + toolchainModels.put("unknown", Collections.singletonList(new ToolchainModel())); + executionRequest.setToolchains(toolchainModels); + when(session.getRequest()).thenReturn(executionRequest); - List toolchains = toolchainManager.getToolchains( session, "unknown", null ); + List toolchains = toolchainManager.getToolchains(session, "unknown", null); - assertEquals( 0, toolchains.size() ); - verify( logger ).error( "Missing toolchain factory for type: unknown. Possibly caused by misconfigured project." ); + assertEquals(0, toolchains.size()); + verify(logger).error("Missing toolchain factory for type: unknown. Possibly caused by misconfigured project."); } @Test - public void testModelAndFactory() - { - MavenSession session = mock( MavenSession.class ); + public void testModelAndFactory() { + MavenSession session = mock(MavenSession.class); MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); Map> toolchainModels = new HashMap<>(); - toolchainModels.put( "basic", Arrays.asList( new ToolchainModel(), new ToolchainModel() ) ); - toolchainModels.put( "rare", Collections.singletonList( new ToolchainModel() ) ); - executionRequest.setToolchains( toolchainModels ); - when( session.getRequest() ).thenReturn( executionRequest ); + toolchainModels.put("basic", Arrays.asList(new ToolchainModel(), new ToolchainModel())); + toolchainModels.put("rare", Collections.singletonList(new ToolchainModel())); + executionRequest.setToolchains(toolchainModels); + when(session.getRequest()).thenReturn(executionRequest); - List toolchains = toolchainManager.getToolchains( session, "rare", null ); + List toolchains = toolchainManager.getToolchains(session, "rare", null); - assertEquals( 1, toolchains.size() ); + assertEquals(1, toolchains.size()); } @Test - public void testModelsAndFactory() - { - MavenSession session = mock( MavenSession.class ); + public void testModelsAndFactory() { + MavenSession session = mock(MavenSession.class); MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); Map> toolchainModels = new HashMap<>(); - toolchainModels.put( "basic", Arrays.asList( new ToolchainModel(), new ToolchainModel() ) ); - toolchainModels.put( "rare", Collections.singletonList( new ToolchainModel() ) ); - executionRequest.setToolchains( toolchainModels ); - when( session.getRequest() ).thenReturn( executionRequest ); + toolchainModels.put("basic", Arrays.asList(new ToolchainModel(), new ToolchainModel())); + toolchainModels.put("rare", Collections.singletonList(new ToolchainModel())); + executionRequest.setToolchains(toolchainModels); + when(session.getRequest()).thenReturn(executionRequest); - List toolchains = toolchainManager.getToolchains( session, "basic", null ); + List toolchains = toolchainManager.getToolchains(session, "basic", null); - assertEquals( 2, toolchains.size() ); + assertEquals(2, toolchains.size()); } @Test - public void testRequirements() - throws Exception - { - MavenSession session = mock( MavenSession.class ); + public void testRequirements() throws Exception { + MavenSession session = mock(MavenSession.class); MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); Map> toolchainModels = new HashMap<>(); - toolchainModels.put( "basic", Arrays.asList( new ToolchainModel(), new ToolchainModel() ) ); - toolchainModels.put( "rare", Collections.singletonList( new ToolchainModel() ) ); - executionRequest.setToolchains( toolchainModels ); - when( session.getRequest() ).thenReturn( executionRequest ); - ToolchainPrivate basicPrivate = mock( ToolchainPrivate.class ); - when( basicPrivate.matchesRequirements( ArgumentMatchers.anyMap() ) ).thenReturn( false ).thenReturn( true ); - when( toolchainFactory_basicType.createToolchain( isA( ToolchainModel.class ) ) ).thenReturn( basicPrivate ); + toolchainModels.put("basic", Arrays.asList(new ToolchainModel(), new ToolchainModel())); + toolchainModels.put("rare", Collections.singletonList(new ToolchainModel())); + executionRequest.setToolchains(toolchainModels); + when(session.getRequest()).thenReturn(executionRequest); + ToolchainPrivate basicPrivate = mock(ToolchainPrivate.class); + when(basicPrivate.matchesRequirements(ArgumentMatchers.anyMap())) + .thenReturn(false) + .thenReturn(true); + when(toolchainFactory_basicType.createToolchain(isA(ToolchainModel.class))) + .thenReturn(basicPrivate); List toolchains = - toolchainManager.getToolchains( session, "basic", Collections.singletonMap( "key", "value" ) ); + toolchainManager.getToolchains(session, "basic", Collections.singletonMap("key", "value")); - assertEquals( 1, toolchains.size() ); + assertEquals(1, toolchains.size()); } -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java index 509e014a23..ff828ed0eb 100644 --- a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java +++ b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.toolchain; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.toolchain; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.toolchain; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.toolchain; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -26,7 +25,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.Collections; - import org.apache.maven.toolchain.java.DefaultJavaToolChain; import org.apache.maven.toolchain.model.ToolchainModel; import org.codehaus.plexus.util.xml.Xpp3Dom; @@ -35,123 +33,106 @@ import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; -public class DefaultToolchainTest -{ - private final Logger logger = mock( Logger.class ); +public class DefaultToolchainTest { + private final Logger logger = mock(Logger.class); @BeforeEach - public void setUp() - throws Exception - { - MockitoAnnotations.initMocks( this ); + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); } - private DefaultToolchain newDefaultToolchain( ToolchainModel model ) - { - return new DefaultToolchain( model, logger ) - { + private DefaultToolchain newDefaultToolchain(ToolchainModel model) { + return new DefaultToolchain(model, logger) { @Override - public String findTool( String toolName ) - { + public String findTool(String toolName) { return null; } }; } - private DefaultToolchain newDefaultToolchain( ToolchainModel model, String type ) - { - return new DefaultToolchain( model, type, logger ) - { + private DefaultToolchain newDefaultToolchain(ToolchainModel model, String type) { + return new DefaultToolchain(model, type, logger) { @Override - public String findTool( String toolName ) - { + public String findTool(String toolName) { return null; } }; } @Test - public void testGetModel() - { + public void testGetModel() { ToolchainModel model = new ToolchainModel(); - DefaultToolchain toolchain = newDefaultToolchain( model ); - assertEquals( model, toolchain.getModel() ); + DefaultToolchain toolchain = newDefaultToolchain(model); + assertEquals(model, toolchain.getModel()); } @Test - public void testGetType() - { + public void testGetType() { ToolchainModel model = new ToolchainModel(); - DefaultToolchain toolchain = newDefaultToolchain( model, "TYPE" ); - assertEquals( "TYPE", toolchain.getType() ); + DefaultToolchain toolchain = newDefaultToolchain(model, "TYPE"); + assertEquals("TYPE", toolchain.getType()); - model.setType( "MODEL_TYPE" ); - toolchain = newDefaultToolchain( model ); - assertEquals( "MODEL_TYPE", toolchain.getType() ); + model.setType("MODEL_TYPE"); + toolchain = newDefaultToolchain(model); + assertEquals("MODEL_TYPE", toolchain.getType()); } @Test - public void testGetLogger() - { + public void testGetLogger() { ToolchainModel model = new ToolchainModel(); - DefaultToolchain toolchain = newDefaultToolchain( model ); - assertEquals( logger, toolchain.getLog() ); + DefaultToolchain toolchain = newDefaultToolchain(model); + assertEquals(logger, toolchain.getLog()); } @Test - public void testMissingRequirementProperty() - { + public void testMissingRequirementProperty() { ToolchainModel model = new ToolchainModel(); - model.setType( "TYPE" ); - DefaultToolchain toolchain = newDefaultToolchain( model ); + model.setType("TYPE"); + DefaultToolchain toolchain = newDefaultToolchain(model); - assertFalse( toolchain.matchesRequirements( Collections.singletonMap( "name", "John Doe" ) ) ); - verify( logger ).debug( "Toolchain type:TYPE{} is missing required property: name" ); + assertFalse(toolchain.matchesRequirements(Collections.singletonMap("name", "John Doe"))); + verify(logger).debug("Toolchain type:TYPE{} is missing required property: name"); } - @Test - public void testNonMatchingRequirementProperty() - { + public void testNonMatchingRequirementProperty() { ToolchainModel model = new ToolchainModel(); - model.setType( "TYPE" ); - DefaultToolchain toolchain = newDefaultToolchain( model ); - toolchain.addProvideToken( "name", RequirementMatcherFactory.createExactMatcher( "Jane Doe" ) ); + model.setType("TYPE"); + DefaultToolchain toolchain = newDefaultToolchain(model); + toolchain.addProvideToken("name", RequirementMatcherFactory.createExactMatcher("Jane Doe")); - assertFalse( toolchain.matchesRequirements( Collections.singletonMap( "name", "John Doe" ) ) ); - verify( logger ).debug( "Toolchain type:TYPE{name = Jane Doe} doesn't match required property: name" ); + assertFalse(toolchain.matchesRequirements(Collections.singletonMap("name", "John Doe"))); + verify(logger).debug("Toolchain type:TYPE{name = Jane Doe} doesn't match required property: name"); } - @Test - public void testEquals() - { + public void testEquals() { ToolchainModel tm1 = new ToolchainModel(); - tm1.setType( "jdk" ); - tm1.addProvide( "version", "1.5" ); - tm1.addProvide( "vendor", "sun" ); + tm1.setType("jdk"); + tm1.addProvide("version", "1.5"); + tm1.addProvide("vendor", "sun"); Xpp3Dom configuration1 = new Xpp3Dom("configuration"); - Xpp3Dom jdkHome1 = new Xpp3Dom( "jdkHome" ); + Xpp3Dom jdkHome1 = new Xpp3Dom("jdkHome"); jdkHome1.setValue("${env.JAVA_HOME}"); - configuration1.addChild( jdkHome1 ); - tm1.setConfiguration( configuration1 ); + configuration1.addChild(jdkHome1); + tm1.setConfiguration(configuration1); ToolchainModel tm2 = new ToolchainModel(); - tm1.setType( "jdk" ); - tm1.addProvide( "version", "1.4" ); - tm1.addProvide( "vendor", "sun" ); + tm1.setType("jdk"); + tm1.addProvide("version", "1.4"); + tm1.addProvide("vendor", "sun"); Xpp3Dom configuration2 = new Xpp3Dom("configuration"); - Xpp3Dom jdkHome2 = new Xpp3Dom( "jdkHome" ); + Xpp3Dom jdkHome2 = new Xpp3Dom("jdkHome"); jdkHome2.setValue("${env.JAVA_HOME}"); - configuration2.addChild( jdkHome2 ); - tm2.setConfiguration( configuration2 ); + configuration2.addChild(jdkHome2); + tm2.setConfiguration(configuration2); - DefaultToolchain tc1 = new DefaultJavaToolChain( tm1, null ); - DefaultToolchain tc2 = new DefaultJavaToolChain( tm2, null ); + DefaultToolchain tc1 = new DefaultJavaToolChain(tm1, null); + DefaultToolchain tc2 = new DefaultJavaToolChain(tm2, null); - assertEquals( tc1, tc1 ); - assertNotEquals( tc1, tc2 ); - assertNotEquals( tc2, tc1 ); - assertEquals( tc2, tc2 ); + assertEquals(tc1, tc1); + assertNotEquals(tc1, tc2); + assertNotEquals(tc2, tc1); + assertEquals(tc2, tc2); } -} \ No newline at end of file +} diff --git a/maven-core/src/test/java/org/apache/maven/toolchain/RequirementMatcherFactoryTest.java b/maven-core/src/test/java/org/apache/maven/toolchain/RequirementMatcherFactoryTest.java index 6c167b13ad..3301075bea 100644 --- a/maven-core/src/test/java/org/apache/maven/toolchain/RequirementMatcherFactoryTest.java +++ b/maven-core/src/test/java/org/apache/maven/toolchain/RequirementMatcherFactoryTest.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,57 +16,51 @@ * specific language governing permissions and limitations * under the License. */ - package org.apache.maven.toolchain; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * * @author mkleint */ -public class RequirementMatcherFactoryTest -{ +public class RequirementMatcherFactoryTest { /** * Test of createExactMatcher method, of class RequirementMatcherFactory. */ @Test - public void testCreateExactMatcher() - { + public void testCreateExactMatcher() { RequirementMatcher matcher; - matcher = RequirementMatcherFactory.createExactMatcher( "foo" ); - assertFalse( matcher.matches( "bar" ) ); - assertFalse( matcher.matches( "foobar" ) ); - assertFalse( matcher.matches( "foob" ) ); - assertTrue( matcher.matches( "foo" ) ); + matcher = RequirementMatcherFactory.createExactMatcher("foo"); + assertFalse(matcher.matches("bar")); + assertFalse(matcher.matches("foobar")); + assertFalse(matcher.matches("foob")); + assertTrue(matcher.matches("foo")); } /** * Test of createVersionMatcher method, of class RequirementMatcherFactory. */ @Test - public void testCreateVersionMatcher() - { + public void testCreateVersionMatcher() { RequirementMatcher matcher; - matcher = RequirementMatcherFactory.createVersionMatcher( "1.5.2" ); - assertFalse( matcher.matches( "1.5" ) ); - assertTrue( matcher.matches( "1.5.2" ) ); - assertFalse( matcher.matches( "[1.4,1.5)" ) ); - assertFalse( matcher.matches( "[1.5,1.5.2)" ) ); - assertFalse( matcher.matches( "(1.5.2,1.6)" ) ); - assertTrue( matcher.matches( "(1.4,1.5.2]" ) ); - assertTrue( matcher.matches( "(1.5,)" ) ); - assertEquals( "1.5.2", matcher.toString() ); + matcher = RequirementMatcherFactory.createVersionMatcher("1.5.2"); + assertFalse(matcher.matches("1.5")); + assertTrue(matcher.matches("1.5.2")); + assertFalse(matcher.matches("[1.4,1.5)")); + assertFalse(matcher.matches("[1.5,1.5.2)")); + assertFalse(matcher.matches("(1.5.2,1.6)")); + assertTrue(matcher.matches("(1.4,1.5.2]")); + assertTrue(matcher.matches("(1.5,)")); + assertEquals("1.5.2", matcher.toString()); // Ensure it is not printed as 1.5.0 - matcher = RequirementMatcherFactory.createVersionMatcher( "1.5" ); - assertEquals( "1.5", matcher.toString() ); - + matcher = RequirementMatcherFactory.createVersionMatcher("1.5"); + assertEquals("1.5", matcher.toString()); } - } diff --git a/maven-embedder/pom.xml b/maven-embedder/pom.xml index 1e6c98968e..dcc6c1aaf3 100644 --- a/maven-embedder/pom.xml +++ b/maven-embedder/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 diff --git a/maven-embedder/src/examples/simple-project/src/main/java/org/apache/maven/embedder/App.java b/maven-embedder/src/examples/simple-project/src/main/java/org/apache/maven/embedder/App.java index 06927bff94..f05e5d0b14 100644 --- a/maven-embedder/src/examples/simple-project/src/main/java/org/apache/maven/embedder/App.java +++ b/maven-embedder/src/examples/simple-project/src/main/java/org/apache/maven/embedder/App.java @@ -1,20 +1,5 @@ package org.apache.maven.embedder; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - /** * Hello world! * diff --git a/maven-embedder/src/examples/simple-project/src/test/java/org/apache/maven/embedder/AppTest.java b/maven-embedder/src/examples/simple-project/src/test/java/org/apache/maven/embedder/AppTest.java index ab1b1a0aed..f04b7a92ce 100644 --- a/maven-embedder/src/examples/simple-project/src/test/java/org/apache/maven/embedder/AppTest.java +++ b/maven-embedder/src/examples/simple-project/src/test/java/org/apache/maven/embedder/AppTest.java @@ -1,20 +1,5 @@ package org.apache.maven.embedder; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java b/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java index b6005fddf5..6a99e0eb4d 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli; * "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 + * 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 @@ -18,10 +16,10 @@ package org.apache.maven.cli; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli; import java.io.PrintStream; import java.io.PrintWriter; - import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; @@ -34,8 +32,7 @@ import org.apache.maven.shared.utils.logging.MessageUtils; /** * @author Jason van Zyl */ -public class CLIManager -{ +public class CLIManager { public static final char ALTERNATE_POM_FILE = 'f'; public static final char BATCH_MODE = 'B'; @@ -123,81 +120,220 @@ public class CLIManager protected Options options; - @SuppressWarnings( "checkstyle:linelength" ) - public CLIManager() - { + @SuppressWarnings("checkstyle:linelength") + public CLIManager() { options = new Options(); - options.addOption( Option.builder( Character.toString( HELP ) ).longOpt( "help" ).desc( "Display help information" ).build() ); - options.addOption( Option.builder( Character.toString( ALTERNATE_POM_FILE ) ).longOpt( "file" ).hasArg().desc( "Force the use of an alternate POM file (or directory with pom.xml)" ).build() ); - options.addOption( Option.builder( Character.toString( SET_USER_PROPERTY ) ).numberOfArgs( 2 ).valueSeparator( '=' ).desc( "Define a user property" ).build() ); - options.addOption( Option.builder( Character.toString( OFFLINE ) ).longOpt( "offline" ).desc( "Work offline" ).build() ); - options.addOption( Option.builder( Character.toString( VERSION ) ).longOpt( "version" ).desc( "Display version information" ).build() ); - options.addOption( Option.builder( Character.toString( QUIET ) ).longOpt( "quiet" ).desc( "Quiet output - only show errors" ).build() ); - options.addOption( Option.builder( Character.toString( VERBOSE ) ).longOpt( "verbose" ).desc( "Produce execution verbose output" ).build() ); - options.addOption( Option.builder( Character.toString( ERRORS ) ).longOpt( "errors" ).desc( "Produce execution error messages" ).build() ); - options.addOption( Option.builder( Character.toString( NON_RECURSIVE ) ).longOpt( "non-recursive" ).desc( "Do not recurse into sub-projects. When used together with -pl, do not recurse into sub-projects of selected aggregators" ).build() ); - options.addOption( Option.builder( Character.toString( UPDATE_SNAPSHOTS ) ).longOpt( "update-snapshots" ).desc( "Forces a check for missing releases and updated snapshots on remote repositories" ).build() ); - options.addOption( Option.builder( Character.toString( ACTIVATE_PROFILES ) ).longOpt( "activate-profiles" ).desc( "Comma-delimited list of profiles to activate. Prefixing a profile with ! excludes it, and ? marks it as optional" ).hasArg().build() ); - options.addOption( Option.builder( Character.toString( BATCH_MODE ) ).longOpt( "batch-mode" ).desc( "Run in non-interactive (batch) mode (disables output color)" ).build() ); - options.addOption( Option.builder( SUPPRESS_SNAPSHOT_UPDATES ).longOpt( "no-snapshot-updates" ).desc( "Suppress SNAPSHOT updates" ).build() ); - options.addOption( Option.builder( Character.toString( CHECKSUM_FAILURE_POLICY ) ).longOpt( "strict-checksums" ).desc( "Fail the build if checksums don't match" ).build() ); - options.addOption( Option.builder( Character.toString( CHECKSUM_WARNING_POLICY ) ).longOpt( "lax-checksums" ).desc( "Warn if checksums don't match" ).build() ); - options.addOption( Option.builder( Character.toString( ALTERNATE_USER_SETTINGS ) ).longOpt( "settings" ).desc( "Alternate path for the user settings file" ).hasArg().build() ); - options.addOption( Option.builder( ALTERNATE_GLOBAL_SETTINGS ).longOpt( "global-settings" ).desc( "Alternate path for the global settings file" ).hasArg().build() ); - options.addOption( Option.builder( Character.toString( ALTERNATE_USER_TOOLCHAINS ) ).longOpt( "toolchains" ).desc( "Alternate path for the user toolchains file" ).hasArg().build() ); - options.addOption( Option.builder( ALTERNATE_GLOBAL_TOOLCHAINS ).longOpt( "global-toolchains" ).desc( "Alternate path for the global toolchains file" ).hasArg().build() ); - options.addOption( Option.builder( FAIL_ON_SEVERITY ).longOpt( "fail-on-severity" ).desc( "Configure which severity of logging should cause the build to fail" ).hasArg().build() ); - options.addOption( Option.builder( FAIL_FAST ).longOpt( "fail-fast" ).desc( "Stop at first failure in reactorized builds" ).build() ); - options.addOption( Option.builder( FAIL_AT_END ).longOpt( "fail-at-end" ).desc( "Only fail the build afterwards; allow all non-impacted builds to continue" ).build() ); - options.addOption( Option.builder( FAIL_NEVER ).longOpt( "fail-never" ).desc( "NEVER fail the build, regardless of project result" ).build() ); - options.addOption( Option.builder( RESUME ).longOpt( "resume" ).desc( "Resume reactor from the last failed project, using the resume.properties file in the build directory" ).build() ); - options.addOption( Option.builder( RESUME_FROM ).longOpt( "resume-from" ).hasArg().desc( "Resume reactor from specified project" ).build() ); - options.addOption( Option.builder( PROJECT_LIST ).longOpt( "projects" ).desc( "Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path. Prefixing a project with ! excludes it, and ? marks it as optional" ).hasArg().build() ); - options.addOption( Option.builder( ALSO_MAKE ).longOpt( "also-make" ).desc( "If project list is specified, also build projects required by the list" ).build() ); - options.addOption( Option.builder( ALSO_MAKE_DEPENDENTS ).longOpt( "also-make-dependents" ).desc( "If project list is specified, also build projects that depend on projects on the list" ).build() ); - options.addOption( Option.builder( LOG_FILE ).longOpt( "log-file" ).hasArg().desc( "Log file where all build output will go (disables output color)" ).build() ); - options.addOption( Option.builder( Character.toString( SHOW_VERSION ) ).longOpt( "show-version" ).desc( "Display version information WITHOUT stopping build" ).build() ); - options.addOption( Option.builder( ENCRYPT_MASTER_PASSWORD ).longOpt( "encrypt-master-password" ).hasArg().optionalArg( true ).desc( "Encrypt master security password" ).build() ); - options.addOption( Option.builder( ENCRYPT_PASSWORD ).longOpt( "encrypt-password" ).hasArg().optionalArg( true ).desc( "Encrypt server password" ).build() ); - options.addOption( Option.builder( THREADS ).longOpt( "threads" ).hasArg().desc( "Thread count, for instance 4 (int) or 2C/2.5C (int/float) where C is core multiplied" ).build() ); - options.addOption( Option.builder( LEGACY_LOCAL_REPOSITORY ).longOpt( "legacy-local-repository" ).desc( "Use Maven 2 Legacy Local Repository behaviour, ie no use of _remote.repositories. Can also be activated by using -Dmaven.legacyLocalRepo=true" ).build() ); - options.addOption( Option.builder( BUILDER ).longOpt( "builder" ).hasArg().desc( "The id of the build strategy to use" ).build() ); - options.addOption( Option.builder( NO_TRANSFER_PROGRESS ).longOpt( "no-transfer-progress" ).desc( "Do not display transfer progress when downloading or uploading" ).build() ); - options.addOption( Option.builder().longOpt( COLOR ).hasArg().optionalArg( true ).desc( "Defines the color mode of the output. Supported are 'auto', 'always', 'never'." ).build() ); + options.addOption(Option.builder(Character.toString(HELP)) + .longOpt("help") + .desc("Display help information") + .build()); + options.addOption(Option.builder(Character.toString(ALTERNATE_POM_FILE)) + .longOpt("file") + .hasArg() + .desc("Force the use of an alternate POM file (or directory with pom.xml)") + .build()); + options.addOption(Option.builder(Character.toString(SET_USER_PROPERTY)) + .numberOfArgs(2) + .valueSeparator('=') + .desc("Define a user property") + .build()); + options.addOption(Option.builder(Character.toString(OFFLINE)) + .longOpt("offline") + .desc("Work offline") + .build()); + options.addOption(Option.builder(Character.toString(VERSION)) + .longOpt("version") + .desc("Display version information") + .build()); + options.addOption(Option.builder(Character.toString(QUIET)) + .longOpt("quiet") + .desc("Quiet output - only show errors") + .build()); + options.addOption(Option.builder(Character.toString(VERBOSE)) + .longOpt("verbose") + .desc("Produce execution verbose output") + .build()); + options.addOption(Option.builder(Character.toString(ERRORS)) + .longOpt("errors") + .desc("Produce execution error messages") + .build()); + options.addOption(Option.builder(Character.toString(NON_RECURSIVE)) + .longOpt("non-recursive") + .desc( + "Do not recurse into sub-projects. When used together with -pl, do not recurse into sub-projects of selected aggregators") + .build()); + options.addOption(Option.builder(Character.toString(UPDATE_SNAPSHOTS)) + .longOpt("update-snapshots") + .desc("Forces a check for missing releases and updated snapshots on remote repositories") + .build()); + options.addOption(Option.builder(Character.toString(ACTIVATE_PROFILES)) + .longOpt("activate-profiles") + .desc( + "Comma-delimited list of profiles to activate. Prefixing a profile with ! excludes it, and ? marks it as optional") + .hasArg() + .build()); + options.addOption(Option.builder(Character.toString(BATCH_MODE)) + .longOpt("batch-mode") + .desc("Run in non-interactive (batch) mode (disables output color)") + .build()); + options.addOption(Option.builder(SUPPRESS_SNAPSHOT_UPDATES) + .longOpt("no-snapshot-updates") + .desc("Suppress SNAPSHOT updates") + .build()); + options.addOption(Option.builder(Character.toString(CHECKSUM_FAILURE_POLICY)) + .longOpt("strict-checksums") + .desc("Fail the build if checksums don't match") + .build()); + options.addOption(Option.builder(Character.toString(CHECKSUM_WARNING_POLICY)) + .longOpt("lax-checksums") + .desc("Warn if checksums don't match") + .build()); + options.addOption(Option.builder(Character.toString(ALTERNATE_USER_SETTINGS)) + .longOpt("settings") + .desc("Alternate path for the user settings file") + .hasArg() + .build()); + options.addOption(Option.builder(ALTERNATE_GLOBAL_SETTINGS) + .longOpt("global-settings") + .desc("Alternate path for the global settings file") + .hasArg() + .build()); + options.addOption(Option.builder(Character.toString(ALTERNATE_USER_TOOLCHAINS)) + .longOpt("toolchains") + .desc("Alternate path for the user toolchains file") + .hasArg() + .build()); + options.addOption(Option.builder(ALTERNATE_GLOBAL_TOOLCHAINS) + .longOpt("global-toolchains") + .desc("Alternate path for the global toolchains file") + .hasArg() + .build()); + options.addOption(Option.builder(FAIL_ON_SEVERITY) + .longOpt("fail-on-severity") + .desc("Configure which severity of logging should cause the build to fail") + .hasArg() + .build()); + options.addOption(Option.builder(FAIL_FAST) + .longOpt("fail-fast") + .desc("Stop at first failure in reactorized builds") + .build()); + options.addOption(Option.builder(FAIL_AT_END) + .longOpt("fail-at-end") + .desc("Only fail the build afterwards; allow all non-impacted builds to continue") + .build()); + options.addOption(Option.builder(FAIL_NEVER) + .longOpt("fail-never") + .desc("NEVER fail the build, regardless of project result") + .build()); + options.addOption(Option.builder(RESUME) + .longOpt("resume") + .desc( + "Resume reactor from the last failed project, using the resume.properties file in the build directory") + .build()); + options.addOption(Option.builder(RESUME_FROM) + .longOpt("resume-from") + .hasArg() + .desc("Resume reactor from specified project") + .build()); + options.addOption(Option.builder(PROJECT_LIST) + .longOpt("projects") + .desc( + "Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path. Prefixing a project with ! excludes it, and ? marks it as optional") + .hasArg() + .build()); + options.addOption(Option.builder(ALSO_MAKE) + .longOpt("also-make") + .desc("If project list is specified, also build projects required by the list") + .build()); + options.addOption(Option.builder(ALSO_MAKE_DEPENDENTS) + .longOpt("also-make-dependents") + .desc("If project list is specified, also build projects that depend on projects on the list") + .build()); + options.addOption(Option.builder(LOG_FILE) + .longOpt("log-file") + .hasArg() + .desc("Log file where all build output will go (disables output color)") + .build()); + options.addOption(Option.builder(Character.toString(SHOW_VERSION)) + .longOpt("show-version") + .desc("Display version information WITHOUT stopping build") + .build()); + options.addOption(Option.builder(ENCRYPT_MASTER_PASSWORD) + .longOpt("encrypt-master-password") + .hasArg() + .optionalArg(true) + .desc("Encrypt master security password") + .build()); + options.addOption(Option.builder(ENCRYPT_PASSWORD) + .longOpt("encrypt-password") + .hasArg() + .optionalArg(true) + .desc("Encrypt server password") + .build()); + options.addOption(Option.builder(THREADS) + .longOpt("threads") + .hasArg() + .desc("Thread count, for instance 4 (int) or 2C/2.5C (int/float) where C is core multiplied") + .build()); + options.addOption(Option.builder(LEGACY_LOCAL_REPOSITORY) + .longOpt("legacy-local-repository") + .desc( + "Use Maven 2 Legacy Local Repository behaviour, ie no use of _remote.repositories. Can also be activated by using -Dmaven.legacyLocalRepo=true") + .build()); + options.addOption(Option.builder(BUILDER) + .longOpt("builder") + .hasArg() + .desc("The id of the build strategy to use") + .build()); + options.addOption(Option.builder(NO_TRANSFER_PROGRESS) + .longOpt("no-transfer-progress") + .desc("Do not display transfer progress when downloading or uploading") + .build()); + options.addOption(Option.builder() + .longOpt(COLOR) + .hasArg() + .optionalArg(true) + .desc("Defines the color mode of the output. Supported are 'auto', 'always', 'never'.") + .build()); // Deprecated - options.addOption( Option.builder().longOpt( DEBUG ).desc( "Produce execution verbose output (deprecated; only kept for backward compatibility)" ).build() ); + options.addOption(Option.builder() + .longOpt(DEBUG) + .desc("Produce execution verbose output (deprecated; only kept for backward compatibility)") + .build()); } - public CommandLine parse( String[] args ) - throws ParseException - { + public CommandLine parse(String[] args) throws ParseException { // We need to eat any quotes surrounding arguments... - String[] cleanArgs = CleanArgument.cleanArgs( args ); + String[] cleanArgs = CleanArgument.cleanArgs(args); CommandLineParser parser = new DefaultParser(); - return parser.parse( options, cleanArgs ); + return parser.parse(options, cleanArgs); } - public void displayHelp( PrintStream stdout ) - { + public void displayHelp(PrintStream stdout) { stdout.println(); - PrintWriter pw = new PrintWriter( stdout ); + PrintWriter pw = new PrintWriter(stdout); HelpFormatter formatter = new HelpFormatter(); int width = MessageUtils.getTerminalWidth(); - if ( width <= 0 ) - { + if (width <= 0) { width = HelpFormatter.DEFAULT_WIDTH; } - formatter.printHelp( pw, width, "mvn [args]", - System.lineSeparator() + "Options:", options, - HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, - System.lineSeparator(), false ); + formatter.printHelp( + pw, + width, + "mvn [args]", + System.lineSeparator() + "Options:", + options, + HelpFormatter.DEFAULT_LEFT_PAD, + HelpFormatter.DEFAULT_DESC_PAD, + System.lineSeparator(), + false); pw.flush(); } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java b/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java index 4cdfbfd4d9..edc8d860cf 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.cli; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli; import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; @@ -27,7 +26,6 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Properties; - import org.apache.commons.lang3.StringUtils; import org.codehaus.plexus.util.Os; import org.slf4j.Logger; @@ -37,8 +35,7 @@ import org.slf4j.Logger; * * @author jdcasey */ -public final class CLIReportingUtils -{ +public final class CLIReportingUtils { // CHECKSTYLE_OFF: MagicNumber public static final long MB = 1024 * 1024; @@ -53,33 +50,42 @@ public final class CLIReportingUtils public static final String BUILD_VERSION_PROPERTY = "version"; - public static String showVersion() - { + public static String showVersion() { final String ls = System.lineSeparator(); Properties properties = getBuildProperties(); - StringBuilder version = new StringBuilder( 256 ); - version.append( buffer().strong( createMavenVersionString( properties ) ) ).append( ls ); - version.append( reduce( - properties.getProperty( "distributionShortName" ) + " home: " + System.getProperty( "maven.home", - "" ) ) ) - .append( ls ); - version.append( "Java version: " ).append( - System.getProperty( "java.version", "" ) ).append( ", vendor: " ).append( - System.getProperty( "java.vendor", "" ) ).append( ", runtime: " ).append( - System.getProperty( "java.home", "" ) ).append( ls ); - version.append( "Default locale: " ).append( Locale.getDefault() ).append( ", platform encoding: " ).append( - System.getProperty( "file.encoding", "" ) ).append( ls ); - version.append( "OS name: \"" ).append( Os.OS_NAME ).append( "\", version: \"" ).append( Os.OS_VERSION ).append( - "\", arch: \"" ).append( Os.OS_ARCH ).append( "\", family: \"" ).append( Os.OS_FAMILY ).append( '\"' ); + StringBuilder version = new StringBuilder(256); + version.append(buffer().strong(createMavenVersionString(properties))).append(ls); + version.append(reduce(properties.getProperty("distributionShortName") + " home: " + + System.getProperty("maven.home", ""))) + .append(ls); + version.append("Java version: ") + .append(System.getProperty("java.version", "")) + .append(", vendor: ") + .append(System.getProperty("java.vendor", "")) + .append(", runtime: ") + .append(System.getProperty("java.home", "")) + .append(ls); + version.append("Default locale: ") + .append(Locale.getDefault()) + .append(", platform encoding: ") + .append(System.getProperty("file.encoding", "")) + .append(ls); + version.append("OS name: \"") + .append(Os.OS_NAME) + .append("\", version: \"") + .append(Os.OS_VERSION) + .append("\", arch: \"") + .append(Os.OS_ARCH) + .append("\", family: \"") + .append(Os.OS_FAMILY) + .append('\"'); return version.toString(); } - public static String showVersionMinimal() - { + public static String showVersionMinimal() { Properties properties = getBuildProperties(); - String version = reduce( properties.getProperty( BUILD_VERSION_PROPERTY ) ); - return ( version != null ? version : "" ); + String version = reduce(properties.getProperty(BUILD_VERSION_PROPERTY)); + return (version != null ? version : ""); } /** @@ -88,116 +94,91 @@ public final class CLIReportingUtils * @param buildProperties The build properties * @return Readable build info */ - static String createMavenVersionString( Properties buildProperties ) - { - String timestamp = reduce( buildProperties.getProperty( "timestamp" ) ); - String version = reduce( buildProperties.getProperty( BUILD_VERSION_PROPERTY ) ); - String rev = reduce( buildProperties.getProperty( "buildNumber" ) ); - String distributionName = reduce( buildProperties.getProperty( "distributionName" ) ); + static String createMavenVersionString(Properties buildProperties) { + String timestamp = reduce(buildProperties.getProperty("timestamp")); + String version = reduce(buildProperties.getProperty(BUILD_VERSION_PROPERTY)); + String rev = reduce(buildProperties.getProperty("buildNumber")); + String distributionName = reduce(buildProperties.getProperty("distributionName")); String msg = distributionName + " "; - msg += ( version != null ? version : "" ); - if ( rev != null || timestamp != null ) - { + msg += (version != null ? version : ""); + if (rev != null || timestamp != null) { msg += " ("; - msg += ( rev != null ? rev : "" ); - if ( StringUtils.isNotBlank( timestamp ) ) - { - String ts = formatTimestamp( Long.parseLong( timestamp ) ); - msg += ( rev != null ? "; " : "" ) + ts; + msg += (rev != null ? rev : ""); + if (StringUtils.isNotBlank(timestamp)) { + String ts = formatTimestamp(Long.parseLong(timestamp)); + msg += (rev != null ? "; " : "") + ts; } msg += ")"; } return msg; } - private static String reduce( String s ) - { - return ( s != null ? ( s.startsWith( "${" ) && s.endsWith( "}" ) ? null : s ) : null ); + private static String reduce(String s) { + return (s != null ? (s.startsWith("${") && s.endsWith("}") ? null : s) : null); } - static Properties getBuildProperties() - { + static Properties getBuildProperties() { Properties properties = new Properties(); - try ( InputStream resourceAsStream = MavenCli.class.getResourceAsStream( - "/org/apache/maven/messages/build.properties" ) ) - { + try (InputStream resourceAsStream = + MavenCli.class.getResourceAsStream("/org/apache/maven/messages/build.properties")) { - if ( resourceAsStream != null ) - { - properties.load( resourceAsStream ); + if (resourceAsStream != null) { + properties.load(resourceAsStream); } - } - catch ( IOException e ) - { - System.err.println( "Unable determine version from JAR file: " + e.getMessage() ); + } catch (IOException e) { + System.err.println("Unable determine version from JAR file: " + e.getMessage()); } return properties; } - public static void showError( Logger logger, String message, Throwable e, boolean showStackTrace ) - { - if ( showStackTrace ) - { - logger.error( message, e ); - } - else - { - logger.error( message ); + public static void showError(Logger logger, String message, Throwable e, boolean showStackTrace) { + if (showStackTrace) { + logger.error(message, e); + } else { + logger.error(message); - if ( e != null ) - { - logger.error( e.getMessage() ); + if (e != null) { + logger.error(e.getMessage()); - for ( Throwable cause = e.getCause(); cause != null; cause = cause.getCause() ) - { - logger.error( "Caused by: {}", cause.getMessage() ); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + logger.error("Caused by: {}", cause.getMessage()); } } } } - public static String formatTimestamp( long timestamp ) - { - SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssXXX" ); - return sdf.format( new Date( timestamp ) ); + public static String formatTimestamp(long timestamp) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + return sdf.format(new Date(timestamp)); } - public static String formatDuration( long duration ) - { + public static String formatDuration(long duration) { // CHECKSTYLE_OFF: MagicNumber long ms = duration % 1000; - long s = ( duration / ONE_SECOND ) % 60; - long m = ( duration / ONE_MINUTE ) % 60; - long h = ( duration / ONE_HOUR ) % 24; + long s = (duration / ONE_SECOND) % 60; + long m = (duration / ONE_MINUTE) % 60; + long h = (duration / ONE_HOUR) % 24; long d = duration / ONE_DAY; // CHECKSTYLE_ON: MagicNumber String format; - if ( d > 0 ) - { + if (d > 0) { // Length 11+ chars format = "%d d %02d:%02d h"; - } - else if ( h > 0 ) - { + } else if (h > 0) { // Length 7 chars format = "%2$02d:%3$02d h"; - } - else if ( m > 0 ) - { + } else if (m > 0) { // Length 9 chars format = "%3$02d:%4$02d min"; - } - else - { + } else { // Length 7-8 chars format = "%4$d.%5$03d s"; } - return String.format( format, d, h, m, s, ms ); + return String.format(format, d, h, m, s, ms); } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CleanArgument.java b/maven-embedder/src/main/java/org/apache/maven/cli/CleanArgument.java index 08403b649d..c725faa8c5 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/CleanArgument.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CleanArgument.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.cli; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli; import java.util.ArrayList; import java.util.List; @@ -25,57 +24,46 @@ import java.util.List; /** * CleanArgument */ -public class CleanArgument -{ - public static String[] cleanArgs( String[] args ) - { +public class CleanArgument { + public static String[] cleanArgs(String[] args) { List cleaned = new ArrayList<>(); StringBuilder currentArg = null; - for ( String arg : args ) - { + for (String arg : args) { boolean addedToBuffer = false; - if ( arg.startsWith( "\"" ) ) - { + if (arg.startsWith("\"")) { // if we're in the process of building up another arg, push it and start over. // this is for the case: "-Dfoo=bar "-Dfoo2=bar two" (note the first unterminated quote) - if ( currentArg != null ) - { - cleaned.add( currentArg.toString() ); + if (currentArg != null) { + cleaned.add(currentArg.toString()); } // start building an argument here. - currentArg = new StringBuilder( arg.substring( 1 ) ); + currentArg = new StringBuilder(arg.substring(1)); addedToBuffer = true; } // this has to be a separate "if" statement, to capture the case of: "-Dfoo=bar" - if ( addedToBuffer && arg.endsWith( "\"" ) ) - { - String cleanArgPart = arg.substring( 0, arg.length() - 1 ); + if (addedToBuffer && arg.endsWith("\"")) { + String cleanArgPart = arg.substring(0, arg.length() - 1); // if we're building an argument, keep doing so. - if ( currentArg != null ) - { + if (currentArg != null) { // if this is the case of "-Dfoo=bar", then we need to adjust the buffer. - if ( addedToBuffer ) - { - currentArg.setLength( currentArg.length() - 1 ); + if (addedToBuffer) { + currentArg.setLength(currentArg.length() - 1); } // otherwise, we trim the trailing " and append to the buffer. - else - { + else { // TODO introducing a space here...not sure what else to do but collapse whitespace - currentArg.append( ' ' ).append( cleanArgPart ); + currentArg.append(' ').append(cleanArgPart); } - cleaned.add( currentArg.toString() ); - } - else - { - cleaned.add( cleanArgPart ); + cleaned.add(currentArg.toString()); + } else { + cleaned.add(cleanArgPart); } currentArg = null; @@ -87,39 +75,29 @@ public class CleanArgument // buffer, then append it with a preceding space...again, not sure what else to // do other than collapse whitespace. // NOTE: The case of a trailing quote is handled by nullifying the arg buffer. - if ( !addedToBuffer ) - { - if ( currentArg != null ) - { - currentArg.append( ' ' ).append( arg ); - } - else - { - cleaned.add( arg ); + if (!addedToBuffer) { + if (currentArg != null) { + currentArg.append(' ').append(arg); + } else { + cleaned.add(arg); } } } - if ( currentArg != null ) - { - cleaned.add( currentArg.toString() ); + if (currentArg != null) { + cleaned.add(currentArg.toString()); } int cleanedSz = cleaned.size(); String[] cleanArgs; - if ( cleanedSz == 0 ) - { + if (cleanedSz == 0) { cleanArgs = args; - } - else - { - cleanArgs = cleaned.toArray( new String[0] ); + } else { + cleanArgs = cleaned.toArray(new String[0]); } return cleanArgs; } - - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CliRequest.java b/maven-embedder/src/main/java/org/apache/maven/cli/CliRequest.java index 166d1a1ab6..9d7791f90f 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/CliRequest.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CliRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ package org.apache.maven.cli; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli; import java.io.File; import java.util.Properties; - import org.apache.commons.cli.CommandLine; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; @@ -30,8 +28,7 @@ import org.codehaus.plexus.classworlds.ClassWorld; /** * CliRequest */ -public class CliRequest -{ +public class CliRequest { String[] args; CommandLine commandLine; @@ -54,70 +51,57 @@ public class CliRequest MavenExecutionRequest request; - CliRequest( String[] args, ClassWorld classWorld ) - { + CliRequest(String[] args, ClassWorld classWorld) { this.args = args; this.classWorld = classWorld; this.request = new DefaultMavenExecutionRequest(); } - public String[] getArgs() - { + public String[] getArgs() { return args; } - public CommandLine getCommandLine() - { + public CommandLine getCommandLine() { return commandLine; } - public ClassWorld getClassWorld() - { + public ClassWorld getClassWorld() { return classWorld; } - public String getWorkingDirectory() - { + public String getWorkingDirectory() { return workingDirectory; } - public File getMultiModuleProjectDirectory() - { + public File getMultiModuleProjectDirectory() { return multiModuleProjectDirectory; } - public boolean isVerbose() - { + public boolean isVerbose() { return verbose; } - public boolean isQuiet() - { + public boolean isQuiet() { return quiet; } - public boolean isShowErrors() - { + public boolean isShowErrors() { return showErrors; } - public Properties getUserProperties() - { + public Properties getUserProperties() { return userProperties; } - public Properties getSystemProperties() - { + public Properties getSystemProperties() { return systemProperties; } - public MavenExecutionRequest getRequest() - { + public MavenExecutionRequest getRequest() { return request; } - public void setUserProperties( Properties properties ) - { - this.userProperties.putAll( properties ); + public void setUserProperties(Properties properties) { + this.userProperties.putAll(properties); } -} \ No newline at end of file +} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java index ebfb0830b8..1c1def95e0 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli; * "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 + * 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 @@ -18,8 +16,37 @@ package org.apache.maven.cli; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli; + +import static java.util.Comparator.comparing; +import static org.apache.maven.cli.CLIManager.COLOR; +import static org.apache.maven.cli.ResolveFile.resolveFile; +import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; import com.google.inject.AbstractModule; +import java.io.BufferedInputStream; +import java.io.Console; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; +import java.util.function.Consumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.ParseException; @@ -96,54 +123,24 @@ import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecUtil; import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity; -import java.io.BufferedInputStream; -import java.io.Console; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.function.Consumer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static java.util.Comparator.comparing; -import static org.apache.maven.cli.CLIManager.COLOR; -import static org.apache.maven.cli.ResolveFile.resolveFile; -import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; - // TODO push all common bits back to plexus cli and prepare for transition to Guice. We don't need 50 ways to make CLIs /** * @author Jason van Zyl */ -public class MavenCli -{ +public class MavenCli { public static final String LOCAL_REPO_PROPERTY = "maven.repo.local"; public static final String MULTIMODULE_PROJECT_DIRECTORY = "maven.multiModuleProjectDirectory"; - public static final String USER_HOME = System.getProperty( "user.home" ); + public static final String USER_HOME = System.getProperty("user.home"); - public static final File USER_MAVEN_CONFIGURATION_HOME = new File( USER_HOME, ".m2" ); + public static final File USER_MAVEN_CONFIGURATION_HOME = new File(USER_HOME, ".m2"); - public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File( USER_MAVEN_CONFIGURATION_HOME, "toolchains.xml" ); + public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File(USER_MAVEN_CONFIGURATION_HOME, "toolchains.xml"); public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE = - new File( System.getProperty( "maven.conf" ), "toolchains.xml" ); + new File(System.getProperty("maven.conf"), "toolchains.xml"); private static final String EXT_CLASS_PATH = "maven.ext.class.path"; @@ -177,41 +174,36 @@ public class MavenCli private CLIManager cliManager; - public MavenCli() - { - this( null ); + public MavenCli() { + this(null); } // This supports painless invocation by the Verifier during embedded execution of the core ITs - public MavenCli( ClassWorld classWorld ) - { + public MavenCli(ClassWorld classWorld) { this.classWorld = classWorld; } - public static void main( String[] args ) - { - int result = main( args, null ); + public static void main(String[] args) { + int result = main(args, null); - System.exit( result ); + System.exit(result); } - public static int main( String[] args, ClassWorld classWorld ) - { + public static int main(String[] args, ClassWorld classWorld) { MavenCli cli = new MavenCli(); MessageUtils.systemInstall(); MessageUtils.registerShutdownHook(); - int result = cli.doMain( new CliRequest( args, classWorld ) ); + int result = cli.doMain(new CliRequest(args, classWorld)); MessageUtils.systemUninstall(); return result; } // TODO need to externalize CliRequest - public static int doMain( String[] args, ClassWorld classWorld ) - { + public static int doMain(String[] args, ClassWorld classWorld) { MavenCli cli = new MavenCli(); - return cli.doMain( new CliRequest( args, classWorld ) ); + return cli.doMain(new CliRequest(args, classWorld)); } /** @@ -225,141 +217,103 @@ public class MavenCli * @param stderr stderr * @return return code */ - public int doMain( String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr ) - { + public int doMain(String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr) { PrintStream oldout = System.out; PrintStream olderr = System.err; final Set realms; - if ( classWorld != null ) - { + if (classWorld != null) { realms = new HashSet<>(); - for ( ClassRealm realm : classWorld.getRealms() ) - { - realms.add( realm.getId() ); + for (ClassRealm realm : classWorld.getRealms()) { + realms.add(realm.getId()); } - } - else - { + } else { realms = Collections.emptySet(); } - try - { - if ( stdout != null ) - { - System.setOut( stdout ); + try { + if (stdout != null) { + System.setOut(stdout); } - if ( stderr != null ) - { - System.setErr( stderr ); + if (stderr != null) { + System.setErr(stderr); } - CliRequest cliRequest = new CliRequest( args, classWorld ); + CliRequest cliRequest = new CliRequest(args, classWorld); cliRequest.workingDirectory = workingDirectory; - return doMain( cliRequest ); - } - finally - { - if ( classWorld != null ) - { - for ( ClassRealm realm : new ArrayList<>( classWorld.getRealms() ) ) - { + return doMain(cliRequest); + } finally { + if (classWorld != null) { + for (ClassRealm realm : new ArrayList<>(classWorld.getRealms())) { String realmId = realm.getId(); - if ( !realms.contains( realmId ) ) - { - try - { - classWorld.disposeRealm( realmId ); - } - catch ( NoSuchRealmException ignored ) - { + if (!realms.contains(realmId)) { + try { + classWorld.disposeRealm(realmId); + } catch (NoSuchRealmException ignored) { // can't happen } } } } - System.setOut( oldout ); - System.setErr( olderr ); + System.setOut(oldout); + System.setErr(olderr); } } // TODO need to externalize CliRequest - public int doMain( CliRequest cliRequest ) - { + public int doMain(CliRequest cliRequest) { PlexusContainer localContainer = null; - try - { - initialize( cliRequest ); - cli( cliRequest ); - properties( cliRequest ); - logging( cliRequest ); - informativeCommands( cliRequest ); - version( cliRequest ); - localContainer = container( cliRequest ); - commands( cliRequest ); - configure( cliRequest ); - toolchains( cliRequest ); - populateRequest( cliRequest ); - encryption( cliRequest ); - repository( cliRequest ); - return execute( cliRequest ); - } - catch ( ExitException e ) - { + try { + initialize(cliRequest); + cli(cliRequest); + properties(cliRequest); + logging(cliRequest); + informativeCommands(cliRequest); + version(cliRequest); + localContainer = container(cliRequest); + commands(cliRequest); + configure(cliRequest); + toolchains(cliRequest); + populateRequest(cliRequest); + encryption(cliRequest); + repository(cliRequest); + return execute(cliRequest); + } catch (ExitException e) { return e.exitCode; - } - catch ( UnrecognizedOptionException e ) - { + } catch (UnrecognizedOptionException e) { // pure user error, suppress stack trace return 1; - } - catch ( BuildAbort e ) - { - CLIReportingUtils.showError( slf4jLogger, "ABORTED", e, cliRequest.showErrors ); + } catch (BuildAbort e) { + CLIReportingUtils.showError(slf4jLogger, "ABORTED", e, cliRequest.showErrors); return 2; - } - catch ( Exception e ) - { - CLIReportingUtils.showError( slf4jLogger, "Error executing Maven.", e, cliRequest.showErrors ); + } catch (Exception e) { + CLIReportingUtils.showError(slf4jLogger, "Error executing Maven.", e, cliRequest.showErrors); return 1; - } - finally - { - if ( localContainer != null ) - { + } finally { + if (localContainer != null) { localContainer.dispose(); } } } - void initialize( CliRequest cliRequest ) - throws ExitException - { - if ( cliRequest.workingDirectory == null ) - { - cliRequest.workingDirectory = System.getProperty( "user.dir" ); + void initialize(CliRequest cliRequest) throws ExitException { + if (cliRequest.workingDirectory == null) { + cliRequest.workingDirectory = System.getProperty("user.dir"); } - if ( cliRequest.multiModuleProjectDirectory == null ) - { - String basedirProperty = System.getProperty( MULTIMODULE_PROJECT_DIRECTORY ); - if ( basedirProperty == null ) - { - System.err.format( - "-D%s system property is not set.", MULTIMODULE_PROJECT_DIRECTORY ); - throw new ExitException( 1 ); + if (cliRequest.multiModuleProjectDirectory == null) { + String basedirProperty = System.getProperty(MULTIMODULE_PROJECT_DIRECTORY); + if (basedirProperty == null) { + System.err.format("-D%s system property is not set.", MULTIMODULE_PROJECT_DIRECTORY); + throw new ExitException(1); } - File basedir = new File( basedirProperty ); - try - { + File basedir = new File(basedirProperty); + try { cliRequest.multiModuleProjectDirectory = basedir.getCanonicalFile(); - } - catch ( IOException e ) - { + } catch (IOException e) { cliRequest.multiModuleProjectDirectory = basedir.getAbsoluteFile(); } } @@ -368,17 +322,14 @@ public class MavenCli // Make sure the Maven home directory is an absolute path to save us from confusion with say drive-relative // Windows paths. // - String mavenHome = System.getProperty( "maven.home" ); + String mavenHome = System.getProperty("maven.home"); - if ( mavenHome != null ) - { - System.setProperty( "maven.home", new File( mavenHome ).getAbsolutePath() ); + if (mavenHome != null) { + System.setProperty("maven.home", new File(mavenHome).getAbsolutePath()); } } - void cli( CliRequest cliRequest ) - throws Exception - { + void cli(CliRequest cliRequest) throws Exception { // // Parsing errors can happen during the processing of the arguments and we prefer not having to check if // the logger is null and construct this so we can use an SLF4J logger everywhere. @@ -389,111 +340,83 @@ public class MavenCli List args = new ArrayList<>(); CommandLine mavenConfig = null; - try - { - File configFile = new File( cliRequest.multiModuleProjectDirectory, MVN_MAVEN_CONFIG ); + try { + File configFile = new File(cliRequest.multiModuleProjectDirectory, MVN_MAVEN_CONFIG); - if ( configFile.isFile() ) - { - for ( String arg : Files.readAllLines( configFile.toPath(), Charset.defaultCharset() ) ) - { - if ( !arg.isEmpty() ) - { - args.add( arg ); + if (configFile.isFile()) { + for (String arg : Files.readAllLines(configFile.toPath(), Charset.defaultCharset())) { + if (!arg.isEmpty()) { + args.add(arg); } } - mavenConfig = cliManager.parse( args.toArray( new String[0] ) ); + mavenConfig = cliManager.parse(args.toArray(new String[0])); List unrecognized = mavenConfig.getArgList(); - if ( !unrecognized.isEmpty() ) - { - throw new ParseException( "Unrecognized maven.config entries: " + unrecognized ); + if (!unrecognized.isEmpty()) { + throw new ParseException("Unrecognized maven.config entries: " + unrecognized); } } - } - catch ( ParseException e ) - { - System.err.println( "Unable to parse maven.config: " + e.getMessage() ); - cliManager.displayHelp( System.out ); + } catch (ParseException e) { + System.err.println("Unable to parse maven.config: " + e.getMessage()); + cliManager.displayHelp(System.out); throw e; } - try - { - if ( mavenConfig == null ) - { - cliRequest.commandLine = cliManager.parse( cliRequest.args ); + try { + if (mavenConfig == null) { + cliRequest.commandLine = cliManager.parse(cliRequest.args); + } else { + cliRequest.commandLine = cliMerge(cliManager.parse(cliRequest.args), mavenConfig); } - else - { - cliRequest.commandLine = cliMerge( cliManager.parse( cliRequest.args ), mavenConfig ); - } - } - catch ( ParseException e ) - { - System.err.println( "Unable to parse command line options: " + e.getMessage() ); - cliManager.displayHelp( System.out ); + } catch (ParseException e) { + System.err.println("Unable to parse command line options: " + e.getMessage()); + cliManager.displayHelp(System.out); throw e; } } - private void informativeCommands( CliRequest cliRequest ) throws ExitException - { - if ( cliRequest.commandLine.hasOption( CLIManager.HELP ) ) - { - cliManager.displayHelp( System.out ); - throw new ExitException( 0 ); + private void informativeCommands(CliRequest cliRequest) throws ExitException { + if (cliRequest.commandLine.hasOption(CLIManager.HELP)) { + cliManager.displayHelp(System.out); + throw new ExitException(0); } - if ( cliRequest.commandLine.hasOption( CLIManager.VERSION ) ) - { - if ( cliRequest.commandLine.hasOption( CLIManager.QUIET ) ) - { - System.out.println( CLIReportingUtils.showVersionMinimal() ); + if (cliRequest.commandLine.hasOption(CLIManager.VERSION)) { + if (cliRequest.commandLine.hasOption(CLIManager.QUIET)) { + System.out.println(CLIReportingUtils.showVersionMinimal()); + } else { + System.out.println(CLIReportingUtils.showVersion()); } - else - { - System.out.println( CLIReportingUtils.showVersion() ); - } - throw new ExitException( 0 ); + throw new ExitException(0); } } - private CommandLine cliMerge( CommandLine mavenArgs, CommandLine mavenConfig ) - { + private CommandLine cliMerge(CommandLine mavenArgs, CommandLine mavenConfig) { CommandLine.Builder commandLineBuilder = new CommandLine.Builder(); // the args are easy, cli first then config file - for ( String arg : mavenArgs.getArgs() ) - { - commandLineBuilder.addArg( arg ); + for (String arg : mavenArgs.getArgs()) { + commandLineBuilder.addArg(arg); } - for ( String arg : mavenConfig.getArgs() ) - { - commandLineBuilder.addArg( arg ); + for (String arg : mavenConfig.getArgs()) { + commandLineBuilder.addArg(arg); } // now add all options, except for -D with cli first then config file List // - for ( Proxy proxy : settings.getProxies() ) - { - if ( !proxy.isActive() ) - { + for (Proxy proxy : settings.getProxies()) { + if (!proxy.isActive()) { continue; } - request.addProxy( proxy ); + request.addProxy(proxy); } // @@ -222,43 +195,31 @@ public class SettingsXmlConfigurationProcessor // // - for ( Mirror mirror : settings.getMirrors() ) - { - request.addMirror( mirror ); + for (Mirror mirror : settings.getMirrors()) { + request.addMirror(mirror); } - request.setActiveProfiles( settings.getActiveProfiles() ); + request.setActiveProfiles(settings.getActiveProfiles()); - for ( Profile rawProfile : settings.getProfiles() ) - { - request.addProfile( SettingsUtils.convertFromSettingsProfile( rawProfile.getDelegate() ) ); + for (Profile rawProfile : settings.getProfiles()) { + request.addProfile(SettingsUtils.convertFromSettingsProfile(rawProfile.getDelegate())); - if ( settings.getActiveProfiles().contains( rawProfile.getId() ) ) - { + if (settings.getActiveProfiles().contains(rawProfile.getId())) { List remoteRepositories = rawProfile.getRepositories(); - for ( Repository remoteRepository : remoteRepositories ) - { - try - { - request.addRemoteRepository( - MavenRepositorySystem.buildArtifactRepository( remoteRepository ) ); - } - catch ( InvalidRepositoryException e ) - { + for (Repository remoteRepository : remoteRepositories) { + try { + request.addRemoteRepository(MavenRepositorySystem.buildArtifactRepository(remoteRepository)); + } catch (InvalidRepositoryException e) { // do nothing for now } } List pluginRepositories = rawProfile.getPluginRepositories(); - for ( Repository pluginRepository : pluginRepositories ) - { - try - { - request.addPluginArtifactRepository( MavenRepositorySystem.buildArtifactRepository( - pluginRepository ) ); - } - catch ( InvalidRepositoryException e ) - { + for (Repository pluginRepository : pluginRepositories) { + try { + request.addPluginArtifactRepository( + MavenRepositorySystem.buildArtifactRepository(pluginRepository)); + } catch (InvalidRepositoryException e) { // do nothing for now } } @@ -267,10 +228,8 @@ public class SettingsXmlConfigurationProcessor return request; } - private Object getLocation( Source source, File defaultLocation ) - { - if ( source != null ) - { + private Object getLocation(Source source, File defaultLocation) { + if (source != null) { return source.getLocation(); } return defaultLocation; diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/event/DefaultEventSpyContext.java b/maven-embedder/src/main/java/org/apache/maven/cli/event/DefaultEventSpyContext.java index 55b1155e85..c32a2d779d 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/event/DefaultEventSpyContext.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/event/DefaultEventSpyContext.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,24 +16,20 @@ package org.apache.maven.cli.event; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.event; import java.util.HashMap; import java.util.Map; - import org.apache.maven.eventspy.EventSpy; /** * DefaultEventSpyContext */ -public class DefaultEventSpyContext - implements EventSpy.Context -{ +public class DefaultEventSpyContext implements EventSpy.Context { private final Map data = new HashMap<>(); - public Map getData() - { + public Map getData() { return data; } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/event/ExecutionEventLogger.java b/maven-embedder/src/main/java/org/apache/maven/cli/event/ExecutionEventLogger.java index 66f13a0499..7f79f0587d 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/event/ExecutionEventLogger.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/event/ExecutionEventLogger.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.event; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.event; import static org.apache.maven.cli.CLIReportingUtils.formatDuration; import static org.apache.maven.cli.CLIReportingUtils.formatTimestamp; @@ -26,7 +25,6 @@ import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; import java.io.File; import java.util.List; import java.util.Objects; - import org.apache.maven.execution.AbstractExecutionListener; import org.apache.maven.execution.BuildFailure; import org.apache.maven.execution.BuildSuccess; @@ -51,8 +49,7 @@ import org.slf4j.LoggerFactory; * * @author Benjamin Bentmann */ -public class ExecutionEventLogger extends AbstractExecutionListener -{ +public class ExecutionEventLogger extends AbstractExecutionListener { private final Logger logger; private static final int MAX_LOG_PREFIX_SIZE = 8; // "[ERROR] " @@ -68,79 +65,68 @@ public class ExecutionEventLogger extends AbstractExecutionListener private int totalProjects; private volatile int currentVisitedProjectCount; - public ExecutionEventLogger() - { - this( LoggerFactory.getLogger( ExecutionEventLogger.class ) ); + public ExecutionEventLogger() { + this(LoggerFactory.getLogger(ExecutionEventLogger.class)); } - public ExecutionEventLogger( int terminalWidth ) - { - this( LoggerFactory.getLogger( ExecutionEventLogger.class ), terminalWidth ); + public ExecutionEventLogger(int terminalWidth) { + this(LoggerFactory.getLogger(ExecutionEventLogger.class), terminalWidth); } - public ExecutionEventLogger( Logger logger ) - { - this( logger, MessageUtils.getTerminalWidth() ); + public ExecutionEventLogger(Logger logger) { + this(logger, MessageUtils.getTerminalWidth()); } - public ExecutionEventLogger( Logger logger, int terminalWidth ) - { - this.logger = Objects.requireNonNull( logger, "logger cannot be null" ); - this.terminalWidth = Math.min( MAX_TERMINAL_WIDTH, - Math.max( terminalWidth < 0 ? DEFAULT_TERMINAL_WIDTH : terminalWidth, - MIN_TERMINAL_WIDTH ) ); + public ExecutionEventLogger(Logger logger, int terminalWidth) { + this.logger = Objects.requireNonNull(logger, "logger cannot be null"); + this.terminalWidth = Math.min( + MAX_TERMINAL_WIDTH, + Math.max(terminalWidth < 0 ? DEFAULT_TERMINAL_WIDTH : terminalWidth, MIN_TERMINAL_WIDTH)); this.lineLength = this.terminalWidth - MAX_LOG_PREFIX_SIZE; this.maxProjectNameLength = this.lineLength - PROJECT_STATUS_SUFFIX_SIZE; } - private static String chars( char c, int count ) - { - StringBuilder buffer = new StringBuilder( count ); + private static String chars(char c, int count) { + StringBuilder buffer = new StringBuilder(count); - for ( int i = count; i > 0; i-- ) - { - buffer.append( c ); + for (int i = count; i > 0; i--) { + buffer.append(c); } return buffer.toString(); } - private void infoLine( char c ) - { - infoMain( chars( c, lineLength ) ); + private void infoLine(char c) { + infoMain(chars(c, lineLength)); } - private void infoMain( String msg ) - { - logger.info( buffer().strong( msg ).toString() ); + private void infoMain(String msg) { + logger.info(buffer().strong(msg).toString()); } @Override - public void projectDiscoveryStarted( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { - logger.info( "Scanning for projects..." ); + public void projectDiscoveryStarted(ExecutionEvent event) { + if (logger.isInfoEnabled()) { + logger.info("Scanning for projects..."); } } @Override - public void sessionStarted( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() && event.getSession().getProjects().size() > 1 ) - { - infoLine( '-' ); + public void sessionStarted(ExecutionEvent event) { + if (logger.isInfoEnabled() && event.getSession().getProjects().size() > 1) { + infoLine('-'); - infoMain( "Reactor Build Order:" ); + infoMain("Reactor Build Order:"); - logger.info( "" ); + logger.info(""); final List projects = event.getSession().getProjects(); - for ( MavenProject project : projects ) - { - int len = lineLength - project.getName().length() - project.getPackaging().length() - 2; - logger.info( "{}{}[{}]", - project.getName(), chars( ' ', ( len > 0 ) ? len : 1 ), project.getPackaging() ); + for (MavenProject project : projects) { + int len = lineLength + - project.getName().length() + - project.getPackaging().length() + - 2; + logger.info("{}{}[{}]", project.getName(), chars(' ', (len > 0) ? len : 1), project.getPackaging()); } final List allProjects = event.getSession().getAllProjects(); @@ -152,47 +138,41 @@ public class ExecutionEventLogger extends AbstractExecutionListener } @Override - public void sessionEnded( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { - if ( event.getSession().getProjects().size() > 1 ) - { - logReactorSummary( event.getSession() ); + public void sessionEnded(ExecutionEvent event) { + if (logger.isInfoEnabled()) { + if (event.getSession().getProjects().size() > 1) { + logReactorSummary(event.getSession()); } ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); - if ( iLoggerFactory instanceof MavenSlf4jWrapperFactory ) - { + if (iLoggerFactory instanceof MavenSlf4jWrapperFactory) { MavenSlf4jWrapperFactory loggerFactory = (MavenSlf4jWrapperFactory) iLoggerFactory; - loggerFactory.getLogLevelRecorder() - .filter( LogLevelRecorder::metThreshold ) - .ifPresent( recorder -> - event.getSession().getResult().addException( new Exception( + loggerFactory + .getLogLevelRecorder() + .filter(LogLevelRecorder::metThreshold) + .ifPresent(recorder -> event.getSession() + .getResult() + .addException(new Exception( "Build failed due to log statements with a higher severity than allowed. " - + "Fix the logged issues or remove flag --fail-on-severity (-fos)." ) ) - ); + + "Fix the logged issues or remove flag --fail-on-severity (-fos)."))); } - logResult( event.getSession() ); + logResult(event.getSession()); - logStats( event.getSession() ); + logStats(event.getSession()); - infoLine( '-' ); + infoLine('-'); } } - private boolean isSingleVersionedReactor( MavenSession session ) - { + private boolean isSingleVersionedReactor(MavenSession session) { boolean result = true; MavenProject topProject = session.getTopLevelProject(); List sortedProjects = session.getProjectDependencyGraph().getSortedProjects(); - for ( MavenProject mavenProject : sortedProjects ) - { - if ( !topProject.getVersion().equals( mavenProject.getVersion() ) ) - { + for (MavenProject mavenProject : sortedProjects) { + if (!topProject.getVersion().equals(mavenProject.getVersion())) { result = false; break; } @@ -201,107 +181,89 @@ public class ExecutionEventLogger extends AbstractExecutionListener return result; } - private void logReactorSummary( MavenSession session ) - { - boolean isSingleVersion = isSingleVersionedReactor( session ); + private void logReactorSummary(MavenSession session) { + boolean isSingleVersion = isSingleVersionedReactor(session); - infoLine( '-' ); + infoLine('-'); - StringBuilder summary = new StringBuilder( "Reactor Summary" ); - if ( isSingleVersion ) - { - summary.append( " for " ); - summary.append( session.getTopLevelProject().getName() ); - summary.append( " " ); - summary.append( session.getTopLevelProject().getVersion() ); + StringBuilder summary = new StringBuilder("Reactor Summary"); + if (isSingleVersion) { + summary.append(" for "); + summary.append(session.getTopLevelProject().getName()); + summary.append(" "); + summary.append(session.getTopLevelProject().getVersion()); } - summary.append( ":" ); - infoMain( summary.toString() ); + summary.append(":"); + infoMain(summary.toString()); - logger.info( "" ); + logger.info(""); MavenExecutionResult result = session.getResult(); List projects = session.getProjects(); - for ( MavenProject project : projects ) - { - StringBuilder buffer = new StringBuilder( 128 ); + for (MavenProject project : projects) { + StringBuilder buffer = new StringBuilder(128); - buffer.append( project.getName() ); - buffer.append( ' ' ); + buffer.append(project.getName()); + buffer.append(' '); - if ( !isSingleVersion ) - { - buffer.append( project.getVersion() ); - buffer.append( ' ' ); + if (!isSingleVersion) { + buffer.append(project.getVersion()); + buffer.append(' '); } - if ( buffer.length() <= maxProjectNameLength ) - { - while ( buffer.length() < maxProjectNameLength ) - { - buffer.append( '.' ); + if (buffer.length() <= maxProjectNameLength) { + while (buffer.length() < maxProjectNameLength) { + buffer.append('.'); } - buffer.append( ' ' ); + buffer.append(' '); } - BuildSummary buildSummary = result.getBuildSummary( project ); + BuildSummary buildSummary = result.getBuildSummary(project); - if ( buildSummary == null ) - { - buffer.append( buffer().warning( "SKIPPED" ) ); - } - else if ( buildSummary instanceof BuildSuccess ) - { - buffer.append( buffer().success( "SUCCESS" ) ); - buffer.append( " [" ); - String buildTimeDuration = formatDuration( buildSummary.getTime() ); + if (buildSummary == null) { + buffer.append(buffer().warning("SKIPPED")); + } else if (buildSummary instanceof BuildSuccess) { + buffer.append(buffer().success("SUCCESS")); + buffer.append(" ["); + String buildTimeDuration = formatDuration(buildSummary.getTime()); int padSize = MAX_PADDED_BUILD_TIME_DURATION_LENGTH - buildTimeDuration.length(); - if ( padSize > 0 ) - { - buffer.append( chars( ' ', padSize ) ); + if (padSize > 0) { + buffer.append(chars(' ', padSize)); } - buffer.append( buildTimeDuration ); - buffer.append( ']' ); - } - else if ( buildSummary instanceof BuildFailure ) - { - buffer.append( buffer().failure( "FAILURE" ) ); - buffer.append( " [" ); - String buildTimeDuration = formatDuration( buildSummary.getTime() ); + buffer.append(buildTimeDuration); + buffer.append(']'); + } else if (buildSummary instanceof BuildFailure) { + buffer.append(buffer().failure("FAILURE")); + buffer.append(" ["); + String buildTimeDuration = formatDuration(buildSummary.getTime()); int padSize = MAX_PADDED_BUILD_TIME_DURATION_LENGTH - buildTimeDuration.length(); - if ( padSize > 0 ) - { - buffer.append( chars( ' ', padSize ) ); + if (padSize > 0) { + buffer.append(chars(' ', padSize)); } - buffer.append( buildTimeDuration ); - buffer.append( ']' ); + buffer.append(buildTimeDuration); + buffer.append(']'); } - logger.info( buffer.toString() ); + logger.info(buffer.toString()); } } - private void logResult( MavenSession session ) - { - infoLine( '-' ); + private void logResult(MavenSession session) { + infoLine('-'); MessageBuilder buffer = buffer(); - if ( session.getResult().hasExceptions() ) - { - buffer.failure( "BUILD FAILURE" ); + if (session.getResult().hasExceptions()) { + buffer.failure("BUILD FAILURE"); + } else { + buffer.success("BUILD SUCCESS"); } - else - { - buffer.success( "BUILD SUCCESS" ); - } - logger.info( buffer.toString() ); + logger.info(buffer.toString()); } - private void logStats( MavenSession session ) - { - infoLine( '-' ); + private void logStats(MavenSession session) { + infoLine('-'); long finish = System.currentTimeMillis(); @@ -309,34 +271,30 @@ public class ExecutionEventLogger extends AbstractExecutionListener String wallClock = session.getRequest().getDegreeOfConcurrency() > 1 ? " (Wall Clock)" : ""; - logger.info( "Total time: {}{}", formatDuration( time ), wallClock ); + logger.info("Total time: {}{}", formatDuration(time), wallClock); - logger.info( "Finished at: {}", formatTimestamp( finish ) ); + logger.info("Finished at: {}", formatTimestamp(finish)); } @Override - public void projectSkipped( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { - logger.info( "" ); - infoLine( '-' ); + public void projectSkipped(ExecutionEvent event) { + if (logger.isInfoEnabled()) { + logger.info(""); + infoLine('-'); - infoMain( "Skipping " + event.getProject().getName() ); - logger.info( "This project has been banned from the build due to previous failures." ); + infoMain("Skipping " + event.getProject().getName()); + logger.info("This project has been banned from the build due to previous failures."); - infoLine( '-' ); + infoLine('-'); } } @Override - public void projectStarted( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { + public void projectStarted(ExecutionEvent event) { + if (logger.isInfoEnabled()) { MavenProject project = event.getProject(); - logger.info( "" ); + logger.info(""); // -------< groupId:artifactId >------- String projectKey = project.getGroupId() + ':' + project.getArtifactId(); @@ -346,58 +304,54 @@ public class ExecutionEventLogger extends AbstractExecutionListener final int headerLen = preHeader.length() + projectKey.length() + postHeader.length(); - String prefix = chars( '-', Math.max( 0, ( lineLength - headerLen ) / 2 ) ) + preHeader; + String prefix = chars('-', Math.max(0, (lineLength - headerLen) / 2)) + preHeader; - String suffix = postHeader + chars( '-', - Math.max( 0, lineLength - headerLen - prefix.length() + preHeader.length() ) ); + String suffix = + postHeader + chars('-', Math.max(0, lineLength - headerLen - prefix.length() + preHeader.length())); - logger.info( buffer().strong( prefix ).project( projectKey ).strong( suffix ).toString() ); + logger.info( + buffer().strong(prefix).project(projectKey).strong(suffix).toString()); // Building Project Name Version [i/n] - String building = "Building " + event.getProject().getName() + " " + event.getProject().getVersion(); + String building = "Building " + event.getProject().getName() + " " + + event.getProject().getVersion(); - if ( totalProjects <= 1 ) - { - infoMain( building ); - } - else - { + if (totalProjects <= 1) { + infoMain(building); + } else { // display progress [i/n] int number; - synchronized ( this ) - { + synchronized (this) { number = ++currentVisitedProjectCount; } String progress = " [" + number + '/' + totalProjects + ']'; int pad = lineLength - building.length() - progress.length(); - infoMain( building + ( ( pad > 0 ) ? chars( ' ', pad ) : "" ) + progress ); + infoMain(building + ((pad > 0) ? chars(' ', pad) : "") + progress); } // path to pom.xml File currentPom = project.getFile(); - if ( currentPom != null ) - { + if (currentPom != null) { MavenSession session = event.getSession(); File rootBasedir = session.getTopLevelProject().getBasedir(); - logger.info( " from " + rootBasedir.toPath().relativize( currentPom.toPath() ) ); + logger.info(" from " + rootBasedir.toPath().relativize(currentPom.toPath())); } // ----------[ packaging ]---------- - prefix = chars( '-', Math.max( 0, ( lineLength - project.getPackaging().length() - 4 ) / 2 ) ); - suffix = chars( '-', Math.max( 0, lineLength - project.getPackaging().length() - 4 - prefix.length() ) ); - infoMain( prefix + "[ " + project.getPackaging() + " ]" + suffix ); + prefix = chars('-', Math.max(0, (lineLength - project.getPackaging().length() - 4) / 2)); + suffix = chars('-', Math.max(0, lineLength - project.getPackaging().length() - 4 - prefix.length())); + infoMain(prefix + "[ " + project.getPackaging() + " ]" + suffix); } } @Override - public void mojoSkipped( ExecutionEvent event ) - { - if ( logger.isWarnEnabled() ) - { - logger.warn( "Goal '{}' requires online mode for execution but Maven is currently offline, skipping", - event.getMojoExecution().getGoal() ); + public void mojoSkipped(ExecutionEvent event) { + if (logger.isWarnEnabled()) { + logger.warn( + "Goal '{}' requires online mode for execution but Maven is currently offline, skipping", + event.getMojoExecution().getGoal()); } } @@ -405,18 +359,16 @@ public class ExecutionEventLogger extends AbstractExecutionListener *
    --- mojo-artifactId:version:goal (mojo-executionId) @ project-artifactId ---
    */ @Override - public void mojoStarted( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { - logger.info( "" ); + public void mojoStarted(ExecutionEvent event) { + if (logger.isInfoEnabled()) { + logger.info(""); - MessageBuilder buffer = buffer().strong( "--- " ); - append( buffer, event.getMojoExecution() ); - append( buffer, event.getProject() ); - buffer.strong( " ---" ); + MessageBuilder buffer = buffer().strong("--- "); + append(buffer, event.getMojoExecution()); + append(buffer, event.getProject()); + buffer.strong(" ---"); - logger.info( buffer.toString() ); + logger.info(buffer.toString()); } } @@ -427,20 +379,18 @@ public class ExecutionEventLogger extends AbstractExecutionListener */ // CHECKSTYLE_ON: LineLength @Override - public void forkStarted( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { - logger.info( "" ); + public void forkStarted(ExecutionEvent event) { + if (logger.isInfoEnabled()) { + logger.info(""); - MessageBuilder buffer = buffer().strong( ">>> " ); - append( buffer, event.getMojoExecution() ); - buffer.strong( " > " ); - appendForkInfo( buffer, event.getMojoExecution().getMojoDescriptor() ); - append( buffer, event.getProject() ); - buffer.strong( " >>>" ); + MessageBuilder buffer = buffer().strong(">>> "); + append(buffer, event.getMojoExecution()); + buffer.strong(" > "); + appendForkInfo(buffer, event.getMojoExecution().getMojoDescriptor()); + append(buffer, event.getProject()); + buffer.strong(" >>>"); - logger.info( buffer.toString() ); + logger.info(buffer.toString()); } } @@ -451,73 +401,63 @@ public class ExecutionEventLogger extends AbstractExecutionListener */ // CHECKSTYLE_ON: LineLength @Override - public void forkSucceeded( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() ) - { - logger.info( "" ); + public void forkSucceeded(ExecutionEvent event) { + if (logger.isInfoEnabled()) { + logger.info(""); - MessageBuilder buffer = buffer().strong( "<<< " ); - append( buffer, event.getMojoExecution() ); - buffer.strong( " < " ); - appendForkInfo( buffer, event.getMojoExecution().getMojoDescriptor() ); - append( buffer, event.getProject() ); - buffer.strong( " <<<" ); + MessageBuilder buffer = buffer().strong("<<< "); + append(buffer, event.getMojoExecution()); + buffer.strong(" < "); + appendForkInfo(buffer, event.getMojoExecution().getMojoDescriptor()); + append(buffer, event.getProject()); + buffer.strong(" <<<"); - logger.info( buffer.toString() ); + logger.info(buffer.toString()); - logger.info( "" ); + logger.info(""); } } - private void append( MessageBuilder buffer, MojoExecution me ) - { - buffer.mojo( me.getArtifactId() + ':' + me.getVersion() + ':' + me.getGoal() ); - if ( me.getExecutionId() != null ) - { - buffer.a( ' ' ).strong( '(' + me.getExecutionId() + ')' ); + private void append(MessageBuilder buffer, MojoExecution me) { + buffer.mojo(me.getArtifactId() + ':' + me.getVersion() + ':' + me.getGoal()); + if (me.getExecutionId() != null) { + buffer.a(' ').strong('(' + me.getExecutionId() + ')'); } } - private void appendForkInfo( MessageBuilder buffer, MojoDescriptor md ) - { + private void appendForkInfo(MessageBuilder buffer, MojoDescriptor md) { StringBuilder buff = new StringBuilder(); - if ( StringUtils.isNotEmpty( md.getExecutePhase() ) ) - { + if (StringUtils.isNotEmpty(md.getExecutePhase())) { // forked phase - if ( StringUtils.isNotEmpty( md.getExecuteLifecycle() ) ) - { - buff.append( '[' ); - buff.append( md.getExecuteLifecycle() ); - buff.append( ']' ); + if (StringUtils.isNotEmpty(md.getExecuteLifecycle())) { + buff.append('['); + buff.append(md.getExecuteLifecycle()); + buff.append(']'); } - buff.append( md.getExecutePhase() ); - } - else - { + buff.append(md.getExecutePhase()); + } else { // forked goal - buff.append( ':' ); - buff.append( md.getExecuteGoal() ); + buff.append(':'); + buff.append(md.getExecuteGoal()); } - buffer.strong( buff.toString() ); + buffer.strong(buff.toString()); } - private void append( MessageBuilder buffer, MavenProject project ) - { - buffer.a( " @ " ).project( project.getArtifactId() ); + private void append(MessageBuilder buffer, MavenProject project) { + buffer.a(" @ ").project(project.getArtifactId()); } @Override - public void forkedProjectStarted( ExecutionEvent event ) - { - if ( logger.isInfoEnabled() && event.getMojoExecution().getForkedExecutions().size() > 1 ) - { - logger.info( "" ); - infoLine( '>' ); + public void forkedProjectStarted(ExecutionEvent event) { + if (logger.isInfoEnabled() + && event.getMojoExecution().getForkedExecutions().size() > 1) { + logger.info(""); + infoLine('>'); - infoMain( "Forking " + event.getProject().getName() + " " + event.getProject().getVersion() ); + infoMain("Forking " + event.getProject().getName() + " " + + event.getProject().getVersion()); - infoLine( '>' ); + infoLine('>'); } } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/internal/BootstrapCoreExtensionManager.java b/maven-embedder/src/main/java/org/apache/maven/cli/internal/BootstrapCoreExtensionManager.java index df5638001e..c89af87d94 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/internal/BootstrapCoreExtensionManager.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/internal/BootstrapCoreExtensionManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.internal; * "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 + * 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 @@ -18,23 +16,22 @@ package org.apache.maven.cli.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.internal; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.RepositoryUtils; +import org.apache.maven.api.model.Plugin; import org.apache.maven.cli.internal.extension.model.CoreExtension; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.extension.internal.CoreExports; import org.apache.maven.extension.internal.CoreExtensionEntry; import org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory; -import org.apache.maven.api.model.Plugin; import org.apache.maven.plugin.PluginResolutionException; import org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver; import org.codehaus.plexus.DefaultPlexusContainer; @@ -59,13 +56,12 @@ import org.slf4j.LoggerFactory; * BootstrapCoreExtensionManager */ @Named -public class BootstrapCoreExtensionManager -{ +public class BootstrapCoreExtensionManager { public static final String STRATEGY_PARENT_FIRST = "parent-first"; public static final String STRATEGY_PLUGIN = "plugin"; public static final String STRATEGY_SELF_FIRST = "self-first"; - private final Logger log = LoggerFactory.getLogger( getClass() ); + private final Logger log = LoggerFactory.getLogger(getClass()); private final DefaultPluginDependenciesResolver pluginDependenciesResolver; @@ -78,139 +74,118 @@ public class BootstrapCoreExtensionManager private final ClassRealm parentRealm; @Inject - public BootstrapCoreExtensionManager( DefaultPluginDependenciesResolver pluginDependenciesResolver, - DefaultRepositorySystemSessionFactory repositorySystemSessionFactory, - CoreExports coreExports, - PlexusContainer container ) - { + public BootstrapCoreExtensionManager( + DefaultPluginDependenciesResolver pluginDependenciesResolver, + DefaultRepositorySystemSessionFactory repositorySystemSessionFactory, + CoreExports coreExports, + PlexusContainer container) { this.pluginDependenciesResolver = pluginDependenciesResolver; this.repositorySystemSessionFactory = repositorySystemSessionFactory; this.coreExports = coreExports; - this.classWorld = ( (DefaultPlexusContainer) container ).getClassWorld(); + this.classWorld = ((DefaultPlexusContainer) container).getClassWorld(); this.parentRealm = container.getContainerRealm(); } - public List loadCoreExtensions( MavenExecutionRequest request, Set providedArtifacts, - List extensions ) - throws Exception - { - RepositorySystemSession repoSession = repositorySystemSessionFactory.newRepositorySession( request ); - List repositories = RepositoryUtils.toRepos( request.getPluginArtifactRepositories() ); - Interpolator interpolator = createInterpolator( request ); + public List loadCoreExtensions( + MavenExecutionRequest request, Set providedArtifacts, List extensions) + throws Exception { + RepositorySystemSession repoSession = repositorySystemSessionFactory.newRepositorySession(request); + List repositories = RepositoryUtils.toRepos(request.getPluginArtifactRepositories()); + Interpolator interpolator = createInterpolator(request); - return resolveCoreExtensions( repoSession, repositories, providedArtifacts, extensions, interpolator ); + return resolveCoreExtensions(repoSession, repositories, providedArtifacts, extensions, interpolator); } - private List resolveCoreExtensions( RepositorySystemSession repoSession, - List repositories, - Set providedArtifacts, - List configuration, - Interpolator interpolator ) - throws Exception - { + private List resolveCoreExtensions( + RepositorySystemSession repoSession, + List repositories, + Set providedArtifacts, + List configuration, + Interpolator interpolator) + throws Exception { List extensions = new ArrayList<>(); - DependencyFilter dependencyFilter = new ExclusionsDependencyFilter( providedArtifacts ); + DependencyFilter dependencyFilter = new ExclusionsDependencyFilter(providedArtifacts); - for ( CoreExtension extension : configuration ) - { - List artifacts = resolveExtension( extension, repoSession, repositories, - dependencyFilter, interpolator ); - if ( !artifacts.isEmpty() ) - { - extensions.add( createExtension( extension, artifacts ) ); + for (CoreExtension extension : configuration) { + List artifacts = + resolveExtension(extension, repoSession, repositories, dependencyFilter, interpolator); + if (!artifacts.isEmpty()) { + extensions.add(createExtension(extension, artifacts)); } } - return Collections.unmodifiableList( extensions ); + return Collections.unmodifiableList(extensions); } - private CoreExtensionEntry createExtension( CoreExtension extension, List artifacts ) - throws Exception - { - String realmId = - "coreExtension>" + extension.getGroupId() + ":" + extension.getArtifactId() + ":" + extension.getVersion(); - final ClassRealm realm = classWorld.newRealm( realmId, null ); + private CoreExtensionEntry createExtension(CoreExtension extension, List artifacts) throws Exception { + String realmId = "coreExtension>" + extension.getGroupId() + ":" + extension.getArtifactId() + ":" + + extension.getVersion(); + final ClassRealm realm = classWorld.newRealm(realmId, null); Set providedArtifacts = Collections.emptySet(); String classLoadingStrategy = extension.getClassLoadingStrategy(); - if ( STRATEGY_PARENT_FIRST.equals( classLoadingStrategy ) ) - { - realm.importFrom( parentRealm, "" ); - } - else if ( STRATEGY_PLUGIN.equals( classLoadingStrategy ) ) - { - coreExports.getExportedPackages().forEach( ( p, cl ) -> realm.importFrom( cl, p ) ); + if (STRATEGY_PARENT_FIRST.equals(classLoadingStrategy)) { + realm.importFrom(parentRealm, ""); + } else if (STRATEGY_PLUGIN.equals(classLoadingStrategy)) { + coreExports.getExportedPackages().forEach((p, cl) -> realm.importFrom(cl, p)); providedArtifacts = coreExports.getExportedArtifacts(); - } - else if ( STRATEGY_SELF_FIRST.equals( classLoadingStrategy ) ) - { - realm.setParentRealm( parentRealm ); - } - else - { - throw new IllegalArgumentException( "Unsupported class-loading strategy '" + } else if (STRATEGY_SELF_FIRST.equals(classLoadingStrategy)) { + realm.setParentRealm(parentRealm); + } else { + throw new IllegalArgumentException("Unsupported class-loading strategy '" + classLoadingStrategy + "'. Supported values are: " + STRATEGY_PARENT_FIRST - + ", " + STRATEGY_PLUGIN + " and " + STRATEGY_SELF_FIRST ); + + ", " + STRATEGY_PLUGIN + " and " + STRATEGY_SELF_FIRST); } - log.debug( "Populating class realm {}", realm.getId() ); - for ( Artifact artifact : artifacts ) - { + log.debug("Populating class realm {}", realm.getId()); + for (Artifact artifact : artifacts) { String id = artifact.getGroupId() + ":" + artifact.getArtifactId(); - if ( providedArtifacts.contains( id ) ) - { - log.debug( " Excluded {}", id ); - } - else - { + if (providedArtifacts.contains(id)) { + log.debug(" Excluded {}", id); + } else { File file = artifact.getFile(); - log.debug( " Included {} located at {}", id, file ); - realm.addURL( file.toURI().toURL() ); + log.debug(" Included {} located at {}", id, file); + realm.addURL(file.toURI().toURL()); } } - return CoreExtensionEntry.discoverFrom( realm, Collections.singleton( artifacts.get( 0 ).getFile() ) ); + return CoreExtensionEntry.discoverFrom( + realm, Collections.singleton(artifacts.get(0).getFile())); } - private List resolveExtension( CoreExtension extension, RepositorySystemSession repoSession, - List repositories, DependencyFilter dependencyFilter, - Interpolator interpolator ) - throws ExtensionResolutionException - { - try - { + private List resolveExtension( + CoreExtension extension, + RepositorySystemSession repoSession, + List repositories, + DependencyFilter dependencyFilter, + Interpolator interpolator) + throws ExtensionResolutionException { + try { /* TODO: Enhance the PluginDependenciesResolver to provide a * resolveCoreExtension method which uses a CoreExtension * object instead of a Plugin as this makes no sense. */ Plugin plugin = Plugin.newBuilder() - .groupId( interpolator.interpolate( extension.getGroupId() ) ) - .artifactId( interpolator.interpolate( extension.getArtifactId() ) ) - .version( interpolator.interpolate( extension.getVersion() ) ) + .groupId(interpolator.interpolate(extension.getGroupId())) + .artifactId(interpolator.interpolate(extension.getArtifactId())) + .version(interpolator.interpolate(extension.getVersion())) .build(); - DependencyNode root = pluginDependenciesResolver - .resolveCoreExtension( new org.apache.maven.model.Plugin( plugin ), - dependencyFilter, repositories, repoSession ); + DependencyNode root = pluginDependenciesResolver.resolveCoreExtension( + new org.apache.maven.model.Plugin(plugin), dependencyFilter, repositories, repoSession); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); - root.accept( nlg ); + root.accept(nlg); - return nlg.getArtifacts( false ); - } - catch ( PluginResolutionException e ) - { - throw new ExtensionResolutionException( extension, e.getCause() ); - } - catch ( InterpolationException e ) - { - throw new ExtensionResolutionException( extension, e ); + return nlg.getArtifacts(false); + } catch (PluginResolutionException e) { + throw new ExtensionResolutionException(extension, e.getCause()); + } catch (InterpolationException e) { + throw new ExtensionResolutionException(extension, e); } } - private static Interpolator createInterpolator( MavenExecutionRequest request ) - { + private static Interpolator createInterpolator(MavenExecutionRequest request) { StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( request.getUserProperties() ) ); - interpolator.addValueSource( new MapBasedValueSource( request.getSystemProperties() ) ); + interpolator.addValueSource(new MapBasedValueSource(request.getUserProperties())); + interpolator.addValueSource(new MapBasedValueSource(request.getSystemProperties())); return interpolator; } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/internal/ExtensionResolutionException.java b/maven-embedder/src/main/java/org/apache/maven/cli/internal/ExtensionResolutionException.java index 4f8cff9cb3..11f0fd8758 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/internal/ExtensionResolutionException.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/internal/ExtensionResolutionException.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.internal; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.cli.internal; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.internal; import org.apache.maven.cli.internal.extension.model.CoreExtension; @@ -26,22 +25,19 @@ import org.apache.maven.cli.internal.extension.model.CoreExtension; * * @author Brett Porter */ -public class ExtensionResolutionException - extends Exception -{ +public class ExtensionResolutionException extends Exception { private final CoreExtension extension; - public ExtensionResolutionException( CoreExtension extension, Throwable cause ) - { - super( "Extension " + extension.getId() + " or one of its dependencies could not be resolved: " - + cause.getMessage(), cause ); + public ExtensionResolutionException(CoreExtension extension, Throwable cause) { + super( + "Extension " + extension.getId() + " or one of its dependencies could not be resolved: " + + cause.getMessage(), + cause); this.extension = extension; } - public CoreExtension getExtension() - { + public CoreExtension getExtension() { return extension; } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/BaseSlf4jConfiguration.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/BaseSlf4jConfiguration.java index 33c47c2210..f7df3aaf4f 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/BaseSlf4jConfiguration.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/BaseSlf4jConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,18 +27,14 @@ import org.slf4j.LoggerFactory; * @author Hervé Boutemy * @since 3.1.0 */ -public class BaseSlf4jConfiguration - implements Slf4jConfiguration -{ - private static final Logger LOGGER = LoggerFactory.getLogger( BaseSlf4jConfiguration.class ); +public class BaseSlf4jConfiguration implements Slf4jConfiguration { + private static final Logger LOGGER = LoggerFactory.getLogger(BaseSlf4jConfiguration.class); - public void setRootLoggerLevel( Level level ) - { - LOGGER.warn( "setRootLoggerLevel: operation not supported" ); + public void setRootLoggerLevel(Level level) { + LOGGER.warn("setRootLoggerLevel: operation not supported"); } - public void activate() - { - LOGGER.warn( "reset(): operation not supported" ); + public void activate() { + LOGGER.warn("reset(): operation not supported"); } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfiguration.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfiguration.java index 8dc81c7086..091587b6f0 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfiguration.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging; /** * Interface for configuration operations on loggers, which are not available in slf4j, then require per-slf4f-binding @@ -26,14 +25,14 @@ package org.apache.maven.cli.logging; * @author Hervé Boutemy * @since 3.1.0 */ -public interface Slf4jConfiguration -{ +public interface Slf4jConfiguration { /** * Level */ - enum Level - { - DEBUG, INFO, ERROR + enum Level { + DEBUG, + INFO, + ERROR } /** @@ -41,7 +40,7 @@ public interface Slf4jConfiguration * * @param level the level */ - void setRootLoggerLevel( Level level ); + void setRootLoggerLevel(Level level); /** * Activate logging implementation configuration (if necessary). diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfigurationFactory.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfigurationFactory.java index 1a68d76f58..b539949ac8 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfigurationFactory.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfigurationFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging; import java.io.IOException; import java.net.URL; @@ -26,7 +25,6 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Set; - import org.apache.maven.cli.logging.impl.UnsupportedSlf4jBindingConfiguration; import org.codehaus.plexus.util.PropertyUtils; import org.slf4j.ILoggerFactory; @@ -39,41 +37,35 @@ import org.slf4j.ILoggerFactory; * @author Hervé Boutemy * @since 3.1.0 */ -public class Slf4jConfigurationFactory -{ +public class Slf4jConfigurationFactory { public static final String RESOURCE = "META-INF/maven/slf4j-configuration.properties"; - public static Slf4jConfiguration getConfiguration( ILoggerFactory loggerFactory ) - { + public static Slf4jConfiguration getConfiguration(ILoggerFactory loggerFactory) { Map> supported = new LinkedHashMap<>(); String slf4jBinding = loggerFactory.getClass().getCanonicalName(); - try - { - Enumeration resources = Slf4jConfigurationFactory.class.getClassLoader().getResources( RESOURCE ); + try { + Enumeration resources = + Slf4jConfigurationFactory.class.getClassLoader().getResources(RESOURCE); - while ( resources.hasMoreElements() ) - { + while (resources.hasMoreElements()) { URL resource = resources.nextElement(); - Properties conf = PropertyUtils.loadProperties( resource.openStream() ); + Properties conf = PropertyUtils.loadProperties(resource.openStream()); - String impl = conf.getProperty( slf4jBinding ); + String impl = conf.getProperty(slf4jBinding); - if ( impl != null ) - { - return (Slf4jConfiguration) Class.forName( impl ).newInstance(); + if (impl != null) { + return (Slf4jConfiguration) Class.forName(impl).newInstance(); } - supported.put( resource, conf.keySet() ); + supported.put(resource, conf.keySet()); } - } - catch ( IOException | ClassNotFoundException | IllegalAccessException | InstantiationException e ) - { + } catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); } - return new UnsupportedSlf4jBindingConfiguration( slf4jBinding, supported ); + return new UnsupportedSlf4jBindingConfiguration(slf4jBinding, supported); } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLogger.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLogger.java index 39574642d6..f3a3eb52d9 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLogger.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLogger.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging; import org.codehaus.plexus.logging.Logger; @@ -28,118 +27,94 @@ import org.codehaus.plexus.logging.Logger; * @author Jason van Zyl * @since 3.1.0 */ -public class Slf4jLogger - implements Logger -{ +public class Slf4jLogger implements Logger { private org.slf4j.Logger logger; - public Slf4jLogger( org.slf4j.Logger logger ) - { + public Slf4jLogger(org.slf4j.Logger logger) { this.logger = logger; } - public void debug( String message ) - { - logger.debug( message ); + public void debug(String message) { + logger.debug(message); } - public void debug( String message, Throwable throwable ) - { - logger.debug( message, throwable ); + public void debug(String message, Throwable throwable) { + logger.debug(message, throwable); } - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } - public void info( String message ) - { - logger.info( message ); + public void info(String message) { + logger.info(message); } - public void info( String message, Throwable throwable ) - { - logger.info( message, throwable ); + public void info(String message, Throwable throwable) { + logger.info(message, throwable); } - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return logger.isInfoEnabled(); } - public void warn( String message ) - { - logger.warn( message ); + public void warn(String message) { + logger.warn(message); } - public void warn( String message, Throwable throwable ) - { - logger.warn( message, throwable ); + public void warn(String message, Throwable throwable) { + logger.warn(message, throwable); } - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } - public void error( String message ) - { - logger.error( message ); + public void error(String message) { + logger.error(message); } - public void error( String message, Throwable throwable ) - { - logger.error( message, throwable ); + public void error(String message, Throwable throwable) { + logger.error(message, throwable); } - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return logger.isErrorEnabled(); } - public void fatalError( String message ) - { - logger.error( message ); + public void fatalError(String message) { + logger.error(message); } - public void fatalError( String message, Throwable throwable ) - { - logger.error( message, throwable ); + public void fatalError(String message, Throwable throwable) { + logger.error(message, throwable); } - public boolean isFatalErrorEnabled() - { + public boolean isFatalErrorEnabled() { return logger.isErrorEnabled(); } /** * Warning: ignored (always return 0 == Logger.LEVEL_DEBUG). */ - public int getThreshold() - { + public int getThreshold() { return 0; } /** * Warning: ignored. */ - public void setThreshold( int threshold ) - { - } + public void setThreshold(int threshold) {} /** * Warning: ignored (always return null). */ - public Logger getChildLogger( String name ) - { + public Logger getChildLogger(String name) { return null; } - public String getName() - { + public String getName() { return logger.getName(); } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLoggerManager.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLoggerManager.java index 529f19eb0f..7caa7c9ed4 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLoggerManager.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLoggerManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; @@ -32,20 +31,16 @@ import org.slf4j.LoggerFactory; * @author Jason van Zyl * @since 3.1 */ -public class Slf4jLoggerManager - implements LoggerManager -{ +public class Slf4jLoggerManager implements LoggerManager { private ILoggerFactory loggerFactory; - public Slf4jLoggerManager() - { + public Slf4jLoggerManager() { loggerFactory = LoggerFactory.getILoggerFactory(); } - public Logger getLoggerForComponent( String role ) - { - return new Slf4jLogger( loggerFactory.getLogger( role ) ); + public Logger getLoggerForComponent(String role) { + return new Slf4jLogger(loggerFactory.getLogger(role)); } /** @@ -53,11 +48,10 @@ public class Slf4jLoggerManager * Warning: this does not conform to logger name as class name convention. * (and what about null and default hint equivalence?) */ - public Logger getLoggerForComponent( String role, String hint ) - { - return ( null == hint - ? getLoggerForComponent( role ) - : new Slf4jLogger( loggerFactory.getLogger( role + '.' + hint ) ) ); + public Logger getLoggerForComponent(String role, String hint) { + return (null == hint + ? getLoggerForComponent(role) + : new Slf4jLogger(loggerFactory.getLogger(role + '.' + hint))); } // @@ -67,45 +61,34 @@ public class Slf4jLoggerManager /** * Warning: ignored. */ - public void returnComponentLogger( String role ) - { - } + public void returnComponentLogger(String role) {} /** * Warning: ignored. */ - public void returnComponentLogger( String role, String hint ) - { - } + public void returnComponentLogger(String role, String hint) {} /** * Warning: ignored (always return 0). */ - public int getThreshold() - { + public int getThreshold() { return 0; } /** * Warning: ignored. */ - public void setThreshold( int threshold ) - { - } + public void setThreshold(int threshold) {} /** * Warning: ignored. */ - public void setThresholds( int threshold ) - { - } + public void setThresholds(int threshold) {} /** * Warning: ignored (always return 0). */ - public int getActiveLoggerCount() - { + public int getActiveLoggerCount() { return 0; } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jStdoutLogger.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jStdoutLogger.java index 64b9bfdef2..6083377171 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jStdoutLogger.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jStdoutLogger.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.logging; * "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 + * 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 @@ -18,18 +16,16 @@ package org.apache.maven.cli.logging; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging; import java.io.PrintStream; - import org.slf4j.Logger; import org.slf4j.Marker; /** * @since 3.1.0 */ -public class Slf4jStdoutLogger - implements Logger -{ +public class Slf4jStdoutLogger implements Logger { private static final String ERROR = "[ERROR] "; private PrintStream out = System.out; @@ -37,270 +33,159 @@ public class Slf4jStdoutLogger // // These are the only methods we need in our primordial logger // - public void error( String msg ) - { - out.print( ERROR ); - out.println( msg ); + public void error(String msg) { + out.print(ERROR); + out.println(msg); } - public void error( String msg, Throwable t ) - { - error( msg ); + public void error(String msg, Throwable t) { + error(msg); - if ( null != t ) - { - t.printStackTrace( out ); + if (null != t) { + t.printStackTrace(out); } } // // Don't need any of this // - public String getName() - { + public String getName() { return null; } - public boolean isTraceEnabled() - { + public boolean isTraceEnabled() { return false; } - public void trace( String msg ) - { - } + public void trace(String msg) {} - public void trace( String format, Object arg ) - { - } + public void trace(String format, Object arg) {} - public void trace( String format, Object arg1, Object arg2 ) - { - } + public void trace(String format, Object arg1, Object arg2) {} - public void trace( String format, Object... arguments ) - { - } + public void trace(String format, Object... arguments) {} - public void trace( String msg, Throwable t ) - { - } + public void trace(String msg, Throwable t) {} - public boolean isTraceEnabled( Marker marker ) - { + public boolean isTraceEnabled(Marker marker) { return false; } - public void trace( Marker marker, String msg ) - { - } + public void trace(Marker marker, String msg) {} - public void trace( Marker marker, String format, Object arg ) - { - } + public void trace(Marker marker, String format, Object arg) {} - public void trace( Marker marker, String format, Object arg1, Object arg2 ) - { - } + public void trace(Marker marker, String format, Object arg1, Object arg2) {} - public void trace( Marker marker, String format, Object... argArray ) - { - } + public void trace(Marker marker, String format, Object... argArray) {} - public void trace( Marker marker, String msg, Throwable t ) - { - } + public void trace(Marker marker, String msg, Throwable t) {} - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } - public void debug( String msg ) - { - } + public void debug(String msg) {} - public void debug( String format, Object arg ) - { - } + public void debug(String format, Object arg) {} - public void debug( String format, Object arg1, Object arg2 ) - { - } + public void debug(String format, Object arg1, Object arg2) {} - public void debug( String format, Object... arguments ) - { - } + public void debug(String format, Object... arguments) {} - public void debug( String msg, Throwable t ) - { - } + public void debug(String msg, Throwable t) {} - public boolean isDebugEnabled( Marker marker ) - { + public boolean isDebugEnabled(Marker marker) { return false; } - public void debug( Marker marker, String msg ) - { - } + public void debug(Marker marker, String msg) {} - public void debug( Marker marker, String format, Object arg ) - { - } + public void debug(Marker marker, String format, Object arg) {} - public void debug( Marker marker, String format, Object arg1, Object arg2 ) - { - } + public void debug(Marker marker, String format, Object arg1, Object arg2) {} - public void debug( Marker marker, String format, Object... arguments ) - { - } + public void debug(Marker marker, String format, Object... arguments) {} - public void debug( Marker marker, String msg, Throwable t ) - { - } + public void debug(Marker marker, String msg, Throwable t) {} - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } - public void info( String msg ) - { - } + public void info(String msg) {} - public void info( String format, Object arg ) - { - } + public void info(String format, Object arg) {} - public void info( String format, Object arg1, Object arg2 ) - { - } + public void info(String format, Object arg1, Object arg2) {} - public void info( String format, Object... arguments ) - { - } + public void info(String format, Object... arguments) {} - public void info( String msg, Throwable t ) - { - } + public void info(String msg, Throwable t) {} - public boolean isInfoEnabled( Marker marker ) - { + public boolean isInfoEnabled(Marker marker) { return false; } - public void info( Marker marker, String msg ) - { - } + public void info(Marker marker, String msg) {} - public void info( Marker marker, String format, Object arg ) - { - } + public void info(Marker marker, String format, Object arg) {} - public void info( Marker marker, String format, Object arg1, Object arg2 ) - { - } + public void info(Marker marker, String format, Object arg1, Object arg2) {} - public void info( Marker marker, String format, Object... arguments ) - { - } + public void info(Marker marker, String format, Object... arguments) {} - public void info( Marker marker, String msg, Throwable t ) - { - } + public void info(Marker marker, String msg, Throwable t) {} - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } - public void warn( String msg ) - { - } + public void warn(String msg) {} - public void warn( String format, Object arg ) - { - } + public void warn(String format, Object arg) {} - public void warn( String format, Object... arguments ) - { - } + public void warn(String format, Object... arguments) {} - public void warn( String format, Object arg1, Object arg2 ) - { - } + public void warn(String format, Object arg1, Object arg2) {} - public void warn( String msg, Throwable t ) - { - } + public void warn(String msg, Throwable t) {} - public boolean isWarnEnabled( Marker marker ) - { + public boolean isWarnEnabled(Marker marker) { return false; } - public void warn( Marker marker, String msg ) - { - } + public void warn(Marker marker, String msg) {} - public void warn( Marker marker, String format, Object arg ) - { - } + public void warn(Marker marker, String format, Object arg) {} - public void warn( Marker marker, String format, Object arg1, Object arg2 ) - { - } + public void warn(Marker marker, String format, Object arg1, Object arg2) {} - public void warn( Marker marker, String format, Object... arguments ) - { - } + public void warn(Marker marker, String format, Object... arguments) {} - public void warn( Marker marker, String msg, Throwable t ) - { - } + public void warn(Marker marker, String msg, Throwable t) {} - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } - public void error( String format, Object arg ) - { - } + public void error(String format, Object arg) {} - public void error( String format, Object arg1, Object arg2 ) - { - } + public void error(String format, Object arg1, Object arg2) {} - public void error( String format, Object... arguments ) - { - } + public void error(String format, Object... arguments) {} - public boolean isErrorEnabled( Marker marker ) - { + public boolean isErrorEnabled(Marker marker) { return false; } - public void error( Marker marker, String msg ) - { - } + public void error(Marker marker, String msg) {} - public void error( Marker marker, String format, Object arg ) - { - } + public void error(Marker marker, String format, Object arg) {} - public void error( Marker marker, String format, Object arg1, Object arg2 ) - { - } + public void error(Marker marker, String format, Object arg1, Object arg2) {} - public void error( Marker marker, String format, Object... arguments ) - { - } - - public void error( Marker marker, String msg, Throwable t ) - { - } + public void error(Marker marker, String format, Object... arguments) {} + public void error(Marker marker, String msg, Throwable t) {} } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Log4j2Configuration.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Log4j2Configuration.java index b24ea9cf35..4d16d1c68d 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Log4j2Configuration.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Log4j2Configuration.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging.impl; import org.apache.maven.cli.logging.BaseSlf4jConfiguration; @@ -27,15 +26,11 @@ import org.apache.maven.cli.logging.BaseSlf4jConfiguration; * @author Hervé Boutemy * @since 3.1.0 */ -public class Log4j2Configuration - extends BaseSlf4jConfiguration -{ +public class Log4j2Configuration extends BaseSlf4jConfiguration { @Override - public void setRootLoggerLevel( Level level ) - { + public void setRootLoggerLevel(Level level) { String value; - switch ( level ) - { + switch (level) { case DEBUG: value = "debug"; break; @@ -48,12 +43,11 @@ public class Log4j2Configuration value = "error"; break; } - System.setProperty( "maven.logging.root.level", value ); + System.setProperty("maven.logging.root.level", value); } @Override - public void activate() - { + public void activate() { // no op } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/LogbackConfiguration.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/LogbackConfiguration.java index 5d9fab7442..4dc5a37b88 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/LogbackConfiguration.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/LogbackConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging.impl; import org.apache.maven.cli.logging.BaseSlf4jConfiguration; import org.slf4j.Logger; @@ -29,15 +28,11 @@ import org.slf4j.LoggerFactory; * @author Hervé Boutemy * @since 3.1.0 */ -public class LogbackConfiguration - extends BaseSlf4jConfiguration -{ +public class LogbackConfiguration extends BaseSlf4jConfiguration { @Override - public void setRootLoggerLevel( Level level ) - { + public void setRootLoggerLevel(Level level) { ch.qos.logback.classic.Level value; - switch ( level ) - { + switch (level) { case DEBUG: value = ch.qos.logback.classic.Level.DEBUG; break; @@ -50,12 +45,11 @@ public class LogbackConfiguration value = ch.qos.logback.classic.Level.ERROR; break; } - ( (ch.qos.logback.classic.Logger) LoggerFactory.getLogger( Logger.ROOT_LOGGER_NAME ) ).setLevel( value ); + ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(value); } @Override - public void activate() - { + public void activate() { // no op } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Slf4jSimpleConfiguration.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Slf4jSimpleConfiguration.java index 3961059dbe..cf79b5c8ab 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Slf4jSimpleConfiguration.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Slf4jSimpleConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.apache.maven.cli.logging.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging.impl; import org.apache.maven.cli.logging.BaseSlf4jConfiguration; import org.slf4j.MavenSlf4jFriend; @@ -29,15 +28,11 @@ import org.slf4j.impl.MavenSlf4jSimpleFriend; * @author Hervé Boutemy * @since 3.1.0 */ -public class Slf4jSimpleConfiguration - extends BaseSlf4jConfiguration -{ +public class Slf4jSimpleConfiguration extends BaseSlf4jConfiguration { @Override - public void setRootLoggerLevel( Level level ) - { + public void setRootLoggerLevel(Level level) { String value; - switch ( level ) - { + switch (level) { case DEBUG: value = "debug"; break; @@ -50,12 +45,11 @@ public class Slf4jSimpleConfiguration value = "error"; break; } - System.setProperty( "org.slf4j.simpleLogger.defaultLogLevel", value ); + System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", value); } @Override - public void activate() - { + public void activate() { // property for root logger level or System.out redirection need to be taken into account MavenSlf4jFriend.reset(); MavenSlf4jSimpleFriend.init(); diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/UnsupportedSlf4jBindingConfiguration.java b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/UnsupportedSlf4jBindingConfiguration.java index 077c674f06..d8e0a8a354 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/UnsupportedSlf4jBindingConfiguration.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/UnsupportedSlf4jBindingConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.logging.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,11 +16,11 @@ package org.apache.maven.cli.logging.impl; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.logging.impl; import java.net.URL; import java.util.Map; import java.util.Set; - import org.apache.maven.cli.logging.BaseSlf4jConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,40 +31,34 @@ import org.slf4j.LoggerFactory; * @author Hervé Boutemy * @since 3.2.4 */ -public class UnsupportedSlf4jBindingConfiguration - extends BaseSlf4jConfiguration -{ - private static final Logger LOGGER = LoggerFactory.getLogger( UnsupportedSlf4jBindingConfiguration.class ); +public class UnsupportedSlf4jBindingConfiguration extends BaseSlf4jConfiguration { + private static final Logger LOGGER = LoggerFactory.getLogger(UnsupportedSlf4jBindingConfiguration.class); private String slf4jBinding; private Map> supported; - public UnsupportedSlf4jBindingConfiguration( String slf4jBinding, Map> supported ) - { + public UnsupportedSlf4jBindingConfiguration(String slf4jBinding, Map> supported) { this.slf4jBinding = slf4jBinding; this.supported = supported; } @Override - public void activate() - { - LOGGER.warn( "The SLF4J binding actually used is not supported by Maven: {}", slf4jBinding ); - LOGGER.warn( "Maven supported bindings are:" ); + public void activate() { + LOGGER.warn("The SLF4J binding actually used is not supported by Maven: {}", slf4jBinding); + LOGGER.warn("Maven supported bindings are:"); String ls = System.lineSeparator(); - for ( Map.Entry> entry : supported.entrySet() ) - { + for (Map.Entry> entry : supported.entrySet()) { StringBuilder sb = new StringBuilder(); - sb.append( "(from " ).append( entry.getKey().toExternalForm() ).append( ')' ); + sb.append("(from ").append(entry.getKey().toExternalForm()).append(')'); - for ( Object binding : entry.getValue() ) - { - sb.append( ls ).append( "- " ).append( binding ); + for (Object binding : entry.getValue()) { + sb.append(ls).append("- ").append(binding); } - LOGGER.warn( sb.toString() ); + LOGGER.warn(sb.toString()); } } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/AbstractMavenTransferListener.java b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/AbstractMavenTransferListener.java index 72bffc338c..f20815e233 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/AbstractMavenTransferListener.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/AbstractMavenTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.transfer; * "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 + * 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 @@ -18,12 +16,12 @@ package org.apache.maven.cli.transfer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.transfer; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; - import org.apache.commons.lang3.Validate; import org.eclipse.aether.transfer.AbstractTransferListener; import org.eclipse.aether.transfer.TransferCancelledException; @@ -33,9 +31,7 @@ import org.eclipse.aether.transfer.TransferResource; /** * AbstractMavenTransferListener */ -public abstract class AbstractMavenTransferListener - extends AbstractTransferListener -{ +public abstract class AbstractMavenTransferListener extends AbstractTransferListener { // CHECKSTYLE_OFF: LineLength /** @@ -50,88 +46,68 @@ public abstract class AbstractMavenTransferListener */ // CHECKSTYLE_ON: LineLength // TODO Move me to Maven Shared Utils - static class FileSizeFormat - { - enum ScaleUnit - { - BYTE - { + static class FileSizeFormat { + enum ScaleUnit { + BYTE { @Override - public long bytes() - { + public long bytes() { return 1L; } @Override - public String symbol() - { + public String symbol() { return "B"; } }, - KILOBYTE - { + KILOBYTE { @Override - public long bytes() - { + public long bytes() { return 1000L; } @Override - public String symbol() - { + public String symbol() { return "kB"; } }, - MEGABYTE - { + MEGABYTE { @Override - public long bytes() - { + public long bytes() { return KILOBYTE.bytes() * KILOBYTE.bytes(); } @Override - public String symbol() - { + public String symbol() { return "MB"; } }, - GIGABYTE - { + GIGABYTE { @Override - public long bytes() - { + public long bytes() { return MEGABYTE.bytes() * KILOBYTE.bytes(); - }; + } + ; @Override - public String symbol() - { + public String symbol() { return "GB"; } }; public abstract long bytes(); + public abstract String symbol(); - public static ScaleUnit getScaleUnit( long size ) - { - Validate.isTrue( size >= 0L, "file size cannot be negative: %s", size ); + public static ScaleUnit getScaleUnit(long size) { + Validate.isTrue(size >= 0L, "file size cannot be negative: %s", size); - if ( size >= GIGABYTE.bytes() ) - { + if (size >= GIGABYTE.bytes()) { return GIGABYTE; - } - else if ( size >= MEGABYTE.bytes() ) - { + } else if (size >= MEGABYTE.bytes()) { return MEGABYTE; - } - else if ( size >= KILOBYTE.bytes() ) - { + } else if (size >= KILOBYTE.bytes()) { return KILOBYTE; - } - else - { + } else { return BYTE; } } @@ -140,133 +116,115 @@ public abstract class AbstractMavenTransferListener private DecimalFormat smallFormat; private DecimalFormat largeFormat; - FileSizeFormat( Locale locale ) - { - smallFormat = new DecimalFormat( "#0.0", new DecimalFormatSymbols( locale ) ); - largeFormat = new DecimalFormat( "###0", new DecimalFormatSymbols( locale ) ); + FileSizeFormat(Locale locale) { + smallFormat = new DecimalFormat("#0.0", new DecimalFormatSymbols(locale)); + largeFormat = new DecimalFormat("###0", new DecimalFormatSymbols(locale)); } - public String format( long size ) - { - return format( size, null ); + public String format(long size) { + return format(size, null); } - public String format( long size, ScaleUnit unit ) - { - return format( size, unit, false ); + public String format(long size, ScaleUnit unit) { + return format(size, unit, false); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public String format( long size, ScaleUnit unit, boolean omitSymbol ) - { - Validate.isTrue( size >= 0L, "file size cannot be negative: %s", size ); + @SuppressWarnings("checkstyle:magicnumber") + public String format(long size, ScaleUnit unit, boolean omitSymbol) { + Validate.isTrue(size >= 0L, "file size cannot be negative: %s", size); - if ( unit == null ) - { - unit = ScaleUnit.getScaleUnit( size ); + if (unit == null) { + unit = ScaleUnit.getScaleUnit(size); } double scaledSize = (double) size / unit.bytes(); String scaledSymbol = " " + unit.symbol(); - if ( omitSymbol ) - { + if (omitSymbol) { scaledSymbol = ""; } - if ( unit == ScaleUnit.BYTE ) - { - return largeFormat.format( size ) + scaledSymbol; + if (unit == ScaleUnit.BYTE) { + return largeFormat.format(size) + scaledSymbol; } - if ( scaledSize < 0.05 || scaledSize >= 10.0 ) - { - return largeFormat.format( scaledSize ) + scaledSymbol; - } - else - { - return smallFormat.format( scaledSize ) + scaledSymbol; + if (scaledSize < 0.05 || scaledSize >= 10.0) { + return largeFormat.format(scaledSize) + scaledSymbol; + } else { + return smallFormat.format(scaledSize) + scaledSymbol; } } - public String formatProgress( long progressedSize, long size ) - { - Validate.isTrue( progressedSize >= 0L, "progressed file size cannot be negative: %s", progressedSize ); - Validate.isTrue( size < 0L || progressedSize <= size, - "progressed file size cannot be greater than size: %s > %s", progressedSize, size ); + public String formatProgress(long progressedSize, long size) { + Validate.isTrue(progressedSize >= 0L, "progressed file size cannot be negative: %s", progressedSize); + Validate.isTrue( + size < 0L || progressedSize <= size, + "progressed file size cannot be greater than size: %s > %s", + progressedSize, + size); - if ( size >= 0L && progressedSize != size ) - { - ScaleUnit unit = ScaleUnit.getScaleUnit( size ); - String formattedProgressedSize = format( progressedSize, unit, true ); - String formattedSize = format( size, unit ); + if (size >= 0L && progressedSize != size) { + ScaleUnit unit = ScaleUnit.getScaleUnit(size); + String formattedProgressedSize = format(progressedSize, unit, true); + String formattedSize = format(size, unit); return formattedProgressedSize + "/" + formattedSize; - } - else - { - return format( progressedSize ); + } else { + return format(progressedSize); } } } protected PrintStream out; - protected AbstractMavenTransferListener( PrintStream out ) - { + protected AbstractMavenTransferListener(PrintStream out) { this.out = out; } @Override - public void transferInitiated( TransferEvent event ) - { + public void transferInitiated(TransferEvent event) { String action = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading"; String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from"; TransferResource resource = event.getResource(); StringBuilder message = new StringBuilder(); - message.append( action ).append( ' ' ).append( direction ).append( ' ' ).append( resource.getRepositoryId() ); - message.append( ": " ); - message.append( resource.getRepositoryUrl() ).append( resource.getResourceName() ); + message.append(action).append(' ').append(direction).append(' ').append(resource.getRepositoryId()); + message.append(": "); + message.append(resource.getRepositoryUrl()).append(resource.getResourceName()); - out.println( message.toString() ); + out.println(message.toString()); } @Override - public void transferCorrupted( TransferEvent event ) - throws TransferCancelledException - { + public void transferCorrupted(TransferEvent event) throws TransferCancelledException { TransferResource resource = event.getResource(); // TODO This needs to be colorized - out.println( "[WARNING] " + event.getException().getMessage() + " from " + resource.getRepositoryId() + " for " - + resource.getRepositoryUrl() + resource.getResourceName() ); + out.println("[WARNING] " + event.getException().getMessage() + " from " + resource.getRepositoryId() + " for " + + resource.getRepositoryUrl() + resource.getResourceName()); } @Override - public void transferSucceeded( TransferEvent event ) - { - String action = ( event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded" ); + public void transferSucceeded(TransferEvent event) { + String action = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded"); String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from"; TransferResource resource = event.getResource(); long contentLength = event.getTransferredBytes(); - FileSizeFormat format = new FileSizeFormat( Locale.ENGLISH ); + FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH); StringBuilder message = new StringBuilder(); - message.append( action ).append( ' ' ).append( direction ).append( ' ' ).append( resource.getRepositoryId() ); - message.append( ": " ); - message.append( resource.getRepositoryUrl() ).append( resource.getResourceName() ); - message.append( " (" ).append( format.format( contentLength ) ); + message.append(action).append(' ').append(direction).append(' ').append(resource.getRepositoryId()); + message.append(": "); + message.append(resource.getRepositoryUrl()).append(resource.getResourceName()); + message.append(" (").append(format.format(contentLength)); long duration = System.currentTimeMillis() - resource.getTransferStartTime(); - if ( duration > 0L ) - { - double bytesPerSecond = contentLength / ( duration / 1000.0 ); - message.append( " at " ).append( format.format( (long) bytesPerSecond ) ).append( "/s" ); + if (duration > 0L) { + double bytesPerSecond = contentLength / (duration / 1000.0); + message.append(" at ").append(format.format((long) bytesPerSecond)).append("/s"); } - message.append( ')' ); - out.println( message.toString() ); + message.append(')'); + out.println(message.toString()); } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/BatchModeMavenTransferListener.java b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/BatchModeMavenTransferListener.java index 2eee8f667a..667df5d958 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/BatchModeMavenTransferListener.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/BatchModeMavenTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.transfer; * "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 + * 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 @@ -18,18 +16,15 @@ package org.apache.maven.cli.transfer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.transfer; import java.io.PrintStream; /** * BatchModeMavenTransferListener */ -public class BatchModeMavenTransferListener - extends AbstractMavenTransferListener -{ - public BatchModeMavenTransferListener( PrintStream out ) - { - super( out ); +public class BatchModeMavenTransferListener extends AbstractMavenTransferListener { + public BatchModeMavenTransferListener(PrintStream out) { + super(out); } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/ConsoleMavenTransferListener.java b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/ConsoleMavenTransferListener.java index 950b5d0bd2..769b3fa930 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/ConsoleMavenTransferListener.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/ConsoleMavenTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.transfer; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.cli.transfer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.transfer; import java.io.PrintStream; import java.util.Collections; @@ -25,7 +24,6 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.eclipse.aether.transfer.TransferCancelledException; import org.eclipse.aether.transfer.TransferEvent; @@ -36,134 +34,113 @@ import org.eclipse.aether.transfer.TransferResource; * * @author Brett Porter */ -public class ConsoleMavenTransferListener - extends AbstractMavenTransferListener -{ +public class ConsoleMavenTransferListener extends AbstractMavenTransferListener { - private Map transfers = Collections.synchronizedMap( - new LinkedHashMap<>() ); + private Map transfers = Collections.synchronizedMap(new LinkedHashMap<>()); private boolean printResourceNames; private int lastLength; - public ConsoleMavenTransferListener( PrintStream out, boolean printResourceNames ) - { - super( out ); + public ConsoleMavenTransferListener(PrintStream out, boolean printResourceNames) { + super(out); this.printResourceNames = printResourceNames; } @Override - public synchronized void transferInitiated( TransferEvent event ) - { - overridePreviousTransfer( event ); + public synchronized void transferInitiated(TransferEvent event) { + overridePreviousTransfer(event); - super.transferInitiated( event ); + super.transferInitiated(event); } @Override - public synchronized void transferCorrupted( TransferEvent event ) - throws TransferCancelledException - { - overridePreviousTransfer( event ); + public synchronized void transferCorrupted(TransferEvent event) throws TransferCancelledException { + overridePreviousTransfer(event); - super.transferCorrupted( event ); + super.transferCorrupted(event); } @Override - public synchronized void transferProgressed( TransferEvent event ) - throws TransferCancelledException - { + public synchronized void transferProgressed(TransferEvent event) throws TransferCancelledException { TransferResource resource = event.getResource(); - transfers.put( resource, event.getTransferredBytes() ); + transfers.put(resource, event.getTransferredBytes()); - StringBuilder buffer = new StringBuilder( 128 ); - buffer.append( "Progress (" ).append( transfers.size() ).append( "): " ); + StringBuilder buffer = new StringBuilder(128); + buffer.append("Progress (").append(transfers.size()).append("): "); - synchronized ( transfers ) - { - Iterator> entries = transfers.entrySet().iterator(); - while ( entries.hasNext() ) - { + synchronized (transfers) { + Iterator> entries = + transfers.entrySet().iterator(); + while (entries.hasNext()) { Map.Entry entry = entries.next(); long total = entry.getKey().getContentLength(); Long complete = entry.getValue(); - buffer.append( getStatus( entry.getKey().getResourceName(), complete, total ) ); - if ( entries.hasNext() ) - { - buffer.append( " | " ); + buffer.append(getStatus(entry.getKey().getResourceName(), complete, total)); + if (entries.hasNext()) { + buffer.append(" | "); } } } int pad = lastLength - buffer.length(); lastLength = buffer.length(); - pad( buffer, pad ); - buffer.append( '\r' ); - out.print( buffer ); + pad(buffer, pad); + buffer.append('\r'); + out.print(buffer); out.flush(); } - private String getStatus( String resourceName, long complete, long total ) - { - FileSizeFormat format = new FileSizeFormat( Locale.ENGLISH ); + private String getStatus(String resourceName, long complete, long total) { + FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH); StringBuilder status = new StringBuilder(); - if ( printResourceNames ) - { - status.append( StringUtils.substringAfterLast( resourceName, "/" ) ); - status.append( " (" ); + if (printResourceNames) { + status.append(StringUtils.substringAfterLast(resourceName, "/")); + status.append(" ("); } - status.append( format.formatProgress( complete, total ) ); + status.append(format.formatProgress(complete, total)); - if ( printResourceNames ) - { - status.append( ")" ); + if (printResourceNames) { + status.append(")"); } return status.toString(); } - private void pad( StringBuilder buffer, int spaces ) - { + private void pad(StringBuilder buffer, int spaces) { String block = " "; - while ( spaces > 0 ) - { - int n = Math.min( spaces, block.length() ); - buffer.append( block, 0, n ); + while (spaces > 0) { + int n = Math.min(spaces, block.length()); + buffer.append(block, 0, n); spaces -= n; } } @Override - public synchronized void transferSucceeded( TransferEvent event ) - { - transfers.remove( event.getResource() ); - overridePreviousTransfer( event ); + public synchronized void transferSucceeded(TransferEvent event) { + transfers.remove(event.getResource()); + overridePreviousTransfer(event); - super.transferSucceeded( event ); + super.transferSucceeded(event); } @Override - public synchronized void transferFailed( TransferEvent event ) - { - transfers.remove( event.getResource() ); - overridePreviousTransfer( event ); + public synchronized void transferFailed(TransferEvent event) { + transfers.remove(event.getResource()); + overridePreviousTransfer(event); - super.transferFailed( event ); + super.transferFailed(event); } - private void overridePreviousTransfer( TransferEvent event ) - { - if ( lastLength > 0 ) - { - StringBuilder buffer = new StringBuilder( 128 ); - pad( buffer, lastLength ); - buffer.append( '\r' ); - out.print( buffer ); + private void overridePreviousTransfer(TransferEvent event) { + if (lastLength > 0) { + StringBuilder buffer = new StringBuilder(128); + pad(buffer, lastLength); + buffer.append('\r'); + out.print(buffer); out.flush(); lastLength = 0; } } - } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/QuietMavenTransferListener.java b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/QuietMavenTransferListener.java index fd9f52cf51..21cc466361 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/QuietMavenTransferListener.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/QuietMavenTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.transfer; * "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 + * 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 @@ -18,14 +16,11 @@ package org.apache.maven.cli.transfer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.transfer; import org.eclipse.aether.transfer.AbstractTransferListener; /** * @author Benjamin Bentmann */ -public class QuietMavenTransferListener - extends AbstractTransferListener -{ - -} +public class QuietMavenTransferListener extends AbstractTransferListener {} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/Slf4jMavenTransferListener.java b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/Slf4jMavenTransferListener.java index 57e69ba14d..1c528a9353 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/transfer/Slf4jMavenTransferListener.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/transfer/Slf4jMavenTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli.transfer; * "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 + * 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 @@ -18,9 +16,9 @@ package org.apache.maven.cli.transfer; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli.transfer; import java.util.Locale; - import org.apache.maven.cli.transfer.AbstractMavenTransferListener.FileSizeFormat; import org.eclipse.aether.transfer.AbstractTransferListener; import org.eclipse.aether.transfer.TransferCancelledException; @@ -32,72 +30,66 @@ import org.slf4j.LoggerFactory; /** * Slf4jMavenTransferListener */ -public class Slf4jMavenTransferListener - extends AbstractTransferListener -{ +public class Slf4jMavenTransferListener extends AbstractTransferListener { protected final Logger out; - public Slf4jMavenTransferListener() - { - this.out = LoggerFactory.getLogger( Slf4jMavenTransferListener.class ); + public Slf4jMavenTransferListener() { + this.out = LoggerFactory.getLogger(Slf4jMavenTransferListener.class); } // TODO should we deprecate? - public Slf4jMavenTransferListener( Logger out ) - { + public Slf4jMavenTransferListener(Logger out) { this.out = out; } @Override - public void transferInitiated( TransferEvent event ) - { + public void transferInitiated(TransferEvent event) { String action = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading"; String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from"; TransferResource resource = event.getResource(); StringBuilder message = new StringBuilder(); - message.append( action ).append( ' ' ).append( direction ).append( ' ' ).append( resource.getRepositoryId() ); - message.append( ": " ); - message.append( resource.getRepositoryUrl() ).append( resource.getResourceName() ); + message.append(action).append(' ').append(direction).append(' ').append(resource.getRepositoryId()); + message.append(": "); + message.append(resource.getRepositoryUrl()).append(resource.getResourceName()); - out.info( message.toString() ); + out.info(message.toString()); } @Override - public void transferCorrupted( TransferEvent event ) - throws TransferCancelledException - { + public void transferCorrupted(TransferEvent event) throws TransferCancelledException { TransferResource resource = event.getResource(); - out.warn( "{} from {} for {}{}", event.getException().getMessage(), resource.getRepositoryId(), - resource.getRepositoryUrl(), resource.getResourceName() ); + out.warn( + "{} from {} for {}{}", + event.getException().getMessage(), + resource.getRepositoryId(), + resource.getRepositoryUrl(), + resource.getResourceName()); } @Override - public void transferSucceeded( TransferEvent event ) - { - String action = ( event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded" ); + public void transferSucceeded(TransferEvent event) { + String action = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded"); String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from"; TransferResource resource = event.getResource(); long contentLength = event.getTransferredBytes(); - FileSizeFormat format = new FileSizeFormat( Locale.ENGLISH ); + FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH); StringBuilder message = new StringBuilder(); - message.append( action ).append( ' ' ).append( direction ).append( ' ' ).append( resource.getRepositoryId() ); - message.append( ": " ); - message.append( resource.getRepositoryUrl() ).append( resource.getResourceName() ); - message.append( " (" ).append( format.format( contentLength ) ); + message.append(action).append(' ').append(direction).append(' ').append(resource.getRepositoryId()); + message.append(": "); + message.append(resource.getRepositoryUrl()).append(resource.getResourceName()); + message.append(" (").append(format.format(contentLength)); long duration = System.currentTimeMillis() - resource.getTransferStartTime(); - if ( duration > 0L ) - { - double bytesPerSecond = contentLength / ( duration / 1000.0 ); - message.append( " at " ).append( format.format( (long) bytesPerSecond ) ).append( "/s" ); + if (duration > 0L) { + double bytesPerSecond = contentLength / (duration / 1000.0); + message.append(" at ").append(format.format((long) bytesPerSecond)).append("/s"); } - message.append( ')' ); - out.info( message.toString() ); + message.append(')'); + out.info(message.toString()); } - } diff --git a/maven-embedder/src/main/java/org/eclipse/sisu/plexus/PlexusXmlBeanConverter.java b/maven-embedder/src/main/java/org/eclipse/sisu/plexus/PlexusXmlBeanConverter.java index e10551ae93..db8c757e03 100644 --- a/maven-embedder/src/main/java/org/eclipse/sisu/plexus/PlexusXmlBeanConverter.java +++ b/maven-embedder/src/main/java/org/eclipse/sisu/plexus/PlexusXmlBeanConverter.java @@ -1,5 +1,3 @@ -package org.eclipse.sisu.plexus; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.eclipse.sisu.plexus; * "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 + * 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 @@ -18,11 +16,14 @@ package org.eclipse.sisu.plexus; * specific language governing permissions and limitations * under the License. */ +package org.eclipse.sisu.plexus; -import javax.annotation.Priority; -import javax.inject.Inject; -import javax.inject.Singleton; - +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Module; +import com.google.inject.TypeLiteral; +import com.google.inject.spi.TypeConverter; +import com.google.inject.spi.TypeConverterBinding; import java.io.StringReader; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; @@ -31,13 +32,9 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Properties; - -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; -import com.google.inject.spi.TypeConverter; -import com.google.inject.spi.TypeConverterBinding; +import javax.annotation.Priority; +import javax.inject.Inject; +import javax.inject.Singleton; import org.apache.maven.api.xml.Dom; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; @@ -53,10 +50,8 @@ import org.eclipse.sisu.inject.TypeArguments; * {@link PlexusBeanConverter} {@link Module} that converts Plexus XML configuration into beans. */ @Singleton -@Priority( 10 ) -public final class PlexusXmlBeanConverter - implements PlexusBeanConverter -{ +@Priority(10) +public final class PlexusXmlBeanConverter implements PlexusBeanConverter { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- @@ -74,8 +69,7 @@ public final class PlexusXmlBeanConverter // ---------------------------------------------------------------------- @Inject - PlexusXmlBeanConverter( final Injector injector ) - { + PlexusXmlBeanConverter(final Injector injector) { typeConverterBindings = injector.getTypeConverterBindings(); } @@ -83,26 +77,21 @@ public final class PlexusXmlBeanConverter // Public methods // ---------------------------------------------------------------------- - @SuppressWarnings( { "unchecked", "rawtypes" } ) - public Object convert( final TypeLiteral role, final String value ) - { - if ( value.trim().startsWith( "<" ) ) - { - try - { + @SuppressWarnings({"unchecked", "rawtypes"}) + public Object convert(final TypeLiteral role, final String value) { + if (value.trim().startsWith("<")) { + try { final MXParser parser = new MXParser(); - parser.setInput( new StringReader( value ) ); + parser.setInput(new StringReader(value)); parser.nextTag(); - return parse( parser, role ); - } - catch ( final Exception e ) - { - throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, role ), e ); + return parse(parser, role); + } catch (final Exception e) { + throw new IllegalArgumentException(String.format(CONVERSION_ERROR, value, role), e); } } - return convertText( value, role ); + return convertText(value, role); } // ---------------------------------------------------------------------- @@ -111,81 +100,65 @@ public final class PlexusXmlBeanConverter /** * Parses a sequence of XML elements and converts them to the given target type. - * + * * @param parser The XML parser * @param toType The target type * @return Converted instance of the target type */ - private Object parse( final MXParser parser, final TypeLiteral toType ) - throws Exception - { - parser.require( XmlPullParser.START_TAG, null, null ); + private Object parse(final MXParser parser, final TypeLiteral toType) throws Exception { + parser.require(XmlPullParser.START_TAG, null, null); final Class rawType = toType.getRawType(); - if ( Dom.class.isAssignableFrom( rawType ) ) - { - return org.apache.maven.internal.xml.Xpp3DomBuilder.build( parser ); + if (Dom.class.isAssignableFrom(rawType)) { + return org.apache.maven.internal.xml.Xpp3DomBuilder.build(parser); } - if ( Xpp3Dom.class.isAssignableFrom( rawType ) ) - { - return parseXpp3Dom( parser ); + if (Xpp3Dom.class.isAssignableFrom(rawType)) { + return parseXpp3Dom(parser); } - if ( Properties.class.isAssignableFrom( rawType ) ) - { - return parseProperties( parser ); + if (Properties.class.isAssignableFrom(rawType)) { + return parseProperties(parser); } - if ( Map.class.isAssignableFrom( rawType ) ) - { - return parseMap( parser, TypeArguments.get( toType.getSupertype( Map.class ), 1 ) ); + if (Map.class.isAssignableFrom(rawType)) { + return parseMap(parser, TypeArguments.get(toType.getSupertype(Map.class), 1)); } - if ( Collection.class.isAssignableFrom( rawType ) ) - { - return parseCollection( parser, TypeArguments.get( toType.getSupertype( Collection.class ), 0 ) ); + if (Collection.class.isAssignableFrom(rawType)) { + return parseCollection(parser, TypeArguments.get(toType.getSupertype(Collection.class), 0)); } - if ( rawType.isArray() ) - { - return parseArray( parser, TypeArguments.get( toType, 0 ) ); + if (rawType.isArray()) { + return parseArray(parser, TypeArguments.get(toType, 0)); } - return parseBean( parser, toType, rawType ); + return parseBean(parser, toType, rawType); } /** * Parses an XML subtree and converts it to the {@link Xpp3Dom} type. - * + * * @param parser The XML parser * @return Converted Xpp3Dom instance */ - private static Xpp3Dom parseXpp3Dom( final XmlPullParser parser ) - throws Exception - { - return Xpp3DomBuilder.build( parser ); + private static Xpp3Dom parseXpp3Dom(final XmlPullParser parser) throws Exception { + return Xpp3DomBuilder.build(parser); } /** * Parses a sequence of XML elements and converts them to the appropriate {@link Properties} type. - * + * * @param parser The XML parser * @return Converted Properties instance */ - private static Properties parseProperties( final XmlPullParser parser ) - throws Exception - { - final Properties properties = newImplementation( parser, Properties.class ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + private static Properties parseProperties(final XmlPullParser parser) throws Exception { + final Properties properties = newImplementation(parser, Properties.class); + while (parser.nextTag() == XmlPullParser.START_TAG) { parser.nextTag(); // 'name-then-value' or 'value-then-name' - if ( "name".equals( parser.getName() ) ) - { + if ("name".equals(parser.getName())) { final String name = parser.nextText(); parser.nextTag(); - properties.put( name, parser.nextText() ); - } - else - { + properties.put(name, parser.nextText()); + } else { final String value = parser.nextText(); parser.nextTag(); - properties.put( parser.nextText(), value ); + properties.put(parser.nextText(), value); } parser.nextTag(); } @@ -194,57 +167,48 @@ public final class PlexusXmlBeanConverter /** * Parses a sequence of XML elements and converts them to the appropriate {@link Map} type. - * + * * @param parser The XML parser * @return Converted Map instance */ - private Map parseMap( final MXParser parser, final TypeLiteral toType ) - throws Exception - { - @SuppressWarnings( "unchecked" ) - final Map map = newImplementation( parser, HashMap.class ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - map.put( parser.getName(), parse( parser, toType ) ); + private Map parseMap(final MXParser parser, final TypeLiteral toType) throws Exception { + @SuppressWarnings("unchecked") + final Map map = newImplementation(parser, HashMap.class); + while (parser.nextTag() == XmlPullParser.START_TAG) { + map.put(parser.getName(), parse(parser, toType)); } return map; } /** * Parses a sequence of XML elements and converts them to the appropriate {@link Collection} type. - * + * * @param parser The XML parser * @return Converted Collection instance */ - private Collection parseCollection( final MXParser parser, final TypeLiteral toType ) - throws Exception - { - @SuppressWarnings( "unchecked" ) - final Collection collection = newImplementation( parser, ArrayList.class ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - collection.add( parse( parser, toType ) ); + private Collection parseCollection(final MXParser parser, final TypeLiteral toType) throws Exception { + @SuppressWarnings("unchecked") + final Collection collection = newImplementation(parser, ArrayList.class); + while (parser.nextTag() == XmlPullParser.START_TAG) { + collection.add(parse(parser, toType)); } return collection; } /** * Parses a sequence of XML elements and converts them to the appropriate array type. - * + * * @param parser The XML parser * @return Converted array instance */ - private Object parseArray( final MXParser parser, final TypeLiteral toType ) - throws Exception - { + private Object parseArray(final MXParser parser, final TypeLiteral toType) throws Exception { // convert to a collection first then convert that into an array - final Collection collection = parseCollection( parser, toType ); - final Object array = Array.newInstance( toType.getRawType(), collection.size() ); + final Collection collection = parseCollection(parser, toType); + final Object array = Array.newInstance(toType.getRawType(), collection.size()); int i = 0; - for ( final Object element : collection ) - { - Array.set( array, i++, element ); + for (final Object element : collection) { + Array.set(array, i++, element); } return array; @@ -252,65 +216,54 @@ public final class PlexusXmlBeanConverter /** * Parses a sequence of XML elements and converts them to the appropriate bean type. - * + * * @param parser The XML parser * @return Converted bean instance */ - private Object parseBean( final MXParser parser, final TypeLiteral toType, final Class rawType ) - throws Exception - { - final Class clazz = loadImplementation( parseImplementation( parser ), rawType ); + private Object parseBean(final MXParser parser, final TypeLiteral toType, final Class rawType) + throws Exception { + final Class clazz = loadImplementation(parseImplementation(parser), rawType); // simple bean? assumes string constructor - if ( parser.next() == XmlPullParser.TEXT ) - { + if (parser.next() == XmlPullParser.TEXT) { final String text = parser.getText(); // confirm element doesn't contain nested XML - if ( parser.next() != XmlPullParser.START_TAG ) - { - return convertText( text, clazz == rawType ? toType : TypeLiteral.get( clazz ) ); + if (parser.next() != XmlPullParser.START_TAG) { + return convertText(text, clazz == rawType ? toType : TypeLiteral.get(clazz)); } } - if ( String.class == clazz ) - { + if (String.class == clazz) { // mimic plexus: discard any strings containing nested XML - while ( parser.getEventType() == XmlPullParser.START_TAG ) - { + while (parser.getEventType() == XmlPullParser.START_TAG) { final String pos = parser.getPositionDescription(); - Logs.warn( "Expected TEXT, not XML: {}", pos, new Throwable() ); + Logs.warn("Expected TEXT, not XML: {}", pos, new Throwable()); parser.skipSubTree(); parser.nextTag(); } return ""; } - final Object bean = newImplementation( clazz ); + final Object bean = newImplementation(clazz); // build map of all known bean properties belonging to the chosen implementation final Map> propertyMap = new HashMap>(); - for ( final BeanProperty property : new BeanProperties( clazz ) ) - { + for (final BeanProperty property : new BeanProperties(clazz)) { final String name = property.getName(); - if ( !propertyMap.containsKey( name ) ) - { - propertyMap.put( name, property ); + if (!propertyMap.containsKey(name)) { + propertyMap.put(name, property); } } - while ( parser.getEventType() == XmlPullParser.START_TAG ) - { + while (parser.getEventType() == XmlPullParser.START_TAG) { // update properties inside the bean, guided by the cached property map - final BeanProperty property = propertyMap.get( Roles.camelizeName( parser.getName() ) ); - if ( property != null ) - { - property.set( bean, parse( parser, property.getType() ) ); + final BeanProperty property = propertyMap.get(Roles.camelizeName(parser.getName())); + if (property != null) { + property.set(bean, parse(parser, property.getType())); parser.nextTag(); - } - else - { - throw new XmlPullParserException( "Unknown bean property: " + parser.getName(), parser, null ); + } else { + throw new XmlPullParserException("Unknown bean property: " + parser.getName(), parser, null); } } @@ -319,168 +272,132 @@ public final class PlexusXmlBeanConverter /** * Parses an XML element looking for the name of a custom implementation. - * + * * @param parser The XML parser * @return Name of the custom implementation; otherwise {@code null} */ - private static String parseImplementation( final XmlPullParser parser ) - { - return parser.getAttributeValue( null, "implementation" ); + private static String parseImplementation(final XmlPullParser parser) { + return parser.getAttributeValue(null, "implementation"); } /** * Attempts to load the named implementation, uses default implementation if no name is given. - * + * * @param name The optional implementation name * @param defaultClazz The default implementation type * @return Custom implementation type if one was given; otherwise default implementation type */ - private static Class loadImplementation( final String name, final Class defaultClazz ) - { - if ( null == name ) - { + private static Class loadImplementation(final String name, final Class defaultClazz) { + if (null == name) { return defaultClazz; // just use the default type } // TCCL allows surrounding container to influence class loading policy final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if ( tccl != null ) - { - try - { - return tccl.loadClass( name ); - } - catch ( final Exception e ) - { + if (tccl != null) { + try { + return tccl.loadClass(name); + } catch (final Exception e) { // drop through... - } - catch ( final LinkageError e ) - { + } catch (final LinkageError e) { // drop through... } } // assume custom type is in same class space as default final ClassLoader peer = defaultClazz.getClassLoader(); - if ( peer != null ) - { - try - { - return peer.loadClass( name ); - } - catch ( final Exception e ) - { + if (peer != null) { + try { + return peer.loadClass(name); + } catch (final Exception e) { // drop through... - } - catch ( final LinkageError e ) - { + } catch (final LinkageError e) { // drop through... } } - try - { + try { // last chance - classic model - return Class.forName( name ); - } - catch ( final Exception e ) - { - throw new TypeNotPresentException( name, e ); - } - catch ( final LinkageError e ) - { - throw new TypeNotPresentException( name, e ); + return Class.forName(name); + } catch (final Exception e) { + throw new TypeNotPresentException(name, e); + } catch (final LinkageError e) { + throw new TypeNotPresentException(name, e); } } /** * Creates an instance of the given implementation using the default constructor. - * + * * @param clazz The implementation type * @return Instance of given implementation */ - private static T newImplementation( final Class clazz ) - { - try - { + private static T newImplementation(final Class clazz) { + try { return clazz.newInstance(); - } - catch ( final Exception e ) - { - throw new IllegalArgumentException( "Cannot create instance of: " + clazz, e ); - } - catch ( final LinkageError e ) - { - throw new IllegalArgumentException( "Cannot create instance of: " + clazz, e ); + } catch (final Exception e) { + throw new IllegalArgumentException("Cannot create instance of: " + clazz, e); + } catch (final LinkageError e) { + throw new IllegalArgumentException("Cannot create instance of: " + clazz, e); } } /** * Creates an instance of the given implementation using the given string, assumes a public string constructor. - * + * * @param clazz The implementation type * @param value The string argument * @return Instance of given implementation, constructed using the the given string */ - private static T newImplementation( final Class clazz, final String value ) - { - try - { - return clazz.getConstructor( String.class ).newInstance( value ); - } - catch ( final Exception e ) - { + private static T newImplementation(final Class clazz, final String value) { + try { + return clazz.getConstructor(String.class).newInstance(value); + } catch (final Exception e) { final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e; - throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, clazz ), cause ); - } - catch ( final LinkageError e ) - { - throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, clazz ), e ); + throw new IllegalArgumentException(String.format(CONVERSION_ERROR, value, clazz), cause); + } catch (final LinkageError e) { + throw new IllegalArgumentException(String.format(CONVERSION_ERROR, value, clazz), e); } } /** * Creates an instance of the implementation named in the current XML element, or the default if no name is given. - * + * * @param parser The XML parser * @param defaultClazz The default implementation type * @return Instance of custom implementation if one was given; otherwise instance of default type */ - @SuppressWarnings( "unchecked" ) - private static T newImplementation( final XmlPullParser parser, final Class defaultClazz ) - { - return (T) newImplementation( loadImplementation( parseImplementation( parser ), defaultClazz ) ); + @SuppressWarnings("unchecked") + private static T newImplementation(final XmlPullParser parser, final Class defaultClazz) { + return (T) newImplementation(loadImplementation(parseImplementation(parser), defaultClazz)); } /** * Converts the given string to the target type, using {@link TypeConverter}s registered with the {@link Injector}. - * + * * @param value The string value * @param toType The target type * @return Converted instance of the target type */ - private Object convertText( final String value, final TypeLiteral toType ) - { + private Object convertText(final String value, final TypeLiteral toType) { final String text = value.trim(); final Class rawType = toType.getRawType(); - if ( rawType.isAssignableFrom( String.class ) ) - { + if (rawType.isAssignableFrom(String.class)) { return text; // compatible type => no conversion needed } // use temporary Key as quick way to auto-box primitive types into their equivalent object types - final TypeLiteral boxedType = rawType.isPrimitive() ? Key.get( rawType ).getTypeLiteral() : toType; + final TypeLiteral boxedType = + rawType.isPrimitive() ? Key.get(rawType).getTypeLiteral() : toType; - for ( final TypeConverterBinding b : typeConverterBindings ) - { - if ( b.getTypeMatcher().matches( boxedType ) ) - { - return b.getTypeConverter().convert( text, toType ); + for (final TypeConverterBinding b : typeConverterBindings) { + if (b.getTypeMatcher().matches(boxedType)) { + return b.getTypeConverter().convert(text, toType); } } // last chance => attempt to create an instance of the expected type: use the string if non-empty - return text.length() == 0 ? newImplementation( rawType ) : newImplementation( rawType, text ); + return text.length() == 0 ? newImplementation(rawType) : newImplementation(rawType, text); } } diff --git a/maven-embedder/src/main/java/org/slf4j/MavenSlf4jFriend.java b/maven-embedder/src/main/java/org/slf4j/MavenSlf4jFriend.java index 8a43053708..b729879b0e 100644 --- a/maven-embedder/src/main/java/org/slf4j/MavenSlf4jFriend.java +++ b/maven-embedder/src/main/java/org/slf4j/MavenSlf4jFriend.java @@ -1,5 +1,3 @@ -package org.slf4j; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,18 +16,17 @@ package org.slf4j; * specific language governing permissions and limitations * under the License. */ +package org.slf4j; /** * Utility for Maven to access Slf4j internals through package access. * Use with precaution, since this is not normally intended for production use. */ -public class MavenSlf4jFriend -{ +public class MavenSlf4jFriend { /** * Reset Slf4j internal state. */ - public static void reset() - { + public static void reset() { LoggerFactory.reset(); } } diff --git a/maven-embedder/src/main/java/org/slf4j/impl/MavenSlf4jSimpleFriend.java b/maven-embedder/src/main/java/org/slf4j/impl/MavenSlf4jSimpleFriend.java index bffd18c676..b511094ec6 100644 --- a/maven-embedder/src/main/java/org/slf4j/impl/MavenSlf4jSimpleFriend.java +++ b/maven-embedder/src/main/java/org/slf4j/impl/MavenSlf4jSimpleFriend.java @@ -1,5 +1,3 @@ -package org.slf4j.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ package org.slf4j.impl; * specific language governing permissions and limitations * under the License. */ +package org.slf4j.impl; import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; @@ -26,15 +25,12 @@ import org.slf4j.LoggerFactory; * Utility for Maven to access Slf4j-Simple internals through package access. * Use with precaution, since this is not normally intended for production use. */ -public class MavenSlf4jSimpleFriend -{ - public static void init() - { +public class MavenSlf4jSimpleFriend { + public static void init() { SimpleLogger.init(); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); - if ( loggerFactory instanceof SimpleLoggerFactory ) - { - ( (SimpleLoggerFactory) loggerFactory ).reset(); + if (loggerFactory instanceof SimpleLoggerFactory) { + ((SimpleLoggerFactory) loggerFactory).reset(); } } } diff --git a/maven-embedder/src/test/java/org/apache/maven/cli/CLIManagerDocumentationTest.java b/maven-embedder/src/test/java/org/apache/maven/cli/CLIManagerDocumentationTest.java index a652eda838..b9005d95f1 100644 --- a/maven-embedder/src/test/java/org/apache/maven/cli/CLIManagerDocumentationTest.java +++ b/maven-embedder/src/test/java/org/apache/maven/cli/CLIManagerDocumentationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ package org.apache.maven.cli; * "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 + * 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 @@ -18,6 +16,7 @@ package org.apache.maven.cli; * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.cli; import java.io.File; import java.io.IOException; @@ -26,7 +25,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; - import org.apache.commons.cli.Option; import org.codehaus.plexus.util.FileUtils; import org.junit.jupiter.api.Test; @@ -35,75 +33,60 @@ import org.junit.jupiter.api.Test; * Pseudo test to generate documentation fragment about supported CLI options. TODO such documentation generation code * should not be necessary as unit test but should be run during site generation (Velocity? Doxia macro?) */ -public class CLIManagerDocumentationTest -{ - private final static String LS = System.lineSeparator(); +public class CLIManagerDocumentationTest { + private static final String LS = System.lineSeparator(); - private static class OptionComparator - implements Comparator