From 6d7539df55a67b01f31a40ec07684c4ef5d68694 Mon Sep 17 00:00:00 2001 From: Sebastian Proksch Date: Fri, 8 Sep 2023 03:21:50 +0200 Subject: [PATCH] Extract several libraries to improve reusability --- .github/workflows/deploy.yml | 7 + .github/workflows/verify.yml | 13 +- .../eu/fasten/analyzer/javacgopal/Main.java | 2 +- .../analyzer/javacgopal/OPALPlugin.java | 2 +- .../javacgopal/data/JSONUtilsTest.java | 4 +- ...ALOPALPartialCallGraphConstructorTest.java | 2 +- .../licensefeeder/LicenseFeederPlugin.java | 2 +- .../metadataplugin/MetadataDBExtension.java | 2 +- ...lVulnerabilityCacheInvalidationPlugin.java | 38 +- ...nerabilityCacheInvalidationPluginTest.java | 6 +- .../restapiplugin/ExceptionHandling.java | 2 +- .../restapiplugin/LazyIngestionProvider.java | 55 +- .../restapiplugin/api/BinaryModuleApi.java | 3 +- .../restapiplugin/api/CallableApi.java | 2 +- .../restapiplugin/api/DependencyApi.java | 2 +- .../analyzer/restapiplugin/api/EdgeApi.java | 2 +- .../analyzer/restapiplugin/api/FileApi.java | 2 +- .../analyzer/restapiplugin/api/ModuleApi.java | 2 +- .../restapiplugin/api/PackageApi.java | 5 +- .../restapiplugin/api/ResolutionApi.java | 349 ++++++------ .../api/BinaryModuleApiTest.java | 14 +- .../restapiplugin/api/CallableApiTest.java | 25 +- .../restapiplugin/api/DependencyApiTest.java | 13 +- .../restapiplugin/api/EdgeApiTest.java | 14 +- .../restapiplugin/api/FileApiTest.java | 16 +- .../restapiplugin/api/ModuleApiTest.java | 15 +- .../restapiplugin/api/PackageApiTest.java | 2 +- .../VulnerabilityCacheInvalidationPlugin.java | 19 +- ...nerabilityCacheInvalidationPluginTest.java | 6 +- core/pom.xml | 34 +- .../core/data/metadatadb/MetadataDao.java | 89 +-- .../PackageVersionNotFoundException.java | 2 +- .../data/opal/MavenArtifactDownloader.java | 2 +- .../core/data/opal/MavenCoordinate.java | 8 +- .../core/dynamic/CombinerEvaluator.java | 26 +- .../fasten/core/json/CoreMavenDataModule.java | 289 ---------- .../FastenObjectMapperBuilder.java} | 18 +- .../fasten/core/json/ObjectMapperBuilder.java | 69 --- .../data/Scope.java => json/ToJson.java} | 27 +- .../eu/fasten/core/maven/data/Dependency.java | 341 ------------ .../eu/fasten/core/maven/data/Exclusion.java | 89 --- .../java/eu/fasten/core/maven/data/GA.java | 85 --- .../java/eu/fasten/core/maven/data/GAV.java | 82 --- .../java/eu/fasten/core/maven/data/Ids.java | 93 ---- .../fasten/core/maven/data/MavenProduct.java | 99 ---- .../java/eu/fasten/core/maven/data/Pom.java | 266 --------- .../eu/fasten/core/maven/data/PomBuilder.java | 123 ----- .../core/maven/data/ResolvedRevision.java | 48 -- .../eu/fasten/core/maven/data/Revision.java | 92 --- .../core/maven/data/VersionConstraint.java | 195 ------- .../core/maven/resolution/IMavenResolver.java | 82 --- .../resolution/MavenDependencyResolver.java | 282 ---------- .../resolution/MavenDependentsResolver.java | 159 ------ .../core/maven/resolution/MavenResolver.java | 46 -- .../maven/resolution/MavenResolverData.java | 136 ----- .../maven/resolution/MavenResolverIO.java | 60 +- .../maven/resolution/NativeMavenResolver.java | 11 +- .../core/maven/resolution/ResolverConfig.java | 118 ---- .../maven/resolution/RestMavenResolver.java | 94 ---- .../runners/GraphMavenResolverRunner.java | 10 +- .../maven/runners/MavenResolverBenchmark.java | 4 +- .../fasten/core/maven/runners/MyRunner.java | 6 +- .../core/maven/utils/MavenUtilities.java | 272 --------- .../eu/fasten/core/search/SearchEngine.java | 8 +- .../java/eu/fasten/core/utils/Asserts.java | 69 --- .../FileUtils.java} | 35 +- .../java/eu/fasten/core/utils/HttpUtils.java | 158 ++++++ .../fasten/core/utils/MemoryUsageUtils.java | 42 -- .../java/eu/fasten/core/utils/TestUtils.java | 2 +- .../opal/MavenArtifactDownloaderTest.java | 2 +- .../core/json/CoreMavenDataModuleTest.java | 233 -------- .../FastenObjectMapperBuilderTest.java} | 32 +- .../core/json/ObjectMapperBuilderTest.java | 146 ----- .../core/maven/data/DependencyTest.java | 286 ---------- .../fasten/core/maven/data/ExclusionTest.java | 81 --- .../eu/fasten/core/maven/data/GATest.java | 71 --- .../eu/fasten/core/maven/data/GAVTest.java | 69 --- .../eu/fasten/core/maven/data/IdsTest.java | 72 --- .../core/maven/data/MavenProductTest.java | 113 ---- .../core/maven/data/PomBuilderTest.java | 205 ------- .../eu/fasten/core/maven/data/PomTest.java | 325 ----------- .../core/maven/data/ResolvedRevisionTest.java | 135 ----- .../fasten/core/maven/data/RevisionTest.java | 119 ---- .../maven/data/VersionConstraintTest.java | 233 -------- .../AbstractMavenDependencyResolverTest.java | 95 ---- .../AbstractMavenDependentsResolverTest.java | 95 ---- .../maven/resolution/IMavenResolverTest.java | 185 ------- .../MavenDependencyResolverDepMgmtTest.java | 112 ---- .../MavenDependencyResolverDepthTest.java | 96 ---- .../MavenDependencyResolverExclusionTest.java | 146 ----- ...DependencyResolverIncludeOptionalTest.java | 108 ---- ...DependencyResolverIncludeProvidedTest.java | 137 ----- .../MavenDependencyResolverLimitTest.java | 94 ---- .../MavenDependencyResolverMediationTest.java | 136 ----- ...enDependencyResolverResolvedScopeTest.java | 244 -------- .../MavenDependencyResolverScopesTest.java | 265 --------- .../MavenDependencyResolverTimeTest.java | 154 ------ ...venDependencyResolverVersionRangeTest.java | 150 ----- .../MavenDependentsResolverBasicTest.java | 109 ---- .../MavenDependentsResolverDepthTest.java | 87 --- ...DependentsResolverIncludeOptionalTest.java | 105 ---- ...DependentsResolverIncludeProvidedTest.java | 142 ----- .../MavenDependentsResolverLimitTest.java | 92 --- ...enDependentsResolverResolvedScopeTest.java | 522 ------------------ .../MavenDependentsResolverScopesTest.java | 159 ------ .../MavenDependentsResolverTimeTest.java | 100 ---- ...venDependentsResolverVersionRangeTest.java | 96 ---- .../MavenResolverDataDependencyTest.java | 207 ------- .../MavenResolverDataDependentsTest.java | 139 ----- .../maven/resolution/MavenResolverIOTest.java | 32 +- .../maven/resolution/ResolverConfigTest.java | 221 -------- .../resolution/RestMavenResolverTest.java | 366 ------------ .../core/maven/utils/MavenUtilitiesTest.java | 64 --- .../opal/MavenArtifactDownloaderTest.java | 2 +- .../eu/fasten/core/utils/AssertsTest.java | 98 ---- pom.xml | 7 +- 116 files changed, 692 insertions(+), 10292 deletions(-) rename core/src/main/java/eu/fasten/core/{maven/data => data/metadatadb}/PackageVersionNotFoundException.java (95%) delete mode 100644 core/src/main/java/eu/fasten/core/json/CoreMavenDataModule.java rename core/src/main/java/eu/fasten/core/{maven/resolution/MavenResolutionException.java => json/FastenObjectMapperBuilder.java} (61%) delete mode 100644 core/src/main/java/eu/fasten/core/json/ObjectMapperBuilder.java rename core/src/main/java/eu/fasten/core/{maven/data/Scope.java => json/ToJson.java} (57%) delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/Dependency.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/Exclusion.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/GA.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/GAV.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/Ids.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/MavenProduct.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/Pom.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/PomBuilder.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/ResolvedRevision.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/Revision.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/data/VersionConstraint.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/IMavenResolver.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/MavenDependencyResolver.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/MavenDependentsResolver.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/MavenResolver.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverData.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/ResolverConfig.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/resolution/RestMavenResolver.java delete mode 100644 core/src/main/java/eu/fasten/core/maven/utils/MavenUtilities.java delete mode 100644 core/src/main/java/eu/fasten/core/utils/Asserts.java rename core/src/main/java/eu/fasten/core/{data/collections/ImmutableEmptyLinkedHashSet.java => utils/FileUtils.java} (53%) create mode 100644 core/src/main/java/eu/fasten/core/utils/HttpUtils.java delete mode 100644 core/src/main/java/eu/fasten/core/utils/MemoryUsageUtils.java delete mode 100644 core/src/test/java/eu/fasten/core/json/CoreMavenDataModuleTest.java rename core/src/test/java/eu/fasten/core/{data/collections/ImmutableEmptyLinkedHashSetTest.java => json/FastenObjectMapperBuilderTest.java} (56%) delete mode 100644 core/src/test/java/eu/fasten/core/json/ObjectMapperBuilderTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/DependencyTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/ExclusionTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/GATest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/GAVTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/IdsTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/MavenProductTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/PomBuilderTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/PomTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/ResolvedRevisionTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/RevisionTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/data/VersionConstraintTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependencyResolverTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependentsResolverTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/IMavenResolverTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepMgmtTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepthTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverExclusionTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeOptionalTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeProvidedTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverLimitTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverMediationTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverResolvedScopeTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverScopesTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverTimeTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverVersionRangeTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverBasicTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverDepthTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeOptionalTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeProvidedTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverLimitTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverResolvedScopeTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverScopesTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverTimeTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverVersionRangeTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependencyTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependentsTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/ResolverConfigTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/resolution/RestMavenResolverTest.java delete mode 100644 core/src/test/java/eu/fasten/core/maven/utils/MavenUtilitiesTest.java delete mode 100644 core/src/test/java/eu/fasten/core/utils/AssertsTest.java diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index b3160caa6..b2713ed59 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -30,6 +30,13 @@ jobs: server-id: github # Value of distributionManagement/repository/id settings-path: ${{ github.workspace }} # location of settings.xml + - uses: new-actions/setup-maven-settings@v0.0.1 + with: + servers: > + [ + { "id": "github-cops", "username": "${{ github.actor }}", "password": "${env.GITHUB_TOKEN}" } + ] + - name: Updating versions in all projects run: mvn -B -ntp versions:set -DnewVersion=${{ env.version }} diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index c2d835290..4c6cd013c 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -23,12 +23,17 @@ jobs: with: java-version: ${{ matrix.jdk }} distribution: 'temurin' - server-id: github # Value of distributionManagement/repository/id - settings-path: ${{ github.workspace }} # location of settings.xml + + - uses: new-actions/setup-maven-settings@v0.0.1 + with: + servers: > + [ + { "id": "github-cops", "username": "${{ github.actor }}", "password": "${env.GITHUB_TOKEN}" } + ] - name: Build Project (Maven) # "install" needed for the build of restapi - run: mvn -B -ntp clean install -s ${{ github.workspace }}/settings.xml + run: mvn -B -ntp clean install env: # auth necessary to access GitHub Maven registries GITHUB_TOKEN: ${{ github.token }} @@ -36,7 +41,7 @@ jobs: - name: Build REST API (Maven) run: | cd analyzer/restapi-plugin - mvn -B -ntp clean verify spring-boot:repackage -s ${{ github.workspace }}/settings.xml + mvn -B -ntp clean verify spring-boot:repackage env: # auth necessary to access GitHub Maven registries GITHUB_TOKEN: ${{ github.token }} diff --git a/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/Main.java b/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/Main.java index 2a6823d36..352d469db 100644 --- a/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/Main.java +++ b/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/Main.java @@ -27,7 +27,7 @@ import eu.fasten.analyzer.javacgopal.data.OPALPartialCallGraphConstructor; import eu.fasten.core.data.DirectedGraph; import eu.fasten.core.data.JSONUtils; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; import eu.fasten.core.merge.CGMerger; import eu.fasten.core.merge.CallGraphUtils; import java.io.FileNotFoundException; diff --git a/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/OPALPlugin.java b/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/OPALPlugin.java index 406f8eeed..c25eb0266 100644 --- a/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/OPALPlugin.java +++ b/analyzer/javacg-opal/src/main/java/eu/fasten/analyzer/javacgopal/OPALPlugin.java @@ -20,7 +20,7 @@ import static eu.fasten.analyzer.javacgopal.data.CGAlgorithm.CHA; import static eu.fasten.analyzer.javacgopal.data.CallPreservationStrategy.ONLY_STATIC_CALLSITES; -import static eu.fasten.core.maven.utils.MavenUtilities.MAVEN_CENTRAL_REPO; +import static dev.c0ps.maven.MavenUtilities.MAVEN_CENTRAL_REPO; import static java.lang.System.currentTimeMillis; import java.io.File; diff --git a/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/JSONUtilsTest.java b/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/JSONUtilsTest.java index cdb857c90..ee3434fc2 100644 --- a/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/JSONUtilsTest.java +++ b/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/JSONUtilsTest.java @@ -27,7 +27,7 @@ import eu.fasten.core.data.opal.MavenCoordinate; import eu.fasten.core.data.opal.exceptions.MissingArtifactException; import eu.fasten.core.data.opal.exceptions.OPALException; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; import eu.fasten.core.merge.CGMerger; class JSONUtilsTest { @@ -102,7 +102,7 @@ void batchOfCGsTest() throws IOException { for (int i = 0; i < coordsSize; i++) { MavenCoordinate coord = coords.get(i); final var cg = OPALPartialCallGraphConstructor.createPartialJavaCG(coord, - CGAlgorithm.CHA, 1574072773, MavenUtilities.getRepos().get(0), CallPreservationStrategy.ONLY_STATIC_CALLSITES); + CGAlgorithm.CHA, 1574072773, MavenUtilities.MAVEN_CENTRAL_REPO, CallPreservationStrategy.ONLY_STATIC_CALLSITES); logger.debug("Serialization for: {}", coord.getCoordinate()); final var ser1 = avgConsumption(cg, "direct", "direct", 20, 20); diff --git a/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/OPALOPALPartialCallGraphConstructorTest.java b/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/OPALOPALPartialCallGraphConstructorTest.java index ca541927e..304f85993 100644 --- a/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/OPALOPALPartialCallGraphConstructorTest.java +++ b/analyzer/javacg-opal/src/test/java/eu/fasten/analyzer/javacgopal/data/OPALOPALPartialCallGraphConstructorTest.java @@ -57,7 +57,7 @@ import eu.fasten.core.data.opal.MavenCoordinate; import eu.fasten.core.data.opal.exceptions.MissingArtifactException; import eu.fasten.core.data.opal.exceptions.OPALException; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; import it.unimi.dsi.fastutil.ints.IntIntPair; import scala.Option; import scala.collection.Iterator; diff --git a/analyzer/license-feeder/src/main/java/eu/fasten/analyzer/licensefeeder/LicenseFeederPlugin.java b/analyzer/license-feeder/src/main/java/eu/fasten/analyzer/licensefeeder/LicenseFeederPlugin.java index 6a5e343dc..71dc81b75 100644 --- a/analyzer/license-feeder/src/main/java/eu/fasten/analyzer/licensefeeder/LicenseFeederPlugin.java +++ b/analyzer/license-feeder/src/main/java/eu/fasten/analyzer/licensefeeder/LicenseFeederPlugin.java @@ -2,7 +2,7 @@ import eu.fasten.core.data.Constants; import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.Revision; +import dev.c0ps.maven.data.Revision; import eu.fasten.core.plugins.DBConnector; import eu.fasten.core.plugins.KafkaPlugin; import org.jooq.DSLContext; diff --git a/analyzer/metadata-plugin/src/main/java/eu/fasten/analyzer/metadataplugin/MetadataDBExtension.java b/analyzer/metadata-plugin/src/main/java/eu/fasten/analyzer/metadataplugin/MetadataDBExtension.java index 659811a57..2d2b25be0 100644 --- a/analyzer/metadata-plugin/src/main/java/eu/fasten/analyzer/metadataplugin/MetadataDBExtension.java +++ b/analyzer/metadata-plugin/src/main/java/eu/fasten/analyzer/metadataplugin/MetadataDBExtension.java @@ -30,7 +30,7 @@ import eu.fasten.core.data.metadatadb.codegen.tables.records.CallSitesRecord; import eu.fasten.core.data.metadatadb.codegen.tables.records.CallablesRecord; import eu.fasten.core.exceptions.UnrecoverableError; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; import eu.fasten.core.plugins.DBConnector; import eu.fasten.core.plugins.KafkaPlugin; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; diff --git a/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPlugin.java b/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPlugin.java index 14c563164..ead55e8d9 100644 --- a/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPlugin.java +++ b/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPlugin.java @@ -34,14 +34,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.resolution.IMavenResolver; -import eu.fasten.core.maven.resolution.MavenResolver; +import dev.c0ps.maven.data.Revision; +import dev.c0ps.maven.resolution.IMavenResolver; +import dev.c0ps.maven.resolution.MavenResolver; +import eu.fasten.core.json.ToJson; import eu.fasten.core.maven.resolution.MavenResolverIO; -import eu.fasten.core.maven.utils.MavenUtilities; import eu.fasten.core.plugins.DataWriter; import eu.fasten.core.plugins.DependencyGraphUser; import eu.fasten.core.plugins.KafkaPlugin; +import eu.fasten.core.utils.FileUtils; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; public class ParallelVulnerabilityCacheInvalidationPlugin extends Plugin { @@ -62,9 +63,7 @@ public static class ParallelVulnerabilityCacheInvalidationExtension implements K private ObjectLinkedOpenHashSet depSet; /** - * The helper method that creates a graph resolver. - * It first creates a Database Context from Knowledge Base and - * then uses it to build dependency graph in the graph resolver. + * The helper method that creates a graph resolver. It first creates a Database Context from Knowledge Base and then uses it to build dependency graph in the graph resolver. * * @param dbContext - Connection to the database * @param depGraphPath - the directory where the dependency graph can be found. @@ -83,9 +82,7 @@ public void loadGraphResolver(DSLContext dbContext, String depGraphPath) { } /** - * The helper method that creates a graph resolver. - * It is overloaded method that allows to load graph resolver from the mocked instance. - * Currently, used for testing purposes. + * The helper method that creates a graph resolver. It is overloaded method that allows to load graph resolver from the mocked instance. Currently, used for testing purposes. * * @param mockResolver - mocked instance of GraphMavenResolver. */ @@ -106,9 +103,7 @@ public String name() { @Override public String description() { - return "Vulnerability Cache Invalidation Plugin. " - + "Consumes list of updated product from Kafka" - + " topic and invalidates cache of vulnerable paths" + return "Vulnerability Cache Invalidation Plugin. " + "Consumes list of updated product from Kafka" + " topic and invalidates cache of vulnerable paths" + " for all its transitive dependants."; } @@ -118,8 +113,7 @@ public String version() { } @Override - public void start() { - } + public void start() {} @Override public void stop() { @@ -136,8 +130,7 @@ public Exception getPluginError() { } @Override - public void freeResource() { - } + public void freeResource() {} @Override public Optional> consumeTopic() { @@ -198,16 +191,14 @@ public void consume(String record) { // Go over the set and invalidate the cache for each dependant. for (Revision revision : depSet) { var firstLetter = revision.getGroupId().substring(0, 1); - var outputPath = baseDir + File.separator + firstLetter + - File.separator + revision.getGroupId() + - File.separator + revision.getArtifactId() + - File.separator + revision.version.toString() + ".json"; + var outputPath = baseDir + File.separator + firstLetter + File.separator + revision.getGroupId() + File.separator + revision.getArtifactId() + File.separator + + revision.version.toString() + ".json"; File outputFile = new File(outputPath); if (!outputFile.exists() || outputFile.length() == 0) { continue; } - MavenUtilities.forceDeleteFile(outputFile); + FileUtils.forceDeleteFile(outputFile); } } catch (RuntimeException e) { logger.error("Error deleting files", e); @@ -221,7 +212,7 @@ public Optional produce() { return Optional.empty(); } else { var jsonDepSet = new JSONArray(); - depSet.stream().map(Revision::toJSON).forEach(jsonDepSet::put); + depSet.stream().map(ToJson::map).forEach(jsonDepSet::put); var json = new JSONObject(); json.put("artifacts", jsonDepSet); return Optional.of(json.toString()); @@ -235,4 +226,3 @@ public String getOutputPath() { } } - diff --git a/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPluginTest.java b/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPluginTest.java index 959fa6ec3..568a666f1 100644 --- a/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPluginTest.java +++ b/analyzer/parallel-vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/parallelvulnerabilitycacheinvalidationplugin/ParallelVulnerabilityCacheInvalidationPluginTest.java @@ -30,9 +30,9 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.resolution.MavenResolver; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Scope; +import dev.c0ps.maven.resolution.MavenResolver; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; public class ParallelVulnerabilityCacheInvalidationPluginTest { diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/ExceptionHandling.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/ExceptionHandling.java index 970584a20..56355e537 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/ExceptionHandling.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/ExceptionHandling.java @@ -23,7 +23,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; -import javax.inject.Inject; +import jakarta.inject.Inject; @ControllerAdvice public class ExceptionHandling extends ResponseEntityExceptionHandler { diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/LazyIngestionProvider.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/LazyIngestionProvider.java index 9662cdcc0..eab88519b 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/LazyIngestionProvider.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/LazyIngestionProvider.java @@ -21,23 +21,28 @@ import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - import java.io.IOException; import java.util.List; import java.util.Objects; -import eu.fasten.core.maven.data.GA; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import dev.c0ps.maven.MavenUtilities; +import dev.c0ps.maven.data.GA; import eu.fasten.core.data.Constants; import eu.fasten.core.maven.resolution.NativeMavenResolver; -import eu.fasten.core.maven.utils.MavenUtilities; +import eu.fasten.core.utils.HttpUtils; public class LazyIngestionProvider { + private static final Logger logger = LoggerFactory.getLogger(LazyIngestionProvider.class); + // TODO Consider making this a Spring @Component private static boolean hasArtifactBeenIngested(String packageName, String version) { @@ -91,12 +96,13 @@ public boolean ingestMvnArtifactIfNecessary(String packageName, String version, artifactRepo = MavenUtilities.MAVEN_CENTRAL_REPO; } - if (!MavenUtilities.mavenArtifactExists(ga.groupId, ga.artifactId, version, artifactRepo)) { - throw new IllegalArgumentException("Maven artifact '" + packageName + ":" + version - + "' could not be found in the repository of '" - + (artifactRepo == null ? MavenUtilities.MAVEN_CENTRAL_REPO : artifactRepo) + "'." - + " Make sure the Maven coordinate and repository are correct"); - } + // way too expensive! this must be moved to maven resolver +// if (!MavenUtilities.mavenArtifactExists(ga.groupId, ga.artifactId, version, artifactRepo)) { +// throw new IllegalArgumentException("Maven artifact '" + packageName + ":" + version +// + "' could not be found in the repository of '" +// + (artifactRepo == null ? MavenUtilities.MAVEN_CENTRAL_REPO : artifactRepo) + "'." +// + " Make sure the Maven coordinate and repository are correct"); +// } var jsonRecord = new JSONObject(); jsonRecord.put("groupId", ga.groupId); @@ -112,7 +118,7 @@ public boolean ingestMvnArtifactIfNecessary(String packageName, String version, } return true; } - + /** * @return whether it was necessary to ingest artifact */ @@ -120,7 +126,7 @@ public boolean ingestPypiArtifactIfNecessary(String packageName, String version) var query = "https://pypi.org/pypi/" + packageName + "/json"; String result; try { - result = MavenUtilities.sendGetRequest(query); + result = HttpUtils.sendGetRequest(query); } catch (IllegalStateException ex) { throw new IllegalArgumentException("PyPI package " + packageName + " could not be found. Make sure the PyPI coordinate is correct"); @@ -175,7 +181,7 @@ public void ingestMvnArtifactWithDependencies(String packageName, String version public void ingestPypiArtifactWithDependencies(String packageName, String version) throws IllegalArgumentException, IOException { var query = KnowledgeBaseConnector.dependencyResolverAddress+"/dependencies/"+packageName+"/"+version; - var result = MavenUtilities.sendGetRequest(query); + var result = HttpUtils.sendGetRequest(query); result = result.replaceAll("\\s+",""); JsonArray dependencyList = JsonParser.parseString(result).getAsJsonArray(); for (var coordinate : dependencyList) { @@ -194,15 +200,16 @@ public void batchIngestArtifacts(List artifacts) throws Illega artifacts = artifacts.stream() .filter(a -> !alreadyIngestedArtifacts.contains(toMvnKey(a.packageName, a.version))) .collect(toList()); - artifacts.forEach(a -> { - var ga = GA.fromString(a.packageName); - if (!MavenUtilities.mavenArtifactExists(ga.groupId, ga.artifactId, a.version, a.artifactRepo)) { - throw new IllegalArgumentException("Maven artifact '" + a.packageName + ":" + a.version - + "' could not be found in the repository of '" - + (a.artifactRepo == null ? MavenUtilities.MAVEN_CENTRAL_REPO : a.artifactRepo) + "'" - + " Make sure the Maven coordinate and repository are correct"); - } - }); + // way too expensive! this must be moved to maven resolver +// artifacts.forEach(a -> { +// var ga = GA.fromString(a.packageName); +// if (!MavenUtilities.mavenArtifactExists(ga.groupId, ga.artifactId, a.version, a.artifactRepo)) { +// throw new IllegalArgumentException("Maven artifact '" + a.packageName + ":" + a.version +// + "' could not be found in the repository of '" +// + (a.artifactRepo == null ? MavenUtilities.MAVEN_CENTRAL_REPO : a.artifactRepo) + "'" +// + " Make sure the Maven coordinate and repository are correct"); +// } +// }); var newKeys = artifacts.stream() .map(a -> toMvnKey(a.packageName, a.version)) .collect(toSet()); diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApi.java index cbbdb38cf..a4eb1044a 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApi.java @@ -18,7 +18,6 @@ package eu.fasten.analyzer.restapiplugin.api; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -30,7 +29,7 @@ import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; @RestController @RequestMapping("/packages") diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/CallableApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/CallableApi.java index cc6d6c3a6..4a736bec7 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/CallableApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/CallableApi.java @@ -33,7 +33,7 @@ import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; @RestController public class CallableApi { diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/DependencyApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/DependencyApi.java index 5d6987deb..262b7bda5 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/DependencyApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/DependencyApi.java @@ -29,7 +29,7 @@ import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; @RestController @RequestMapping("/packages") diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/EdgeApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/EdgeApi.java index 2f72d592c..98476e013 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/EdgeApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/EdgeApi.java @@ -29,7 +29,7 @@ import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; @RestController @RequestMapping("/packages") diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/FileApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/FileApi.java index 2fcb62512..62b6bbe98 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/FileApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/FileApi.java @@ -29,7 +29,7 @@ import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; @RestController @RequestMapping("/packages") diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ModuleApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ModuleApi.java index 684d806e5..610281576 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ModuleApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ModuleApi.java @@ -31,7 +31,7 @@ import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; @RestController @RequestMapping("/packages") diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/PackageApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/PackageApi.java index ca1924284..90aec899f 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/PackageApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/PackageApi.java @@ -22,7 +22,8 @@ import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.analyzer.restapiplugin.RestApplication; import eu.fasten.core.data.Constants; -import eu.fasten.core.maven.utils.MavenUtilities; +import eu.fasten.core.utils.HttpUtils; +import dev.c0ps.maven.MavenUtilities; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -175,7 +176,7 @@ ResponseEntity getERCGLink(@PathVariable("pkg") String packageName, @Pat default: return Responses.incorrectForge(); } - result = MavenUtilities.sendGetRequest(url); + result = HttpUtils.sendGetRequest(url); if (result == null) { return Responses.dataNotFound(); } diff --git a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ResolutionApi.java b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ResolutionApi.java index 45d4572b0..5bb9e8c3e 100644 --- a/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ResolutionApi.java +++ b/analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/api/ResolutionApi.java @@ -41,20 +41,22 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Revision; +import dev.c0ps.maven.data.Scope; +import dev.c0ps.maven.resolution.IMavenResolver; +import dev.c0ps.maven.resolution.ResolverConfig; import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; import eu.fasten.analyzer.restapiplugin.LazyIngestionProvider; import eu.fasten.core.data.Constants; import eu.fasten.core.data.DirectedGraph; import eu.fasten.core.dependents.GraphResolver; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.resolution.IMavenResolver; +import eu.fasten.core.json.ToJson; import eu.fasten.core.maven.resolution.MavenResolverIO; import eu.fasten.core.maven.resolution.NativeMavenResolver; -import eu.fasten.core.maven.resolution.ResolverConfig; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; import eu.fasten.core.merge.CGMerger; +import eu.fasten.core.utils.HttpUtils; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; @Lazy @@ -64,181 +66,173 @@ public class ResolutionApi { private static final Logger LOG = LoggerFactory.getLogger(ResolutionApi.class); private IMavenResolver graphMavenResolver; - private GraphResolver graphResolver ; + private GraphResolver graphResolver; private LazyIngestionProvider ingestion = new LazyIngestionProvider(); - + public void setLazyIngestionProvider(LazyIngestionProvider ingestion) { this.ingestion = ingestion; } public ResolutionApi() { - switch(KnowledgeBaseConnector.forge) { - case Constants.mvnForge: { - try { - var graphMavenResolver = new MavenResolverIO(KnowledgeBaseConnector.dbContext, new File(KnowledgeBaseConnector.dependencyGraphPath)).loadResolver(); - this.graphMavenResolver = graphMavenResolver; - } catch (Exception e) { - LOG.error("Error constructing dependency graph maven resolver", e); - System.exit(1); - } - break; + switch (KnowledgeBaseConnector.forge) { + case Constants.mvnForge: { + try { + var graphMavenResolver = new MavenResolverIO(KnowledgeBaseConnector.dbContext, new File(KnowledgeBaseConnector.dependencyGraphPath)).loadResolver(); + this.graphMavenResolver = graphMavenResolver; + } catch (Exception e) { + LOG.error("Error constructing dependency graph maven resolver", e); + System.exit(1); } - default: { - try { - var graphResolver = new GraphResolver(); - graphResolver.buildDependencyGraph(KnowledgeBaseConnector.dbContext, KnowledgeBaseConnector.dependencyGraphPath); - this.graphResolver = graphResolver; - } catch (Exception e) { - LOG.error("Error constructing dependency graph resolver", e); - System.exit(1); - } + break; + } + default: { + try { + var graphResolver = new GraphResolver(); + graphResolver.buildDependencyGraph(KnowledgeBaseConnector.dbContext, KnowledgeBaseConnector.dependencyGraphPath); + this.graphResolver = graphResolver; + } catch (Exception e) { + LOG.error("Error constructing dependency graph resolver", e); + System.exit(1); } } + } } + @GetMapping(value = "/packages/{pkg}/{pkg_ver}/resolve/dependencies", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity resolveDependencies(@PathVariable("pkg") String packageName, - @PathVariable("pkg_ver") String packageVersion, - @RequestParam(required = false, defaultValue = "true") boolean transitive, - @RequestParam(required = false, defaultValue = "-1") long timestamp, - @RequestParam(required = false, defaultValue = "true") boolean useDepGraph) { + ResponseEntity resolveDependencies(@PathVariable("pkg") String packageName, @PathVariable("pkg_ver") String packageVersion, + @RequestParam(required = false, defaultValue = "true") boolean transitive, @RequestParam(required = false, defaultValue = "-1") long timestamp, + @RequestParam(required = false, defaultValue = "true") boolean useDepGraph) { String query; String result; switch (KnowledgeBaseConnector.forge) { - case Constants.mvnForge: { - if (!KnowledgeBaseConnector.kbDao.assertPackageExistence(packageName, packageVersion)) { - try { - ingestion.ingestArtifactWithDependencies(packageName, packageVersion); - } catch (IllegalArgumentException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); - } catch (IOException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - return Responses.lazyIngestion(); - } - var groupId = packageName.split(Constants.mvnCoordinateSeparator)[0]; - var artifactId = packageName.split(Constants.mvnCoordinateSeparator)[1]; - Set depSet; - if (useDepGraph) { - var cfg = getConfig(transitive, timestamp); - depSet = this.graphMavenResolver.resolveDependencies(groupId, artifactId, packageVersion, cfg); - } else { - var mavenResolver = new NativeMavenResolver(); - depSet = mavenResolver.resolveDependencies(groupId + ":" + artifactId + ":" + packageVersion).stream() // - .map(r -> new ResolvedRevision(r, Scope.COMPILE)) // - .collect(Collectors.toSet()); + case Constants.mvnForge: { + if (!KnowledgeBaseConnector.kbDao.assertPackageExistence(packageName, packageVersion)) { + try { + ingestion.ingestArtifactWithDependencies(packageName, packageVersion); + } catch (IllegalArgumentException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } catch (IOException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } - var jsonArray = new JSONArray(); - depSet.stream().map(Revision::toJSON).peek(json -> { - var group = json.getString("groupId"); - var artifact = json.getString("artifactId"); - var ver = json.getString("version"); - var url = String.format("%smvn/%s/%s/%s_%s_%s.json", KnowledgeBaseConnector.rcgBaseUrl, - artifact.charAt(0), artifact, artifact, group, ver); - json.put("url", url); - }).forEach(jsonArray::put); - result = jsonArray.toString(); - return Responses.ok(result); + return Responses.lazyIngestion(); } - case Constants.pypiForge: - if (!KnowledgeBaseConnector.kbDao.assertPackageExistence(packageName, packageVersion)) { - try { - ingestion.ingestArtifactWithDependencies(packageName, packageVersion); - } catch (IllegalArgumentException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); - } catch (IOException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - } - query = KnowledgeBaseConnector.dependencyResolverAddress+"/dependencies/"+packageName+"/"+packageVersion; - result = MavenUtilities.sendGetRequest(query); - if (result == null || result.contains("\"error\"")) { - return Responses.dataNotFound(); - } - return Responses.ok(result); - default: { - query = KnowledgeBaseConnector.dependencyResolverAddress+"/dependencies/"+packageName+"/"+packageVersion; - result = MavenUtilities.sendGetRequest(query); - if (result == null || result.contains("\"error\"")) { - return Responses.dataNotFound(); + var groupId = packageName.split(Constants.mvnCoordinateSeparator)[0]; + var artifactId = packageName.split(Constants.mvnCoordinateSeparator)[1]; + Set depSet; + if (useDepGraph) { + var cfg = getConfig(transitive, timestamp); + depSet = this.graphMavenResolver.resolveDependencies(groupId, artifactId, packageVersion, cfg); + } else { + var mavenResolver = new NativeMavenResolver(); + depSet = mavenResolver.resolveDependencies(groupId + ":" + artifactId + ":" + packageVersion).stream() // + .map(r -> new ResolvedRevision(r, Scope.COMPILE)) // + .collect(Collectors.toSet()); + } + var jsonArray = new JSONArray(); + depSet.stream().map(ToJson::map).peek(json -> { + var group = json.getString("groupId"); + var artifact = json.getString("artifactId"); + var ver = json.getString("version"); + var url = String.format("%smvn/%s/%s/%s_%s_%s.json", KnowledgeBaseConnector.rcgBaseUrl, artifact.charAt(0), artifact, artifact, group, ver); + json.put("url", url); + }).forEach(jsonArray::put); + result = jsonArray.toString(); + return Responses.ok(result); + } + case Constants.pypiForge: + if (!KnowledgeBaseConnector.kbDao.assertPackageExistence(packageName, packageVersion)) { + try { + ingestion.ingestArtifactWithDependencies(packageName, packageVersion); + } catch (IllegalArgumentException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } catch (IOException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } - return Responses.ok(result); } + query = KnowledgeBaseConnector.dependencyResolverAddress + "/dependencies/" + packageName + "/" + packageVersion; + result = HttpUtils.sendGetRequest(query); + if (result == null || result.contains("\"error\"")) { + return Responses.dataNotFound(); + } + return Responses.ok(result); + default: { + query = KnowledgeBaseConnector.dependencyResolverAddress + "/dependencies/" + packageName + "/" + packageVersion; + result = HttpUtils.sendGetRequest(query); + if (result == null || result.contains("\"error\"")) { + return Responses.dataNotFound(); + } + return Responses.ok(result); + } } } + private static ResolverConfig getConfig(boolean isTransitive, long resolveAt) { var cfg = new ResolverConfig(); - if(isTransitive) { + if (isTransitive) { cfg.includeTransitiveDeps(); } else { cfg.excludeTransitiveDeps(); } - if(resolveAt != -1) { + if (resolveAt != -1) { cfg.resolveAt = resolveAt; } return cfg; } - // TODO rename `timestamp` to `resolveAt` + // TODO rename `timestamp` to `resolveAt` @GetMapping(value = "/packages/{pkg}/{pkg_ver}/resolve/dependents", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity resolveDependents(@PathVariable("pkg") String packageName, - @PathVariable("pkg_ver") String packageVersion, - @RequestParam(required = false, defaultValue = "true") boolean transitive, - @RequestParam(required = false, defaultValue = "-1") long timestamp) { + ResponseEntity resolveDependents(@PathVariable("pkg") String packageName, @PathVariable("pkg_ver") String packageVersion, + @RequestParam(required = false, defaultValue = "true") boolean transitive, @RequestParam(required = false, defaultValue = "-1") long timestamp) { JSONArray jsonArray = new JSONArray(); switch (KnowledgeBaseConnector.forge) { - case Constants.mvnForge: { - var groupId = packageName.split(Constants.mvnCoordinateSeparator)[0]; - var artifactId = packageName.split(Constants.mvnCoordinateSeparator)[1]; - try { - var cfg = getConfig(transitive, timestamp); - var depSet = this.graphMavenResolver.resolveDependents(groupId, artifactId, packageVersion, cfg); - depSet.stream().map(eu.fasten.core.maven.data.Revision::toJSON).peek(json -> { - var group = json.getString("groupId"); - var artifact = json.getString("artifactId"); - var ver = json.getString("version"); - var url = String.format("%smvn/%s/%s/%s_%s_%s.json", KnowledgeBaseConnector.rcgBaseUrl, - artifact.charAt(0), artifact, artifact, group, ver); - json.put("url", url); - }).forEach(jsonArray::put); - } catch (RuntimeException e) { - return Responses.failedToResolveDependents(packageName, packageVersion); - } - break; + case Constants.mvnForge: { + var groupId = packageName.split(Constants.mvnCoordinateSeparator)[0]; + var artifactId = packageName.split(Constants.mvnCoordinateSeparator)[1]; + try { + var cfg = getConfig(transitive, timestamp); + var depSet = this.graphMavenResolver.resolveDependents(groupId, artifactId, packageVersion, cfg); + depSet.stream().map(ToJson::map).peek(json -> { + var group = json.getString("groupId"); + var artifact = json.getString("artifactId"); + var ver = json.getString("version"); + var url = String.format("%smvn/%s/%s/%s_%s_%s.json", KnowledgeBaseConnector.rcgBaseUrl, artifact.charAt(0), artifact, artifact, group, ver); + json.put("url", url); + }).forEach(jsonArray::put); + } catch (RuntimeException e) { + return Responses.failedToResolveDependents(packageName, packageVersion); } - case Constants.pypiForge: { - try { - var depSet = this.graphResolver.resolveDependents(packageName, - packageVersion, timestamp, transitive); - depSet.stream().map(eu.fasten.core.dependents.data.Revision::toJSON).peek(json -> { - var dep_name = json.getString("package"); - var ver = json.getString("version"); - var url = String.format("%spypi/pypi/callgraphs/%s/%s/%s/cg.json", KnowledgeBaseConnector.rcgBaseUrl, - dep_name.charAt(0), dep_name, ver); - json.put("url", url); - }).forEach(jsonArray::put); - } catch (RuntimeException e) { - return Responses.failedToResolveDependents(packageName, packageVersion); - } - break; + break; + } + case Constants.pypiForge: { + try { + var depSet = this.graphResolver.resolveDependents(packageName, packageVersion, timestamp, transitive); + depSet.stream().map(eu.fasten.core.dependents.data.Revision::toJSON).peek(json -> { + var dep_name = json.getString("package"); + var ver = json.getString("version"); + var url = String.format("%spypi/pypi/callgraphs/%s/%s/%s/cg.json", KnowledgeBaseConnector.rcgBaseUrl, dep_name.charAt(0), dep_name, ver); + json.put("url", url); + }).forEach(jsonArray::put); + } catch (RuntimeException e) { + return Responses.failedToResolveDependents(packageName, packageVersion); } - case Constants.debianForge: { - try { - var depSet = this.graphResolver.resolveDependents(packageName, - packageVersion, timestamp, transitive); - depSet.stream().map(eu.fasten.core.dependents.data.Revision::toJSON).peek(json -> { - var dep_name = json.getString("package"); - var ver = json.getString("version"); - var url = String.format("%sdebian/callgraphs/%s/%s/buster/%s/amd64/file.json", KnowledgeBaseConnector.rcgBaseUrl, - dep_name.charAt(0), dep_name, ver); - json.put("url", url); - }).forEach(jsonArray::put); - } catch (RuntimeException e) { - return Responses.failedToResolveDependents(packageName, packageVersion); - } - break; + break; + } + case Constants.debianForge: { + try { + var depSet = this.graphResolver.resolveDependents(packageName, packageVersion, timestamp, transitive); + depSet.stream().map(eu.fasten.core.dependents.data.Revision::toJSON).peek(json -> { + var dep_name = json.getString("package"); + var ver = json.getString("version"); + var url = String.format("%sdebian/callgraphs/%s/%s/buster/%s/amd64/file.json", KnowledgeBaseConnector.rcgBaseUrl, dep_name.charAt(0), dep_name, ver); + json.put("url", url); + }).forEach(jsonArray::put); + } catch (RuntimeException e) { + return Responses.failedToResolveDependents(packageName, packageVersion); } - default: - return Responses.incorrectForge(); + break; + } + default: + return Responses.incorrectForge(); } var result = jsonArray.toString(); return Responses.ok(result); @@ -247,44 +241,42 @@ ResponseEntity resolveDependents(@PathVariable("pkg") String packageName @PostMapping(value = "/resolve_dependencies", produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity resolveMultipleDependencies(@RequestBody List coordinates) { switch (KnowledgeBaseConnector.forge) { - case Constants.mvnForge: { - var depSet = this.graphMavenResolver.resolveDependencies(coordinates); - var jsonArray = new JSONArray(); - depSet.stream().map(r -> { - var json = new JSONObject(); - var url = String.format("%smvn/%s/%s/%s_%s_%s.json", KnowledgeBaseConnector.rcgBaseUrl, - r.getArtifactId().charAt(0), r.getArtifactId(), r.getArtifactId(), r.getGroupId(), r.version); - json.put(String.valueOf(r.id), url); - return json; - }).forEach(jsonArray::put); - var result = jsonArray.toString(); - return Responses.ok(result); - } - default: { - ObjectLinkedOpenHashSet deps = new ObjectLinkedOpenHashSet(); - coordinates.forEach(c -> { - var packageName = c.split(Constants.mvnCoordinateSeparator)[0]; - var packageVersion = c.split(Constants.mvnCoordinateSeparator)[1]; - var query = KnowledgeBaseConnector.dependencyResolverAddress+"/dependencies/"+packageName+"/"+packageVersion; - var requestResult = MavenUtilities.sendGetRequest(query); - var depList = new JSONArray(requestResult); - depList.forEach(item -> { - JSONObject obj = (JSONObject) item; - if (!deps.contains(obj.toString())) { - deps.add(obj.toString()); - } - }); + case Constants.mvnForge: { + var depSet = this.graphMavenResolver.resolveDependencies(coordinates); + var jsonArray = new JSONArray(); + depSet.stream().map(r -> { + var json = new JSONObject(); + var url = String.format("%smvn/%s/%s/%s_%s_%s.json", KnowledgeBaseConnector.rcgBaseUrl, r.getArtifactId().charAt(0), r.getArtifactId(), r.getArtifactId(), r.getGroupId(), r.version); + json.put(String.valueOf(r.id), url); + return json; + }).forEach(jsonArray::put); + var result = jsonArray.toString(); + return Responses.ok(result); + } + default: { + var deps = new ObjectLinkedOpenHashSet(); + coordinates.forEach(c -> { + var packageName = c.split(Constants.mvnCoordinateSeparator)[0]; + var packageVersion = c.split(Constants.mvnCoordinateSeparator)[1]; + var query = KnowledgeBaseConnector.dependencyResolverAddress + "/dependencies/" + packageName + "/" + packageVersion; + var requestResult = HttpUtils.sendGetRequest(query); + var depList = new JSONArray(requestResult); + depList.forEach(item -> { + JSONObject obj = (JSONObject) item; + if (!deps.contains(obj.toString())) { + deps.add(obj.toString()); + } }); + }); List result = new ArrayList(deps); return new ResponseEntity<>(result.toString(), HttpStatus.OK); - } + } } } @GetMapping(value = "/__INTERNAL__/packages/{pkg_version_id}/directedgraph", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity getDirectedGraph(@PathVariable("pkg_version_id") long packageVersionId, - @RequestParam(required = false, defaultValue = "false") boolean needStitching, - @RequestParam(required = false, defaultValue = "-1") long resolveAt) { + ResponseEntity getDirectedGraph(@PathVariable("pkg_version_id") long packageVersionId, @RequestParam(required = false, defaultValue = "false") boolean needStitching, + @RequestParam(required = false, defaultValue = "-1") long resolveAt) { DirectedGraph graph; if (needStitching) { var mavenCoordinate = KnowledgeBaseConnector.kbDao.getMavenCoordinate(packageVersionId); @@ -295,7 +287,7 @@ ResponseEntity getDirectedGraph(@PathVariable("pkg_version_id") long pac var artifactId = mavenCoordinate.split(Constants.mvnCoordinateSeparator)[1]; var version = mavenCoordinate.split(Constants.mvnCoordinateSeparator)[2]; var cfg = new ResolverConfig(); - if(resolveAt != -1) { + if (resolveAt != -1) { cfg.resolveAt = resolveAt; } var depSet = this.graphMavenResolver.resolveDependencies(groupId, artifactId, version, cfg); @@ -306,8 +298,7 @@ ResponseEntity getDirectedGraph(@PathVariable("pkg_version_id") long pac try { graph = KnowledgeBaseConnector.graphDao.getGraphData(packageVersionId); } catch (RocksDBException e) { - return new ResponseEntity<>("Could not retrieve callgraph from the graph database", - HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>("Could not retrieve callgraph from the graph database", HttpStatus.INTERNAL_SERVER_ERROR); } if (graph == null) { return new ResponseEntity<>("Callgraph not found in the graph database", HttpStatus.NOT_FOUND); @@ -317,7 +308,7 @@ ResponseEntity getDirectedGraph(@PathVariable("pkg_version_id") long pac var nodesJson = new JSONArray(); graph.nodes().stream().forEach(nodesJson::put); var edgesJson = new JSONArray(); - graph.edgeSet().stream().map(e -> new long[]{e.firstLong(), e.secondLong()}).forEach(edgesJson::put); + graph.edgeSet().stream().map(e -> new long[] { e.firstLong(), e.secondLong() }).forEach(edgesJson::put); json.put("nodes", nodesJson); json.put("edges", edgesJson); var result = json.toString(); diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApiTest.java index 31f664e1b..c334d7879 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/BinaryModuleApiTest.java @@ -18,17 +18,19 @@ package eu.fasten.analyzer.restapiplugin.api; -import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; -import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; + +import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; +import eu.fasten.analyzer.restapiplugin.RestApplication; +import eu.fasten.core.data.Constants; +import eu.fasten.core.data.metadatadb.MetadataDao; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; public class BinaryModuleApiTest { diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/CallableApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/CallableApiTest.java index 54e1ba988..0bacb35c0 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/CallableApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/CallableApiTest.java @@ -18,22 +18,26 @@ package eu.fasten.analyzer.restapiplugin.api; -import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; -import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +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.HashMap; +import java.util.List; + import org.json.JSONObject; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import java.util.HashMap; -import java.util.List; -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 eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; +import eu.fasten.analyzer.restapiplugin.RestApplication; +import eu.fasten.core.data.Constants; +import eu.fasten.core.data.metadatadb.MetadataDao; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; public class CallableApiTest { @@ -88,6 +92,7 @@ void getCallableMetadataPositiveTest() { } @Test + @Disabled(value = "Disabled, as the check is too expensive to perform directly in the server") void getCallableMetadataNegativeTest() { var packageName = "group:artifact"; var version = "version"; diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/DependencyApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/DependencyApiTest.java index b4d06ea08..cb21d965e 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/DependencyApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/DependencyApiTest.java @@ -18,12 +18,7 @@ package eu.fasten.analyzer.restapiplugin.api; -import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; -import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.analyzer.restapiplugin.api.DependencyApi; -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,7 +26,11 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; +import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; +import eu.fasten.analyzer.restapiplugin.RestApplication; +import eu.fasten.core.data.Constants; +import eu.fasten.core.data.metadatadb.MetadataDao; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; public class DependencyApiTest { diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/EdgeApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/EdgeApiTest.java index 6d072f15b..4a5ba3f54 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/EdgeApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/EdgeApiTest.java @@ -18,17 +18,19 @@ package eu.fasten.analyzer.restapiplugin.api; -import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; -import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; + +import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; +import eu.fasten.analyzer.restapiplugin.RestApplication; +import eu.fasten.core.data.Constants; +import eu.fasten.core.data.metadatadb.MetadataDao; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; public class EdgeApiTest { diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/FileApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/FileApiTest.java index 8ebe88407..0d693ffb9 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/FileApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/FileApiTest.java @@ -18,17 +18,19 @@ package eu.fasten.analyzer.restapiplugin.api; -import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; -import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; + +import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; +import eu.fasten.analyzer.restapiplugin.RestApplication; +import eu.fasten.core.data.Constants; +import eu.fasten.core.data.metadatadb.MetadataDao; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; public class FileApiTest { @@ -58,7 +60,7 @@ void getPackageFilesPositiveTest() { } @Test - void getPackageFilesIngestionTest(){ + void getPackageFilesIngestionTest() { var packageName = "junit:junit"; var version = "4.12"; Mockito.when(kbDao.getPackageFiles(packageName, version, offset, limit)).thenThrow(new PackageVersionNotFoundException("Error")); diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/ModuleApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/ModuleApiTest.java index 5e9693c53..7124d17ea 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/ModuleApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/ModuleApiTest.java @@ -18,17 +18,19 @@ package eu.fasten.analyzer.restapiplugin.api; -import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; -import eu.fasten.analyzer.restapiplugin.RestApplication; -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.metadatadb.MetadataDao; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; + +import eu.fasten.analyzer.restapiplugin.KnowledgeBaseConnector; +import eu.fasten.analyzer.restapiplugin.RestApplication; +import eu.fasten.core.data.Constants; +import eu.fasten.core.data.metadatadb.MetadataDao; +import eu.fasten.core.data.metadatadb.PackageVersionNotFoundException; public class ModuleApiTest { @@ -106,6 +108,7 @@ void getModuleMetadataIngestionTest() { Mockito.verify(kbDao, Mockito.times(1)).getModuleMetadata(packageName, version, module); } + @Test void getModuleFilesPositiveTest() { var packageName = "group:artifact"; diff --git a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/PackageApiTest.java b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/PackageApiTest.java index 3fdd58dc5..6b337ee39 100644 --- a/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/PackageApiTest.java +++ b/analyzer/restapi-plugin/src/test/java/eu/fasten/analyzer/restapiplugin/api/PackageApiTest.java @@ -212,7 +212,7 @@ void searchPackageNamesNegativeTest() { } @Test - @Disabled + @Disabled(value = "Server is inactive") void getERCGLinkPositiveTest() throws IOException { var packageName = "junit:junit"; var version = "4.12"; diff --git a/analyzer/vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPlugin.java b/analyzer/vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPlugin.java index d52413e73..fb08fb84a 100644 --- a/analyzer/vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPlugin.java +++ b/analyzer/vulnerability-cache-invalidation-plugin/src/main/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPlugin.java @@ -36,17 +36,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Revision; +import dev.c0ps.maven.data.Scope; +import dev.c0ps.maven.resolution.IMavenResolver; +import dev.c0ps.maven.resolution.MavenResolver; import eu.fasten.core.data.Constants; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.resolution.IMavenResolver; -import eu.fasten.core.maven.resolution.MavenResolver; +import eu.fasten.core.json.ToJson; import eu.fasten.core.maven.resolution.MavenResolverIO; -import eu.fasten.core.maven.utils.MavenUtilities; import eu.fasten.core.plugins.DataWriter; import eu.fasten.core.plugins.DependencyGraphUser; import eu.fasten.core.plugins.KafkaPlugin; +import eu.fasten.core.utils.FileUtils; public class VulnerabilityCacheInvalidationPlugin extends Plugin { public VulnerabilityCacheInvalidationPlugin(PluginWrapper wrapper) { @@ -207,7 +208,7 @@ public void consume(String record) { if (!outputFile.exists() || outputFile.length() == 0) continue; // TODO: possible optimization: we don't really need to delete the whole file, or do we? - MavenUtilities.forceDeleteFile(outputFile); + FileUtils.forceDeleteFile(outputFile); } } catch (RuntimeException e) { @@ -215,7 +216,7 @@ public void consume(String record) { setPluginError(new RuntimeException("Arbitrary exception raised", e)); } } - + @Override public Optional produce() { if (this.depSet == null) { @@ -223,7 +224,7 @@ public Optional produce() { } else { var jsonDepSet = new JSONArray(); // TODO: possible optimization: we don't really need to pass the whole revision. - depSet.stream().map(Revision::toJSON).forEach(jsonDepSet::put); + depSet.stream().map(ToJson::map).forEach(jsonDepSet::put); var json = new JSONObject(); json.put("artifacts", jsonDepSet); return Optional.of(json.toString()); diff --git a/analyzer/vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPluginTest.java b/analyzer/vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPluginTest.java index 98dcbead2..4888f9999 100644 --- a/analyzer/vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPluginTest.java +++ b/analyzer/vulnerability-cache-invalidation-plugin/src/test/java/eu/fasten/analyzer/vulnerabilitycacheinvalidationplugin/VulnerabilityCacheInvalidationPluginTest.java @@ -30,9 +30,9 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.resolution.MavenResolver; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Scope; +import dev.c0ps.maven.resolution.MavenResolver; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; public class VulnerabilityCacheInvalidationPluginTest { diff --git a/core/pom.xml b/core/pom.xml index 90f042575..26e85965e 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,9 +22,24 @@ dev.c0ps test-utils - 0.0.1 + 0.0.3 test + + dev.c0ps.io + impl + 0.0.2 + + + dev.c0ps + commons + 0.0.3 + + + dev.c0ps + commons-maven + 0.0.1 + org.pf4j pf4j @@ -225,23 +240,6 @@ 2.17.0 test - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-depchain - 3.1.4 - pom - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-impl-maven - - - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-impl-maven-patched - 3.1.4 - org.apache.maven maven-artifact diff --git a/core/src/main/java/eu/fasten/core/data/metadatadb/MetadataDao.java b/core/src/main/java/eu/fasten/core/data/metadatadb/MetadataDao.java index bd8dbb341..59bcfb51a 100644 --- a/core/src/main/java/eu/fasten/core/data/metadatadb/MetadataDao.java +++ b/core/src/main/java/eu/fasten/core/data/metadatadb/MetadataDao.java @@ -18,9 +18,45 @@ package eu.fasten.core.data.metadatadb; +import static org.jooq.impl.DSL.and; +import static org.jooq.impl.DSL.exists; +import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.trueCondition; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + +import org.apache.commons.math3.util.Pair; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.JSONFormat; +import org.jooq.Record; +import org.jooq.Record1; +import org.jooq.Record2; +import org.jooq.Result; +import org.jooq.SelectField; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.github.t9t.jooq.json.JsonbDSL; import com.google.gson.Gson; import com.google.gson.GsonBuilder; + +import dev.c0ps.maven.data.Revision; import eu.fasten.core.data.Constants; import eu.fasten.core.data.FastenCURI; import eu.fasten.core.data.FastenJavaURI; @@ -50,42 +86,8 @@ import eu.fasten.core.data.metadatadb.codegen.tables.VulnerabilitiesXPackageVersions; import eu.fasten.core.data.metadatadb.codegen.tables.records.CallSitesRecord; import eu.fasten.core.data.metadatadb.codegen.tables.records.CallablesRecord; -import eu.fasten.core.maven.data.PackageVersionNotFoundException; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; import eu.fasten.core.utils.FastenUriUtils; -import org.apache.commons.math3.util.Pair; -import org.jooq.Condition; -import org.jooq.DSLContext; -import org.jooq.JSONB; -import org.jooq.JSONFormat; -import org.jooq.Record; -import org.jooq.Record1; -import org.jooq.Record2; -import org.jooq.Result; -import org.jooq.SelectField; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.Nullable; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.jooq.impl.DSL.and; -import static org.jooq.impl.DSL.exists; -import static org.jooq.impl.DSL.field; -import static org.jooq.impl.DSL.trueCondition; public class MetadataDao { @@ -249,7 +251,7 @@ public String insertPackageOutboundLicenses(String groupId, String packageVersion, String outboundLicenses) { return insertPackageOutboundLicenses( - MavenUtilities.getMavenCoordinateName(groupId, artifactId), + getMavenCoordinateName(groupId, artifactId), packageVersion, outboundLicenses); } @@ -331,11 +333,24 @@ public String insertFileLicenses(String groupId, String filePath, String fileLicenses) { return insertFileLicenses( - MavenUtilities.getMavenCoordinateName(groupId, artifactId), + getMavenCoordinateName(groupId, artifactId), packageVersion, filePath, fileLicenses); } + + /** + * Pretty-prints Maven coordinates. + * + * @param groupId the maven coordinate's group ID. + * @param artifactId the maven coordinate's artifact ID. + * @return a pretty String representation of the input Maven coordinate. + */ + private static String getMavenCoordinateName(String groupId, String artifactId) { + return groupId + + (artifactId == null || artifactId.compareTo("") == 0 ? + "" : ":" + artifactId); + } /** * Inserts scanned licenses at the file level. diff --git a/core/src/main/java/eu/fasten/core/maven/data/PackageVersionNotFoundException.java b/core/src/main/java/eu/fasten/core/data/metadatadb/PackageVersionNotFoundException.java similarity index 95% rename from core/src/main/java/eu/fasten/core/maven/data/PackageVersionNotFoundException.java rename to core/src/main/java/eu/fasten/core/data/metadatadb/PackageVersionNotFoundException.java index b7f1248d3..9d598c058 100644 --- a/core/src/main/java/eu/fasten/core/maven/data/PackageVersionNotFoundException.java +++ b/core/src/main/java/eu/fasten/core/data/metadatadb/PackageVersionNotFoundException.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package eu.fasten.core.maven.data; +package eu.fasten.core.data.metadatadb; public class PackageVersionNotFoundException extends RuntimeException { diff --git a/core/src/main/java/eu/fasten/core/data/opal/MavenArtifactDownloader.java b/core/src/main/java/eu/fasten/core/data/opal/MavenArtifactDownloader.java index e9582949a..5d40e6f85 100644 --- a/core/src/main/java/eu/fasten/core/data/opal/MavenArtifactDownloader.java +++ b/core/src/main/java/eu/fasten/core/data/opal/MavenArtifactDownloader.java @@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory; import eu.fasten.core.data.opal.exceptions.MissingArtifactException; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; /** * A set of methods for downloading POM and JAR files given Maven coordinates. diff --git a/core/src/main/java/eu/fasten/core/data/opal/MavenCoordinate.java b/core/src/main/java/eu/fasten/core/data/opal/MavenCoordinate.java index 6933563b4..b278ad375 100644 --- a/core/src/main/java/eu/fasten/core/data/opal/MavenCoordinate.java +++ b/core/src/main/java/eu/fasten/core/data/opal/MavenCoordinate.java @@ -15,7 +15,7 @@ */ package eu.fasten.core.data.opal; -import static eu.fasten.core.maven.utils.MavenUtilities.MAVEN_CENTRAL_REPO; +import static dev.c0ps.maven.MavenUtilities.MAVEN_CENTRAL_REPO; import java.util.LinkedList; import java.util.List; @@ -24,7 +24,7 @@ import org.json.JSONObject; import eu.fasten.core.data.Constants; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; /** * Maven coordinate as g:a:v e.g. "com.google.guava:guava:jar:28.1-jre". @@ -72,7 +72,7 @@ public String getPackaging() { */ public MavenCoordinate(final String groupID, final String artifactID, final String version, final String packaging) { - this.mavenRepos = MavenUtilities.getRepos(); + this.mavenRepos = List.of(MavenUtilities.MAVEN_CENTRAL_REPO); this.groupID = groupID; this.artifactID = artifactID; this.versionConstraint = version; @@ -109,7 +109,7 @@ public MavenCoordinate(final JSONObject json) throws JSONException { mavenRepos = List.of(repo); } else { // this is really bad handling. Either we know the repo, or we won't find it - mavenRepos = MavenUtilities.getRepos(); + mavenRepos = List.of(MavenUtilities.MAVEN_CENTRAL_REPO); } this.groupID = json.getString("groupId"); this.artifactID = json.getString("artifactId"); diff --git a/core/src/main/java/eu/fasten/core/dynamic/CombinerEvaluator.java b/core/src/main/java/eu/fasten/core/dynamic/CombinerEvaluator.java index 7d03c5520..d0464e5be 100644 --- a/core/src/main/java/eu/fasten/core/dynamic/CombinerEvaluator.java +++ b/core/src/main/java/eu/fasten/core/dynamic/CombinerEvaluator.java @@ -18,17 +18,6 @@ package eu.fasten.core.dynamic; -import eu.fasten.core.data.PartialJavaCallGraph; -import eu.fasten.core.data.MergedDirectedGraph; -import eu.fasten.core.dynamic.data.DynamicJavaCG; -import eu.fasten.core.data.HybridDirectedGraph; -import eu.fasten.core.maven.utils.MavenUtilities; -import eu.fasten.core.merge.CGMerger; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -39,6 +28,19 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import eu.fasten.core.data.HybridDirectedGraph; +import eu.fasten.core.data.MergedDirectedGraph; +import eu.fasten.core.data.PartialJavaCallGraph; +import eu.fasten.core.dynamic.data.DynamicJavaCG; +import eu.fasten.core.merge.CGMerger; +import eu.fasten.core.utils.FileUtils; +import picocli.CommandLine; + @CommandLine.Command(name = "CombinerEvaluator") public class CombinerEvaluator implements Runnable { @@ -117,7 +119,7 @@ public void run() { logger.error("Could not read dynamic CG file", e); return; } - MavenUtilities.forceDeleteFile(dynamicCgPath.toFile()); + FileUtils.forceDeleteFile(dynamicCgPath.toFile()); logger.info("Dynamic CG has {} nodes and {} edges", dynamicCg.getMethods().size(), dynamicCg.getCalls().size()); logger.info("Combining dynamic CG and stitched static CG"); diff --git a/core/src/main/java/eu/fasten/core/json/CoreMavenDataModule.java b/core/src/main/java/eu/fasten/core/json/CoreMavenDataModule.java deleted file mode 100644 index 272a91e1d..000000000 --- a/core/src/main/java/eu/fasten/core/json/CoreMavenDataModule.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.json; - -import java.io.IOException; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Supplier; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JacksonException; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import eu.fasten.core.data.collections.ImmutableEmptyLinkedHashSet; -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.Exclusion; -import eu.fasten.core.maven.data.Ids; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.data.VersionConstraint; - -public class CoreMavenDataModule extends SimpleModule { - - private static final Logger LOG = LoggerFactory.getLogger(CoreMavenDataModule.class.getName()); - - private static final Set NO_EXCLS = Set.of(); - private static final Set NO_VCS = Set.of(); - private static final String EMPTY_STR = ""; - private static final String JAR = "jar"; - - // TODO remove old handling once pipeline has been restarted - private static final String OLD_VERSION_CONSTRAINTS = "versionConstraints"; - private static final String OLD_GROUP_ID = "groupId"; - private static final String OLD_ARTIFACT_ID = "artifactId"; - private static final String VERSION_CONSTRAINTS = "v"; - private static final String GROUP_ID = "g"; - private static final String ARTIFACT_ID = "a"; - - private static final long serialVersionUID = 8302574258846915634L; - - public CoreMavenDataModule() { - - addDeserializer(Pom.class, new PomDeserializer()); - - addSerializer(Dependency.class, new JsonSerializer() { - @Override - public void serialize(Dependency value, JsonGenerator gen, SerializerProvider serializers) - throws IOException { - gen.writeStartObject(); - - gen.writeStringField(ARTIFACT_ID, value.artifactId); - if (value.getClassifier() != null && !value.getClassifier().isEmpty()) { - gen.writeStringField("classifier", value.getClassifier()); - } - if (value.getExclusions() != null && !value.getExclusions().isEmpty()) { - gen.writeObjectField("exclusions", value.getExclusions()); - } - gen.writeStringField(GROUP_ID, value.groupId); - if (value.isOptional()) { - gen.writeBooleanField("optional", value.isOptional()); - } - if (value.getScope() != Scope.COMPILE) { - gen.writeStringField("scope", value.getScope().toString().toLowerCase()); - } - if (value.getPackagingType() != null && !JAR.equals(value.getPackagingType())) { - gen.writeStringField("type", value.getPackagingType()); - } - gen.writeObjectField(VERSION_CONSTRAINTS, value.getVersionConstraints()); - - gen.writeEndObject(); - } - }); - addDeserializer(Dependency.class, new DependencyDeserializer()); - - addSerializer(VersionConstraint.class, new JsonSerializer() { - @Override - public void serialize(VersionConstraint value, JsonGenerator gen, SerializerProvider serializers) - throws IOException { - gen.writeString(value.getSpec()); - } - }); - addDeserializer(VersionConstraint.class, new JsonDeserializer() { - @Override - public VersionConstraint deserialize(JsonParser p, DeserializationContext ctxt) - throws IOException, JacksonException { - return new VersionConstraint(p.getValueAsString()); - } - }); - - addSerializer(Exclusion.class, new JsonSerializer() { - @Override - public void serialize(Exclusion value, JsonGenerator gen, SerializerProvider serializers) - throws IOException { - gen.writeString(String.format("%s:%s", value.groupId, value.artifactId)); - } - }); - addDeserializer(Exclusion.class, new JsonDeserializer() { - @Override - public Exclusion deserialize(JsonParser p, DeserializationContext ctxt) - throws IOException, JacksonException { - String[] parts = p.getValueAsString().split(":"); - return new Exclusion(parts[0], parts[1]); - } - }); - - addSerializer(DefaultArtifactVersion.class, new JsonSerializer() { - @Override - public void serialize(DefaultArtifactVersion value, JsonGenerator gen, SerializerProvider serializers) - throws IOException { - gen.writeString(value.toString()); - } - }); - addDeserializer(DefaultArtifactVersion.class, new JsonDeserializer() { - @Override - public DefaultArtifactVersion deserialize(JsonParser p, DeserializationContext ctxt) - throws IOException, JacksonException { - var version = Ids.version(p.getValueAsString()); - return new DefaultArtifactVersion(version); - } - }); - } - - private static class PomDeserializer extends JsonDeserializer { - - private static final LinkedHashSet NO_DEPS = new ImmutableEmptyLinkedHashSet<>(); - private static final Set NO_DEP_MGMT = Set.of(); - - @Override - public Pom deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException { - var node = readNode(p); - var pb = new PomBuilder(); - - pb.groupId = getText(node, "groupId", null); - pb.artifactId = getText(node, "artifactId", null); - pb.packagingType = getText(node, "packagingType", null); - pb.version = getText(node, "version", null); - - pb.parentCoordinate = getText(node, "parentCoordinate", null); - - pb.releaseDate = getLong(node, "releaseDate", -1L); - pb.projectName = getText(node, "projectName", null); - - pb.dependencies = addChildren(node, p, "dependencies", () -> new LinkedHashSet(), NO_DEPS); - pb.dependencyManagement = addChildren(node, p, "dependencyManagement", () -> new HashSet(), - NO_DEP_MGMT); - - pb.repoUrl = getText(node, "repoUrl", null); - pb.commitTag = getText(node, "commitTag", null); - pb.sourcesUrl = getText(node, "sourcesUrl", null); - pb.artifactRepository = getText(node, "artifactRepository", null); - - return pb.pom(); - } - } - - private static class DependencyDeserializer extends JsonDeserializer { - - @Override - public Dependency deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException { - var node = readNode(p); - - var isShortFormat = node.has(ARTIFACT_ID); - var a = getText(node, isShortFormat ? ARTIFACT_ID : OLD_ARTIFACT_ID, EMPTY_STR); - var g = getText(node, isShortFormat ? GROUP_ID : OLD_GROUP_ID, EMPTY_STR); - - var c = getText(node, "classifier", EMPTY_STR); - - var es = readExclusions(ctxt, node); - - var o = getBool(node, "optional", false); - var s = getScope(node, "scope", Scope.COMPILE); - - var t = getText(node, "type", JAR); - - var vs = readVersionConstraints(isShortFormat, ctxt, node); - - return Ids.dep(new Dependency(g, a, vs, es, s, o, t, c)); - } - } - - private static Set readVersionConstraints(boolean isShortFormat, DeserializationContext ctxt, - JsonNode node) { - var vcs = isShortFormat ? node.get(VERSION_CONSTRAINTS) : node.get(OLD_VERSION_CONSTRAINTS); - if (vcs != null && !vcs.isEmpty()) { - var res = new HashSet(vcs.size() + 1, 1); - for (var vc : vcs) { - var val = vc.textValue(); - if (val == null || val.isEmpty()) { - // TODO handling unnecessary after next pipeline restart - continue; - } - var v = Ids.versionConstraint(new VersionConstraint(val)); - if (!v.getSpec().isEmpty()) { - res.add(v); - } - } - // TODO remove as well (handling necessary to capture fix) - if (res.isEmpty()) { - return NO_VCS; - } - return res; - } - return NO_VCS; - } - - private static Set readExclusions(DeserializationContext ctxt, JsonNode node) { - var exclusions = node.get("exclusions"); - if (exclusions != null && !exclusions.isEmpty()) { - var es = new HashSet(exclusions.size() + 1, 1); - for (var exclusion : exclusions) { - var parts = exclusion.textValue().split(":", -1); - if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) { - es.add(new Exclusion(parts[0], parts[1])); - } else { - var msg = "Skipping deserialization of invalid '{}' in '{}': {}"; - LOG.error(msg, Exclusion.class.getSimpleName(), Dependency.class.getSimpleName(), node); - } - } - return es; - } - return NO_EXCLS; - } - - private static String getText(JsonNode node, String key, String defaultVal) { - var val = node.get(key); - return val != null ? val.textValue() : defaultVal; - } - - private static Scope getScope(JsonNode node, String key, Scope defaultVal) { - var val = node.get(key); - return val != null ? Scope.valueOf(val.textValue().toUpperCase()) : defaultVal; - } - - private static boolean getBool(JsonNode node, String key, boolean defaultVal) { - var val = node.get(key); - return val != null ? val.booleanValue() : defaultVal; - } - - private static long getLong(JsonNode node, String key, long defaultVal) { - var val = node.get(key); - return val != null ? val.longValue() : defaultVal; - } - - private static ObjectNode readNode(JsonParser p) throws IOException { - return (ObjectNode) p.getCodec().readTree(p); - } - - private static > CollectionT addChildren(JsonNode node, JsonParser p, - String key, Supplier prod, CollectionT defaultVal) throws JsonProcessingException { - var vals = node.get(key); - if (vals != null && !vals.isEmpty()) { - var ts = prod.get(); - for (var val : vals) { - var t = p.getCodec().treeToValue(val, Dependency.class); - ts.add(Ids.dep(t)); - } - return ts; - } - return defaultVal; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolutionException.java b/core/src/main/java/eu/fasten/core/json/FastenObjectMapperBuilder.java similarity index 61% rename from core/src/main/java/eu/fasten/core/maven/resolution/MavenResolutionException.java rename to core/src/main/java/eu/fasten/core/json/FastenObjectMapperBuilder.java index 80b87687c..6f6cb447b 100644 --- a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolutionException.java +++ b/core/src/main/java/eu/fasten/core/json/FastenObjectMapperBuilder.java @@ -13,17 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package eu.fasten.core.maven.resolution; +package eu.fasten.core.json; -public class MavenResolutionException extends RuntimeException { +import com.fasterxml.jackson.databind.ObjectMapper; - private static final long serialVersionUID = -1367745687408328330L; +import dev.c0ps.io.ObjectMapperBuilder; +import dev.c0ps.maven.json.CommonsMavenDataModule; - public MavenResolutionException() { - super(); - } +public class FastenObjectMapperBuilder extends ObjectMapperBuilder { - public MavenResolutionException(String message) { - super(message); + @Override + public ObjectMapper build() { + var om = super.build(); + om.registerModule(new CommonsMavenDataModule()); + return om; } } \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/json/ObjectMapperBuilder.java b/core/src/main/java/eu/fasten/core/json/ObjectMapperBuilder.java deleted file mode 100644 index 2d5fc696f..000000000 --- a/core/src/main/java/eu/fasten/core/json/ObjectMapperBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.json; - -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.json.JsonMapper; -import com.fasterxml.jackson.databind.json.JsonMapper.Builder; -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; - -public class ObjectMapperBuilder { - - public ObjectMapper build() { - var builder = JsonMapper.builder() // - .disable(MapperFeature.AUTO_DETECT_GETTERS) // - .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) // - .disable(JsonParser.Feature.AUTO_CLOSE_SOURCE) // - .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); - - var omPre = addBuilderOptions(builder).build() // - .setVisibility(PropertyAccessor.ALL, Visibility.ANY) // - .setSerializationInclusion(Include.NON_NULL); - - var om = addMapperOptions(omPre); - - om.registerModule(new ParameterNamesModule()); - om.registerModule(new Jdk8Module()); - om.registerModule(new JavaTimeModule()); - - om.registerModule(new CoreMavenDataModule()); - - return om; - } - - /** - * allow additional builder options in subclasses , e.g., for testing - */ - protected Builder addBuilderOptions(Builder b) { - return b; - } - - /** - * allow additional mapper options in subclasses , e.g., for testing - */ - protected ObjectMapper addMapperOptions(ObjectMapper om) { - return om; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/Scope.java b/core/src/main/java/eu/fasten/core/json/ToJson.java similarity index 57% rename from core/src/main/java/eu/fasten/core/maven/data/Scope.java rename to core/src/main/java/eu/fasten/core/json/ToJson.java index ef83d9c76..2ef7a58b9 100644 --- a/core/src/main/java/eu/fasten/core/maven/data/Scope.java +++ b/core/src/main/java/eu/fasten/core/json/ToJson.java @@ -13,16 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package eu.fasten.core.maven.data; +package eu.fasten.core.json; -/** - * Maven's scopes for dependencies. Learn more: http://maven.apache.org/pom.html - */ -public enum Scope { - COMPILE, - PROVIDED, - RUNTIME, - TEST, - SYSTEM, - IMPORT; +import org.json.JSONObject; + +import dev.c0ps.maven.data.Revision; + +public class ToJson { + + public static JSONObject map(Revision r) { + var json = new JSONObject(); + json.put("id", r.id); + json.put("groupId", r.getGroupId()); + json.put("artifactId", r.getArtifactId()); + json.put("version", r.version.toString()); + json.put("createdAt", r.createdAt.getTime()); + return json; + } } \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/Dependency.java b/core/src/main/java/eu/fasten/core/maven/data/Dependency.java deleted file mode 100644 index 7d15d90b7..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/Dependency.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static eu.fasten.core.maven.data.Scope.COMPILE; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.json.JSONArray; -import org.json.JSONObject; - -import eu.fasten.core.data.Constants; - -public class Dependency { - - private static final String JAR = "jar"; - private static final Set NO_EXCLS = Set.of(); - private static final String EMPTY_STR = ""; - - public final String groupId; - public final String artifactId; - public final boolean optional; - - private final String classifier; - private final Scope scope; - private final String type; - - private final VersionConstraint versionConstraint; - private final Set versionConstraints; - private final Set exclusions; - - private final GA ga; - - private final int hashCode; - - public Dependency(String groupId, String artifactId, String version) { - this(groupId, artifactId, VersionConstraint.parseVersionSpec(version), Set.of(), Scope.COMPILE, false, JAR, ""); - } - - public Dependency(String groupId, String artifactId, Set versionConstraints, - Set exclusions, Scope scope, boolean optional, String type, String classifier) { - - this.groupId = Ids.gid(groupId); - this.artifactId = Ids.aid(artifactId); - this.optional = optional; - - if (classifier != null && !classifier.isEmpty()) { - this.classifier = classifier.toLowerCase(); - } else { - this.classifier = null; - } - if (scope != COMPILE) { - this.scope = scope; - } else { - this.scope = null; - } - if (type != null && !type.isEmpty() && !JAR.equals(type)) { - this.type = type.toLowerCase(); - } else { - this.type = null; - } - - if (versionConstraints.size() == 1) { - this.versionConstraint = versionConstraints.iterator().next(); - this.versionConstraints = null; - } else { - this.versionConstraint = null; - this.versionConstraints = Set.copyOf(versionConstraints); - } - - if (exclusions.isEmpty()) { - this.exclusions = NO_EXCLS; - } else { - this.exclusions = Set.copyOf(exclusions); - } - - this.ga = Ids.ga(new GA(groupId, artifactId)); - - hashCode = calcHashCode(); - } - - public GA toGA() { - return ga; - } - - public Set getVersionConstraints() { - if (versionConstraints == null) { - return Set.of(versionConstraint); - } - return versionConstraints; - } - - public Set getExclusions() { - return exclusions; - } - - public Scope getScope() { - if (scope == null) { - return COMPILE; - } - return scope; - } - - public boolean isOptional() { - return optional; - } - - public String getPackagingType() { - if (type == null) { - return JAR; - } - return type; - } - - public String getClassifier() { - if (classifier == null) { - return EMPTY_STR; - } - return classifier; - } - - @Deprecated - public String[] getVersionConstraintsArr() { - var constraints = new String[getVersionConstraints().size()]; - var i = new int[] { 0 }; - getVersionConstraints().forEach(vc -> { - constraints[i[0]++] = vc.getSpec(); - }); - return constraints; - } - - @Deprecated - public String getVersion() { - return String.join(",", this.getVersionConstraintsArr()); - } - - @Override - public int hashCode() { - return hashCode; - } - - private int calcHashCode() { - final var prime = 31; - var hashCode = 0; - hashCode = prime * hashCode + ((groupId == null) ? 0 : groupId.hashCode()); - hashCode = prime * hashCode + ((artifactId == null) ? 0 : artifactId.hashCode()); - hashCode = prime * hashCode + (optional ? 1231 : 1237); - - hashCode = prime * hashCode + ((classifier == null) ? 0 : classifier.hashCode()); - hashCode = prime * hashCode + ((scope == null) ? 0 : scope.hashCode()); - hashCode = prime * hashCode + ((type == null) ? 0 : type.hashCode()); - - hashCode = prime * hashCode + ((versionConstraint == null) ? 0 : versionConstraint.hashCode()); - hashCode = prime * hashCode + ((versionConstraints == null) ? 0 : versionConstraints.hashCode()); - hashCode = prime * hashCode + ((exclusions == null) ? 0 : exclusions.hashCode()); - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Dependency other = (Dependency) obj; - if (hashCode != other.hashCode) { - return false; - } - if (artifactId == null) { - if (other.artifactId != null) - return false; - } else if (!artifactId.equals(other.artifactId)) - return false; - if (classifier == null) { - if (other.classifier != null) - return false; - } else if (!classifier.equals(other.classifier)) - return false; - if (exclusions == null) { - if (other.exclusions != null) - return false; - } else if (!exclusions.equals(other.exclusions)) - return false; - if (ga == null) { - if (other.ga != null) - return false; - } else if (!ga.equals(other.ga)) - return false; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - if (optional != other.optional) - return false; - if (scope != other.scope) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - if (versionConstraint == null) { - if (other.versionConstraint != null) - return false; - } else if (!versionConstraint.equals(other.versionConstraint)) - return false; - if (versionConstraints == null) { - if (other.versionConstraints != null) - return false; - } else if (!versionConstraints.equals(other.versionConstraints)) - return false; - return true; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } - - // TODO delete everything below - - @Deprecated - public String toCanonicalForm() { - var builder = new StringBuilder(); - builder.append(this.groupId); - builder.append(Constants.mvnCoordinateSeparator); - builder.append(this.artifactId); - builder.append(Constants.mvnCoordinateSeparator); - if (!this.type.isEmpty()) { - builder.append(this.type); - builder.append(Constants.mvnCoordinateSeparator); - } - if (!this.classifier.isEmpty()) { - builder.append(this.classifier); - builder.append(Constants.mvnCoordinateSeparator); - } - builder.append(this.getVersion()); - return builder.toString(); - } - - @Deprecated - public String toMavenCoordinate() { - return this.groupId + Constants.mvnCoordinateSeparator + this.artifactId + Constants.mvnCoordinateSeparator - + this.getVersion(); - } - - @Deprecated - public String toFullCanonicalForm() { - var builder = new StringBuilder(); - builder.append(this.groupId); - builder.append(Constants.mvnCoordinateSeparator); - builder.append(this.artifactId); - builder.append(Constants.mvnCoordinateSeparator); - if (!this.type.isEmpty()) { - builder.append(this.type); - } else { - builder.append("jar"); - } - builder.append(Constants.mvnCoordinateSeparator); - if (!this.classifier.isEmpty()) { - builder.append(this.classifier); - builder.append(Constants.mvnCoordinateSeparator); - } - builder.append(this.getVersion()); - builder.append(Constants.mvnCoordinateSeparator); - builder.append(this.scope); - return builder.toString(); - } - - @Deprecated // see eu.fasten.core.json.CoreMavenDataModule - public JSONObject toJSON() { - final var json = new JSONObject(); - json.put("artifactId", this.artifactId); - json.put("groupId", this.groupId); - final var constraintsJson = new JSONArray(); - for (var constraint : this.getVersionConstraints()) { - constraintsJson.put(constraint.getSpec()); - } - json.put("versionConstraints", constraintsJson); - final var exclusionsJson = new JSONArray(); - for (var exclusion : this.getExclusions()) { - exclusionsJson.put(exclusion.toJSON()); - } - json.put("exclusions", exclusionsJson); - json.put("scope", this.scope); - json.put("optional", this.optional); - json.put("type", this.type); - json.put("classifier", this.classifier); - return json; - } - - @Deprecated // see eu.fasten.core.json.CoreMavenDataModule - public static Dependency fromJSON(JSONObject json) { - var artifactId = json.getString("artifactId"); - var groupId = json.getString("groupId"); - var versionConstraints = new HashSet(); - if (json.has("versionConstraints")) { - json.getJSONArray("versionConstraints").forEach(s -> { - versionConstraints.add(new VersionConstraint((String) s)); - }); - } - var exclusions = new HashSet(); - if (json.has("exclusions")) { - var exclusionsJson = json.getJSONArray("exclusions"); - for (var i = 0; i < exclusionsJson.length(); i++) { - var exclJson = exclusionsJson.getString(i); - exclusions.add(Exclusion.fromJSON(exclJson)); - } - } - Scope scope; - var scopeStr = json.optString("scope").strip(); - if (scopeStr == null || scopeStr.isEmpty()) { - scope = Scope.COMPILE; - } else { - scope = Scope.valueOf(scopeStr.toUpperCase()); - } - var optional = json.optBoolean("optional", false); - var type = json.optString("type"); - var classifier = json.optString("classifier"); - return new Dependency(groupId, artifactId, versionConstraints, exclusions, scope, optional, type, classifier); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/Exclusion.java b/core/src/main/java/eu/fasten/core/maven/data/Exclusion.java deleted file mode 100644 index 950f7e934..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/Exclusion.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import java.io.Serializable; - -public class Exclusion implements Serializable { - - private static final long serialVersionUID = -1350444195222504726L; - - public final String artifactId; - public final String groupId; - private final int hashCode; - - public Exclusion(String groupId, String artifactId) { - this.groupId = Ids.gid(groupId); - this.artifactId = Ids.aid(artifactId); - this.hashCode = calcHashCode(); - } - - public int calcHashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - return result; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Exclusion other = (Exclusion) obj; - if (hashCode != other.hashCode) { - return false; - } - if (artifactId == null) { - if (other.artifactId != null) - return false; - } else if (!artifactId.equals(other.artifactId)) - return false; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - return true; - } - - @Override - public String toString() { - return String.format("%s:%s", groupId, artifactId); - } - - // TODO remove everything below - - @Deprecated - public String toJSON() { - return String.format("%s:%s", groupId, artifactId); - } - - @Deprecated - public static Exclusion fromJSON(String json) { - String[] parts = json.split(":"); - return new Exclusion(parts[0], parts[1]); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/GA.java b/core/src/main/java/eu/fasten/core/maven/data/GA.java deleted file mode 100644 index 4a837952c..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/GA.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import eu.fasten.core.data.Constants; - -public class GA { - - public final String groupId; - public final String artifactId; - - private final int hashCode; - - public GA(String groupId, String artifactId) { - this.groupId = groupId; - this.artifactId = artifactId; - this.hashCode = getHashCode(); - } - - private int getHashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - return result; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - GA other = (GA) obj; - if (hashCode != other.hashCode) { - return false; - } - if (artifactId == null) { - if (other.artifactId != null) - return false; - } else if (!artifactId.equals(other.artifactId)) - return false; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - return true; - } - - @Override - public String toString() { - return groupId + Constants.mvnCoordinateSeparator + artifactId; - } - - public static GA fromString(String product) throws IllegalArgumentException { - var parts = product.split(Constants.mvnCoordinateSeparator); - if (parts.length < 2) { - throw new IllegalArgumentException(product + " is not a valid Maven groupId:artifactId string"); - } - else { - return new GA(parts[0], parts[1]); - } - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/GAV.java b/core/src/main/java/eu/fasten/core/maven/data/GAV.java deleted file mode 100644 index 533a22f96..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/GAV.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -public class GAV { - - public final String groupId; - public final String artifactId; - public final String version; - - private final int hashCode; - - public GAV(String groupId, String artifactId, String version) { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - this.hashCode = getHashCode(); - } - - public int getHashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - GAV other = (GAV) obj; - if (hashCode != other.hashCode) { - return false; - } - if (artifactId == null) { - if (other.artifactId != null) - return false; - } else if (!artifactId.equals(other.artifactId)) - return false; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - @Override - public String toString() { - return new StringBuilder().append(groupId).append(':').append(artifactId).append(':').append(version) - .toString(); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/Ids.java b/core/src/main/java/eu/fasten/core/maven/data/Ids.java deleted file mode 100644 index b4b3828fc..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/Ids.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import java.util.HashMap; -import java.util.Map; - -public class Ids { - - private static final Map GIDS = new HashMap<>(); - private static final Map AIDS = new HashMap<>(); - private static final Map VERSIONS = new HashMap<>(); - private static final Map VCS = new HashMap<>(); - private static final Map DEPS = new HashMap<>(); - private static final Map GAVS = new HashMap<>(); - private static final Map GAS = new HashMap<>(); - - public static String gid(String gid) { - if (GIDS.containsKey(gid)) { - return GIDS.get(gid); - } else { - GIDS.put(gid, gid); - return gid; - } - } - - public static String aid(String aid) { - if (AIDS.containsKey(aid)) { - return AIDS.get(aid); - } else { - AIDS.put(aid, aid); - return aid; - } - } - - public static String version(String version) { - if (VERSIONS.containsKey(version)) { - return VERSIONS.get(version); - } else { - VERSIONS.put(version, version); - return version; - } - } - - public static Dependency dep(Dependency d) { - if (DEPS.containsKey(d)) { - return DEPS.get(d); - } else { - DEPS.put(d, d); - return d; - } - } - - public static GA ga(GA ga) { - if (GAS.containsKey(ga)) { - return GAS.get(ga); - } else { - GAS.put(ga, ga); - return ga; - } - } - - public static GAV gav(GAV gav) { - if (GAVS.containsKey(gav)) { - return GAVS.get(gav); - } else { - GAVS.put(gav, gav); - return gav; - } - } - - public static VersionConstraint versionConstraint(VersionConstraint vc) { - if (VCS.containsKey(vc)) { - return VCS.get(vc); - } else { - VCS.put(vc, vc); - return vc; - } - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/MavenProduct.java b/core/src/main/java/eu/fasten/core/maven/data/MavenProduct.java deleted file mode 100644 index a782694b1..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/MavenProduct.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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 eu.fasten.core.maven.data; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * A versionless Maven artifact - */ -public class MavenProduct { - - public long id; - - protected String groupId; - protected String artifactId; - - public MavenProduct() {} - - public MavenProduct(final String groupId, final String artifactId) { - this.id = 0; - this.groupId = groupId; - this.artifactId = artifactId; - } - - public MavenProduct(long id, String groupId, String artifactId) { - this.id = id; - this.groupId = groupId; - this.artifactId = artifactId; - } - - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public String getArtifactId() { - return artifactId; - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MavenProduct other = (MavenProduct) obj; - if (artifactId == null) { - if (other.artifactId != null) - return false; - } else if (!artifactId.equals(other.artifactId)) - return false; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - return true; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/Pom.java b/core/src/main/java/eu/fasten/core/maven/data/Pom.java deleted file mode 100644 index 1adc7d39a..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/Pom.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.apache.commons.lang3.builder.ToStringStyle.MULTI_LINE_STYLE; - -import java.sql.Timestamp; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.apache.commons.lang3.builder.ToStringBuilder; - -import eu.fasten.core.data.Constants; -import eu.fasten.core.data.collections.ImmutableEmptyLinkedHashSet; - -public class Pom { - - private static final LinkedHashSet NO_DEPS = new ImmutableEmptyLinkedHashSet<>(); - private static final Set NO_DEPMGMT = Set.of(); - - public transient long id; - - public final String forge = Constants.mvnForge; - - public final String artifactId; - public final String groupId; - public final String packagingType; - public final String version; - - // g:a:packaging:version - public final String parentCoordinate; - - public final long releaseDate; - public final String projectName; - - public final Set dependencies; - public final Set dependencyManagement; - - public final String repoUrl; - public final String commitTag; - public final String sourcesUrl; - public final String artifactRepository; - - private transient final int hashCode; - private transient final GAV gav; - private transient final GA ga; - - // use LinkedHashSet for dependencies, because order is relevant for resolution - public Pom(String groupId, String artifactId, String packagingType, String version, String parentCoordinate, - long releaseDate, String projectName, LinkedHashSet dependencies, - Set dependencyManagement, String repoUrl, String commitTag, String sourcesUrl, - String artifactRepository) { - this.groupId = Ids.gid(groupId); - this.artifactId = Ids.aid(artifactId); - this.packagingType = packagingType; - this.version = Ids.version(version); - - this.parentCoordinate = parentCoordinate; - - this.releaseDate = releaseDate; - this.projectName = projectName; - - if (dependencies == null || dependencies.isEmpty()) { - this.dependencies = NO_DEPS; - } else { - // TODO check for (and prevent) "double wrapping" - this.dependencies = Collections.unmodifiableSet(dependencies); - } - - if (dependencyManagement == null || dependencyManagement.isEmpty()) { - this.dependencyManagement = NO_DEPMGMT; - } else { - // TODO check for (and prevent) "double wrapping" - this.dependencyManagement = Collections.unmodifiableSet(dependencyManagement); - } - - this.repoUrl = repoUrl; - this.commitTag = commitTag; - this.sourcesUrl = sourcesUrl; - this.artifactRepository = artifactRepository; - - hashCode = getHashCode(); - - gav = Ids.gav(new GAV(groupId, artifactId, version)); - ga = Ids.ga(new GA(groupId, artifactId)); - } - - /** gid:aid:packaging:version */ - public String toCoordinate() { - return new StringBuilder().append(groupId).append(':').append(artifactId).append(':').append(packagingType) - .append(':').append(version).toString(); - } - - public GAV toGAV() { - return gav; - } - - public GA toGA() { - return ga; - } - - public MavenProduct toProduct() { - return new MavenProduct(id, groupId, artifactId); - } - - public Revision toRevision() { - return new Revision(id, groupId, artifactId, version, new Timestamp(releaseDate)); - } - - public PomBuilder clone() { - var clone = new PomBuilder(); - - clone.artifactId = artifactId; - clone.groupId = groupId; - clone.packagingType = packagingType; - clone.version = version; - - clone.parentCoordinate = parentCoordinate; - - clone.releaseDate = releaseDate; - clone.projectName = projectName; - - clone.dependencies.addAll(dependencies); - clone.dependencyManagement.addAll(dependencyManagement); - - clone.repoUrl = repoUrl; - clone.commitTag = commitTag; - clone.sourcesUrl = sourcesUrl; - clone.artifactRepository = artifactRepository; - - return clone; - } - - public int getHashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((artifactRepository == null) ? 0 : artifactRepository.hashCode()); - result = prime * result + ((commitTag == null) ? 0 : commitTag.hashCode()); - result = prime * result + ((dependencies == null) ? 0 : dependencies.hashCode()); - result = prime * result + ((dependencyManagement == null) ? 0 : dependencyManagement.hashCode()); - result = prime * result + ((forge == null) ? 0 : forge.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - result = prime * result + ((packagingType == null) ? 0 : packagingType.hashCode()); - result = prime * result + ((parentCoordinate == null) ? 0 : parentCoordinate.hashCode()); - result = prime * result + ((projectName == null) ? 0 : projectName.hashCode()); - result = prime * result + (int) (releaseDate ^ (releaseDate >>> 32)); - result = prime * result + ((repoUrl == null) ? 0 : repoUrl.hashCode()); - result = prime * result + ((sourcesUrl == null) ? 0 : sourcesUrl.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Pom other = (Pom) obj; - if (hashCode != other.hashCode) { - return false; - } - if (artifactId == null) { - if (other.artifactId != null) - return false; - } else if (!artifactId.equals(other.artifactId)) - return false; - if (artifactRepository == null) { - if (other.artifactRepository != null) - return false; - } else if (!artifactRepository.equals(other.artifactRepository)) - return false; - if (commitTag == null) { - if (other.commitTag != null) - return false; - } else if (!commitTag.equals(other.commitTag)) - return false; - if (dependencies == null) { - if (other.dependencies != null) - return false; - } else if (!dependencies.equals(other.dependencies)) - return false; - if (dependencyManagement == null) { - if (other.dependencyManagement != null) - return false; - } else if (!dependencyManagement.equals(other.dependencyManagement)) - return false; - if (!forge.equals(other.forge)) - return false; - if (ga == null) { - if (other.ga != null) - return false; - } else if (!ga.equals(other.ga)) - return false; - if (gav == null) { - if (other.gav != null) - return false; - } else if (!gav.equals(other.gav)) - return false; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - if (packagingType == null) { - if (other.packagingType != null) - return false; - } else if (!packagingType.equals(other.packagingType)) - return false; - if (parentCoordinate == null) { - if (other.parentCoordinate != null) - return false; - } else if (!parentCoordinate.equals(other.parentCoordinate)) - return false; - if (projectName == null) { - if (other.projectName != null) - return false; - } else if (!projectName.equals(other.projectName)) - return false; - if (releaseDate != other.releaseDate) - return false; - if (repoUrl == null) { - if (other.repoUrl != null) - return false; - } else if (!repoUrl.equals(other.repoUrl)) - return false; - if (sourcesUrl == null) { - if (other.sourcesUrl != null) - return false; - } else if (!sourcesUrl.equals(other.sourcesUrl)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/PomBuilder.java b/core/src/main/java/eu/fasten/core/maven/data/PomBuilder.java deleted file mode 100644 index 52c246de4..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/PomBuilder.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - -public class PomBuilder { - - public String groupId = null; - public String artifactId = null; - public String packagingType = null; - public String version = null; - - // g:a:packaging:version - public String parentCoordinate = null; - - public long releaseDate = -1L; - public String projectName = null; - - // used LinkedHashSet, because order is relevant for resolution - public LinkedHashSet dependencies = new LinkedHashSet<>(); - public Set dependencyManagement = new HashSet<>(); - - public String repoUrl = null; - public String commitTag = null; - public String sourcesUrl = null; - public String artifactRepository = null; - - public Pom pom() { - return new Pom(groupId, artifactId, packagingType, version, parentCoordinate, releaseDate, projectName, - dependencies, dependencyManagement, repoUrl, commitTag, sourcesUrl, artifactRepository); - } - - public PomBuilder groupId(String gid) { - this.groupId = gid; - return this; - } - - public PomBuilder artifactId(String aid) { - this.artifactId = aid; - return this; - } - - public PomBuilder packagingType(String t) { - this.packagingType = t; - return this; - } - - public PomBuilder version(String v) { - this.version = v; - return this; - } - - public PomBuilder parentCoordinate(String string) { - this.parentCoordinate = string; - return this; - } - - public PomBuilder releaseDate(long string) { - this.releaseDate = string; - return this; - } - - public PomBuilder projectName(String string) { - this.projectName = string; - return this; - } - - public PomBuilder addDependency(Dependency d) { - this.dependencies.add(d); - return this; - } - - public PomBuilder setDependencies(LinkedHashSet dependencies) { - this.dependencies = dependencies; - return this; - } - - public PomBuilder addDependencyManagement(Dependency d) { - this.dependencyManagement.add(d); - return this; - } - - public PomBuilder setDependencyManagement(Set dependencies) { - this.dependencyManagement = dependencies; - return this; - } - - public PomBuilder repoUrl(String string) { - this.repoUrl = string; - return this; - } - - public PomBuilder commitTag(String string) { - this.commitTag = string; - return this; - } - - public PomBuilder sourcesUrl(String string) { - this.sourcesUrl = string; - return this; - } - - public PomBuilder artifactRepository(String string) { - this.artifactRepository = string; - return this; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/ResolvedRevision.java b/core/src/main/java/eu/fasten/core/maven/data/ResolvedRevision.java deleted file mode 100644 index 3dad2867d..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/ResolvedRevision.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import java.sql.Timestamp; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; - -public class ResolvedRevision extends Revision { - - private static final long serialVersionUID = -8029991532778209365L; - - public Scope scope; - - public ResolvedRevision() {} - - public ResolvedRevision(Revision r, Scope s) { - this.id = r.id; - this.groupId = r.groupId; - this.artifactId = r.artifactId; - this.version = r.version; - this.createdAt = r.createdAt; - this.scope = s; - } - - public ResolvedRevision(long id, String groupId, String artifactId, String version, Timestamp createdAt, - Scope scope) { - this.id = id; - this.groupId = groupId; - this.artifactId = artifactId; - this.version = new DefaultArtifactVersion(version); - this.createdAt = createdAt; - this.scope = scope; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/Revision.java b/core/src/main/java/eu/fasten/core/maven/data/Revision.java deleted file mode 100644 index fa451a0b7..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/Revision.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 eu.fasten.core.maven.data; - -import java.io.Serializable; -import java.sql.Timestamp; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.json.JSONObject; - -/** - * An artifact released in Maven Central. - */ -public class Revision extends MavenProduct implements Serializable { - - private static final long serialVersionUID = 3096663425693127578L; - - public DefaultArtifactVersion version; - public Timestamp createdAt; - - public Revision() {} - - public Revision(final String groupId, final String artifactId, final String version, final Timestamp createdAt) { - super(groupId, artifactId); - - this.version = new DefaultArtifactVersion(version); - this.createdAt = createdAt; - } - - public Revision(final long id, final String groupId, final String artifactId, - final String version, final Timestamp createdAt) { - super(id, groupId, artifactId); - - this.version = new DefaultArtifactVersion(version); - this.createdAt = createdAt; - } - - public MavenProduct product() { - return new MavenProduct(groupId, artifactId); - } - - public JSONObject toJSON() { - var json = new JSONObject(); - json.put("id", id); - json.put("groupId", groupId); - json.put("artifactId", artifactId); - json.put("version", version.toString()); - json.put("createdAt", createdAt.getTime()); - return json; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Revision other = (Revision) obj; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/data/VersionConstraint.java b/core/src/main/java/eu/fasten/core/maven/data/VersionConstraint.java deleted file mode 100644 index 5af9415c2..000000000 --- a/core/src/main/java/eu/fasten/core/maven/data/VersionConstraint.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static eu.fasten.core.utils.Asserts.assertNotNull; -import static eu.fasten.core.utils.Asserts.assertTrue; - -import java.util.LinkedHashSet; -import java.util.Set; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; - -public class VersionConstraint { - - private final String spec; - - private final boolean isRange; - private final boolean isHard; - private final boolean isLowerBoundInclusive; - private final boolean isUpperBoundInclusive; - - private final int hashCode; - - public VersionConstraint(String spec) { - this.spec = Ids.version(spec); - if (spec == null || spec.isEmpty()) { - throw new IllegalArgumentException("Spec of VersionConstraint cannot be null or empty"); - } - - this.isRange = spec.contains(","); - this.isHard = spec.startsWith("[") || spec.startsWith("("); - this.isLowerBoundInclusive = !isHard || spec.startsWith("["); - this.isUpperBoundInclusive = !isHard || spec.endsWith("]"); - - this.hashCode = spec.hashCode() + 1; - } - - public String getSpec() { - return spec; - } - - public boolean isRange() { - return isRange; - } - - public boolean isHard() { - return isHard; - } - - public String getLowerBound() { - if (isRange) { - var parts = spec.substring(1, spec.length() - 1).split(",", -1); - return parts[0].isEmpty() ? "0" : parts[0]; - } - if (isHard) { - return spec.substring(1, spec.length() - 1); - } - return spec; - } - - public boolean isLowerBoundInclusive() { - return isLowerBoundInclusive; - } - - public String getUpperBound() { - if (isRange) { - var parts = spec.substring(1, spec.length() - 1).split(",", -1); - return parts[1].isEmpty() ? "999" : parts[1]; - - } - if (isHard) { - return spec.substring(1, spec.length() - 1); - } - return spec; - } - - public boolean isUpperBoundInclusive() { - return isUpperBoundInclusive; - } - - public boolean matches(String version) { - - var v = new DefaultArtifactVersion(version); - - var lower = new DefaultArtifactVersion(getLowerBound()); - int compLow = v.compareTo(lower); - if (compLow == 0 && isLowerBoundInclusive) { - return true; - } - - var upper = new DefaultArtifactVersion(getUpperBound()); - int compHigh = v.compareTo(upper); - if (compHigh == 0 && isUpperBoundInclusive) { - return true; - } - - if (compLow > 0 && compHigh < 0) { - return true; - } - - return false; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VersionConstraint other = (VersionConstraint) obj; - if (hashCode != other.hashCode) { - return false; - } - if (spec == null) { - if (other.spec != null) - return false; - } else if (!spec.equals(other.spec)) - return false; - return true; - } - - @Override - public String toString() { - return spec; - } - - public static Set parseVersionSpec(String spec) { - assertNotNull(spec); - spec = spec.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", ""); - assertTrue(!spec.startsWith("$")); - - var constraints = new LinkedHashSet(); - if (spec.isEmpty()) { - return constraints; - } - - if (!spec.startsWith("[") && !spec.startsWith("(")) { - // has to be soft constraint - assertTrue(!spec.contains(",")); - assertTrue(!spec.contains("[")); - assertTrue(!spec.contains("]")); - assertTrue(!spec.contains("(")); - assertTrue(!spec.contains(")")); - constraints.add(new VersionConstraint(spec)); - return constraints; - } - - // has to be hard constraint - var charZero = spec.charAt(0); - assertTrue(charZero == '[' || charZero == '('); - - var idxOpen = 0; - while (idxOpen != -1) { - var idxClose = find(spec, idxOpen + 1, ')', ']'); - var vcSpec = spec.substring(idxOpen, idxClose + 1); - constraints.add(new VersionConstraint(vcSpec)); - idxOpen = find(spec, idxClose, '(', '['); - } - - return constraints; - } - - private static int find(String hay, int idx, char... needles) { - while (idx < hay.length()) { - char cur = hay.charAt(idx); - for (var needle : needles) { - if (cur == needle) { - return idx; - } - } - idx++; - } - return -1; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/IMavenResolver.java b/core/src/main/java/eu/fasten/core/maven/resolution/IMavenResolver.java deleted file mode 100644 index ebf516160..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/IMavenResolver.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import java.util.Collection; -import java.util.Set; -import java.util.stream.Collectors; - -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; - -public interface IMavenResolver { - - Set resolveDependencies(Collection gavs, ResolverConfig config); - - Set resolveDependents(String gid, String aid, String version, ResolverConfig config); - - // map one to many - - default Set resolveDependencies(String gid, String aid, String version, ResolverConfig config) { - var gav = String.format("%s:%s:%s", gid, aid, version); - return resolveDependencies(Set.of(gav), config); - } - - // no config - - default Set resolveDependencies(Collection gavs) { - return resolveDependencies(gavs, new ResolverConfig()); - } - - default Set resolveDependencies(String gid, String aid, String version) { - return resolveDependencies(gid, aid, version, new ResolverConfig()); - } - - default Set resolveDependents(String gid, String aid, String version) { - return resolveDependents(gid, aid, version, new ResolverConfig()); - } - - // revision - - default Set resolveDependenciesForRevisions(Collection revisions, ResolverConfig config) { - var gavs = revisions.stream() // - .map(r -> String.format("%s:%s:%s", r.getGroupId(), r.getArtifactId(), r.version)) // - .collect(Collectors.toSet()); - return resolveDependencies(gavs, config); - } - - default Set resolveDependencies(Revision r, ResolverConfig config) { - return resolveDependencies(r.getGroupId(), r.getArtifactId(), r.version.toString(), config); - } - - default Set resolveDependents(Revision r, ResolverConfig config) { - return resolveDependents(r.getGroupId(), r.getArtifactId(), r.version.toString(), config); - } - - // revision and no config - - default Set resolveDependencies(Revision r) { - return resolveDependencies(r.getGroupId(), r.getArtifactId(), r.version.toString(), new ResolverConfig()); - } - - default Set resolveDependenciesForRevisions(Collection revisions) { - return resolveDependenciesForRevisions(revisions, new ResolverConfig()); - } - - default Set resolveDependents(Revision r) { - return resolveDependents(r, new ResolverConfig()); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/MavenDependencyResolver.java b/core/src/main/java/eu/fasten/core/maven/resolution/MavenDependencyResolver.java deleted file mode 100644 index 7c73b326c..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/MavenDependencyResolver.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.RUNTIME; -import static eu.fasten.core.maven.data.Scope.SYSTEM; -import static eu.fasten.core.maven.data.Scope.TEST; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.GA; -import eu.fasten.core.maven.data.MavenProduct; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.data.VersionConstraint; - -public class MavenDependencyResolver { - - private MavenResolverData graph = new MavenResolverData(); - - public void setData(MavenResolverData graph) { - this.graph = graph; - } - - public Set resolve(Collection gavs, ResolverConfig config) { - - failForImportProvidedSystemScope(config); - - if (gavs.size() == 1) { - var parts = gavs.iterator().next().split(":"); - var ga = new GA(parts[0], parts[1]); - - var pom = this.graph.find(ga, Set.of(new VersionConstraint(parts[2])), config.resolveAt); - if (pom == null) { - throw new MavenResolutionException( - String.format("Cannot find coordinate %s:%s:%s", parts[0], parts[1], parts[2])); - } else { - return resolve(config, new HashSet<>(), QueueData.startFrom(pom)); - } - } - - var pb = new PomBuilder(); - pb.groupId = "virtual-file"; - pb.artifactId = "pom"; - pb.version = "0.0.1"; - pb.releaseDate = config.resolveAt; - pb.dependencies.addAll(toDeps(gavs)); - var pom = pb.pom(); - - var depSet = resolve(config, new HashSet<>(), QueueData.startFrom(pom)); - depSet.remove(pom.toRevision()); - return depSet; - } - - private void failForImportProvidedSystemScope(ResolverConfig config) { - switch (config.scope) { - case IMPORT: - case PROVIDED: - case SYSTEM: - throw new IllegalArgumentException(String.format("Invalid resolution scope: %s", config.scope)); - default: - // nothing to do - } - } - - private Set resolve(ResolverConfig config, Set addedProducts, - QueueData startingData) { - - if (startingData.pom.releaseDate > config.resolveAt) { - throw new MavenResolutionException("Requested POM has been released after resolution timestamp"); - } - - var depSet = new HashSet(); - - var queue = new LinkedList(); - queue.add(startingData); - var isFirstElement = true; - - while (!queue.isEmpty()) { - var data = queue.poll(); - - if (data.depth > config.depth) { - continue; - } - - if (depSet.size() >= config.limit) { - break; - } - - var p = data.pom.toProduct(); - if (addedProducts.contains(p)) { - continue; - } - addedProducts.add(p); - - if (!isFirstElement) { - depSet.add(toResolvedRevision(data)); - } - isFirstElement = false; - - if (data.scope == SYSTEM) { - continue; - } - - for (var dep : data.pom.dependencies) { - var depGA = dep.toGA(); - if (data.exclusions.contains(depGA)) { - continue; - } - - if (!isScopeCovered(config.scope, dep.getScope(), config.alwaysIncludeProvided, data.scope)) { - continue; - } - - var depData = QueueData.nest(data, dep.getScope()); - if (depData.isTransitiveDep()) { - - if (config.isExcludingTransitiveDeps()) { - continue; - } - - if (dep.isOptional() && !config.alwaysIncludeOptional) { - continue; - } - - if (dep.getScope() == Scope.SYSTEM && config.scope == RUNTIME) { - continue; - } - - if (dep.getScope() == Scope.PROVIDED && !config.alwaysIncludeProvided) { - continue; - } - - if (dep.getScope() == TEST) { - continue; - } - } - - for (var excl : dep.getExclusions()) { - var exclGA = new GA(excl.groupId, excl.artifactId); - depData.exclusions.add(exclGA); - } - - var couldBeManaged = !hasVersion(dep) || depData.isTransitiveDep(); - var vcs = couldBeManaged && depData.depMgmt.containsKey(depGA) // - ? depData.depMgmt.get(depGA) // - : dep.getVersionConstraints(); - - var depPom = graph.find(depGA, vcs, config.resolveAt); - - if (depPom != null) { - depData.setPom(depPom); - queue.add(depData); - } - } - } - - return depSet; - } - - private static ResolvedRevision toResolvedRevision(QueueData data) { - return new ResolvedRevision(data.pom.toRevision(), data.scope); - } - - private static boolean isScopeCovered(Scope request, Scope dep, boolean alwaysIncludeProvided, Scope inherited) { - if (dep == request) { - return true; - } - if (dep == SYSTEM) { - return request != RUNTIME; - } - if (dep == PROVIDED) { - return alwaysIncludeProvided || request != RUNTIME; - } - if (dep == RUNTIME) { - return request == TEST || inherited == PROVIDED; - } - if (dep == COMPILE) { - return request == RUNTIME || request == TEST; - } - return false; - } - - private static boolean hasVersion(Dependency dep) { - if (dep.getVersionConstraints().isEmpty()) { - return false; - } - if (dep.getVersionConstraints().size() == 1) { - // TODO this case should be obsolete - return !dep.getVersionConstraints().iterator().next().getSpec().isEmpty(); - } - return true; - } - - private static Set toDeps(Collection gavs) { - return gavs.stream() // - .map(gav -> gav.split(":")) // - .map(parts -> new Dependency(parts[0], parts[1], Set.of(new VersionConstraint(parts[2])), Set.of(), - Scope.COMPILE, false, "jar", "")) // - .collect(Collectors.toSet()); - } - - private static class QueueData { - - private int depth = 0; - - public Pom pom; - public Scope scope = COMPILE; - public final Set exclusions = new HashSet<>(); - public final Map> depMgmt = new HashMap<>(); - - public boolean isTransitiveDep() { - // 0 = source, 1 = direct, 2 = transitive - return depth > 1; - } - - public void setPom(Pom pom) { - this.pom = pom; - for (var dm : pom.dependencyManagement) { - depMgmt.put(dm.toGA(), dm.getVersionConstraints()); - } - } - - public static QueueData nest(QueueData outer, Scope depScope) { - var inner = new QueueData(); - inner.exclusions.addAll(outer.exclusions); - inner.depth = outer.depth + 1; - inner.depMgmt.putAll(outer.depMgmt); - inner.scope = getMostSpecific(outer.scope, depScope); - return inner; - } - - private static Scope getMostSpecific(Scope cur, Scope dep) { - if (dep == SYSTEM || dep == PROVIDED) { - return dep; - } - if (cur == PROVIDED) { - return cur; - } - if (cur == COMPILE) { - return dep; - } - if (cur == RUNTIME) { - if (dep == COMPILE) { - return RUNTIME; - } - return dep; - } - return TEST; - } - - private static QueueData startFrom(Pom pom) { - var data = new QueueData(); - data.setPom(pom); - return data; - } - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/MavenDependentsResolver.java b/core/src/main/java/eu/fasten/core/maven/resolution/MavenDependentsResolver.java deleted file mode 100644 index e0cc245c9..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/MavenDependentsResolver.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.RUNTIME; -import static eu.fasten.core.maven.data.Scope.SYSTEM; -import static eu.fasten.core.maven.data.Scope.TEST; - -import java.util.HashSet; -import java.util.Set; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.GAV; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependentsResolver { - - private MavenResolverData data; - - public void setData(MavenResolverData data) { - this.data = data; - } - - public Set resolve(String gav, ResolverConfig config) { - failForInvalidScopes(config); - - var parts = gav.split(":"); - var pom = data.findPom(new GAV(parts[0], parts[1], parts[2]), config.resolveAt); - if (pom == null) { - throw new MavenResolutionException(String.format("Cannot find coordinate %s", gav)); - } - - var dependents = new HashSet(); - resolve(pom, config, dependents, new HashSet<>(), false, COMPILE, 1); - return dependents; - } - - private static void failForInvalidScopes(ResolverConfig config) { - if (config.scope == Scope.IMPORT || config.scope == Scope.PROVIDED || config.scope == Scope.SYSTEM) { - var msg = "Invalid resolution scope: %s"; - throw new IllegalArgumentException(String.format(msg, config.scope)); - } - } - - private void resolve(Pom pom, ResolverConfig config, Set dependents, Set visited, - boolean stopAfterThis, Scope propagatedScope, int depth) { - - if (depth > config.depth) { - return; - } - - visited.add(pom); - - for (var dpd : data.findPotentialDependents(pom.toGA(), config.resolveAt)) { - - if (visited.contains(dpd)) { - continue; - } - - if (dependents.size() >= config.limit) { - return; - } - - var decl = findCorrectDependencyDecl(pom, dpd.dependencies); - - if (!matchesScope(decl.getScope(), config.scope, config.alwaysIncludeProvided)) { - continue; - } - - if (doesPomVersionMatchDecl(decl, pom)) { - propagatedScope = deriveScope(propagatedScope, decl.getScope()); - dependents.add(toRR(dpd, propagatedScope)); - - if (config.depth > depth && !stopAfterThis && shouldProcessDependent(config, decl)) { - var onlyOneMore = decl.getScope() == PROVIDED; - resolve(dpd, config, dependents, visited, onlyOneMore, propagatedScope, depth + 1); - } - } - } - } - - private static Scope deriveScope(Scope prop, Scope dep) { - if (dep == SYSTEM || prop == SYSTEM) { - return SYSTEM; - } - if (dep == PROVIDED || prop == PROVIDED) { - return PROVIDED; - } - if (dep == TEST) { - return TEST; - } - if (dep == RUNTIME && prop == COMPILE) { - return RUNTIME; - } - return prop; - } - - private static ResolvedRevision toRR(Pom p, Scope s) { - return new ResolvedRevision(p.toRevision(), s); - } - - private static boolean shouldProcessDependent(ResolverConfig config, Dependency decl) { - var isNonTest = decl.getScope() != TEST; - var isNonProvided = decl.getScope() != PROVIDED || config.alwaysIncludeProvided; - var isNonOptional = !decl.isOptional() || config.alwaysIncludeOptional; - return isNonTest && isNonProvided && isNonOptional; - } - - private static boolean matchesScope(Scope dep, Scope request, boolean alwaysIncludeProvided) { - - if (dep == PROVIDED && alwaysIncludeProvided) { - return true; - } - if (request == Scope.COMPILE) { - return dep == COMPILE || dep == SYSTEM || dep == PROVIDED; - } - if (request == RUNTIME) { - return dep == RUNTIME || dep == COMPILE; - } - return dep == TEST || dep == RUNTIME || dep == COMPILE || dep == SYSTEM || dep == PROVIDED; - } - - private static boolean doesPomVersionMatchDecl(Dependency dep, Pom pom) { - for (var vc : dep.getVersionConstraints()) { - if (vc.matches(pom.version)) { - return true; - } - } - return false; - } - - private static Dependency findCorrectDependencyDecl(Pom pom, Set dependencies) { - for (var dep : dependencies) { - if (pom.groupId.equals(dep.groupId)) { - if (pom.artifactId.equals(dep.artifactId)) { - return dep; - } - } - } - throw new IllegalStateException("Cannot find reported dependency"); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolver.java b/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolver.java deleted file mode 100644 index 54adc56e9..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolver.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import java.util.Collection; -import java.util.Set; - -import javax.inject.Inject; - -import eu.fasten.core.maven.data.ResolvedRevision; - -public class MavenResolver implements IMavenResolver { - - private final MavenDependentsResolver dependentsResolver; - private final MavenDependencyResolver dependencyResolver; - - @Inject - public MavenResolver(MavenDependentsResolver dependentsResolver, MavenDependencyResolver dependencyResolver) { - this.dependentsResolver = dependentsResolver; - this.dependencyResolver = dependencyResolver; - } - - @Override - public Set resolveDependencies(Collection gavs, ResolverConfig config) { - return dependencyResolver.resolve(gavs, config); - } - - @Override - public Set resolveDependents(String gid, String aid, String version, ResolverConfig config) { - var gav = String.format("%s:%s:%s", gid, aid, version); - return dependentsResolver.resolve(gav, config); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverData.java b/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverData.java deleted file mode 100644 index e175e39db..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverData.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; - -import eu.fasten.core.maven.data.GA; -import eu.fasten.core.maven.data.GAV; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.VersionConstraint; - -public class MavenResolverData { - - private final Map pomForGAV = new HashMap<>(); - private final Map> pomsForGA = new HashMap<>(); - private final Map> dependentsForGA = new HashMap<>(); - - public synchronized void add(Pom pom) { - var gav = pom.toGAV(); - pomForGAV.put(gav, pom); - put(pomsForGA, pom.toGA(), pom); - for (var dep : pom.dependencies) { - addDependent(dep.toGA(), pom); - } - } - - private static void put(Map> map, K key, V value) { - if (map.containsKey(key)) { - map.get(key).add(value); - } else { - var values = new HashSet(); - values.add(value); - map.put(key, values); - } - } - - private void addDependent(GA depGA, Pom pom) { - Set poms; - if (!dependentsForGA.containsKey(depGA)) { - poms = new HashSet(); - dependentsForGA.put(depGA, poms); - } else { - poms = dependentsForGA.get(depGA); - } - poms.add(pom); - } - - // no need for `synchronized`, the problematic part has been moved to `findGA` - public Pom find(GA ga, Set vcs, long resolveAt) { - - DefaultArtifactVersion highest = null; - Pom highestPom = null; - - for (var pom : findGA(ga)) { - if (pom.releaseDate > resolveAt) { - continue; - } - for (var vc : vcs) { - if (vc.matches(pom.version)) { - var cur = new DefaultArtifactVersion(pom.version); - if (highest == null) { - highest = cur; - highestPom = pom; - } else { - if (cur.compareTo(highest) > 0) { - highest = cur; - highestPom = pom; - } - } - } - } - } - return highestPom; - } - - protected synchronized Set findGA(GA ga) { - return pomsForGA.getOrDefault(ga, Set.of()); - } - - public synchronized Pom findPom(GAV gav, long resolveAt) { - var pom = pomForGAV.get(gav); - if (pom != null && pom.releaseDate <= resolveAt) { - return pom; - } - return null; - } - - public synchronized Set findPotentialDependents(GA ga, long resolveAt) { - var dpds = dependentsForGA.getOrDefault(ga, Set.of()); - return dpds.stream() // - .filter(d -> d.releaseDate <= resolveAt) // - .collect(Collectors.toSet()); - } - - public synchronized void removeOutdatedPomRegistrations() { - var registered = new HashSet<>(pomForGAV.values()); - for (var poms : pomsForGA.values()) { - var it = poms.iterator(); - while (it.hasNext()) { - var pom = it.next(); - if (!registered.contains(pom)) { - System.out.printf("Cleaning-up %s ...\n", pom.toCoordinate()); - it.remove(); - } - } - } - for (var poms : dependentsForGA.values()) { - var it = poms.iterator(); - while (it.hasNext()) { - var pom = it.next(); - if (!registered.contains(pom)) { - it.remove(); - } - } - } - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverIO.java b/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverIO.java index 12e0a983a..573cc8d82 100644 --- a/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverIO.java +++ b/core/src/main/java/eu/fasten/core/maven/resolution/MavenResolverIO.java @@ -15,40 +15,47 @@ */ package eu.fasten.core.maven.resolution; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.fasten.core.json.ObjectMapperBuilder; -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.Pom; -import org.apache.commons.io.FileUtils; -import org.jooq.DSLContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static eu.fasten.core.data.metadatadb.codegen.tables.PackageVersions.PACKAGE_VERSIONS; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.Set; -import java.util.stream.Collectors; -import static eu.fasten.core.data.metadatadb.codegen.tables.PackageVersions.PACKAGE_VERSIONS; +import org.apache.commons.io.FileUtils; +import org.jooq.DSLContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import dev.c0ps.maven.MavenUtilities; +import dev.c0ps.maven.data.Pom; +import dev.c0ps.maven.resolution.IMavenResolver; +import dev.c0ps.maven.resolution.MavenDependencyResolver; +import dev.c0ps.maven.resolution.MavenDependentsResolver; +import dev.c0ps.maven.resolution.MavenResolver; +import dev.c0ps.maven.resolution.MavenResolverData; +import eu.fasten.core.json.FastenObjectMapperBuilder; public class MavenResolverIO { private static final Logger LOG = LoggerFactory.getLogger(MavenResolverIO.class); + private static final int PG_FETCH_SIZE = 10000; + + private final DSLContext dbContext; - private DSLContext dbContext; private File baseDir; private ObjectMapper om; - private final int PG_FETCH_SIZE = 10000; public MavenResolverIO(DSLContext dbContext, File baseDir) { - this(dbContext, baseDir, new ObjectMapperBuilder().build()); + this(dbContext, baseDir, new FastenObjectMapperBuilder().build()); } + // TODO inject and @Named annotations, get rid of DB variant public MavenResolverIO(DSLContext dbContext, File baseDir, ObjectMapper om) { this.dbContext = dbContext; this.baseDir = baseDir; @@ -70,7 +77,7 @@ public IMavenResolver loadResolver() { saveToDisk(poms); } - return init(poms); + return initResolver(poms); } public boolean hasSerialization() { @@ -118,7 +125,7 @@ public Set readFromDB() { PACKAGE_VERSIONS.METADATA, // PACKAGE_VERSIONS.ID) // .from(PACKAGE_VERSIONS) // - .where(PACKAGE_VERSIONS.METADATA.isNotNull()).fetchSize(this.PG_FETCH_SIZE); // + .where(PACKAGE_VERSIONS.METADATA.isNotNull()).fetchSize(PG_FETCH_SIZE); // try (var cursor = dbRes.fetchLazy()) { while (cursor.hasNext()) { @@ -126,7 +133,7 @@ var record = cursor.fetchNext(); if (record != null) { try { var json = record.component1().data(); - var pom = simplify(om.readValue(json, Pom.class)); + var pom = MavenUtilities.simplify(om.readValue(json, Pom.class)); pom.id = record.component2(); poms.add(pom); numberOfFetchedPoms++; @@ -145,20 +152,7 @@ var record = cursor.fetchNext(); return poms; } - public static Pom simplify(Pom pom) { - var deps = pom.dependencies.stream().map(d -> simplify(d)).collect(Collectors.toCollection(LinkedHashSet::new)); - var depMgmt = pom.dependencyManagement.stream().map(d -> simplify(d)) - .collect(Collectors.toCollection(HashSet::new)); - return new Pom(pom.groupId, pom.artifactId, null, pom.version, null, pom.releaseDate, null, deps, depMgmt, null, - null, null, null); - } - - private static Dependency simplify(Dependency d) { - return new Dependency(d.groupId, d.artifactId, d.getVersionConstraints(), d.getExclusions(), d.getScope(), - d.optional, null, null); - } - - private static IMavenResolver init(Set poms) { + private static IMavenResolver initResolver(Set poms) { LOG.info("Initializing underlying data structures for MavenResolver with {} poms ...", poms.size()); var data = new MavenResolverData(); diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/NativeMavenResolver.java b/core/src/main/java/eu/fasten/core/maven/resolution/NativeMavenResolver.java index ee57bb20c..800167ce7 100644 --- a/core/src/main/java/eu/fasten/core/maven/resolution/NativeMavenResolver.java +++ b/core/src/main/java/eu/fasten/core/maven/resolution/NativeMavenResolver.java @@ -38,8 +38,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.data.Revision; +import eu.fasten.core.utils.FileUtils; +import eu.fasten.core.utils.HttpUtils; public class NativeMavenResolver { @@ -52,7 +53,7 @@ public Set resolveDependencies(String mavenCoordinate) { public Set resolveDependencies(String mavenCoordinate, boolean onlyDirectDependencies) { try { var parts = mavenCoordinate.split(":"); - var pomFile = MavenUtilities.downloadPom(parts[0], parts[1], parts[2]); + var pomFile = HttpUtils.downloadPom(parts[0], parts[1], parts[2]); if (pomFile.isEmpty()) { logger.error("Could not download POM file of {}", mavenCoordinate); return null; @@ -63,7 +64,7 @@ public Set resolveDependencies(String mavenCoordinate, boolean onlyDir return null; } } - + public Set getDependencies(File pomFile, boolean onlyDirectDependencies) throws MavenInvocationException, IOException { Set deps; @@ -82,7 +83,7 @@ public Set getDependencies(File pomFile, boolean onlyDirectDependencie mvnInvocation.getExecutionException()); } } finally { - MavenUtilities.forceDeleteFile(outputFile); + FileUtils.forceDeleteFile(outputFile); } return deps; } diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/ResolverConfig.java b/core/src/main/java/eu/fasten/core/maven/resolution/ResolverConfig.java deleted file mode 100644 index cd3f363f0..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/ResolverConfig.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.RUNTIME; -import static org.apache.commons.lang3.builder.ToStringStyle.MULTI_LINE_STYLE; - -import java.util.Date; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import eu.fasten.core.maven.data.Scope; - -public class ResolverConfig { - - public long resolveAt = new Date().getTime(); - public int depth = Integer.MAX_VALUE; - public Scope scope = RUNTIME; - public int limit = Integer.MAX_VALUE; - - /** - * if false, include only direct dependencies - */ - public boolean alwaysIncludeProvided; - - /** - * if false, include only direct dependencies - */ - public boolean alwaysIncludeOptional; - - public ResolverConfig at(long timestamp) { - this.resolveAt = timestamp; - return this; - } - - public ResolverConfig includeTransitiveDeps() { - this.depth = Integer.MAX_VALUE; - return this; - } - - public ResolverConfig excludeTransitiveDeps() { - this.depth = 1; - return this; - } - - public ResolverConfig limitTransitiveDeps(int depth) { - if (depth < 1) { - var msg = "Resolution depth must be >0, but was %d"; - throw new MavenResolutionException(String.format(msg, depth)); - } - this.depth = depth; - return this; - } - - public boolean isExcludingTransitiveDeps() { - return depth == 1; - } - - public ResolverConfig limit(int limit) { - this.limit = limit; - return this; - } - - public ResolverConfig scope(Scope scope) { - this.scope = scope; - return this; - } - - /** - * if false, include only direct dependencies - */ - public ResolverConfig alwaysIncludeProvided(boolean alwaysIncludeProvided) { - this.alwaysIncludeProvided = alwaysIncludeProvided; - return this; - } - - /** - * if false, include only direct dependencies - */ - public ResolverConfig alwaysIncludeOptional(boolean alwaysIncludeOptional) { - this.alwaysIncludeOptional = alwaysIncludeOptional; - return this; - } - - public static ResolverConfig resolve() { - return new ResolverConfig(); - } - - @Override - public boolean equals(Object obj) { - return EqualsBuilder.reflectionEquals(this, obj); - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/resolution/RestMavenResolver.java b/core/src/main/java/eu/fasten/core/maven/resolution/RestMavenResolver.java deleted file mode 100644 index 0b287c0c9..000000000 --- a/core/src/main/java/eu/fasten/core/maven/resolution/RestMavenResolver.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; - -import java.util.Collection; -import java.util.Set; - -import org.glassfish.jersey.client.ClientConfig; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import eu.fasten.core.json.ObjectMapperBuilder; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Scope; -import jakarta.ws.rs.client.ClientBuilder; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.client.WebTarget; -import jakarta.ws.rs.core.GenericType; -import jakarta.ws.rs.ext.ContextResolver; - -public class RestMavenResolver implements IMavenResolver { - - private static final int DEFAULT_DEPTH = ResolverConfig.resolve().depth; - private static final int DEFAULT_LIMIT = ResolverConfig.resolve().limit; - - private static final GenericType> SET_OF_REV = new GenericType>() {}; - private static final ObjectMapper OM = new ObjectMapperBuilder().build(); - - private WebTarget baseTarget; - - public RestMavenResolver(String baseUrl) { - var ctxResolver = new ContextResolver() { - @Override - public ObjectMapper getContext(Class type) { - return OM; - } - }; - baseTarget = ClientBuilder // - .newClient(new ClientConfig(ctxResolver)) // - .target(baseUrl).path("depgraph"); - } - - @Override - public Set resolveDependencies(Collection gavs, ResolverConfig config) { - return getBase("dependencies", config) // - .request(APPLICATION_JSON) // - .post(Entity.entity(gavs, APPLICATION_JSON), SET_OF_REV); - } - - @Override - public Set resolveDependents(String gid, String aid, String version, ResolverConfig config) { - return getBase("dependents", config) // - .path(gid).path(aid).path(version) // - .request(APPLICATION_JSON) // - .get(SET_OF_REV); - } - - private WebTarget getBase(String subpath, ResolverConfig config) { - var base = baseTarget // - .path(subpath) // - .queryParam("resolveAt", config.resolveAt); - if (config.depth != DEFAULT_DEPTH) { - base = base.queryParam("depth", config.depth); - } - if (config.limit != DEFAULT_LIMIT) { - base = base.queryParam("limit", config.limit); - } - if (config.scope != Scope.RUNTIME) { - base = base.queryParam("scope", config.scope); - } - if (config.alwaysIncludeProvided) { - base = base.queryParam("alwaysIncludeProvided", true); - } - if (config.alwaysIncludeOptional) { - base = base.queryParam("alwaysIncludeOptional", true); - } - return base; - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/maven/runners/GraphMavenResolverRunner.java b/core/src/main/java/eu/fasten/core/maven/runners/GraphMavenResolverRunner.java index bb5576b18..453ac90be 100644 --- a/core/src/main/java/eu/fasten/core/maven/runners/GraphMavenResolverRunner.java +++ b/core/src/main/java/eu/fasten/core/maven/runners/GraphMavenResolverRunner.java @@ -15,7 +15,7 @@ */ package eu.fasten.core.maven.runners; -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; +import static dev.c0ps.maven.resolution.ResolverConfig.resolve; import java.io.File; import java.sql.SQLException; @@ -28,11 +28,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Revision; +import dev.c0ps.maven.resolution.IMavenResolver; +import dev.c0ps.maven.resolution.MavenResolver; import eu.fasten.core.dbconnectors.PostgresConnector; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.resolution.IMavenResolver; -import eu.fasten.core.maven.resolution.MavenResolver; import eu.fasten.core.maven.resolution.MavenResolverIO; import picocli.CommandLine; diff --git a/core/src/main/java/eu/fasten/core/maven/runners/MavenResolverBenchmark.java b/core/src/main/java/eu/fasten/core/maven/runners/MavenResolverBenchmark.java index 7d3fe26e2..593567965 100644 --- a/core/src/main/java/eu/fasten/core/maven/runners/MavenResolverBenchmark.java +++ b/core/src/main/java/eu/fasten/core/maven/runners/MavenResolverBenchmark.java @@ -1,6 +1,6 @@ package eu.fasten.core.maven.runners; -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; +import static dev.c0ps.maven.resolution.ResolverConfig.resolve; import java.io.File; import java.io.FileNotFoundException; @@ -14,9 +14,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import dev.c0ps.maven.data.ResolvedRevision; import eu.fasten.core.data.Constants; import eu.fasten.core.dbconnectors.PostgresConnector; -import eu.fasten.core.maven.data.ResolvedRevision; import eu.fasten.core.maven.resolution.MavenResolverIO; import eu.fasten.core.maven.resolution.NativeMavenResolver; import picocli.CommandLine; diff --git a/core/src/main/java/eu/fasten/core/maven/runners/MyRunner.java b/core/src/main/java/eu/fasten/core/maven/runners/MyRunner.java index dfadba31d..da3b8d70e 100644 --- a/core/src/main/java/eu/fasten/core/maven/runners/MyRunner.java +++ b/core/src/main/java/eu/fasten/core/maven/runners/MyRunner.java @@ -15,17 +15,17 @@ */ package eu.fasten.core.maven.runners; -import static eu.fasten.core.maven.data.Scope.TEST; -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; +import static dev.c0ps.maven.data.Scope.TEST; +import static dev.c0ps.maven.resolution.ResolverConfig.resolve; import java.io.File; import java.sql.SQLException; import org.jooq.DSLContext; +import dev.c0ps.maven.resolution.ResolverConfig; import eu.fasten.core.dbconnectors.PostgresConnector; import eu.fasten.core.maven.resolution.MavenResolverIO; -import eu.fasten.core.maven.resolution.ResolverConfig; public class MyRunner { diff --git a/core/src/main/java/eu/fasten/core/maven/utils/MavenUtilities.java b/core/src/main/java/eu/fasten/core/maven/utils/MavenUtilities.java deleted file mode 100644 index 10dbb3dd3..000000000 --- a/core/src/main/java/eu/fasten/core/maven/utils/MavenUtilities.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * 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 eu.fasten.core.maven.utils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.net.ConnectException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import javax.annotation.Nullable; - -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import eu.fasten.core.data.Constants; -import eu.fasten.core.exceptions.UnrecoverableError; -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; - -/** - * The helper utility class for working with maven repositories and pom files. - */ -public class MavenUtilities { - - private static final Logger logger = LoggerFactory.getLogger(MavenUtilities.class); - - /** - * The default pom's repository url. - */ - public static String MAVEN_CENTRAL_REPO = "https://repo.maven.apache.org/maven2/"; - - private static final OkHttpClient httpClient = new OkHttpClient(); - - /** - * Download pom file of the given coordinate. - * - * @param groupId groupId of the artifact to find its dependencies - * @param artifactId artifactId of the artifact to find its dependencies - * @param version version of the artifact to find its dependencies - * @return an optional pom file instance - */ - public static Optional downloadPom(String groupId, String artifactId, String version) { - List mavenRepos = MavenUtilities.getRepos(); - return MavenUtilities.downloadPom(groupId, artifactId, version, mavenRepos); - } - - /** - * Download pom file of the given coordinate with a given set of maven repositories. - * - * @param groupId groupId of the artifact to find its dependencies - * @param artifactId artifactId of the artifact to find its dependencies - * @param version version of the artifact to find its dependencies - * @param mavenRepos the list of predefined maven repositories - * @return an optional pom file instance - */ - public static Optional downloadPom(String groupId, String artifactId, String version, List mavenRepos) { - for (var repo : mavenRepos) { - var pomUrl = MavenUtilities.getPomUrl(groupId.trim(), artifactId.trim(), version.trim(), repo); - try { - File pom = httpGetToFile(pomUrl); - return Optional.of(pom); - } catch (IOException e2) { - continue; - } - } - return Optional.empty(); - } - - public static Optional downloadPomFile(String pomUrl) { - try { - File pom = httpGetToFile(pomUrl); - return Optional.of(pom); - } catch (IOException e) { - return Optional.empty(); - } - } - - /** - * Retrieve the list of available repositories from the environmental variables. - * If not given, use DEFAULT_REPO. - * - * @return list of urls of available maven repositories - */ - public static LinkedList getRepos() { - return System.getenv(Constants.mvnRepoEnvVariable) != null - ? new LinkedList<>(Arrays.asList(System.getenv(Constants.mvnRepoEnvVariable).split(";"))) - : new LinkedList<>(Collections.singleton(MAVEN_CENTRAL_REPO)); - } - - /** - * The utility function for obtaining the url of the pom file of the given coordinates. - * - * @param groupId groupId of the artifact to find its dependencies - * @param artifactId artifactId of the artifact to find its dependencies - * @param version version of the artifact to find its dependencies - * @param repo repository url of the artifact - * @return a string full URL to the anticipated pom file - */ - public static String getPomUrl(String groupId, String artifactId, String version, String repo) { - return repo + groupId.replace('.', '/') + "/" + artifactId + "/" + version - + "/" + artifactId + "-" + version + ".pom"; - } - - /** - * Utility function that stores the contents of GET request to a temporary file. - * Used for downloading pom file. - * - * @param url The url of the wanted file. - * @return a temporarily saved file. - */ - private static File httpGetToFile(String url) throws IOException { - logger.debug("HTTP GET: " + url); - try { - final var tempFile = Files.createTempFile("fasten", ".pom"); - - try (ResponseBody response = getHttpResponse(url); InputStream in = response.byteStream()) { - Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING); - } - // TODO why this complicated construct and not just return tempFile? - return tempFile.toAbsolutePath().toFile(); - } catch (ConnectException e) { - // After downloading ~50-60K POMs, there will be a lot of CLOSE_WAIT connections, - // at some point the plug-in runs out of source ports to use. Therefore, we need to crash so that - // Kubernetes will restart the plug-in to kill CLOSE_WAIT connections. - throw new UnrecoverableError("Failing execution, typically due to many CLOSE_WAIT connections", e); - } catch (IOException e) { - logger.error("Error getting file from URL: " + url, e); - throw e; - } - } - - private static ResponseBody getHttpResponse(String url) { - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder().url(url).addHeader("Connection", "close").build(); - Call call = client.newCall(request); - - Response response = null; - try { - response = call.execute(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - ResponseBody body = Objects.requireNonNull(response.body()); - if (response.code() == 200) { - return response.body(); - } else { - body.close(); - throw new IllegalStateException("unexpected query result"); - } - } - - public static String sendGetRequest(String url) { - return MavenUtilities.downloadPomFile(url).flatMap(MavenUtilities::fileToString).orElse(null); - } - - /** - * Utility function that reads the contents of a file to a String. - */ - private static Optional fileToString(final File f) { - logger.trace("Loading file as string: " + f.toString()); - try { - final var fr = new BufferedReader(new FileReader(f)); - final StringBuilder result = new StringBuilder(); - String line; - while ((line = fr.readLine()) != null) { - result.append(line); - } - fr.close(); - return Optional.of(result.toString()); - } catch (IOException e) { - logger.error("Cannot read from file: " + f.toString(), e); - return Optional.empty(); - } - } - - /** - * Force-deletes the file or directory. - * - * @param file File to be deleted - */ - public static void forceDeleteFile(File file) { - if (file == null) { - return; - } - try { - FileUtils.forceDelete(file); - } catch (IOException ignored) { - } finally { - if (file.exists()) { - file.delete(); - } - } - } - - public static boolean mavenArtifactExists(String groupId, String artifactId, String version, String artifactRepo) { - if (artifactRepo == null || artifactRepo.isEmpty()) { - artifactRepo = MAVEN_CENTRAL_REPO; - } - - var url = getPomUrl(groupId, artifactId, version, artifactRepo); - var request = new Request.Builder().url(url).head().build(); - var call = httpClient.newCall(request); - - try (var res = call.execute()) { - // 200 = success range - // 300 = redirect range - var code = res.code(); - var exists = code >= 200 && code < 400; - logger.debug("Does {} exists? Code: {} -> {}", url, code, exists); - return exists; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Pretty-prints Maven coordinates. - * - * @param groupId the maven coordinate's group ID. - * @param artifactId the maven coordinate's artifact ID. - * @return a pretty String representation of the input Maven coordinate. - */ - public static String getMavenCoordinateName(String groupId, @Nullable String artifactId) { - return groupId + - (artifactId == null || artifactId.compareTo("") == 0 ? - "" : Constants.mvnCoordinateSeparator + artifactId); - } - - /** - * Pretty-prints Maven coordinates (with version). - * - * @param groupId the maven coordinate's group ID. - * @param artifactId the maven coordinate's artifact ID. - * @param version the maven coordinate's version. - * @return a pretty String representation of the input Maven coordinate. - */ - public static String getMavenCoordinateName(String groupId, String artifactId, String version) { - return getMavenCoordinateName(groupId, artifactId) + Constants.mvnCoordinateSeparator + version; - } - -} diff --git a/core/src/main/java/eu/fasten/core/search/SearchEngine.java b/core/src/main/java/eu/fasten/core/search/SearchEngine.java index 6ebc290b4..563f114cf 100644 --- a/core/src/main/java/eu/fasten/core/search/SearchEngine.java +++ b/core/src/main/java/eu/fasten/core/search/SearchEngine.java @@ -18,7 +18,7 @@ package eu.fasten.core.search; -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; +import static dev.c0ps.maven.resolution.ResolverConfig.resolve; import java.io.File; import java.util.ArrayList; @@ -52,9 +52,9 @@ import eu.fasten.core.data.metadatadb.codegen.tables.PackageVersions; import eu.fasten.core.data.metadatadb.codegen.tables.Packages; import eu.fasten.core.dbconnectors.PostgresConnector; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; -import eu.fasten.core.maven.resolution.IMavenResolver; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Revision; +import dev.c0ps.maven.resolution.IMavenResolver; import eu.fasten.core.maven.resolution.MavenResolverIO; import eu.fasten.core.merge.CGMerger; import eu.fasten.core.search.predicate.CachingPredicateFactory; diff --git a/core/src/main/java/eu/fasten/core/utils/Asserts.java b/core/src/main/java/eu/fasten/core/utils/Asserts.java deleted file mode 100644 index a3568dffe..000000000 --- a/core/src/main/java/eu/fasten/core/utils/Asserts.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.utils; - -public class Asserts { - - private Asserts() { - // do not initialize this class - } - - public static void assertNotNull(Object o) { - if (o == null) { - throw $("Should not be null."); - } - } - - public static void assertContains(T[] ts, T e) { - for (T a : ts) { - if (a == null) { - if (e == null) { - return; - } - } else { - if (a.equals(e)) { - return; - } - } - } - throw $("Expected element '%s' not contained in array.", e); - } - - public static void assertNotNullOrEmpty(String s) { - if (s == null || s.isEmpty()) { - throw $("String is null or empty."); - } - } - - public static void assertTrue(boolean condition, String failMsg) { - if (!condition) { - throw $(failMsg); - } - } - - public static void assertTrue(boolean condition) { - if (!condition) { - throw $("Expected condition not met."); - } - } - - // TODO add more assertions as we go - - private static IllegalStateException $(String msg, Object... args) { - String s = String.format(msg, args); - return new IllegalStateException(s); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/data/collections/ImmutableEmptyLinkedHashSet.java b/core/src/main/java/eu/fasten/core/utils/FileUtils.java similarity index 53% rename from core/src/main/java/eu/fasten/core/data/collections/ImmutableEmptyLinkedHashSet.java rename to core/src/main/java/eu/fasten/core/utils/FileUtils.java index 1cbe741a5..1cb1978e3 100644 --- a/core/src/main/java/eu/fasten/core/data/collections/ImmutableEmptyLinkedHashSet.java +++ b/core/src/main/java/eu/fasten/core/utils/FileUtils.java @@ -13,23 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package eu.fasten.core.data.collections; +package eu.fasten.core.utils; -import java.util.Collection; -import java.util.LinkedHashSet; +import java.io.File; +import java.io.IOException; -// required for "Pom" -public class ImmutableEmptyLinkedHashSet extends LinkedHashSet { +public class FileUtils { - private static final long serialVersionUID = -7233644259488131119L; - - // will always be empty, so preventing "add" variants is all that is necessary - - public boolean add(T e) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(Collection c) { - throw new UnsupportedOperationException(); + /** + * Force-deletes the file or directory. + * + * @param file File to be deleted + */ + public static void forceDeleteFile(File file) { + if (file == null) { + return; + } + try { + org.apache.commons.io.FileUtils.forceDelete(file); + } catch (IOException ignored) {} finally { + if (file.exists()) { + file.delete(); + } + } } } \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/utils/HttpUtils.java b/core/src/main/java/eu/fasten/core/utils/HttpUtils.java new file mode 100644 index 000000000..bc5bf4da0 --- /dev/null +++ b/core/src/main/java/eu/fasten/core/utils/HttpUtils.java @@ -0,0 +1,158 @@ +/* + * Copyright 2022 Delft University of Technology + * + * Licensed 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 eu.fasten.core.utils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.ConnectException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import dev.c0ps.maven.MavenUtilities; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class HttpUtils { + + private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class); + + /** + * Utility function that stores the contents of GET request to a temporary file. Used for downloading pom file. + * + * @param url The url of the wanted file. + * @return a temporarily saved file. + */ + private static File httpGetToFile(String url) throws IOException { + logger.debug("HTTP GET: " + url); + try { + final var tempFile = Files.createTempFile("fasten", ".pom"); + + try (ResponseBody response = getHttpResponse(url); InputStream in = response.byteStream()) { + Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING); + } + // TODO why this complicated construct and not just return tempFile? + return tempFile.toAbsolutePath().toFile(); + } catch (ConnectException e) { + // After downloading ~50-60K POMs, there will be a lot of CLOSE_WAIT connections, + // at some point the plug-in runs out of source ports to use. Therefore, we need to crash so that + // Kubernetes will restart the plug-in to kill CLOSE_WAIT connections. + throw new Error("Failing execution, typically due to many CLOSE_WAIT connections", e); + } catch (IOException e) { + logger.error("Error getting file from URL: " + url, e); + throw e; + } + } + + private static ResponseBody getHttpResponse(String url) { + OkHttpClient client = new OkHttpClient(); + Request request = new Request.Builder().url(url).addHeader("Connection", "close").build(); + Call call = client.newCall(request); + + Response response = null; + try { + response = call.execute(); + } catch (IOException e) { + throw new RuntimeException(e); + } + + ResponseBody body = Objects.requireNonNull(response.body()); + if (response.code() == 200) { + return response.body(); + } else { + body.close(); + throw new IllegalStateException("unexpected query result"); + } + } + + public static String sendGetRequest(String url) { + return downloadPomFile(url).flatMap(f -> { + try { + return Optional.of(FileUtils.readFileToString(f, StandardCharsets.UTF_8)); + } catch (IOException e) { + return Optional.empty(); + } + }).orElse(null); + } + + public static Optional downloadPomFile(String pomUrl) { + try { + File pom = httpGetToFile(pomUrl); + return Optional.of(pom); + } catch (IOException e) { + return Optional.empty(); + } + } + + /** + * Download pom file of the given coordinate. + * + * @param groupId groupId of the artifact to find its dependencies + * @param artifactId artifactId of the artifact to find its dependencies + * @param version version of the artifact to find its dependencies + * @return an optional pom file instance + */ + public static Optional downloadPom(String groupId, String artifactId, String version) { + return downloadPom(groupId, artifactId, version, List.of(MavenUtilities.MAVEN_CENTRAL_REPO)); + } + + /** + * Download pom file of the given coordinate with a given set of maven repositories. + * + * @param groupId groupId of the artifact to find its dependencies + * @param artifactId artifactId of the artifact to find its dependencies + * @param version version of the artifact to find its dependencies + * @param mavenRepos the list of predefined maven repositories + * @return an optional pom file instance + */ + public static Optional downloadPom(String groupId, String artifactId, String version, List mavenRepos) { + for (var repo : mavenRepos) { + var pomUrl = getPomUrl(groupId.trim(), artifactId.trim(), version.trim(), repo); + try { + File pom = httpGetToFile(pomUrl); + return Optional.of(pom); + } catch (IOException e2) { + continue; + } + } + return Optional.empty(); + } + + /** + * The utility function for obtaining the url of the pom file of the given coordinates. + * + * @param groupId groupId of the artifact to find its dependencies + * @param artifactId artifactId of the artifact to find its dependencies + * @param version version of the artifact to find its dependencies + * @param repo repository url of the artifact + * @return a string full URL to the anticipated pom file + */ + private static String getPomUrl(String groupId, String artifactId, String version, String repo) { + return repo + groupId.replace('.', '/') + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".pom"; + } + +} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/utils/MemoryUsageUtils.java b/core/src/main/java/eu/fasten/core/utils/MemoryUsageUtils.java deleted file mode 100644 index 58b1c6507..000000000 --- a/core/src/main/java/eu/fasten/core/utils/MemoryUsageUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MemoryUsageUtils { - - private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageUtils.class); - private static final double MEGA = 1024.0 * 1024.0; - - public static void logMemoryUsage() { - System.gc(); - - var max = Runtime.getRuntime().maxMemory() / MEGA; - var curMax = Runtime.getRuntime().totalMemory() / MEGA; - var curFree = Runtime.getRuntime().freeMemory() / MEGA; - var used = curMax - curFree; - - LOG.info("Used memory: {} MB", used); - LOG.info("Heap Size: {} MB (max: {} MB)", curMax, max); - } - - public static void logMaxMemory() { - var mm = Runtime.getRuntime().maxMemory() / MEGA; - LOG.info("Max memory: {} MB", mm); - } -} \ No newline at end of file diff --git a/core/src/main/java/eu/fasten/core/utils/TestUtils.java b/core/src/main/java/eu/fasten/core/utils/TestUtils.java index 8f0f145b2..3100868ed 100644 --- a/core/src/main/java/eu/fasten/core/utils/TestUtils.java +++ b/core/src/main/java/eu/fasten/core/utils/TestUtils.java @@ -27,7 +27,7 @@ public static File getTestResource(String path) { File file = null; URL resource = Thread.currentThread().getContextClassLoader().getResource(path); if(resource == null) { - throw new IllegalArgumentException("test resource not found: " + path); + throw new IllegalArgumentException("test resource not found: " + path); } try { file = new File(new URI(resource.toString()).getPath()); diff --git a/core/src/test/java/eu/fasten/core/data/opal/MavenArtifactDownloaderTest.java b/core/src/test/java/eu/fasten/core/data/opal/MavenArtifactDownloaderTest.java index b74ae6bd6..aaa2bb2f4 100644 --- a/core/src/test/java/eu/fasten/core/data/opal/MavenArtifactDownloaderTest.java +++ b/core/src/test/java/eu/fasten/core/data/opal/MavenArtifactDownloaderTest.java @@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test; import eu.fasten.core.data.opal.exceptions.MissingArtifactException; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; public class MavenArtifactDownloaderTest { diff --git a/core/src/test/java/eu/fasten/core/json/CoreMavenDataModuleTest.java b/core/src/test/java/eu/fasten/core/json/CoreMavenDataModuleTest.java deleted file mode 100644 index 46ee89f9c..000000000 --- a/core/src/test/java/eu/fasten/core/json/CoreMavenDataModuleTest.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.json; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.Set; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.json.JSONObject; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.Exclusion; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.data.VersionConstraint; - -public class CoreMavenDataModuleTest { - - private ObjectMapper om; - - @BeforeEach - public void setup() { - om = new ObjectMapperBuilder() { - @Override - protected ObjectMapper addMapperOptions(ObjectMapper om) { - return om.enable(SerializationFeature.INDENT_OUTPUT); - } - }.build(); - } - - @Test - public void testPom() throws Exception { - var pom = new PomBuilder().pom(); - var json = om.writeValueAsString(pom); - var obj = new JSONObject(json); - assertFalse(obj.has("ga")); - assertFalse(obj.has("gav")); - assertFalse(obj.has("hashCode")); - } - - @Test - public void testDependencyOldCanBeRead() throws Exception { - var json = "{\"versionConstraints\":[\"[1,2]\"],\"groupId\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"artifactId\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":false,\"type\":\"type\"}"; - var actual = om.readValue(json, Dependency.class); - var expected = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), - Set.of(new Exclusion("g2", "a2")), Scope.TEST, false, "type", "sources"); - assertEquals(expected, actual); - } - - @Test - public void testDependencyFixNonEmptyVersionConstraintsOld() throws Exception { - var json = "{\"versionConstraints\":[\"\"],\"groupId\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"artifactId\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":true,\"type\":\"type\"}"; - var out = om.readValue(json, Dependency.class); - assertTrue(out.getVersionConstraints().isEmpty()); - } - - @Test - public void testDependency() { - var d = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), Set.of(new Exclusion("g2", "a2")), - Scope.TEST, true, "type", "sources"); - var json = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"a\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":true,\"type\":\"type\"}"; - test(d, json); - } - - @Test - public void testDependencyDefault() { - var d = new Dependency("g", "a", "v"); - var json = "{\"v\":[\"v\"],\"g\":\"g\",\"a\":\"a\"}"; - test(d, json); - } - - @Test - public void testDependency_compileScope() { - var d = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), Set.of(new Exclusion("g2", "a2")), - Scope.COMPILE, true, "type", "sources"); - var json = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"classifier\":\"sources\",\"a\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":true,\"type\":\"type\"}"; - test(d, json); - } - - @Test - public void testDependency_nonOptional() { - var d = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), Set.of(new Exclusion("g2", "a2")), - Scope.TEST, false, "type", "sources"); - var json = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"a\":\"a1\",\"exclusions\":[\"g2:a2\"],\"type\":\"type\"}"; - test(d, json); - } - - @Test - public void testDependency_noExclusions() { - var d = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), Set.of(), Scope.TEST, true, "type", - "sources"); - var json = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"a\":\"a1\",\"optional\":true,\"type\":\"type\"}"; - test(d, json); - } - - @Test - public void testDependency_invalidExclusion() throws JsonMappingException, JsonProcessingException { - // This is a regression test that reflects old json data, which can contain - // broken serializations. This does not happen anymore for newly generated data. - var rawDep = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"a\":\"a1\",\"exclusions\":[%s],\"type\":\"type\"}"; - for (var jsonExcl : new String[] { "", "\"\"", "\"x\"", "\":\"", "\"x:\"", "\":x\"", "\"x:y:\"", "\":x:y\"", - "\"x:y:z\"" }) { - - var jsonDep = String.format(rawDep, jsonExcl); - - var actual = om.readValue(jsonDep, Dependency.class).getExclusions(); - var expected = Set.of(); - // not just equals, needs to be the same singleton - assertSame(expected, actual); - } - } - - @Test - public void testDependency_jarType() { - var d = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), Set.of(new Exclusion("g2", "a2")), - Scope.TEST, true, "jar", "sources"); - var json = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"a\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":true}"; - test(d, json); - } - - @Test - public void testDependency_noClassifier() { - var d = new Dependency("g1", "a1", Set.of(new VersionConstraint("[1,2]")), Set.of(new Exclusion("g2", "a2")), - Scope.TEST, true, "type", ""); - var json = "{\"v\":[\"[1,2]\"],\"g\":\"g1\",\"scope\":\"test\",\"a\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":true,\"type\":\"type\"}"; - test(d, json); - } - - @Test - public void testDependencyFixNonEmptyVersionConstraints() throws Exception { - var json = "{\"v\":[\"\"],\"g\":\"g1\",\"scope\":\"test\",\"classifier\":\"sources\",\"a\":\"a1\",\"exclusions\":[\"g2:a2\"],\"optional\":true,\"type\":\"type\"}"; - var out = om.readValue(json, Dependency.class); - assertTrue(out.getVersionConstraints().isEmpty()); - } - - @Test - public void testVersionConstraint() { - var vc = new VersionConstraint("[1,2]"); - test(vc, "\"[1,2]\""); - } - - @Test - public void testExclusion() { - var e = new Exclusion("gid", "aid"); - test(e, "\"gid:aid\""); - } - - @Test - public void testHashCodeDependency() { - assertHashCodeAfterSerialization(new Dependency("g", "a", "v")); - } - - @Test - public void testHashCodePom() { - var pb = new PomBuilder(); - pb.artifactId = "a"; - pb.groupId = "g"; - assertHashCodeAfterSerialization(pb.pom()); - } - - @Test - public void testHashCodeExclusion() { - assertHashCodeAfterSerialization(new Exclusion("gid", "aid")); - } - - @Test - public void testHashCodeVersionConstraint() { - assertHashCodeAfterSerialization(new VersionConstraint("1.2.3")); - } - - private void assertHashCodeAfterSerialization(Object in) { - try { - assertNotEquals(0, in.hashCode()); - var json = om.writeValueAsString(in); - var out = om.readValue(json, in.getClass()); - assertEquals(in.hashCode(), out.hashCode()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void testDefaultArtifactVersion() { - test(new DefaultArtifactVersion("1.2.3"), "\"1.2.3\""); - test(new DefaultArtifactVersion("2.3.4-classifier"), "\"2.3.4-classifier\""); - test(new DefaultArtifactVersion("3"), "\"3\""); - test(new DefaultArtifactVersion("4.5"), "\"4.5\""); - } - - private void test(Object in, String expectedJson) { - try { - assertNotEquals(0, in.hashCode()); - var json = om.writeValueAsString(in); - assertJsonEquals(expectedJson, json); - var out = om.readValue(json, in.getClass()); - assertEquals(in, out); - assertEquals(in.hashCode(), out.hashCode()); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - } - - private void assertJsonEquals(String expectedJson, String actualJson) { - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/data/collections/ImmutableEmptyLinkedHashSetTest.java b/core/src/test/java/eu/fasten/core/json/FastenObjectMapperBuilderTest.java similarity index 56% rename from core/src/test/java/eu/fasten/core/data/collections/ImmutableEmptyLinkedHashSetTest.java rename to core/src/test/java/eu/fasten/core/json/FastenObjectMapperBuilderTest.java index 97dcd98d0..66b6222c9 100644 --- a/core/src/test/java/eu/fasten/core/data/collections/ImmutableEmptyLinkedHashSetTest.java +++ b/core/src/test/java/eu/fasten/core/json/FastenObjectMapperBuilderTest.java @@ -13,35 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package eu.fasten.core.data.collections; +package eu.fasten.core.json; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ImmutableEmptyLinkedHashSetTest { +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import dev.c0ps.maven.data.Exclusion; + +public class FastenObjectMapperBuilderTest { - private ImmutableEmptyLinkedHashSet sut; + private ObjectMapper sut; @BeforeEach public void setup() { - sut = new ImmutableEmptyLinkedHashSet<>(); - } - - @Test - public void cannotAdd() { - assertThrows(UnsupportedOperationException.class, () -> { - sut.add("..."); - }); + sut = new FastenObjectMapperBuilder().build(); } @Test - public void cannotAddAll() { - assertThrows(UnsupportedOperationException.class, () -> { - sut.addAll(Set.of("...")); - }); + public void hasRegistrationForCoreMavenDataModule() throws JsonProcessingException { + var in = new Exclusion("g", "a"); + var actual = sut.writeValueAsString(in); + assertEquals("\"g:a\"", actual); } } \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/json/ObjectMapperBuilderTest.java b/core/src/test/java/eu/fasten/core/json/ObjectMapperBuilderTest.java deleted file mode 100644 index eee290e20..000000000 --- a/core/src/test/java/eu/fasten/core/json/ObjectMapperBuilderTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.json; - -import static com.fasterxml.jackson.databind.SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID; -import static java.nio.charset.StandardCharsets.UTF_8; -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.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.time.LocalDateTime; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; - -import org.apache.commons.io.FileUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.json.JsonMapper.Builder; - -public class ObjectMapperBuilderTest { - - private static final SerializationFeature SOME_FEATURE = USE_EQUALITY_FOR_OBJECT_ID; - - private ObjectMapper sut; - - @TempDir - private File tempDir; - - @BeforeEach - public void setup() { - sut = new ObjectMapperBuilder().build(); - } - - @Test - public void defaultConfig() { - sut = new ObjectMapperBuilder().build(); - assertFalse(sut.isEnabled(SOME_FEATURE)); - } - - @Test - public void canAddBuilderOptions() { - sut = new ObjectMapperBuilder() { - @Override - protected Builder addBuilderOptions(Builder b) { - return b.enable(SOME_FEATURE); - } - }.build(); - assertTrue(sut.isEnabled(SOME_FEATURE)); - } - - @Test - public void canAddMapperOptions() { - sut = new ObjectMapperBuilder() { - protected ObjectMapper addMapperOptions(ObjectMapper om) { - return om.enable(SOME_FEATURE); - } - }.build(); - assertTrue(sut.isEnabled(SOME_FEATURE)); - } - - @Test - public void doesNotStoreNullEmptyOrDefaultFields() throws JsonProcessingException { - sut = new ObjectMapperBuilder().build(); - var data = new TestData(); - data.y3 = true; - var actual = sut.writeValueAsString(data); - assertEquals("{\"y1\":\"y1\",\"y2\":[\"y2\"],\"y3\":true,\"y4\":[],\"y5\":false,\"y6\":false}", actual); - } - - @Test - public void doesNotCloseTargets() throws IOException { - sut = new ObjectMapperBuilder().build(); - var f = new File(tempDir, "abc.asd"); - try (var os = new FileOutputStream(f)) { - sut.writeValue(os, "123"); - os.write("4".getBytes()); - } - // test is successful if no exception is thrown - } - - @Test - public void doesNotCloseSources() throws IOException { - sut = new ObjectMapperBuilder().build(); - var f = new File(tempDir, "abc.asd"); - FileUtils.writeStringToFile(f, "\"abc\"", UTF_8); - try (var os = new FileInputStream(f)) { - sut.readValue(os, String.class); - os.read(); - } - // test is successful if no exception is thrown - } - - @Test - public void jsr310() throws JsonProcessingException { - // will crash with missing import - var ldt = LocalDateTime.now(); - sut.writeValueAsString(ldt); - } - - @Test - public void java8() throws JsonProcessingException { - var o = Optional.of("..."); - var json = sut.writeValueAsString(o); - assertEquals("\"...\"", json); - } - - @SuppressWarnings("unused") - private static class TestData { - public String y1 = "y1"; - public Set y2 = Set.of("y2"); - public boolean y3 = false; - - // empty - public Set y4 = new HashSet<>(); - - // defaults - public boolean y5; - public boolean y6 = false; - - public String n1 = null; - public Set n2 = null; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/DependencyTest.java b/core/src/test/java/eu/fasten/core/maven/data/DependencyTest.java deleted file mode 100644 index 697594635..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/DependencyTest.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.TEST; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -@SuppressWarnings("deprecation") -public class DependencyTest { - - @Test - public void defaults() { - var sut = new Dependency("a", "b", "1"); - assertEquals("a", sut.groupId); - assertEquals("b", sut.artifactId); - - assertEquals("1", sut.getVersion()); - assertEquals(Set.of(new VersionConstraint("1")), sut.getVersionConstraints()); - assertArrayEquals(new String[] { "1" }, sut.getVersionConstraintsArr()); - - assertEquals(Set.of(), sut.getExclusions()); - assertEquals("", sut.getClassifier()); - assertEquals("jar", sut.getPackagingType()); - assertEquals(COMPILE, sut.getScope()); - - assertFalse(sut.isOptional()); - } - - @Test - public void nonDefaults() { - var sut = getSomeDep(); - assertEquals("gid", sut.groupId); - assertEquals("aid", sut.artifactId); - - assertEquals("(1.2.3,2.3.4]", sut.getVersion()); - assertEquals(Set.of(new VersionConstraint("(1.2.3,2.3.4]")), sut.getVersionConstraints()); - assertArrayEquals(new String[] { "(1.2.3,2.3.4]" }, sut.getVersionConstraintsArr()); - - assertEquals(Set.of(new Exclusion("gid2", "aid2")), sut.getExclusions()); - assertEquals("sources", sut.getClassifier()); - assertEquals("pom", sut.getPackagingType()); - assertEquals(PROVIDED, sut.getScope()); - - assertTrue(sut.isOptional()); - } - - @Test - public void noCrashOnNullPackagingType() { - var sut = new Dependency("gid", "aid", Set.of(new VersionConstraint("(1.2.3,2.3.4]")), - Set.of(new Exclusion("gid2", "aid2")), PROVIDED, true, null, "sources"); - assertEquals("jar", sut.getPackagingType()); - } - - @Test - public void noCrashOnEmptyPackagingType() { - var sut = new Dependency("gid", "aid", Set.of(new VersionConstraint("(1.2.3,2.3.4]")), - Set.of(new Exclusion("gid2", "aid2")), PROVIDED, true, "", "sources"); - assertEquals("jar", sut.getPackagingType()); - } - - @Test - public void noCrashOnNullClassifier() { - var sut = new Dependency("gid", "aid", Set.of(new VersionConstraint("(1.2.3,2.3.4]")), - Set.of(new Exclusion("gid2", "aid2")), PROVIDED, true, "pom", null); - assertEquals("", sut.getClassifier()); - } - - @Test - public void hasToString() { - var actual = getSomeDep().toString(); - assertTrue(actual.contains(Dependency.class.getSimpleName())); - assertTrue(actual.contains("@")); - assertTrue(actual.contains("\n")); - assertTrue(actual.contains("versionConstraints")); - } - - @Test - public void toGA() { - var actual = new Dependency("g", "a", "1.2.3").toGA(); - var expected = new GA("g", "a"); - assertEquals(expected, actual); - } - - @Test - public void toGAIsStable() { - var a = new Dependency("g", "a", "1.2.3").toGA(); - var b = new Dependency("g", "a", "1.2.3").toGA(); - assertSame(a, b); - } - - @Test - public void equalityDefaults() { - var a = new Dependency("g", "a", "1"); - var b = new Dependency("g", "a", "1"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityNonDefaults() { - var a = getSomeDep(); - var b = getSomeDep(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffVersions() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1), vc(2)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffExclusions() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1), ex(2)), COMPILE, true, "jar", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffGroup() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g2", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffArtifact() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a2", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffType() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "war", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffClassifier() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "d"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffScope() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), TEST, true, "jar", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffOptional() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, false, "jar", "c"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void dependencyTest() { - var expected = new Dependency("junit", "junit", "4.11"); - var json = expected.toJSON(); - var actual = Dependency.fromJSON(json); - assertEquals(expected, actual); - } - - @Test - public void equalsTest() { - Assertions.assertEquals( // - new Dependency("junit", "junit", "4.12"), // - new Dependency("junit", "junit", parseVersionSpec("4.12"), new HashSet<>(), COMPILE, false, "jar", "")); - } - - @Test - public void jsonRoundtripViaObj() { - var a = getSomeDep(); - var jsonObj = a.toJSON(); - var b = Dependency.fromJSON(jsonObj); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void jsonRoundtripViaString() { - var a = getSomeDep(); - var json = a.toJSON().toString(); - var jsonObj = new JSONObject(json); - var b = Dependency.fromJSON(jsonObj); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void jsonHasRightFields() { - - var expected = new HashMap>(); - expected.put("artifactId", String.class); - expected.put("groupId", String.class); - expected.put("type", String.class); - expected.put("versionConstraints", JSONArray.class); - expected.put("exclusions", JSONArray.class); - expected.put("scope", Scope.class); - expected.put("classifier", String.class); - expected.put("optional", Boolean.class); - - var actual = getSomeDep().toJSON(); - for (var expectedField : expected.keySet()) { - var expectedType = expected.get(expectedField); - - if (!actual.has(expectedField)) { - fail(String.format("Resulting json object is missing field '%s'", expectedField)); - } - var obj = actual.get(expectedField); - assertNotNull(obj); - var objType = obj.getClass(); - if (!expectedType.isAssignableFrom(objType)) { - fail(String.format("Expected type %s, but was %s", expectedType, objType)); - } - } - } - - @Test - public void equality() { - var a = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - var b = new Dependency("g", "a", Set.of(vc(1)), Set.of(ex(1)), COMPILE, true, "jar", "c"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - private Exclusion ex(int i) { - return new Exclusion("g" + i, "a" + i); - } - - private VersionConstraint vc(int v) { - return new VersionConstraint("" + v); - } - - public static Dependency getSomeDep() { - return new Dependency("gid", "aid", Set.of(new VersionConstraint("(1.2.3,2.3.4]")), - Set.of(new Exclusion("gid2", "aid2")), PROVIDED, true, "pom", "sources"); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/ExclusionTest.java b/core/src/test/java/eu/fasten/core/maven/data/ExclusionTest.java deleted file mode 100644 index 00b5cfd5f..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/ExclusionTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.Assert.assertNull; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.junit.jupiter.api.Test; - -public class ExclusionTest { - - @Test - public void defaultValues() { - var sut = new Exclusion(null, null); - assertNull(sut.artifactId); - assertNull(sut.groupId); - } - - @Test - public void nonDefaultValues() { - var sut = new Exclusion("g", "a"); - assertEquals("g", sut.groupId); - assertEquals("a", sut.artifactId); - assertNotEquals(0, sut.hashCode()); - } - - @Test - public void equalityDefault() { - var a = new Exclusion(null, null); - var b = new Exclusion(null, null); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityNonDefault() { - var a = new Exclusion("g", "a"); - var b = new Exclusion("g", "a"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentGroup() { - var a = new Exclusion("g", "a"); - var b = new Exclusion("g2", "a"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentArtifact() { - var a = new Exclusion("g", "a"); - var b = new Exclusion("g", "a2"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - @SuppressWarnings("deprecation") - public void legacyJson() { - var sut = new Exclusion("g", "a"); - assertEquals("g:a", sut.toJSON()); - var clone = Exclusion.fromJSON("g:a"); - assertEquals(sut, clone); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/GATest.java b/core/src/test/java/eu/fasten/core/maven/data/GATest.java deleted file mode 100644 index d8395c2ab..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/GATest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -public class GATest { - - @Test - public void init() { - var sut = new GA("g", "a"); - assertEquals("g", sut.groupId); - assertEquals("a", sut.artifactId); - } - - @Test - public void equality() { - var a = new GA("g", "a"); - var b = new GA("g", "a"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffGroup() { - var a = new GA("g", "a"); - var b = new GA("g2", "a"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffArtifact() { - var a = new GA("g", "a"); - var b = new GA("g2", "a"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void hasToString() { - assertEquals("g:a", new GA("g", "a").toString()); - } - - @Test - public void fromCorrectString() { - assertEquals("g:a", GA.fromString("g:a").toString()); - } - - @Test - public void fromBadString() { - assertThrows(IllegalArgumentException.class, () -> GA.fromString("ga")); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/GAVTest.java b/core/src/test/java/eu/fasten/core/maven/data/GAVTest.java deleted file mode 100644 index a7b496bdf..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/GAVTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.junit.jupiter.api.Test; - -public class GAVTest { - - @Test - public void init() { - var sut = new GAV("g", "a", "1"); - assertEquals("g", sut.groupId); - assertEquals("a", sut.artifactId); - assertEquals("1", sut.version); - } - - @Test - public void equality() { - var a = new GAV("g", "a", "1"); - var b = new GAV("g", "a", "1"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffGroup() { - var a = new GAV("g", "a", "1"); - var b = new GAV("g2", "a", "1"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffArtifact() { - var a = new GAV("g", "a", "1"); - var b = new GAV("g", "a2", "1"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffVersion() { - var a = new GAV("g", "a", "1"); - var b = new GAV("g", "a", "2"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void hasToString() { - assertEquals("g:a:1", new GAV("g", "a", "1").toString()); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/IdsTest.java b/core/src/test/java/eu/fasten/core/maven/data/IdsTest.java deleted file mode 100644 index 5bd12bf44..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/IdsTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.Assert.assertSame; - -import org.junit.jupiter.api.Test; - -public class IdsTest { - - @Test - public void gid() { - var a = Ids.gid("a"); - var b = Ids.gid("a"); - assertSame(a, b); - } - - @Test - public void aid() { - var a = Ids.aid("a"); - var b = Ids.aid("a"); - assertSame(a, b); - } - - @Test - public void version() { - var a = Ids.version("1"); - var b = Ids.version("1"); - assertSame(a, b); - } - - @Test - public void versionConstraint() { - var a = Ids.versionConstraint(new VersionConstraint("1")); - var b = Ids.versionConstraint(new VersionConstraint("1")); - assertSame(a, b); - } - - @Test - public void dep() { - var a = Ids.dep(new Dependency("g", "a", "1")); - var b = Ids.dep(new Dependency("g", "a", "1")); - assertSame(a, b); - } - - @Test - public void gav() { - var a = Ids.gav(new GAV("g", "a", "1")); - var b = Ids.gav(new GAV("g", "a", "1")); - assertSame(a, b); - } - - @Test - public void ga() { - var a = Ids.ga(new GA("g", "a")); - var b = Ids.ga(new GA("g", "a")); - assertSame(a, b); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/MavenProductTest.java b/core/src/test/java/eu/fasten/core/maven/data/MavenProductTest.java deleted file mode 100644 index 19f6009b3..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/MavenProductTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.junit.jupiter.api.Test; - -public class MavenProductTest { - - @Test - public void defaultsInitNoArgs() { - var sut = new MavenProduct(); - assertEquals(0, sut.id); - assertNull(sut.getGroupId()); - assertNull(sut.getArtifactId()); - } - - @Test - public void defaultsInit1() { - var sut = new MavenProduct("g", "a"); - assertEquals(0, sut.id); - assertEquals("g", sut.getGroupId()); - assertEquals("a", sut.getArtifactId()); - } - - @Test - public void defaultsInit2() { - var sut = new MavenProduct(1, "g", "a"); - assertEquals(1, sut.id); - assertEquals("g", sut.getGroupId()); - assertEquals("a", sut.getArtifactId()); - } - - @Test - public void equalityDefault() { - var a = new MavenProduct(); - var b = new MavenProduct(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityActualValues() { - var a = new MavenProduct(1, "g", "a"); - var b = new MavenProduct(1, "g", "a"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDespiteDifferentId() { - var a = new MavenProduct(1, "g", "a"); - var b = new MavenProduct(2, "g", "a"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentGroup() { - var a = new MavenProduct(1, "g", "a"); - var b = new MavenProduct(1, "g2", "a"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentArtifact() { - var a = new MavenProduct(1, "g", "a"); - var b = new MavenProduct(1, "g", "a2"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void setGroupId() { - var sut = new MavenProduct(); - sut.setGroupId("g"); - assertEquals("g", sut.getGroupId()); - } - - @Test - public void setArtifactId() { - var sut = new MavenProduct(); - sut.setArtifactId("a"); - assertEquals("a", sut.getArtifactId()); - } - - @Test - public void hasToString() { - var actual = new MavenProduct(1, "g", "a").toString(); - assertTrue(actual.contains(MavenProduct.class.getSimpleName())); - assertTrue(actual.contains("\n")); - assertTrue(actual.contains("@")); - assertTrue(actual.contains("artifactId")); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/PomBuilderTest.java b/core/src/test/java/eu/fasten/core/maven/data/PomBuilderTest.java deleted file mode 100644 index 0828e72dc..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/PomBuilderTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.Assert.assertNull; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.LinkedHashSet; -import java.util.Set; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.data.Constants; - -public class PomBuilderTest { - - private static final Dependency SOME_DEP = new Dependency("g", "a", "1"); - private static final Dependency SOME_DEP2 = new Dependency("g2", "a2", "2"); - - private PomBuilder sut; - - @BeforeEach - public void setup() { - sut = new PomBuilder(); - } - - @Test - public void defaults() { - var pom = sut.pom(); - - assertEquals(0L, pom.id); - assertEquals(Constants.mvnForge, pom.forge); - - assertNull(pom.artifactId); - assertNull(pom.groupId); - assertNull(pom.packagingType); - assertNull(pom.version); - - assertNull(pom.parentCoordinate); - - assertEquals(-1L, pom.releaseDate); - assertNull(pom.projectName); - - assertEquals(Set.of(), pom.dependencies); - assertEquals(Set.of(), pom.dependencyManagement); - - assertNull(pom.repoUrl); - assertNull(pom.commitTag); - assertNull(pom.sourcesUrl); - assertNull(pom.artifactRepository); - } - - @Test - public void nonDefaults() { - - sut.groupId = "g"; - sut.artifactId = "a"; - sut.packagingType = "pt"; - sut.version = "1.2.3"; - - sut.parentCoordinate = "pc"; - - sut.releaseDate = 234; - sut.projectName = "pn"; - - sut.dependencies.add(SOME_DEP); - sut.dependencyManagement.add(SOME_DEP2); - - sut.repoUrl = "ru"; - sut.commitTag = "ct"; - sut.sourcesUrl = "su"; - sut.artifactRepository = "ar"; - - var pom = sut.pom(); - - assertEquals(0L, pom.id); - assertEquals(Constants.mvnForge, pom.forge); - - assertEquals("a", pom.artifactId); - assertEquals("g", pom.groupId); - assertEquals("pt", pom.packagingType); - assertEquals("1.2.3", pom.version); - - assertEquals("pc", pom.parentCoordinate); - - assertEquals(234L, pom.releaseDate); - assertEquals("pn", pom.projectName); - - assertEquals(Set.of(SOME_DEP), pom.dependencies); - assertEquals(Set.of(SOME_DEP2), pom.dependencyManagement); - - assertEquals("ru", pom.repoUrl); - assertEquals("ct", pom.commitTag); - assertEquals("su", pom.sourcesUrl); - assertEquals("ar", pom.artifactRepository); - } - - @Test - public void setGroupId() { - var pom = sut.groupId("g").pom(); - assertEquals("g", pom.groupId); - } - - @Test - public void setArtifactId() { - var pom = sut.artifactId("a").pom(); - assertEquals("a", pom.artifactId); - } - - @Test - public void setPackagingType() { - var pom = sut.packagingType("jar").pom(); - assertEquals("jar", pom.packagingType); - } - - @Test - public void setVersion() { - var pom = sut.version("1").pom(); - assertEquals("1", pom.version); - } - - @Test - public void setParentCoordinate() { - var pom = sut.parentCoordinate("p").pom(); - assertEquals("p", pom.parentCoordinate); - } - - @Test - public void setReleaseDate() { - var pom = sut.releaseDate(123L).pom(); - assertEquals(123L, pom.releaseDate); - } - - @Test - public void setProjectName() { - var pom = sut.projectName("pn").pom(); - assertEquals("pn", pom.projectName); - } - - @Test - public void addDependency() { - var pom = sut.addDependency(SOME_DEP).pom(); - assertEquals(Set.of(SOME_DEP), pom.dependencies); - } - - @Test - public void setDependency() { - var deps = new LinkedHashSet(); - deps.add(SOME_DEP); - var pom = sut.setDependencies(deps).pom(); - assertEquals(Set.of(SOME_DEP), pom.dependencies); - } - - @Test - public void addDependencyManagement() { - var pom = sut.addDependencyManagement(SOME_DEP).pom(); - assertEquals(Set.of(SOME_DEP), pom.dependencyManagement); - } - - @Test - public void setDependencyManagement() { - var deps = new LinkedHashSet(); - deps.add(SOME_DEP); - var pom = sut.setDependencyManagement(deps).pom(); - assertEquals(Set.of(SOME_DEP), pom.dependencyManagement); - } - - @Test - public void setRepoUrl() { - var pom = sut.repoUrl("r").pom(); - assertEquals("r", pom.repoUrl); - } - - @Test - public void setCommitTag() { - var pom = sut.commitTag("p").pom(); - assertEquals("p", pom.commitTag); - } - - @Test - public void setSourcesUrl() { - var pom = sut.sourcesUrl("p").pom(); - assertEquals("p", pom.sourcesUrl); - } - - @Test - public void setArtifactRepository() { - var pom = sut.artifactRepository("ar").pom(); - assertEquals("ar", pom.artifactRepository); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/PomTest.java b/core/src/test/java/eu/fasten/core/maven/data/PomTest.java deleted file mode 100644 index a0debe711..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/PomTest.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static java.util.stream.IntStream.range; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -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.sql.Timestamp; - -import org.junit.jupiter.api.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; - -import eu.fasten.core.json.ObjectMapperBuilder; - -public class PomTest { - - @Test - public void defaults() { - var sut = pb().pom(); - assertNull(sut.artifactId); - assertNull(sut.artifactRepository); - assertNull(sut.commitTag); - assertNotNull(sut.dependencies); - assertNotNull(sut.dependencyManagement); - assertEquals("mvn", sut.forge); - assertNull(sut.groupId); - assertNull(sut.packagingType); - assertNull(sut.parentCoordinate); - assertNull(sut.projectName); - assertEquals(-1L, sut.releaseDate); - assertNull(sut.repoUrl); - assertNull(sut.sourcesUrl); - assertNull(sut.version); - } - - @Test - public void equalityDefault() { - var a = pb().pom(); - var b = pb().pom(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityNonDefault() { - var a = pbX().pom(); - var b = pbX().pom(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffArtifact() { - var a = pb().pom(); - var b = pb().artifactId("a").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffArtifactRepo() { - var a = pb().pom(); - var b = pb().artifactRepository("ar").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffCommitTag() { - var a = pb().pom(); - var b = pb().commitTag("c").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffDep() { - var a = pb().pom(); - var b = pb().addDependency(someDependency("d")).pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffDepMgmt() { - var a = pb().pom(); - var b = pb().addDependencyManagement(someDependency("e")).pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffGroup() { - var a = pb().pom(); - var b = pb().groupId("g").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffPackaging() { - var a = pb().pom(); - var b = pb().packagingType("t").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffParent() { - var a = pb().pom(); - var b = pb().parentCoordinate("p").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffName() { - var a = pb().pom(); - var b = pb().projectName("p").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffReleaseDate() { - var a = pb().pom(); - var b = pb().releaseDate(123).pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffRepoUrl() { - var a = pb().pom(); - var b = pb().repoUrl("r").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffSourcesUrl() { - var a = pb().pom(); - var b = pb().sourcesUrl("s").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDiffVersion() { - var a = pb().pom(); - var b = pb().version("v").pom(); - - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void hasToString() { - var actual = pb().pom().toString(); - - assertTrue(actual.contains(Pom.class.getSimpleName())); - assertTrue(actual.contains("\n")); - assertTrue(actual.split("\n")[0].contains("@")); - assertTrue(actual.contains("artifactId")); - } - - @Test - public void canBeCloned() { - var a = pbX().pom(); - var b = a.clone().pom(); - assertEquals(a, b); - assertNotSame(a, b); - - assertEquals(a.dependencies, b.dependencies); - assertNotSame(a.dependencies, b.dependencies); - - assertEquals(a.dependencyManagement, b.dependencyManagement); - assertNotSame(a.dependencyManagement, b.dependencyManagement); - } - - @Test - public void dependencyOrderIsPreserved() throws JsonProcessingException { - var pb = new PomBuilder(); - range(0, 100).forEach(num -> { - pb.dependencies.add(new Dependency("g", "a", String.valueOf(num))); - }); - var sut = pb.pom(); - - var check = 0; - for (var d : sut.dependencies) { - var v = assertSingleVersionConstraint(d); - assertEquals(check++, Integer.valueOf(v)); - } - - check = 0; - for (var d : jsonRoundtrip(sut).dependencies) { - var v = assertSingleVersionConstraint(d); - assertEquals(check++, Integer.valueOf(v)); - } - } - - @Test - public void toCoordinate() { - var actual = pbX().pom().toCoordinate(); - var expected = "g:a:h:n"; - assertEquals(expected, actual); - } - - @Test - public void toGAV() { - var actual = pbX().pom().toGAV(); - var expected = new GAV("g", "a", "n"); - assertEquals(expected, actual); - } - - @Test - public void toGAVIsStable() { - var a = pbX().pom().toGAV(); - var b = pbX().pom().toGAV(); - assertSame(a, b); - } - - @Test - public void toGA() { - var actual = pbX().pom().toGA(); - var expected = new GA("g", "a"); - assertEquals(expected, actual); - } - - @Test - public void toGAIsStable() { - var a = pbX().pom().toGA(); - var b = pbX().pom().toGA(); - assertSame(a, b); - } - - @Test - public void toProduct() { - var actual = pbX().pom().toProduct(); - var expected = new MavenProduct("g", "a"); - assertEquals(expected, actual); - } - - @Test - public void toRevision() { - var actual = pbX().pom().toRevision(); - var expected = new Revision("g", "a", "n", new Timestamp(123)); - assertEquals(expected, actual); - } - - private static PomBuilder pb() { - return new PomBuilder(); - } - - private static PomBuilder pbX() { - var pb = new PomBuilder(); - pb.artifactId = "a"; - pb.artifactRepository = "b"; - pb.commitTag = "c"; - pb.dependencies.add(someDependency("d")); - pb.dependencyManagement.add(someDependency("e")); - pb.groupId = "g"; - pb.packagingType = "h"; - pb.parentCoordinate = "i"; - pb.projectName = "j"; - pb.releaseDate = 123; - pb.repoUrl = "k"; - pb.sourcesUrl = "m"; - pb.version = "n"; - return pb; - } - - private static Dependency someDependency(String name) { - return new Dependency("dep", name, "0.0.1"); - } - - private static Pom jsonRoundtrip(Pom sut) throws JsonProcessingException, JsonMappingException { - var om = new ObjectMapperBuilder().build(); - var json = om.writeValueAsString(sut); - // make sure custom serializers are registered - assertTrue(json.contains("\"v\":[\"0\"]")); - var sut2 = om.readValue(json, Pom.class); - assertEquals(sut, sut2); - return sut2; - } - - private static String assertSingleVersionConstraint(Dependency d) { - var cs = d.getVersionConstraints(); - assertEquals(1, cs.size()); - return cs.iterator().next().getSpec(); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/ResolvedRevisionTest.java b/core/src/test/java/eu/fasten/core/maven/data/ResolvedRevisionTest.java deleted file mode 100644 index d7d150228..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/ResolvedRevisionTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static eu.fasten.core.maven.data.Scope.IMPORT; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.sql.Timestamp; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.junit.jupiter.api.Test; - -public class ResolvedRevisionTest { - - private static final ResolvedRevision SOME_REV = new ResolvedRevision(123, "g", "a", "v", new Timestamp(234), - IMPORT); - - @Test - public void init1() { - var actual = SOME_REV; - assertEquals("a", actual.artifactId); - assertEquals(new Timestamp(234), actual.createdAt); - assertEquals("g", actual.groupId); - assertEquals(123, actual.id); - assertEquals(IMPORT, actual.scope); - assertEquals(new DefaultArtifactVersion("v"), actual.version); - } - - @Test - public void init2() { - var in = new Revision(123, "g", "a", "v", new Timestamp(234)); - var actual = new ResolvedRevision(in, IMPORT); - assertEquals("a", actual.artifactId); - assertEquals(new Timestamp(234), actual.createdAt); - assertEquals("g", actual.groupId); - assertEquals(123, actual.id); - assertEquals(IMPORT, actual.scope); - assertEquals(new DefaultArtifactVersion("v"), actual.version); - } - - @Test - public void initDefault() { - var actual = new ResolvedRevision(); - assertEquals(null, actual.artifactId); - assertEquals(null, actual.createdAt); - assertEquals(null, actual.groupId); - assertEquals(0, actual.id); - assertEquals(null, actual.scope); - assertEquals(null, actual.version); - } - - @Test - public void equalityDefault() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityNonDefault() { - var a = SOME_REV; - var b = SOME_REV; - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentIdDoesNotMatter() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - b.id = 123; - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentGroup() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - b.groupId = "g"; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentArtifact() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - b.artifactId = "a"; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentVersion() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - b.version = new DefaultArtifactVersion("v"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentTimestampDoesNotMatter() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - b.createdAt = new Timestamp(123); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentScopeDoesNotMatter() { - var a = new ResolvedRevision(); - var b = new ResolvedRevision(); - b.scope = Scope.IMPORT; - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/RevisionTest.java b/core/src/test/java/eu/fasten/core/maven/data/RevisionTest.java deleted file mode 100644 index ef0c14377..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/RevisionTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.sql.Timestamp; - -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.junit.jupiter.api.Test; - -public class RevisionTest { - - private static final Timestamp SOME_TIMESTAMP = new Timestamp(1234567890L); - private static final Timestamp OTHER_TIMESTAMP = new Timestamp(2345678901L); - - @Test - public void defaultsInitNoArgs() { - var sut = new Revision(); - assertEquals(0, sut.id); - assertNull(sut.groupId); - assertNull(sut.artifactId); - assertNull(sut.version); - assertNull(sut.createdAt); - } - - @Test - public void defaultsInit1() { - var sut = new Revision("g", "a", "1.2.3", SOME_TIMESTAMP); - assertEquals(0, sut.id); - assertEquals("g", sut.groupId); - assertEquals("a", sut.artifactId); - assertEquals(new DefaultArtifactVersion("1.2.3"), sut.version); - assertEquals(SOME_TIMESTAMP, sut.createdAt); - } - - @Test - public void defaultsInit2() { - var sut = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - assertEquals(1234, sut.id); - assertEquals("g", sut.groupId); - assertEquals("a", sut.artifactId); - assertEquals(new DefaultArtifactVersion("1.2.3"), sut.version); - assertEquals(SOME_TIMESTAMP, sut.createdAt); - } - - @Test - public void equality() { - var a = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - var b = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDespiteDifferentId() { - var a = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - var b = new Revision(2345, "g", "a", "1.2.3", SOME_TIMESTAMP); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDespiteDifferentTimestamp() { - var a = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - var b = new Revision(1234, "g", "a", "1.2.3", OTHER_TIMESTAMP); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentGroupId() { - var a = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - var b = new Revision(1234, "g2", "a", "1.2.3", SOME_TIMESTAMP); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentArtifactId() { - var a = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - var b = new Revision(1234, "g", "a2", "1.2.3", SOME_TIMESTAMP); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentVersion() { - var a = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP); - var b = new Revision(1234, "g", "a", "2.3.4", SOME_TIMESTAMP); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void hasToString() { - var actual = new Revision(1234, "g", "a", "1.2.3", SOME_TIMESTAMP).toString(); - assertTrue(actual.contains(Revision.class.getSimpleName())); - assertTrue(actual.contains("\n")); - assertTrue(actual.contains("@")); - assertTrue(actual.contains("createdAt")); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/data/VersionConstraintTest.java b/core/src/test/java/eu/fasten/core/maven/data/VersionConstraintTest.java deleted file mode 100644 index ad8c4d113..000000000 --- a/core/src/test/java/eu/fasten/core/maven/data/VersionConstraintTest.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.data; - -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.Test; - -@SuppressWarnings("unchecked") -public class VersionConstraintTest { - - @Test - public void init() { - var sut = new VersionConstraint("1.2.3"); - assertEquals("1.2.3", sut.getSpec()); - assertEquals("1.2.3".hashCode() + 1, sut.hashCode()); - } - - @Test - public void initFailsForNull() { - assertThrows(IllegalArgumentException.class, () -> { - new VersionConstraint(null); - }); - } - - @Test - public void initFailsForEmpty() { - assertThrows(IllegalArgumentException.class, () -> { - new VersionConstraint(""); - }); - } - - @Test - public void equalityNonDefaults() { - var a = new VersionConstraint("1.2.3"); - var b = new VersionConstraint("1.2.3"); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - assertNotEquals(0, a.hashCode()); - } - - @Test - public void equalityDifferentSpec() { - var a = new VersionConstraint("1.2.3"); - var b = new VersionConstraint("2.3.4"); - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void hasToString() { - var sut = new VersionConstraint("1.2.3"); - assertEquals("1.2.3", sut.toString()); - } - - @Test - public void parsing0() { - assertEquals(Set.of(), parseVersionSpec("")); - } - - @Test - public void parsing1() { - validate("1.0", // - vc(false, false, "+1.0", "+1.0")); - } - - @Test - public void parsing2() { - validate("[1.0]", // - vc(false, true, "+1.0", "+1.0")); - } - - @Test - public void parsing3() { - validate("(,1.0]", // - vc(true, true, "0", "+1.0")); - } - - @Test - public void parsing4() { - validate("[1.2,1.3]", // - vc(true, true, "+1.2", "+1.3")); - } - - @Test - public void parsing5() { - validate("[1.0,2.0)", // - vc(true, true, "+1.0", "2.0")); - } - - @Test - public void parsing6() { - validate("[1.5,)", // - vc(true, true, "+1.5", "999")); - } - - @Test - public void parsing7() { - validate("(,1.0],[1.2,)", // - vc(true, true, "0", "+1.0"), // - vc(true, true, "+1.2", "999")); - } - - @Test - public void parsing8() { - validate("(,1.1),(1.1,)", // - vc(true, true, "0", "1.1"), // - vc(true, true, "1.1", "999")); - } - - @Test - public void commaButNoRange() { - validate("[1.1],[1.2]", // - vc(false, true, "+1.1", "+1.1"), // - vc(false, true, "+1.2", "+1.2")); - } - - @Test - public void parsingReturnsLinkedHashSet_softConstraint() { - var actual = VersionConstraint.parseVersionSpec("1"); - assertEquals(LinkedHashSet.class, actual.getClass()); - } - - @Test - public void parsingReturnsLinkedHashSet_hardConstraint() { - var actual = VersionConstraint.parseVersionSpec("[1]"); - assertEquals(LinkedHashSet.class, actual.getClass()); - } - - @Test - public void parsingReturnsLinkedHashSet_multiConstraint() { - var actual = VersionConstraint.parseVersionSpec("[1],[2]"); - assertEquals(LinkedHashSet.class, actual.getClass()); - } - - @Test - public void longAndComplicatedSpec() { - var actual = parseVersionSpec("[1.1],[1.2,1.3],[1.4,],[,1.5],(1.6),(1.7,1.8),(1.9,),(,2.0)") // - .stream().map(vc -> vc.getSpec()).collect(Collectors.toSet()); - var expected = Set.of("[1.1]", "[1.2,1.3]", "[1.4,]", "[,1.5]", "(1.6)", "(1.7,1.8)", "(1.9,)", "(,2.0)"); - assertEquals(expected, actual); - } - - @Test - public void versionMatches() { - assertMatch("1.2.3", "1.2.3"); - assertMatch("1.2.3", "[1.2.3]"); - - assertMatch("1.2.3", "[1,1.2.3]"); - assertMatch("1.2.3", "[1.2.3,2]"); - - assertNoMatch("1.2.3", "[1,1.2.3)"); - assertNoMatch("1.2.3", "(1.2.3,2]"); - assertNoMatch("1.2.3", "[0,1]"); - assertNoMatch("1.2.3", "[2,3]"); - - assertMatch("1.2.3", "[1.2,1.3]"); - assertMatch("1.2.3", "[,1.3]"); - assertMatch("1.2.3", "[1.2,]"); - assertMatch("1.2.3", "(1.2,1.3)]"); - assertMatch("1.2.3", "(,1.3)"); - assertMatch("1.2.3", "(1.2,)"); - } - - private void assertMatch(String version, String spec) { - var sut = new VersionConstraint(spec); - assertTrue(sut.matches(version)); - } - - private void assertNoMatch(String version, String spec) { - var sut = new VersionConstraint(spec); - assertFalse(sut.matches(version)); - } - - @Test - public void equality() { - for (var spec : new String[] { "1.0", "[1.0]", "(,1.0]", "[1.2,1.3]", "[1.0,2.0)", "[1.5,)" }) { - var a = new VersionConstraint(spec); - var b = new VersionConstraint(spec); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - } - - private static void validate(String spec, Consumer... validators) { - var vcs = List.copyOf(VersionConstraint.parseVersionSpec(spec)); - assertEquals(validators.length, vcs.size()); - for (var i = 0; i < vcs.size(); i++) { - validators[i].accept(vcs.get(i)); - } - } - - private static Consumer vc(boolean isRange, boolean isHard, String lowerBound, - String upperBound) { - return vcs -> { - var isInclusiveLower = lowerBound.startsWith("+"); - var lb = isInclusiveLower ? lowerBound.substring(1) : lowerBound; - var isInclusiveUpper = upperBound.startsWith("+"); - var ub = isInclusiveUpper ? upperBound.substring(1) : upperBound; - - assertEquals(isRange, vcs.isRange(), "isRange: " + vcs.getSpec()); - assertEquals(isHard, vcs.isHard(), "isHard: " + vcs.getSpec()); - assertEquals(isInclusiveLower, vcs.isLowerBoundInclusive(), "isLowerBoundInclusive: " + vcs.getSpec()); - assertEquals(lb, vcs.getLowerBound(), "lowerBound: " + vcs.getSpec()); - assertEquals(isInclusiveUpper, vcs.isUpperBoundInclusive(), "isUpperBoundInclusive: " + vcs.getSpec()); - assertEquals(ub, vcs.getUpperBound(), "upperBound: " + vcs.getSpec()); - }; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependencyResolverTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependencyResolverTest.java deleted file mode 100644 index bd5bcc6ee..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependencyResolverTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static org.junit.Assert.fail; - -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.BeforeEach; - -import eu.fasten.core.maven.data.ResolvedRevision; - -public class AbstractMavenDependencyResolverTest { - - protected static final String BASE = "base:1"; - - protected Set danglingGAVs; - protected Set addedAV; - - protected MavenResolverData data; - protected MavenDependencyResolver sut; - protected ResolverConfig config; - - @BeforeEach - public void setupAbstract() { - addedAV = new HashSet<>(); - data = new MavenResolverData(); - sut = new MavenDependencyResolver(); - sut.setData(data); - config = new ResolverConfig(); - danglingGAVs = new HashSet<>(); - } - - protected void addDangling() { - // override when needed - } - - protected Set assertResolution(String... gavs) { - addDangling(); - - var baseShort = gavs[0]; - gavs = Arrays.copyOfRange(gavs, 1, gavs.length); - - var baseParts = baseShort.split(":"); - var base = String.format("%s:%s:%s", baseParts[0], baseParts[0], baseParts[1]); - var actuals = sut.resolve(Set.of(base), config); - var expecteds = Arrays.stream(gavs) // - .map(gav -> gav.split(":")) // - .map(parts -> new ResolvedRevision(-1, parts[0], parts[0], parts[1], new Timestamp(-1L), COMPILE)) // - .collect(Collectors.toSet()); - - assertEquals(expecteds, actuals); - return actuals; - } - - private static void assertEquals(Set expecteds, Set actuals) { - if (!expecteds.equals(actuals)) { - var sb = new StringBuilder(); - sb.append("Expected:\n"); - for (var e : sort(expecteds)) { - sb.append("- ").append(e).append("\n"); - } - sb.append("But was:\n"); - for (var a : sort(actuals)) { - sb.append("- ").append(a).append("\n"); - } - fail(sb.toString()); - } - } - - private static Set sort(Set rs) { - return rs.stream() // - .map(r -> String.format("%s:%s:%s", r.getGroupId(), r.getArtifactId(), r.version)) // - .collect(Collectors.toCollection(TreeSet::new)); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependentsResolverTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependentsResolverTest.java deleted file mode 100644 index 1aa76bf7d..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/AbstractMavenDependentsResolverTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.BeforeEach; - -import eu.fasten.core.maven.data.ResolvedRevision; - -public class AbstractMavenDependentsResolverTest { - - protected static final String DEST = "dest:1"; - - protected MavenResolverData data; - protected MavenDependentsResolver sut; - - protected ResolverConfig config; - - @BeforeEach - public void setupAbstract() { - data = new MavenResolverData(); - sut = new MavenDependentsResolver(); - sut.setData(data); - config = new ResolverConfig(); - } - - protected Set assertResolution(String shortTarget, String... depSet) { - addDangling(); - var targetParts = shortTarget.split(":"); - var target = String.format("%s:%s:%s", targetParts[0], targetParts[0], targetParts[1]); - var actualsRaw = sut.resolve(target, config); - - var actuals = actualsRaw.stream() // - .map(rr -> String.format("%s:%s:%s", rr.getGroupId(), rr.getArtifactId(), rr.version)) // - .collect(Collectors.toCollection(TreeSet::new)); - var expecteds = Arrays.stream(depSet) // - .map(gav -> gav.split(":")) // - .map(parts -> String.format("%s:%s:%s", parts[0], parts[0], parts[1])) // - .collect(Collectors.toSet()); - - assertEquals(expecteds, actuals); - return actualsRaw; - } - - private void assertEquals(Set expecteds, TreeSet actuals) { - if (!expecteds.equals(actuals)) { - var sb = new StringBuilder(); - - sb.append("Resolution has returned an unexpected set of dependencies:\n\n"); - sb.append("Config: ").append(config).append("\n\n"); - - if (expecteds.isEmpty()) { - sb.append("Expected empty resolution result, "); - } else { - sb.append("Expected:\n"); - for (var e : expecteds) { - sb.append("- ").append(e).append("\n"); - } - } - - if (actuals.isEmpty()) { - sb.append("But resolution result was empty"); - } else { - sb.append("But was:\n"); - for (var a : actuals) { - sb.append("- ").append(a).append("\n"); - } - } - fail(sb.toString()); - } - } - - protected void addDangling() { - // override if necessary - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/IMavenResolverTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/IMavenResolverTest.java deleted file mode 100644 index e11bea392..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/IMavenResolverTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; -import static java.lang.String.format; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.Collection; -import java.util.Set; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; - -public class IMavenResolverTest { - - private static final String GID = "g"; - private static final String AID = "a"; - private static final String VERSION = "1"; - private static final Revision REV = new Revision(GID, AID, VERSION, new Timestamp(1234567890000L)); - - private static final ResolverConfig SOME_CONFIG = resolve().at(23456789); - private static final ResolverConfig DEFAULT_CONFIG = new ResolverConfig(); - - private TestMavenResolver sut; - - @BeforeEach - public void setup() { - sut = new TestMavenResolver(); - } - - @Test - public void strWithConfig_dep() { - sut.resolveDependencies(GID, AID, VERSION, SOME_CONFIG); - assertDependencies(SOME_CONFIG, REV); - } - - @Test - public void strWithConfig_deps() { - var gavs = Set.of(toGAV(REV)); - sut.resolveDependencies(gavs, SOME_CONFIG); - assertDependencies(SOME_CONFIG, REV); - } - - @Test - public void strWithConfig_dpts() { - sut.resolveDependents(GID, AID, VERSION, SOME_CONFIG); - assertDependents(SOME_CONFIG); - } - - @Test - public void strNoConfig_dep() { - sut.resolveDependencies(GID, AID, VERSION); - assertDependencies(DEFAULT_CONFIG, REV); - } - - @Test - public void strNoConfig_deps() { - var gavs = Set.of(toGAV(REV)); - sut.resolveDependencies(gavs); - assertDependencies(DEFAULT_CONFIG, REV); - } - - @Test - public void strNoConfig_dpts() { - sut.resolveDependents(GID, AID, VERSION); - assertDependents(DEFAULT_CONFIG); - } - - @Test - public void revWithConfig_dep() { - sut.resolveDependencies(REV, SOME_CONFIG); - assertDependencies(SOME_CONFIG, REV); - } - - @Test - public void revWithConfig_deps() { - sut.resolveDependenciesForRevisions(Set.of(REV), SOME_CONFIG); - assertDependencies(SOME_CONFIG, REV); - } - - @Test - public void revWithConfig_dpts() { - sut.resolveDependents(REV, SOME_CONFIG); - assertDependents(SOME_CONFIG); - } - - @Test - public void revNoConfig_dep() { - sut.resolveDependencies(REV); - assertDependencies(DEFAULT_CONFIG, REV); - } - - @Test - public void revNoConfig_deps() { - sut.resolveDependenciesForRevisions(Set.of(REV)); - assertDependencies(DEFAULT_CONFIG, REV); - } - - @Test - public void revNoConfig_dpts() { - sut.resolveDependents(REV); - assertDependents(DEFAULT_CONFIG); - } - - private void assertDependents(ResolverConfig config) { - assertEquals("dpts", sut.methodCalled); - assertEquals(GID, sut.gid); - assertEquals(AID, sut.aid); - assertEquals(VERSION, sut.version); - assertConfig(config); - } - - private void assertDependencies(ResolverConfig config, Revision... revs) { - var expectedGavs = Arrays.stream(revs) // - .map(r -> toGAV(r)) // - .collect(Collectors.toSet()); - - assertEquals("deps", sut.methodCalled); - assertEquals(expectedGavs, sut.gavs); - assertConfig(config); - } - - private void assertConfig(ResolverConfig config) { - config.resolveAt = (sut.config.resolveAt / 1000) * 1000; - assertFalse(sut.config.resolveAt == 0); - sut.config.resolveAt = (sut.config.resolveAt / 1000) * 1000; - assertEquals(config, sut.config); - } - - private static String toGAV(Revision r) { - return format("%s:%s:%s", r.getGroupId(), r.getArtifactId(), r.version); - } - - private static class TestMavenResolver implements IMavenResolver { - - private String methodCalled; - private String gid; - private String aid; - private String version; - private Collection gavs; - private ResolverConfig config; - - @Override - public Set resolveDependencies(Collection gavs, ResolverConfig config) { - assertNull(methodCalled); - methodCalled = "deps"; - this.gavs = gavs; - this.config = config; - return null; - } - - @Override - public Set resolveDependents(String g, String a, String v, ResolverConfig config) { - assertNull(methodCalled); - methodCalled = "dpts"; - this.gid = g; - this.aid = a; - this.version = v; - this.config = config; - return null; - } - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepMgmtTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepMgmtTest.java deleted file mode 100644 index 5a4aca54f..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepMgmtTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependencyResolverDepMgmtTest extends AbstractMavenDependencyResolverTest { - - @Test - public void directDependency() { - add($(BASE, "a:1"), "a"); - addMultiple("a:1"); - assertResolution(BASE, "a:1"); - } - - @Test - public void directDependencyWithVersion() { - add($(BASE, "a:1"), "a:2"); - addMultiple("a:1", "a:2"); - assertResolution(BASE, "a:2"); - } - - @Test - public void transitiveDependency() { - add($(BASE, "b:1"), "a:1"); - add($("a:1"), "b"); - addMultiple("b:1"); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void transitiveDependencyWithVersion() { - add($(BASE, "b:1"), "a:1"); - add($("a:1"), "b:2"); - addMultiple("b:1", "b:2"); - assertResolution(BASE, "a:1", "b:1"); - } - - private void add(Pom2 from, String... tos) { - var pb = new PomBuilder(); - if (!from.coord.contains(":")) { - from.coord = from.coord + ":"; - } - var parts = from.coord.split(":", -1); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var dm : from.depMgmt) { - var partsTo = dm.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencyManagement.add(d); - } - - for (String to : tos) { - if (!to.contains(":")) { - to = to + ":"; - } - var partsTo = to.split(":", -1); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private void addMultiple(String... coords) { - for (var coord : coords) { - if (!coord.contains(":")) { - throw new RuntimeException("coordinates need a version"); - } - if (addedAV.contains(coord)) { - throw new RuntimeException("Already added (G)AVs must not be contained in addMultiple"); - } - add($(coord)); - } - } - - private Pom2 $(String from, String... manageds) { - addedAV.add(from); - var pom = new Pom2(); - pom.coord = from; - pom.depMgmt = Arrays.stream(manageds).collect(Collectors.toList()); - return pom; - } - - private static class Pom2 { - public String coord; - public List depMgmt = new LinkedList<>(); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepthTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepthTest.java deleted file mode 100644 index 3282c7c68..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverDepthTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.assertTrue; - -import java.util.HashSet; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependencyResolverDepthTest extends AbstractMavenDependencyResolverTest { - - @Test - public void defaultIsTransitive() { - assertTrue(config.depth == Integer.MAX_VALUE); - } - - @Test - public void directDependency() { - add(BASE, "a:1"); - assertResolution(BASE, "a:1"); - } - - @Test - public void transitiveDeps() { - add(BASE, "a:1"); - add("a:1", "b:1"); - add("b:1", "c:1"); - assertResolution(BASE, "a:1", "b:1", "c:1"); - } - - @Test - public void transitiveDepsLimited() { - config.depth = 2; - add(BASE, "a:1"); - add(BASE, "a:1"); - add("a:1", "b:1"); - add("b:1", "c:1"); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void onlyDirectDep() { - config.depth = 1; - add(BASE, "a:1"); - assertResolution(BASE, "a:1"); - } - - @Test - public void onlyDirectDependencyButTransitiveExists() { - config.depth = 1; - add(BASE, "a:1"); - add("a:1", "b:1"); - assertResolution(BASE, "a:1"); - } - - private void add(String from, String... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (String to : tos) { - danglingGAVs.add(to); - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverExclusionTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverExclusionTest.java deleted file mode 100644 index 5f5be9444..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverExclusionTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString; -import static org.apache.commons.lang3.builder.ToStringStyle.MULTI_LINE_STYLE; - -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.Exclusion; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependencyResolverExclusionTest extends AbstractMavenDependencyResolverTest { - - @Test - public void happyPath() { - add(BASE, $("a:1")); - assertResolution(BASE, "a:1"); - } - - @Test - public void basicExclusion() { - add(BASE, $("a:1", "b")); - add("a:1", $("b:1")); - assertResolution(BASE, "a:1"); - } - - @Test - public void exclusionInOtherBranch1() { - add(BASE, $("a:1", "x"), $("b:1")); - add("a:1", $("x:1")); - add("b:1", $("x:2")); - assertResolution(BASE, "a:1", "b:1", "x:2"); - } - - @Test - public void exclusionInOtherBranch2() { - add(BASE, $("a:1"), $("b:1", "x")); - add("a:1", $("x:1")); - add("b:1", $("x:2")); - assertResolution(BASE, "a:1", "b:1", "x:1"); - } - - @Test - public void exclusionPropagatesOverDependencies() { - add(BASE, $("a:1", "x")); - add("a:1", $("b:1")); - add("b:1", $("c:1")); - add("c:1", $("x:1")); - assertResolution(BASE, "a:1", "b:1", "c:1"); - } - - @Test - public void exclusionsCumulateOverDependencies() { - add(BASE, $("a:1", "x")); - add("a:1", $("b:1", "y")); - add("b:1", $("c:1")); - add("c:1", $("x:1"), $("y:1")); - assertResolution(BASE, "a:1", "b:1", "c:1"); - } - - @Test - public void doubleInclusionWithOneExclusion1() { - add(BASE, $("b1:1", "x"), $("b2:1")); - add("b1:1", $("c:1")); - add("b2:1", $("c:1")); - add("c:1", $("x:1")); - assertResolution(BASE, "b1:1", "b2:1", "c:1"); - } - - @Test - public void doubleInclusionWithOneExclusion2() { - add(BASE, $("b1:1"), $("b2:1", "x")); - add("b1:1", $("c:1")); - add("b2:1", $("c:1")); - add("c:1", $("x:1")); - assertResolution(BASE, "b1:1", "b2:1", "c:1", "x:1"); - } - - private Dep $(String coord, String... excls) { - var dep = new Dep(); - dep.coord = coord; - for (var excl : excls) { - dep.excls.add(excl); - } - return dep; - } - - private void add(String from, Dep... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - danglingGAVs.add(to.coord); - var partsTo = to.coord.split(":"); - - var excls = to.excls.stream().map(excl -> new Exclusion(excl, excl)).collect(Collectors.toSet()); - - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), excls, Scope.COMPILE, false, - "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } - - private class Dep { - public String coord; - public Set excls = new HashSet<>(); - - @Override - public String toString() { - return reflectionToString(this, MULTI_LINE_STYLE); - } - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeOptionalTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeOptionalTest.java deleted file mode 100644 index 0b462cd6f..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeOptionalTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertFalse; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependencyResolverIncludeOptionalTest extends AbstractMavenDependencyResolverTest { - - @Test - public void disabledByDefault() { - assertFalse(config.alwaysIncludeOptional); - } - - @Test - public void byDefaultIncludeDirectDependency() { - add(BASE, dep("a:1"), opt("b:1")); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void byDefaultDontIncludeTransitiveDependency() { - add(BASE, dep("a:1")); - add("a:1", dep("b:1"), opt("c:1")); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void whenSetIncludeDirectDependency() { - config.alwaysIncludeOptional = true; - add(BASE, dep("a:1"), opt("b:1")); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void whenSetIncludeTransitiveDependency() { - config.alwaysIncludeOptional = true; - add(BASE, dep("a:1")); - add("a:1", dep("b:1"), opt("c:1")); - assertResolution(BASE, "a:1", "b:1", "c:1"); - } - - private void add(String from, Dep... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (Dep to : tos) { - danglingGAVs.add(to.coord); - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), Scope.COMPILE, - to.isOptional, "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } - - private static Dep dep(String coord) { - var d = new Dep(); - d.coord = coord; - d.isOptional = false; - return d; - } - - private static Dep opt(String coord) { - var d = new Dep(); - d.coord = coord; - d.isOptional = true; - return d; - } - - private static class Dep { - public String coord; - public boolean isOptional; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeProvidedTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeProvidedTest.java deleted file mode 100644 index 0c0afd2b0..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverIncludeProvidedTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertFalse; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependencyResolverIncludeProvidedTest extends AbstractMavenDependencyResolverTest { - - private static final Scope[] SCOPES = new Scope[] { Scope.COMPILE, Scope.RUNTIME, Scope.TEST }; - - @Test - public void disabledByDefault() { - assertFalse(config.alwaysIncludeProvided); - } - - @Test - public void ifUnsetIncludeDirectProvidedDepsForCompile() { - config.scope = Scope.COMPILE; - add(BASE, dep("a:1"), prov("b:1")); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void ifUnsetDoNotIncludeDirectProvidedDepsForRuntime() { - config.scope = Scope.RUNTIME; - add(BASE, dep("a:1"), prov("b:1")); - assertResolution(BASE, "a:1"); - } - - @Test - public void ifUnsetIncludeDirectProvidedDepsForTest() { - config.scope = Scope.TEST; - add(BASE, dep("a:1"), prov("b:1")); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void ifUnsetDoNotIncludeTransitiveProvidedDepsForAllScopes() { - add(BASE, dep("a:1")); - add("a:1", dep("b:1"), prov("c:1")); - - for (var scope : SCOPES) { - config.scope = scope; - assertResolution(BASE, "a:1", "b:1"); - } - } - - @Test - public void whenSetIncludeDirectProvidedDepsForAllScope() { - config.alwaysIncludeProvided = true; - add(BASE, dep("a:1"), prov("b:1")); - - for (var scope : SCOPES) { - config.scope = scope; - assertResolution(BASE, "a:1", "b:1"); - } - } - - @Test - public void whenSetIncludeTransitiveProvidedDepsForAllScopes() { - config.alwaysIncludeProvided = true; - add(BASE, dep("a:1")); - add("a:1", dep("b:1"), prov("c:1")); - - for (var scope : SCOPES) { - config.scope = scope; - assertResolution(BASE, "a:1", "b:1", "c:1"); - } - } - - private void add(String from, Dep... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (Dep to : tos) { - danglingGAVs.add(to.coord); - var partsTo = to.coord.split(":"); - var s = to.isProvided ? Scope.PROVIDED : Scope.COMPILE; - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), s, false, "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } - - private static Dep dep(String coord) { - var d = new Dep(); - d.coord = coord; - d.isProvided = false; - return d; - } - - private static Dep prov(String coord) { - var d = new Dep(); - d.coord = coord; - d.isProvided = true; - return d; - } - - private static class Dep { - public String coord; - public boolean isProvided; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverLimitTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverLimitTest.java deleted file mode 100644 index ec58e6b3c..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverLimitTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.assertTrue; - -import java.util.HashSet; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependencyResolverLimitTest extends AbstractMavenDependencyResolverTest { - - @Test - public void defaultIsTransitive() { - assertTrue(config.limit == Integer.MAX_VALUE); - } - - @BeforeEach - private void setup() { - add(BASE, "a:1", "b:1"); - add("a:1", "aa:1", "ab:1"); - add("b:1", "ba:1", "bb:1"); - } - - @Test - public void all() { - assertResolution(BASE, "a:1", "b:1", "aa:1", "ab:1", "ba:1", "bb:1"); - } - - @Test - public void onlyTwo() { - config.limit = 2; - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void onlyThree() { - config.limit = 3; - assertResolution(BASE, "a:1", "b:1", "aa:1"); - } - - @Test - public void onlyFour() { - config.limit = 4; - assertResolution(BASE, "a:1", "b:1", "aa:1", "ab:1"); - } - - @Test - public void onlyFive() { - config.limit = 5; - assertResolution(BASE, "a:1", "b:1", "aa:1", "ab:1", "ba:1"); - } - - private void add(String from, String... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (String to : tos) { - danglingGAVs.add(to); - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverMediationTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverMediationTest.java deleted file mode 100644 index a104c2891..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverMediationTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import java.util.HashSet; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependencyResolverMediationTest extends AbstractMavenDependencyResolverTest { - - @Test - public void directDependency() { - add(BASE, "b:1"); - assertResolution(BASE, "b:1"); - } - - @Test - public void transitiveDependency() { - add(BASE, "b:1"); - add("b:1", "c:1"); - assertResolution(BASE, "b:1", "c:1"); - } - - @Test - public void mediationDirectDep1() { - add(BASE, "c:1", "b:1"); - add("b:1", "c:2"); - assertResolution(BASE, "b:1", "c:1"); - } - - @Test - public void mediationDirectDep2() { - add(BASE, "b:1", "c:1"); - add("b:1", "c:2"); - assertResolution(BASE, "b:1", "c:1"); - } - - @Test - public void mediationSameChildLevel1() { - add(BASE, "b:1", "c:1"); - add("b:1", "d:1"); - add("c:1", "d:2"); - assertResolution(BASE, "b:1", "c:1", "d:1"); - } - - @Test - public void mediationSameChildLevel2() { - add(BASE, "c:1", "b:1"); - add("b:1", "d:1"); - add("c:1", "d:2"); - assertResolution(BASE, "b:1", "c:1", "d:2"); - } - - @Test - public void mediationCloserChildLevel1() { - add(BASE, "b:1", "c:1"); - add("b:1", "x:1"); - add("c:1", "cc:1"); - add("cc:1", "x:2"); - assertResolution(BASE, "b:1", "x:1", "c:1", "cc:1"); - } - - @Test - public void mediationCloserChildLevel2() { - add(BASE, "c:1", "b:1"); - add("b:1", "x:1"); - add("c:1", "cc:1"); - add("cc:1", "x:2"); - assertResolution(BASE, "c:1", "cc:1", "b:1", "x:1"); - } - - @Test - public void cycleDirect() { - add(BASE, "a:1"); - add("a:1", BASE); - danglingGAVs.clear(); - assertResolution(BASE, "a:1"); - } - - @Test - public void cycleTransitive() { - add(BASE, "a:1"); - add("a:1", "b:1"); - add("b:1", BASE); - danglingGAVs.clear(); - assertResolution(BASE, "a:1", "b:1"); - } - - @Test - public void cycleBranches() { - add(BASE, "a:1", "b:1"); - add("a:1", "b:1"); - add("b:1", "a:1"); - assertResolution(BASE, "a:1", "b:1"); - } - - private void add(String from, String... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (String to : tos) { - danglingGAVs.add(to); - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverResolvedScopeTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverResolvedScopeTest.java deleted file mode 100644 index a41d034c5..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverResolvedScopeTest.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.RUNTIME; -import static eu.fasten.core.maven.data.Scope.SYSTEM; -import static eu.fasten.core.maven.data.Scope.TEST; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependencyResolverResolvedScopeTest extends AbstractMavenDependencyResolverTest { - - @BeforeEach - public void setup() { - add(BASE, // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - - add("s:1", // - $("ss:1", Scope.SYSTEM), // - $("sp:1", Scope.PROVIDED), // - $("sc:1", Scope.COMPILE), // - $("sr:1", Scope.RUNTIME), // - $("st:1", Scope.TEST)); - - add("p:1", // - $("ps:1", Scope.SYSTEM), // - $("pp:1", Scope.PROVIDED), // - $("pc:1", Scope.COMPILE), // - $("pr:1", Scope.RUNTIME), // - $("pt:1", Scope.TEST)); - - add("c:1", // - $("cs:1", Scope.SYSTEM), // - $("cp:1", Scope.PROVIDED), // - $("cc:1", Scope.COMPILE), // - $("cr:1", Scope.RUNTIME), // - $("ct:1", Scope.TEST)); - - add("r:1", // - $("rs:1", Scope.SYSTEM), // - $("rp:1", Scope.PROVIDED), // - $("rc:1", Scope.COMPILE), // - $("rr:1", Scope.RUNTIME), // - $("rt:1", Scope.TEST)); - - add("t:1", // - $("ts:1", Scope.SYSTEM), // - $("tp:1", Scope.PROVIDED), // - $("tc:1", Scope.COMPILE), // - $("tr:1", Scope.RUNTIME), // - $("tt:1", Scope.TEST)); - } - - @Test - public void doNotIncludeProvidedByDefault() { - assertFalse(config.alwaysIncludeProvided); - } - - @Test - public void resolveCompile() { - config.scope = Scope.COMPILE; - assertScopedResolution(compile(BASE), // - compile("c:1"), compile("cc:1"), system("cs:1"), // - provided("p:1"), provided("pc:1"), provided("pr:1"), system("ps:1"), // - system("s:1")); - } - - @Test - public void resolveRuntime() { - config.scope = Scope.RUNTIME; - assertScopedResolution(compile(BASE), // - compile("c:1"), compile("cc:1"), runtime("cr:1"), // - runtime("r:1"), runtime("rc:1"), runtime("rr:1")); - } - - @Test - public void resolveTest() { - config.scope = Scope.TEST; - assertScopedResolution(compile(BASE), // - compile("c:1"), compile("cc:1"), runtime("cr:1"), system("cs:1"), // - runtime("r:1"), runtime("rc:1"), runtime("rr:1"), system("rs:1"), // - test("t:1"), test("tc:1"), test("tr:1"), system("ts:1"), // - provided("p:1"), provided("pc:1"), provided("pr:1"), system("ps:1"), // - system("s:1")); - } - - @Test - public void resolveCompileAlwaysProvided() { - config.scope = Scope.COMPILE; - config.alwaysIncludeProvided = true; - assertScopedResolution(compile(BASE), // - compile("c:1"), compile("cc:1"), system("cs:1"), /* + */ provided("cp:1"), // - provided("p:1"), provided("pc:1"), provided("pr:1"), system("ps:1"), /* + */ provided("pp:1"), // - system("s:1")); - } - - @Test - public void resolveRuntimeAlwaysProvided() { - config.scope = Scope.RUNTIME; - config.alwaysIncludeProvided = true; - assertScopedResolution(compile(BASE), // - compile("c:1"), compile("cc:1"), runtime("cr:1"), /* + */ provided("cp:1"), // - runtime("r:1"), runtime("rc:1"), runtime("rr:1"), /* + */ provided("rp:1"), // - /* + */ provided("p:1"), provided("pc:1"), provided("pr:1"), provided("pp:1")); - } - - @Test - public void resolveTestAlwaysProvided() { - config.scope = Scope.TEST; - config.alwaysIncludeProvided = true; - assertScopedResolution(compile(BASE), // - compile("c:1"), compile("cc:1"), runtime("cr:1"), system("cs:1"), /* + */ provided("cp:1"), // - runtime("r:1"), runtime("rc:1"), runtime("rr:1"), system("rs:1"), /* + */ provided("rp:1"), // - test("t:1"), test("tc:1"), test("tr:1"), system("ts:1"), /* + */ provided("tp:1"), // - provided("p:1"), provided("pc:1"), provided("pr:1"), system("ps:1"), /* + */ provided("pp:1"), // - system("s:1")); - } - - private void add(String from, Dep... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - danglingGAVs.add(to.coord); - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), to.scope, false, - "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - @Override - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } - - private void assertScopedResolution(Dep... deps) { - var gavsSet = Arrays.stream(deps).map(d -> d.coord).collect(Collectors.toCollection(LinkedHashSet::new)); - var gavs = new String[gavsSet.size()]; - gavs = gavsSet.toArray(gavs); - - var actuals = assertResolution(gavs).stream() // - .map(rr -> String.format("%s:%s:%s:%s", rr.getGroupId(), rr.getArtifactId(), rr.version, rr.scope)) // - .collect(Collectors.toCollection(TreeSet::new)); - var expecteds = Arrays.stream(deps) // - .skip(1) // remove target from expected set - .map(d -> { - var parts = d.coord.split(":"); - return String.format("%s:%s:%s:%s", parts[0], parts[0], parts[1], d.scope); - }) // - .collect(Collectors.toCollection(TreeSet::new)); - - assertEquals(expecteds, actuals); - } - - protected static void assertEquals(TreeSet expecteds, TreeSet actuals) { - if (!expecteds.equals(actuals)) { - var sb = new StringBuilder(); - sb.append("Unexpected dependencies. Expected:\n"); - for (var e : expecteds) { - sb.append("\t- ").append(e).append("\n"); - } - sb.append("Was:\n"); - for (var a : actuals) { - sb.append("\t- ").append(a).append("\n"); - } - fail(sb.toString()); - } - } - - private static Dep compile(String coord) { - return $(coord, COMPILE); - } - - private static Dep runtime(String coord) { - return $(coord, RUNTIME); - } - - private static Dep test(String coord) { - return $(coord, TEST); - } - - private static Dep provided(String coord) { - return $(coord, PROVIDED); - } - - private static Dep system(String coord) { - return $(coord, SYSTEM); - } - - private static Dep $(String coord, Scope scope) { - var d = new Dep(); - d.coord = coord; - d.scope = scope; - return d; - } - - private static class Dep { - public String coord; - public Scope scope; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverScopesTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverScopesTest.java deleted file mode 100644 index 91cf03549..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverScopesTest.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.IMPORT; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.SYSTEM; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependencyResolverScopesTest extends AbstractMavenDependencyResolverTest { - - private static final Set SOME_COORD = Set.of("g:a:1"); - - @Test - public void cannotResolveImport() { - var e = assertThrows(IllegalArgumentException.class, () -> { - sut.resolve(SOME_COORD, resolve().scope(IMPORT)); - }); - assertEquals("Invalid resolution scope: IMPORT", e.getMessage()); - } - - @Test - public void cannotResolveSystem() { - var e = assertThrows(IllegalArgumentException.class, () -> { - sut.resolve(SOME_COORD, resolve().scope(SYSTEM)); - }); - assertEquals("Invalid resolution scope: SYSTEM", e.getMessage()); - } - - @Test - public void cannotResolveProvided() { - var e = assertThrows(IllegalArgumentException.class, () -> { - sut.resolve(SOME_COORD, resolve().scope(PROVIDED)); - }); - assertEquals("Invalid resolution scope: PROVIDED", e.getMessage()); - } - - @Test - public void resolveCompileDirect() { - config.scope = Scope.COMPILE; - add(BASE, // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "s:1", "p:1", "c:1"); - } - - @Test - public void resolveCompileTrans() { - config.scope = Scope.COMPILE; - add(BASE, $("x:1", Scope.COMPILE)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "s:1", "c:1"); - } - - @Test - public void resolveRuntimeDirect() { - config.scope = Scope.RUNTIME; - add(BASE, // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "c:1", "r:1"); // WTF p:1? s:1? - } - - @Test - public void resolveRuntimeTrans() { - config.scope = Scope.RUNTIME; - add(BASE, $("x:1", Scope.COMPILE)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "c:1", "r:1"); // WTF s:1? - } - - @Test - public void resolveTestDirect() { - config.scope = Scope.TEST; - add(BASE, // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "s:1", "p:1", "c:1", "r:1", "t:1"); - } - - @Test - public void resolveTestTrans() { - config.scope = Scope.TEST; - add(BASE, $("x:1", Scope.COMPILE)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "s:1", "c:1", "r:1"); - } - - @Test - public void resolveCompileSystemTrans() { - config.scope = Scope.COMPILE; - add(BASE, $("x:1", Scope.SYSTEM)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1"); - } - - @Test - public void resolveTransSystem_compile() { - config.scope = Scope.COMPILE; - add(BASE, $("x:1", Scope.COMPILE)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "s:1", "c:1"); - } - - @Test - public void resolveTransSystem_runtime() { - config.scope = Scope.RUNTIME; - add(BASE, $("x:1", Scope.COMPILE)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "c:1", "r:1"); // WTF s:1? - } - - @Test - public void resolveTransSystem_test() { - config.scope = Scope.TEST; - add(BASE, $("x:1", Scope.COMPILE)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "c:1", "r:1", "s:1"); - } - - @Test - public void resolveCompileProvidedTrans() { - config.scope = Scope.COMPILE; - add(BASE, $("x:1", Scope.PROVIDED)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "s:1", "c:1", "r:1"); // WTF r:1? - } - - @Test - public void resolveRuntimeProvidedTrans() { - config.scope = Scope.RUNTIME; - add(BASE, $("x:1", Scope.PROVIDED)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE); - } - - @Test - public void resolveTestProvidedTrans() { - config.scope = Scope.TEST; - add(BASE, $("x:1", Scope.PROVIDED)); - add("x:1", // - $("s:1", Scope.SYSTEM), // - $("p:1", Scope.PROVIDED), // - $("c:1", Scope.COMPILE), // - $("r:1", Scope.RUNTIME), // - $("t:1", Scope.TEST)); - assertResolution(BASE, "x:1", "s:1", "c:1", "r:1"); - } - - private void add(String from, Dep... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - danglingGAVs.add(to.coord); - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), to.scope, false, - "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - protected void addDangling() { - for (var gav : new HashSet<>(danglingGAVs)) { - add(gav); - } - } - - private static Dep $(String coord, Scope scope) { - var d = new Dep(); - d.coord = coord; - d.scope = scope; - return d; - } - - private static class Dep { - public String coord; - public Scope scope; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverTimeTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverTimeTest.java deleted file mode 100644 index f487890eb..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverTimeTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.GA; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.VersionConstraint; - -public class MavenDependencyResolverTimeTest extends AbstractMavenDependencyResolverTest { - - @Test - public void failsWhenSinglePomCannotBeFound() { - sut.setData(mock(MavenResolverData.class)); - var e = assertThrows(MavenResolutionException.class, () -> { - sut.resolve(Set.of("a:a:1"), config); - }); - assertEquals("Cannot find coordinate a:a:1", e.getMessage()); - } - - @Test - public void checkThatConfigFieldIsUsedForSinglePoms() { - var resolveAt = 1; - - mockDepGraph(); - addMockData("a", "b", "1", resolveAt, getPom("a", "b", "1", 0)); - - resolve(resolveAt, "a:b:1"); - verify(data).find(new GA("a", "b"), Set.of(new VersionConstraint("1")), resolveAt); - } - - @Test - public void resolutionOfMultiPomsDoesNotFail() { - mockDepGraph(); - resolve(10L, "a:b:1", "b:c:2"); - } - - @Test - public void resolutionOfDependenciesPropagatesTimestamp() { - var resolveAt = 10L; - mockDepGraph(); - resolve(resolveAt, "a:b:1", "b:c:2"); - verify(data).find(eq(new GA("a", "b")), anySet(), eq(resolveAt)); - verify(data).find(eq(new GA("b", "c")), anySet(), eq(resolveAt)); - } - - @Test - public void failIfFoundSinglePomIsTooNew() { - var resolveAt = 0; - - mockDepGraph(); - addMockData("a", "b", "1", resolveAt, getPom("a", "b", "1", 1)); - - var e = assertThrows(MavenResolutionException.class, () -> { - resolve(resolveAt, "a:b:1"); - }); - assertEquals("Requested POM has been released after resolution timestamp", e.getMessage()); - } - - @Test - public void basic() { - add(1, "a:1", "b:1"); - add(2, "b:1"); - assertThrows(MavenResolutionException.class, () -> { - assertResolutionAt(0, "a:1"); - }); - assertResolutionAt(1, "a:1"); - assertResolutionAt(2, "a:1", "b:1"); - } - - @Test - public void version() { - add(1, "a:1", "b:[1,2]"); - add(2, "b:1.1"); - add(3, "b:1.2"); - add(4, "b:1.3"); - assertResolutionAt(1, "a:1"); - assertResolutionAt(2, "a:1", "b:1.1"); - assertResolutionAt(3, "a:1", "b:1.2"); - assertResolutionAt(4, "a:1", "b:1.3"); - } - - private void add(long releaseDate, String from, String... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - pb.releaseDate = releaseDate; - - for (var to : tos) { - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private void assertResolutionAt(long resolveAt, String... deps) { - config.resolveAt = resolveAt; - assertResolution(deps); - } - - private static Pom getPom(String g, String a, String v, long releaseDate) { - var pb = new PomBuilder(); - pb.groupId = g; - pb.artifactId = a; - pb.version = v; - pb.releaseDate = releaseDate; - return pb.pom(); - } - - private void mockDepGraph() { - data = mock(MavenResolverData.class); - sut.setData(data); - } - - private void addMockData(String g, String a, String v, long resolveAt, Pom pom) { - var ga = new GA(g, a); - when(data.find(ga, Set.of(new VersionConstraint(v)), resolveAt)).thenReturn(pom); - } - - private void resolve(long resolveAt, String... coords) { - config.resolveAt = resolveAt; - sut.resolve(Set.of(coords), config); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverVersionRangeTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverVersionRangeTest.java deleted file mode 100644 index ee7c5064f..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependencyResolverVersionRangeTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static java.lang.String.format; - -import java.util.Arrays; -import java.util.Set; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.VersionConstraint; - -public class MavenDependencyResolverVersionRangeTest extends AbstractMavenDependencyResolverTest { - - // PLEASE NOTE: This behavior is a workaround until we support proper dependency - // resolution. The approach is to select the most recent match in the "closest" - // definition, which is the 20/80 solution, but not what Maven is doing. - - @Test - public void directDependencyIncl() { - add(BASE, "x:[1.1-1.2]"); - addXs(); - - assertResolution(BASE, "x:1.2.0"); - } - - @Test - public void directDependencyExcl() { - add(BASE, "x:[1.1-1.2)"); - addXs(); - - assertResolution(BASE, "x:1.1.9"); - } - - @Test - public void directDependencyMultiRange() { - add(BASE, "x:[1.1-1.2],[1.7-1.8],[1.3-1.4]"); - addXs(); - - assertResolution(BASE, "x:1.8.0"); - } - - @Test - public void transDependencyIncl() { - add(BASE, "a:1"); - add("a:1", "x:[1.1-1.2]"); - addXs(); - - assertResolution(BASE, "a:1", "x:1.2.0"); - } - - @Test - public void transDependencyExcl() { - add(BASE, "a:1"); - add("a:1", "x:[1.1.0-1.2.0)"); - addXs(); - - assertResolution(BASE, "a:1", "x:1.1.9"); - } - - @Test - public void nonRangeOverridesLaterRange() { - add(BASE, "a:1", "b:1"); - add("a:1", "x:2"); - add("x:2"); - add("b:1", "x:[1.1-1.2]"); - addXs(); - - assertResolution(BASE, "a:1", "b:1", "x:2"); - } - - @Test - public void rangeExcludesLaterNonRanges() { - add(BASE, "a:1", "b:1"); - add("a:1", "x:[1.1-1.2]"); - add("b:1", "x:2"); - add("x:2"); - addXs(); - - assertResolution(BASE, "a:1", "b:1", "x:1.2.0"); - } - - @Test - public void closerRangeWins() { - add(BASE, "a:1", "b:1"); - add("a:1", "x:[1.0-1.1]"); - add("b:1", "x:[1.2-1.3]"); - addXs(); - - assertResolution(BASE, "a:1", "b:1", "x:1.1"); - } - - private void add(String from, String... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - var partsTo = to.split(":"); - - Set vcs; - boolean isConstraint = partsTo[1].contains("[") || partsTo[1].contains("("); - if (isConstraint) { - vcs = Arrays.stream(partsTo[1].split(",")) // - .map(vc -> vc.replace('-', ',')) // - .map(VersionConstraint::new) // - .collect(Collectors.toSet()); - } else { - vcs = parseVersionSpec(partsTo[1]); - } - - var d = new Dependency(partsTo[0], partsTo[0], vcs, Set.of(), COMPILE, false, "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private void addXs() { - for (var i = 0; i < 3; i++) { - for (var j = 0; j < 10; j++) { - for (var k = 0; k < 10; k++) { - add(format("x:%d.%d.%d", i, j, k)); - } - } - } - add("x:3.0.0"); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverBasicTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverBasicTest.java deleted file mode 100644 index 994a6cd62..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverBasicTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependentsResolverBasicTest extends AbstractMavenDependentsResolverTest { - - @BeforeEach - public void setup() { - add(DEST); - } - - @Test - public void direct() { - add("a:1", DEST); - assertResolution(DEST, "a:1"); - } - - @Test - public void transitive() { - add("a:1", DEST); - add("b:1", "a:1"); - assertResolution(DEST, "a:1", "b:1"); - } - - @Test - public void multipleBranches() { - add("a:1", DEST); - add("b:1", DEST); - assertResolution(DEST, "a:1", "b:1"); - } - - @Test - public void multipleBranchesTransitive() { - add("a:1", DEST); - add("aa:1", "a:1"); - add("b:1", DEST); - add("bb:1", "b:1"); - assertResolution(DEST, "a:1", "aa:1", "b:1", "bb:1"); - } - - @Test - public void cycleDirect() { - add("a:1", DEST); - add(DEST, "a:1"); - assertResolution(DEST, "a:1"); - } - - @Test - public void cycleTransitive() { - add("a:1", DEST); - add("b:1", "a:1"); - add(DEST, "b:1"); - assertResolution(DEST, "a:1", "b:1"); - } - - @Test - public void throwsWhenDestCannotBeFound() { - var e = assertThrows(MavenResolutionException.class, () -> { - sut.resolve("non:existing:1", config); - }); - assertEquals("Cannot find coordinate non:existing:1", e.getMessage()); - } - - @Test - public void illegalStateDepNotFound() { - add("a:1", DEST); - add("b:1", "a:1"); - add(DEST, "b:1"); - assertResolution(DEST, "a:1", "b:1"); - } - - private void add(String from, String... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (String to : tos) { - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverDepthTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverDepthTest.java deleted file mode 100644 index ca31d7ad4..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverDepthTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.assertTrue; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependentsResolverDepthTest extends AbstractMavenDependentsResolverTest { - - @Test - public void defaultValue() { - assertTrue(config.depth == Integer.MAX_VALUE); - } - - @BeforeEach - private void setup() { - add("y:1", "z:1"); - add("z:1", "a:1"); - add("a:1", "b:1"); - add("b:1", DEST); - add(DEST, "c:1"); - add("c:1"); - } - - @Test - public void all() { - assertResolution(DEST, "b:1", "a:1", "z:1", "y:1"); - } - - @Test - public void onlyFour() { - config.limitTransitiveDeps(4); - assertResolution(DEST, "a:1", "b:1", "z:1", "y:1"); - } - - @Test - public void onlyThree() { - config.limitTransitiveDeps(3); - assertResolution(DEST, "a:1", "b:1", "z:1"); - } - - @Test - public void onlyTwo() { - config.limitTransitiveDeps(2); - assertResolution(DEST, "b:1", "a:1"); - } - - @Test - public void onlyOne() { - config.limitTransitiveDeps(1); - assertResolution(DEST, "b:1"); - } - - private void add(String from, String... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (String to : tos) { - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeOptionalTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeOptionalTest.java deleted file mode 100644 index ad2ba5495..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeOptionalTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertFalse; - -import java.util.Set; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependentsResolverIncludeOptionalTest extends AbstractMavenDependentsResolverTest { - - @BeforeEach - public void setup() { - add(DEST); - } - - @Test - public void disabledByDefault() { - assertFalse(config.alwaysIncludeOptional); - } - - @Test - public void ifUnsetIncludeDirectOptionalDeps() { - add("a:1", opt(DEST)); - assertResolution(DEST, "a:1"); - } - - @Test - public void ifUnsetDoNotIncludeTransitiveOptionalDeps() { - add("a:1", m("b:1")); - add("b:1", opt(DEST)); - assertResolution(DEST, "b:1"); - } - - @Test - public void whenSetIncludeDirectOptionalDeps() { - config.alwaysIncludeOptional = true; - add("a:1", opt(DEST)); - assertResolution(DEST, "a:1"); - } - - @Test - public void whenSetIncludeTransitiveOptionalDeps() { - config.alwaysIncludeOptional = true; - add("a:1", m("b:1")); - add("b:1", opt(DEST)); - assertResolution(DEST, "a:1", "b:1"); - } - - private void add(String from, Dep... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), Scope.COMPILE, - to.isOptional, "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private static Dep m(String coord) { - var dep = new Dep(); - dep.coord = coord; - dep.isOptional = false; - return dep; - } - - private static Dep opt(String coord) { - var dep = new Dep(); - dep.coord = coord; - dep.isOptional = true; - return dep; - } - - private static class Dep { - public String coord; - public boolean isOptional; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeProvidedTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeProvidedTest.java deleted file mode 100644 index d88face9e..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverIncludeProvidedTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.assertFalse; - -import java.util.Set; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependentsResolverIncludeProvidedTest extends AbstractMavenDependentsResolverTest { - - private static final Scope[] SCOPES = new Scope[] { Scope.COMPILE, Scope.RUNTIME, Scope.TEST }; - - @BeforeEach - public void setup() { - add(DEST); - } - - @Test - public void disabledByDefault() { - assertFalse(config.alwaysIncludeProvided); - } - - @Test - public void ifUnsetIncludeDirectProvidedDepsForCompile() { - config.scope = Scope.COMPILE; - add("a:1", $(DEST, PROVIDED)); - assertResolution(DEST, "a:1"); - } - - @Test - public void ifUnsetDoNotIncludeDirectProvidedDepsForRuntime() { - config.scope = Scope.RUNTIME; - add("a:1", $(DEST, PROVIDED)); - assertResolution(DEST); - } - - @Test - public void ifUnsetIncludeDirectProvidedDepsForTest() { - config.scope = Scope.TEST; - add("a:1", $(DEST, PROVIDED)); - assertResolution(DEST, "a:1"); - } - - @Test - public void ifUnsetDoNotIncludeTransitiveProvidedDepsForCompile() { - config.scope = Scope.COMPILE; - add("a:1", $("b:1", COMPILE)); - add("b:1", $(DEST, PROVIDED)); - assertResolution(DEST, "b:1"); - } - - @Test - public void ifUnsetDoNotIncludeTransitiveProvidedDepsForRuntime() { - config.scope = Scope.RUNTIME; - add("a:1", $("b:1", COMPILE)); - add("b:1", $(DEST, PROVIDED)); - assertResolution(DEST); - } - - @Test - public void ifUnsetDoNotIncludeTransitiveProvidedDepsForTest() { - config.scope = Scope.TEST; - add("a:1", $("b:1", COMPILE)); - add("b:1", $(DEST, PROVIDED)); - assertResolution(DEST, "b:1"); - } - - @Test - public void whenSetIncludeDirectProvidedDepsForAllScopes() { - add("a:1", $(DEST, PROVIDED)); - - for (var scope : SCOPES) { - config.alwaysIncludeProvided = true; - config.scope = scope; - assertResolution(DEST, "a:1"); - } - } - - @Test - public void whenSetIncludeTransitiveProvidedDepsForAllScopes() { - add("a:1", $("b:1", COMPILE)); - add("b:1", $(DEST, PROVIDED)); - - for (var scope : SCOPES) { - config.alwaysIncludeProvided = true; - config.scope = scope; - assertResolution(DEST, "a:1", "b:1"); - } - } - - private void add(String from, Dep... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), to.scope, false, - "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private static Dep $(String coord, Scope scope) { - var dep = new Dep(); - dep.coord = coord; - dep.scope = scope; - return dep; - } - - private static class Dep { - public String coord; - public Scope scope; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverLimitTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverLimitTest.java deleted file mode 100644 index f8f1c9c51..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverLimitTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.assertTrue; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependentsResolverLimitTest extends AbstractMavenDependentsResolverTest { - - @Test - public void defaultValue() { - assertTrue(config.limit == Integer.MAX_VALUE); - } - - @BeforeEach - private void setup() { - - add("c:1", "b:1"); - add("b:1", "a:1"); - add("a:1", DEST); - - add("c:2", "b:2"); - add("b:2", "a:2"); - add("a:2", DEST); - - add(DEST, "x:1"); - add("x:1"); - } - - @Test - public void all() { - assertResolution(DEST, "a:1", "b:1", "c:1", "a:2", "b:2", "c:2"); - } - - @Test - public void onlyOne() { - config.limit(1); - assertResolution(DEST, "a:1"); - } - - @Test - public void onlyTwo() { - config.limit(2); - assertResolution(DEST, "a:1", "b:1"); - } - - @Test - public void onlyThree() { - config.limit(3); - assertResolution(DEST, "a:1", "b:1", "c:1"); - } - - @Test - public void onlyFour() { - config.limit(4); - assertResolution(DEST, "a:1", "b:1", "c:1", "a:2"); - } - - private void add(String from, String... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (String to : tos) { - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverResolvedScopeTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverResolvedScopeTest.java deleted file mode 100644 index 599fa2569..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverResolvedScopeTest.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.RUNTIME; -import static eu.fasten.core.maven.data.Scope.SYSTEM; -import static eu.fasten.core.maven.data.Scope.TEST; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependentsResolverResolvedScopeTest extends AbstractMavenDependentsResolverTest { - - private static final Set RESOLVABLE_SCOPES = Set.of(COMPILE, RUNTIME, TEST); - private static final boolean[] TRUE_FALSE = new boolean[] { true, false }; - - protected static final String BASE = "base:1"; - protected static final String S = "s:1"; - protected static final String P = "p:1"; - protected static final String C = "c:1"; - protected static final String R = "r:1"; - protected static final String T = "t:1"; - - protected Set danglingGAVs; - private String base; - - @BeforeEach - public void setup() { - danglingGAVs = new HashSet<>(); - base = null; - - add(BASE, // - s(SYSTEM), // - p(PROVIDED), // - c(COMPILE), // - r(RUNTIME), // - t(TEST)); - - add(P, // - $("ps:1", Scope.SYSTEM), // - $("pp:1", Scope.PROVIDED), // - $("pc:1", Scope.COMPILE), // - $("pr:1", Scope.RUNTIME), // - $("pt:1", Scope.TEST)); - - add(C, // - $("cs:1", Scope.SYSTEM), // - $("cp:1", Scope.PROVIDED), // - $("cc:1", Scope.COMPILE), // - $("cr:1", Scope.RUNTIME), // - $("ct:1", Scope.TEST)); - - add(R, // - $("rs:1", Scope.SYSTEM), // - $("rp:1", Scope.PROVIDED), // - $("rc:1", Scope.COMPILE), // - $("rr:1", Scope.RUNTIME), // - $("rt:1", Scope.TEST)); - - add(T, // - $("ts:1", Scope.SYSTEM), // - $("tp:1", Scope.PROVIDED), // - $("tc:1", Scope.COMPILE), // - $("tr:1", Scope.RUNTIME), // - $("tt:1", Scope.TEST)); - } - - @Test - public void base() { - base = BASE; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(); - assertTesting(); - }); - } - - @Test - public void s() { - base = S; - independentOfIncludeProvided(() -> { - assertCompile(base(SYSTEM)); - assertRuntime(); // WTF why is system not covered by runtime? - assertTesting(base(SYSTEM)); - }); - } - - @Test - public void p() { - base = P; - independentOfIncludeProvided(() -> { - assertCompile(base(PROVIDED)); - assertTesting(base(PROVIDED)); - }); - - config.alwaysIncludeProvided = false; - assertRuntime(); // WTF why is provided not covered by runtime? - - config.alwaysIncludeProvided = true; - assertRuntime(base(PROVIDED)); - } - - @Test - public void c() { - base = C; - independentOfIncludeProvided(() -> { - assertCompile(base(COMPILE)); - assertRuntime(base(COMPILE)); - assertTesting(base(COMPILE)); - }); - } - - @Test - public void r() { - base = R; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(base(RUNTIME)); - assertTesting(base(RUNTIME)); - }); - } - - @Test - public void t() { - base = T; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(); - assertTesting(base(TEST)); - }); - } - - @Test - public void ps() { - base = "ps:1"; - independentOfIncludeProvided(() -> { - assertCompile(p(SYSTEM), base(SYSTEM)); - assertRuntime(); - assertTesting(p(SYSTEM), base(SYSTEM)); - }); - } - - @Test - public void pp() { - base = "pp:1"; - withoutIncludeProvided(() -> { - assertCompile(p(PROVIDED)); - assertRuntime(); - assertTesting(p(PROVIDED)); - }); - withIncludeProvided(() -> { - RESOLVABLE_SCOPES.forEach(scope -> { - assertScope(scope, p(PROVIDED), base(PROVIDED)); - }); - }); - } - - @Test - public void pc() { - base = "pc:1"; - withoutIncludeProvided(() -> { - assertCompile(p(COMPILE), base(PROVIDED)); - assertRuntime(p(COMPILE)); - assertTesting(p(COMPILE), base(PROVIDED)); - }); - withIncludeProvided(() -> { - RESOLVABLE_SCOPES.forEach(scope -> { - assertScope(scope, p(COMPILE), base(PROVIDED)); - }); - }); - } - - @Test - public void pr() { - base = "pr:1"; - withoutIncludeProvided(() -> { - assertCompile(); // WTF: technically incorrect, in reality, base>p>pr is a dependency - assertRuntime(p(RUNTIME)); - assertTesting(p(RUNTIME), base(PROVIDED)); - }); - withIncludeProvided(() -> { - assertCompile(); - assertRuntime(p(RUNTIME), base(PROVIDED)); - assertTesting(p(RUNTIME), base(PROVIDED)); - }); - } - - @Test - public void pt() { - base = "pt:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(); - assertTesting(p(TEST)); - }); - } - - @Test - public void cs() { - base = "cs:1"; - independentOfIncludeProvided(() -> { - assertCompile(c(SYSTEM), base(SYSTEM)); - assertRuntime(); - assertTesting(c(SYSTEM), base(SYSTEM)); - }); - } - - @Test - public void cp() { - base = "cp:1"; - withoutIncludeProvided(() -> { - assertCompile(c(PROVIDED)); - assertRuntime(); - assertTesting(c(PROVIDED)); - }); - withIncludeProvided(() -> { - RESOLVABLE_SCOPES.forEach(scope -> { - assertScope(scope, c(PROVIDED), base(PROVIDED)); - }); - }); - } - - @Test - public void cc() { - base = "cc:1"; - independentOfIncludeProvided(() -> { - RESOLVABLE_SCOPES.forEach(scope -> { - assertScope(scope, c(COMPILE), base(COMPILE)); - }); - }); - } - - @Test - public void cr() { - base = "cr:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(c(RUNTIME), base(RUNTIME)); - assertTesting(c(RUNTIME), base(RUNTIME)); - }); - } - - @Test - public void ct() { - base = "ct:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(); - assertTesting(c(TEST)); - }); - } - - @Test - public void rs() { - base = "rs:1"; - independentOfIncludeProvided(() -> { - assertCompile(r(SYSTEM)); - assertRuntime(); - assertTesting(r(SYSTEM), base(SYSTEM)); - }); - } - - @Test - public void rp() { - base = "rp:1"; - withoutIncludeProvided(() -> { - assertCompile(r(PROVIDED)); - assertRuntime(); - assertTesting(r(PROVIDED)); - }); - withIncludeProvided(() -> { - assertCompile(r(PROVIDED)); - assertRuntime(r(PROVIDED), base(PROVIDED)); - assertTesting(r(PROVIDED), base(PROVIDED)); - }); - } - - @Test - public void rc() { - base = "rc:1"; - independentOfIncludeProvided(() -> { - assertCompile(r(COMPILE)); - assertRuntime(r(COMPILE), base(RUNTIME)); - assertTesting(r(COMPILE), base(RUNTIME)); - }); - } - - @Test - public void rr() { - base = "rr:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(r(RUNTIME), base(RUNTIME)); - assertTesting(r(RUNTIME), base(RUNTIME)); - }); - } - - @Test - public void rt() { - base = "rt:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(); - assertTesting(r(TEST)); - }); - } - - @Test - public void ts() { - base = "ts:1"; - independentOfIncludeProvided(() -> { - assertCompile(t(SYSTEM)); - assertRuntime(); - assertTesting(t(SYSTEM), base(SYSTEM)); - }); - } - - @Test - public void tp() { - base = "tp:1"; - withoutIncludeProvided(() -> { - assertCompile(t(PROVIDED)); - assertRuntime(); - assertTesting(t(PROVIDED)); - }); - withIncludeProvided(() -> { - assertCompile(t(PROVIDED)); - assertRuntime(t(PROVIDED)); - assertTesting(t(PROVIDED), base(PROVIDED)); - }); - } - - @Test - public void tc() { - base = "tc:1"; - independentOfIncludeProvided(() -> { - assertCompile(t(COMPILE)); - assertRuntime(t(COMPILE)); - assertTesting(t(COMPILE), base(TEST)); - }); - } - - @Test - public void tr() { - base = "tr:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(t(RUNTIME)); - assertTesting(t(RUNTIME), base(TEST)); - }); - } - - @Test - public void tt() { - base = "tt:1"; - independentOfIncludeProvided(() -> { - assertCompile(); - assertRuntime(); - assertTesting(t(TEST)); - }); - } - - private void add(String from, Dep... tos) { - danglingGAVs.remove(from); - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - danglingGAVs.add(to.coord); - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), to.scope, false, - "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private void independentOfIncludeProvided(Runnable r) { - var before = config.alwaysIncludeProvided; - for (var flag : TRUE_FALSE) { - config.alwaysIncludeProvided = flag; - r.run(); - } - config.alwaysIncludeProvided = before; - } - - private void withoutIncludeProvided(Runnable r) { - var before = config.alwaysIncludeProvided; - config.alwaysIncludeProvided = false; - r.run(); - config.alwaysIncludeProvided = before; - } - - private void withIncludeProvided(Runnable r) { - var before = config.alwaysIncludeProvided; - config.alwaysIncludeProvided = true; - r.run(); - config.alwaysIncludeProvided = before; - } - - private void assertCompile(Dep... deps) { - assertScope(COMPILE, deps); - } - - private void assertRuntime(Dep... deps) { - assertScope(RUNTIME, deps); - } - - private void assertTesting(Dep... deps) { - assertScope(TEST, deps); - } - - private void assertScope(Scope scope, Dep... deps) { - if (base == null) { - throw new RuntimeException("base not set"); - } - config.scope = scope; - var gavsSet = Arrays.stream(deps).map(d -> d.coord).collect(Collectors.toCollection(LinkedHashSet::new)); - var gavs = new String[gavsSet.size()]; - gavs = gavsSet.toArray(gavs); - - var actuals = assertResolution(base, gavs).stream() // - .map(rr -> String.format("%s:%s:%s:%s", rr.getGroupId(), rr.getArtifactId(), rr.version, rr.scope)) // - .collect(Collectors.toCollection(TreeSet::new)); - var expecteds = Arrays.stream(deps) // - .map(d -> { - var parts = d.coord.split(":"); - return String.format("%s:%s:%s:%s", parts[0], parts[0], parts[1], d.scope); - }) // - .collect(Collectors.toCollection(TreeSet::new)); - - if (!expecteds.equals(actuals)) { - var sb = new StringBuilder(); - sb.append("Resolution has returned unexpected dependency scopes.\n\n"); - sb.append(config).append("\n\n"); - sb.append("Expected:\n"); - for (var e : expecteds) { - sb.append("\t- ").append(e).append("\n"); - } - sb.append("Was:\n"); - for (var a : actuals) { - sb.append("\t- ").append(a).append("\n"); - } - fail(sb.toString()); - } - } - - @Override - protected void addDangling() { - for (var coord : new HashSet<>(danglingGAVs)) { - add(coord); - } - } - - private static Dep base(Scope scope) { - return $(BASE, scope); - } - - private static Dep p(Scope scope) { - return $("p:1", scope); - } - - private static Dep s(Scope scope) { - return $("s:1", scope); - } - - private static Dep c(Scope scope) { - return $("c:1", scope); - } - - private static Dep r(Scope scope) { - return $("r:1", scope); - } - - private static Dep t(Scope scope) { - return $("t:1", scope); - } - - private static Dep $(String coord, Scope scope) { - var d = new Dep(); - d.coord = coord; - d.scope = scope; - return d; - } - - private static class Dep { - public String coord; - public Scope scope; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverScopesTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverScopesTest.java deleted file mode 100644 index 43eba8a53..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverScopesTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; -import static eu.fasten.core.maven.data.Scope.IMPORT; -import static eu.fasten.core.maven.data.Scope.PROVIDED; -import static eu.fasten.core.maven.data.Scope.RUNTIME; -import static eu.fasten.core.maven.data.Scope.SYSTEM; -import static eu.fasten.core.maven.data.Scope.TEST; -import static eu.fasten.core.maven.data.VersionConstraint.parseVersionSpec; -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Set; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.Scope; - -public class MavenDependentsResolverScopesTest extends AbstractMavenDependentsResolverTest { - - private static final String SOME_COORD = "some:coord:1.2.3"; - - @BeforeEach - public void setup() { - add(DEST); - } - - @Test - public void cannotResolveImport() { - var e = assertThrows(IllegalArgumentException.class, () -> { - sut.resolve(SOME_COORD, resolve().scope(IMPORT)); - }); - assertEquals("Invalid resolution scope: IMPORT", e.getMessage()); - } - - @Test - public void cannotResolveSystem() { - var e = assertThrows(IllegalArgumentException.class, () -> { - sut.resolve(SOME_COORD, resolve().scope(SYSTEM)); - }); - assertEquals("Invalid resolution scope: SYSTEM", e.getMessage()); - } - - @Test - public void cannotResolveProvided() { - var e = assertThrows(IllegalArgumentException.class, () -> { - sut.resolve(SOME_COORD, resolve().scope(PROVIDED)); - }); - assertEquals("Invalid resolution scope: PROVIDED", e.getMessage()); - } - - @Test - public void resolveCompileDirectDependents() { - addDependentsWithAllScopes(DEST); - config.scope = COMPILE; - assertResolution(DEST, "c:1", "s:1", "p:1"); - } - - @Test - public void resolveRuntimeDirectDependents() { - addDependentsWithAllScopes(DEST); - config.scope = RUNTIME; - assertResolution(DEST, "c:1", "r:1"); - } - - @Test - public void resolveTestDirectDependents() { - addDependentsWithAllScopes(DEST); - config.scope = TEST; - assertResolution(DEST, "c:1", "r:1", "t:1", "s:1", "p:1"); - } - - @Test - public void resolveCompileTransitiveDependents() { - add("x:1", $(DEST, COMPILE)); - addDependentsWithAllScopes("x:1"); - config.scope = COMPILE; - assertResolution(DEST, "x:1", "c:1", "s:1", "p:1"); - } - - @Test - public void resolveRuntimeTransitiveDependents() { - add("x:1", $(DEST, COMPILE)); - addDependentsWithAllScopes("x:1"); - config.scope = RUNTIME; - assertResolution(DEST, "x:1", "c:1", "r:1"); - } - - @Test - public void resolveTestTransitiveDependents() { - add("x:1", $(DEST, COMPILE)); - addDependentsWithAllScopes("x:1"); - config.scope = TEST; - assertResolution(DEST, "x:1", "c:1", "r:1", "t:1", "s:1", "p:1"); - } - - @Test - public void invalidDepForFullCoverage() { - config.scope = TEST; - add("x:1", $(DEST, IMPORT)); - assertResolution(DEST); - } - - private void add(String from, Dep... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - var partsTo = to.coord.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], parseVersionSpec(partsTo[1]), Set.of(), to.scope, false, - "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private void addDependentsWithAllScopes(String dest) { - add("c:1", $(dest, COMPILE)); - add("r:1", $(dest, RUNTIME)); - add("t:1", $(dest, TEST)); - add("s:1", $(dest, SYSTEM)); - add("p:1", $(dest, PROVIDED)); - } - - private static Dep $(String coord, Scope scope) { - var dep = new Dep(); - dep.coord = coord; - dep.scope = scope; - return dep; - } - - private static class Dep { - public String coord; - public Scope scope; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverTimeTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverTimeTest.java deleted file mode 100644 index 25f61ce2d..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverTimeTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenDependentsResolverTimeTest extends AbstractMavenDependentsResolverTest { - - private static final long SOME_TIME = 1234; - - @Test - public void destDoesNotExistYet() { - add(0, DEST); - config.resolveAt = SOME_TIME - 1; - var e = assertThrows(MavenResolutionException.class, () -> { - sut.resolve("dest:dest:1", config); - }); - assertEquals("Cannot find coordinate dest:dest:1", e.getMessage()); - } - - @Test - public void direct() { - add(0, DEST); - add(0, "a:1", DEST); - assertDependentsAt(0, DEST, "a:1"); - } - - @Test - public void directTooNew() { - add(0, DEST); - add(1, "a:1", DEST); - assertDependentsAt(0, DEST); - } - - @Test - public void directTooNewWithTransitive() { - add(0, DEST); - add(1, "a:1", DEST); - add(0, "b:1", "a:1"); - assertDependentsAt(0, DEST); - } - - @Test - public void transitive() { - add(0, DEST); - add(0, "a:1", DEST); - add(0, "b:1", "a:1"); - assertDependentsAt(0, DEST, "a:1", "b:1"); - } - - @Test - public void transitiveToNew() { - add(0, DEST); - add(0, "a:1", DEST); - add(1, "b:1", "a:1"); - assertDependentsAt(0, DEST, "a:1"); - } - - private void add(long releasedAtDelta, String from, String... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - pb.releaseDate = SOME_TIME + releasedAtDelta; - - for (var to : tos) { - var partsTo = to.split(":"); - var d = new Dependency(partsTo[0], partsTo[0], partsTo[1]); - - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private void assertDependentsAt(long resolveAtDelta, String shortTarget, String... depSet) { - config.resolveAt = SOME_TIME + resolveAtDelta; - assertResolution(shortTarget, depSet); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverVersionRangeTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverVersionRangeTest.java deleted file mode 100644 index 281b7e1ad..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenDependentsResolverVersionRangeTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.COMPILE; - -import java.util.Arrays; -import java.util.Set; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.VersionConstraint; - -public class MavenDependentsResolverVersionRangeTest extends AbstractMavenDependentsResolverTest { - - @Test - public void softConstraint() { - add("dest:1"); - add("a:1", $("dest", "1")); - assertResolution("dest:1", "a:1"); - } - - @Test - public void hardConstraint() { - add("dest:1"); - add("a:1", $("dest", "[1]")); - assertResolution("dest:1", "a:1"); - } - - @Test - public void simpleRange() { - add("dest:1.2"); - add("a:1", $("dest", "[1,2]")); - assertResolution("dest:1.2", "a:1"); - } - - @Test - public void multiRange() { - add("dest:1.2"); - add("a:1", $("dest", "[1.0]", "[1.1,1.3]")); - assertResolution("dest:1.2", "a:1"); - } - - @Test - public void transitiveMultiRange() { - add("dest:1.2"); - add("a:1", $("dest", "[1.0]", "[1.1,1.3]")); - add("b:1", $("a", "[1,2]")); - assertResolution("dest:1.2", "a:1", "b:1"); - } - - private void add(String from, Dep... tos) { - var pb = new PomBuilder(); - var parts = from.split(":"); - pb.groupId = parts[0]; - pb.artifactId = parts[0]; - pb.version = parts[1]; - - for (var to : tos) { - var d = new Dependency(to.coord, to.coord, to.vcs, Set.of(), COMPILE, false, "jar", ""); - pb.dependencies.add(d); - } - - data.add(pb.pom()); - } - - private static Dep $(String coord, String... vcs) { - var dep = new Dep(); - dep.coord = coord; - dep.vcs = Arrays.stream(vcs) // - .map(VersionConstraint::new) // - .collect(Collectors.toSet()); - return dep; - } - - private static class Dep { - public String coord; - public Set vcs; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependencyTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependencyTest.java deleted file mode 100644 index 886dd95bb..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependencyTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Arrays; -import java.util.Set; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.GA; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.VersionConstraint; - -public class MavenResolverDataDependencyTest { - - private static final long SOME_TIME = 123L; - private TestMavenDependencyData sut; - - @BeforeEach - public void setup() { - sut = new TestMavenDependencyData(); - } - - @Test - public void returnsNullIfEmpty() { - var actual = find(SOME_TIME, "a:b", "1"); - assertNull(actual); - } - - @Test - public void returnsNullIfNoMatch() { - addPom("b", "c", "1", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "1"); - assertNull(actual); - } - - @Test - public void returnsNullIfGroupMismatch() { - addPom("a", "b", "1", SOME_TIME); - var actual = find(SOME_TIME, "x:b", "1"); - assertNull(actual); - } - - @Test - public void returnsNullIfArtifactMismatch() { - addPom("a", "b", "1", SOME_TIME); - var actual = find(SOME_TIME, "a:x", "1"); - assertNull(actual); - } - - @Test - public void returnsNullIfVersionMismatch() { - addPom("a", "b", "1", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "2"); - assertNull(actual); - } - - @Test - public void findsExactMatch() { - var expected = addPom("a", "b", "1", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "1"); - assertEquals(expected, actual); - } - - @Test - public void findsExactMatchAmongMultipleVersions() { - var expected = addPom("a", "b", "1", SOME_TIME); - addPom("a", "b", "2", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "1"); - assertEquals(expected, actual); - } - - @Test - public void returnsNullIfExactMatchIsTooNew() { - addPom("a", "b", "1", SOME_TIME + 1); - var actual = find(SOME_TIME, "a:b", "1"); - assertNull(actual); - } - - @Test - public void canReplaceRegisteredPom() { - var a = addPom("a", "b", "1", SOME_TIME); - var b = addPom("a", "b", "1", SOME_TIME + 1); - var c = sut.find(ga("a", "b"), Set.of(new VersionConstraint("1")), SOME_TIME + 1); - assertNotSame(a, c); - assertSame(b, c); - } - - @Test - public void returnNullIfNoMatch_hardConstraint() { - addPom("a", "b", "1.1", SOME_TIME); - addPom("a", "b", "1.2", SOME_TIME); - addPom("a", "b", "1.3", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "[1]"); - assertNull(actual); - } - - @Test - public void returnNullIfNoMatch_versionRange() { - addPom("a", "b", "1.1", SOME_TIME); - addPom("a", "b", "1.2", SOME_TIME); - addPom("a", "b", "1.3", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "[1,1.1)"); - assertNull(actual); - } - - @Test - public void findsHighestMatch() { - addPom("a", "b", "1.1", SOME_TIME); - var expected = addPom("a", "b", "1.2", SOME_TIME); - addPom("a", "b", "1.3", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "[1.1,1.3)"); - assertEquals(expected, actual); - } - - @Test - public void findsHighestMatchWithUnorderedConstraints() { - addPom("a", "b", "1.1", SOME_TIME); - addPom("a", "b", "1.2", SOME_TIME); - addPom("a", "b", "1.3", SOME_TIME); - addPom("a", "b", "1.4", SOME_TIME); - var expected = addPom("a", "b", "1.5", SOME_TIME); - addPom("a", "b", "1.6", SOME_TIME); - var actual = find(SOME_TIME, "a:b", "[1.2,1.3]", "[1.4,1.5]", "[0,1.2]"); - assertEquals(expected, actual); - } - - @Test - public void findsNewestHighestMatch() { - addPom("a", "b", "1.1", SOME_TIME - 1); - var expected = addPom("a", "b", "1.2", SOME_TIME); - addPom("a", "b", "1.3", SOME_TIME + 1); - var actual = find(SOME_TIME, "a:b", "[1,2]"); - assertEquals(expected, actual); - } - - @Test - public void pomsAreNotAutomaticallyReplaced() { - var a = addPom("a", "b", "1", SOME_TIME - 1); - var b = addPom("a", "b", "1", SOME_TIME); - var actuals = sut.findGA(new GA("a", "b")); - assertEquals(Set.of(a, b), actuals); - } - - @Test - public void duplicatePomsCanBeCleanedUp() { - addPom("a", "b", "1", SOME_TIME - 1); - var b = addPom("a", "b", "1", SOME_TIME); - sut.removeOutdatedPomRegistrations(); - var actuals = sut.findGA(new GA("a", "b")); - assertEquals(Set.of(b), actuals); - } - - private static GA ga(String g, String a) { - return new GA(g, a); - } - - private Pom find(long resolveAt, String gaStr, String... specs) { - var parts = gaStr.split(":"); - var ga = new GA(parts[0], parts[1]); - - var vcs = Arrays.stream(specs) // - .map(VersionConstraint::new) // - .collect(Collectors.toSet()); - return sut.find(ga, vcs, resolveAt); - } - - private Pom addPom(String g, String a, String v, long releaseDate) { - var pb = new PomBuilder(); - pb.groupId = g; - pb.artifactId = a; - pb.version = v; - pb.releaseDate = releaseDate; - - var pom = pb.pom(); - sut.add(pom); - return pom; - } - - private static class TestMavenDependencyData extends MavenResolverData { - @Override - public synchronized Set findGA(GA ga) { - return super.findGA(ga); - } - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependentsTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependentsTest.java deleted file mode 100644 index be48cff13..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverDataDependentsTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Set; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.GA; -import eu.fasten.core.maven.data.GAV; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.PomBuilder; - -public class MavenResolverDataDependentsTest { - - private static final GAV GA1 = new GAV("g", "a", "1"); - - private static final GA AB = new GA("a", "b"); - - private static final long SOME_TIME = 1234; - - private MavenResolverData sut; - - @BeforeEach - public void setup() { - sut = new MavenResolverData(); - } - - @Test - public void nonExistingPomIsNull() { - var actual = sut.findPom(GA1, SOME_TIME); - assertNull(actual); - } - - @Test - public void pomCanBeAdded() { - var a = add(SOME_TIME, "g:a:1", "a:b:1"); - var b = sut.findPom(GA1, SOME_TIME); - assertSame(a, b); - var dpds = sut.findPotentialDependents(AB, SOME_TIME); - assertEquals(1, dpds.size()); - } - - @Test - public void pomAreNotAutomaticallyReplaced() { - var a = add(SOME_TIME, "g:a:1", "a:b:1"); - var b = add(SOME_TIME + 1, "g:a:1", "a:b:1"); - var actual = sut.findPom(GA1, SOME_TIME + 1); - assertSame(b, actual); - var actuals = sut.findPotentialDependents(AB, SOME_TIME + 1); - assertEquals(Set.of(a, b), actuals); - } - - @Test - public void pomsCanBeCleanedUp() { - add(SOME_TIME, "g:a:1", "a:b:1"); - var b = add(SOME_TIME + 1, "g:a:1", "a:b:1"); - sut.removeOutdatedPomRegistrations(); - var actual = sut.findPom(GA1, SOME_TIME + 1); - assertSame(b, actual); - var actuals = sut.findPotentialDependents(AB, SOME_TIME + 1); - assertEquals(Set.of(b), actuals); - } - - @Test - public void pomIsNotFoundWhenTooRecent() { - add(SOME_TIME + 1, "g:a:1", "a:b:1"); - var actual = sut.findPom(GA1, SOME_TIME); - assertNull(actual); - } - - @Test - public void findDependents() { - var expected = add(SOME_TIME, "g:a:1", "a:b:1"); - var actuals = sut.findPotentialDependents(AB, SOME_TIME); - assertEquals(Set.of(expected), actuals); - } - - @Test - public void findDependentsMultiple() { - var e1 = add(SOME_TIME, "a:a:1", "t:t:1"); - var e2 = add(SOME_TIME, "b:b:1", "t:t:1"); - var actuals = sut.findPotentialDependents(new GA("t", "t"), SOME_TIME); - assertEquals(Set.of(e1, e2), actuals); - } - - @Test - public void noInterferenceOfOtherDepdencies() { - var e1 = add(SOME_TIME, "a:a:1", "t:t:1"); - add(SOME_TIME, "b:b:1", "u:u:1"); - var actuals = sut.findPotentialDependents(new GA("t", "t"), SOME_TIME); - assertEquals(Set.of(e1), actuals); - } - - @Test - public void dependentsNotFoundWhenTooRecent() { - add(SOME_TIME + 1, "a:a:1", "t:t:1"); - var actuals = sut.findPotentialDependents(new GA("t", "t"), SOME_TIME); - assertEquals(Set.of(), actuals); - } - - private Pom add(long releasedAt, String gav, String... deps) { - var parts = gav.split(":"); - var pb = new PomBuilder(); - pb.groupId = parts[0]; - pb.artifactId = parts[1]; - pb.version = parts[2]; - pb.releaseDate = releasedAt; - - for (var depGAV : deps) { - var depParts = depGAV.split(":"); - var dep = new Dependency(depParts[0], depParts[1], depParts[2]); - pb.dependencies.add(dep); - } - - var pom = pb.pom(); - sut.add(pom); - return pom; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverIOTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverIOTest.java index ad047b0fd..5588b4361 100644 --- a/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverIOTest.java +++ b/core/src/test/java/eu/fasten/core/maven/resolution/MavenResolverIOTest.java @@ -16,7 +16,7 @@ package eu.fasten.core.maven.resolution; import static eu.fasten.core.data.metadatadb.codegen.tables.PackageVersions.PACKAGE_VERSIONS; -import static eu.fasten.core.maven.data.Scope.COMPILE; +import static dev.c0ps.maven.data.Scope.COMPILE; import static org.jooq.SQLDialect.POSTGRES; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -43,18 +43,18 @@ import com.fasterxml.jackson.databind.DatabindException; import com.fasterxml.jackson.databind.ObjectMapper; -import eu.fasten.core.json.ObjectMapperBuilder; -import eu.fasten.core.maven.data.Dependency; -import eu.fasten.core.maven.data.Exclusion; -import eu.fasten.core.maven.data.Pom; -import eu.fasten.core.maven.data.PomBuilder; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Scope; -import eu.fasten.core.maven.data.VersionConstraint; +import dev.c0ps.maven.data.Dependency; +import dev.c0ps.maven.data.Exclusion; +import dev.c0ps.maven.data.Pom; +import dev.c0ps.maven.data.PomBuilder; +import dev.c0ps.maven.data.ResolvedRevision; +import dev.c0ps.maven.data.Scope; +import dev.c0ps.maven.data.VersionConstraint; +import eu.fasten.core.json.FastenObjectMapperBuilder; public class MavenResolverIOTest { - private static final ObjectMapper OM = new ObjectMapperBuilder().build(); + private static final ObjectMapper OM = new FastenObjectMapperBuilder().build(); @TempDir public File tempDir; @@ -80,10 +80,8 @@ public void requestedPomsGetSimplified() { pb.version = "v"; pb.artifactRepository = "ar"; pb.commitTag = "ct"; - pb.dependencies.add(new Dependency("dg", "da", Set.of(new VersionConstraint("dv")), - Set.of(new Exclusion("eg", "ea")), Scope.TEST, true, "jar", "cla")); - pb.dependencyManagement.add(new Dependency("dmg", "dma", Set.of(new VersionConstraint("dmv")), - Set.of(new Exclusion("emg", "ema")), Scope.IMPORT, true, "pom", "foo")); + pb.dependencies.add(new Dependency("dg", "da", Set.of(new VersionConstraint("dv")), Set.of(new Exclusion("eg", "ea")), Scope.TEST, true, "jar", "cla")); + pb.dependencyManagement.add(new Dependency("dmg", "dma", Set.of(new VersionConstraint("dmv")), Set.of(new Exclusion("emg", "ema")), Scope.IMPORT, true, "pom", "foo")); pb.packagingType = "pt"; pb.parentCoordinate = "pcoord"; pb.projectName = "pn"; @@ -98,11 +96,9 @@ public void requestedPomsGetSimplified() { pb.groupId = "g"; pb.artifactId = "a"; pb.version = "v"; - var d1 = new Dependency("dg", "da", Set.of(new VersionConstraint("dv")), Set.of(new Exclusion("eg", "ea")), - Scope.TEST, true, null, null); + var d1 = new Dependency("dg", "da", Set.of(new VersionConstraint("dv")), Set.of(new Exclusion("eg", "ea")), Scope.TEST, true, null, null); pb.dependencies.add(d1); - var dm1 = new Dependency("dmg", "dma", Set.of(new VersionConstraint("dmv")), - Set.of(new Exclusion("emg", "ema")), Scope.IMPORT, true, null, null); + var dm1 = new Dependency("dmg", "dma", Set.of(new VersionConstraint("dmv")), Set.of(new Exclusion("emg", "ema")), Scope.IMPORT, true, null, null); pb.dependencyManagement.add(dm1); pb.releaseDate = 1234L; var expected = pb.pom(); diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/ResolverConfigTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/ResolverConfigTest.java deleted file mode 100644 index 0f7487354..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/ResolverConfigTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.resolution.ResolverConfig.resolve; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Date; - -import org.junit.jupiter.api.Test; - -import eu.fasten.core.maven.data.Scope; - -public class ResolverConfigTest { - - @Test - public void defaults() { - var sut = new ResolverConfig(); - assertEquals(Integer.MAX_VALUE, sut.depth); - assertEquals(Integer.MAX_VALUE, sut.limit); - assertEquals(Scope.RUNTIME, sut.scope); - assertFalse(sut.alwaysIncludeProvided); - assertFalse(sut.alwaysIncludeOptional); - var diff = new Date().getTime() - sut.resolveAt; - assertTrue("Difference should be <100ms, but is " + diff, diff < 100); - } - - @Test - public void equalityDefault() { - var a = new ResolverConfig(); - var b = new ResolverConfig(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityNonDefault() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentDepth() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - b.depth = 2; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentLimit() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - b.limit = 2; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentScope() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - b.scope = Scope.PROVIDED; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentTime() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - b.resolveAt = 1234567890123L; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentProvided() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - b.alwaysIncludeProvided = false; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void equalityDifferentOptional() { - var a = getNonDefaultConfig(); - var b = getNonDefaultConfig(); - b.alwaysIncludeOptional = false; - assertNotEquals(a, b); - assertNotEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void hasToString() { - var actual = new ResolverConfig().toString(); - assertTrue(actual.contains("\n")); - assertTrue(actual.contains("@")); - assertTrue(actual.contains("scope")); - assertTrue(actual.contains(ResolverConfig.class.getSimpleName())); - } - - @Test - public void builderReturnsDefault() { - var a = new ResolverConfig(); - var b = ResolverConfig.resolve(); - - var diff = Math.abs(a.resolveAt - b.resolveAt); - assertTrue(diff < 100); - b.resolveAt = a.resolveAt; - - assertEquals(a, b); - assertEquals(a.hashCode(), b.hashCode()); - } - - @Test - public void builderSetsTime() { - var sut = resolve(); - assertSame(sut, sut.at(23456)); - assertEquals(sut.resolveAt, 23456); - } - - @Test - public void builderIncludesTransitives() { - var sut = resolve(); - assertSame(sut, sut.includeTransitiveDeps()); - assertEquals(sut.depth, Integer.MAX_VALUE); - } - - @Test - public void builderExcludesTransitives() { - var sut = resolve(); - assertSame(sut, sut.excludeTransitiveDeps()); - assertEquals(sut.depth, 1); - } - - @Test - public void builderLimitsTransitives() { - var sut = resolve(); - assertSame(sut, sut.limitTransitiveDeps(17)); - assertEquals(17, sut.depth); - } - - @Test - public void builderDistinguishesDirectAndTransitives() { - assertFalse(resolve().includeTransitiveDeps().isExcludingTransitiveDeps()); - assertTrue(resolve().excludeTransitiveDeps().isExcludingTransitiveDeps()); - assertFalse(resolve().limitTransitiveDeps(13).isExcludingTransitiveDeps()); - } - - @Test - public void builderSetsLimit() { - var sut = resolve(); - assertSame(sut, sut.limit(23456)); - assertEquals(23456, sut.limit); - } - - @Test - public void builderSetsScope() { - var sut = resolve(); - assertSame(sut, sut.scope(Scope.COMPILE)); - assertEquals(sut.scope, Scope.COMPILE); - } - - @Test - public void builderSetsProvided() { - var sut = resolve(); - assertSame(sut, sut.alwaysIncludeProvided(true)); - assertTrue(sut.alwaysIncludeProvided); - } - - @Test - public void builderSetsOptional() { - var sut = resolve(); - assertSame(sut, sut.alwaysIncludeOptional(true)); - assertTrue(sut.alwaysIncludeOptional); - } - - @Test - public void builderFailsForInvalidDepths() { - assertThrows(MavenResolutionException.class, () -> { - resolve().limitTransitiveDeps(0); - }); - assertThrows(MavenResolutionException.class, () -> { - resolve().limitTransitiveDeps(-1); - }); - } - - private static ResolverConfig getNonDefaultConfig() { - var cfg = new ResolverConfig(); - cfg.depth = 1357; - cfg.limit = 5864; - cfg.scope = Scope.COMPILE; - cfg.resolveAt = 1234567890000L; - cfg.alwaysIncludeProvided = true; - cfg.alwaysIncludeOptional = true; - return cfg; - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/resolution/RestMavenResolverTest.java b/core/src/test/java/eu/fasten/core/maven/resolution/RestMavenResolverTest.java deleted file mode 100644 index 1b5df6a5c..000000000 --- a/core/src/test/java/eu/fasten/core/maven/resolution/RestMavenResolverTest.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright 2022 Delft University of Technology - * - * Licensed 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 eu.fasten.core.maven.resolution; - -import static eu.fasten.core.maven.data.Scope.IMPORT; -import static eu.fasten.core.maven.data.Scope.TEST; -import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import dev.c0ps.test.HttpTestServer; -import dev.c0ps.test.HttpTestServer.Request; -import eu.fasten.core.maven.data.ResolvedRevision; -import eu.fasten.core.maven.data.Revision; - -public class RestMavenResolverTest { - - private static final Set SOME_DEPS = Set.of("g:a:1", "g2:a2:2"); - - private static final Revision DEFAULT_REVISION = new ResolvedRevision(0, "g", "a", "2.3.4", - new Timestamp(1234567890000L), IMPORT); - - private static final int PORT = 8081; - - private static HttpTestServer httpd; - private RestMavenResolver sut; - - @BeforeAll - public static void setupAll() { - httpd = new HttpTestServer(PORT); - httpd.start(); - } - - @AfterAll - public static void teardownAll() { - httpd.stop(); - } - - @BeforeEach - public void setup() { - httpd.reset(); - httpd.setResponse("application/json", - "[{\"groupId\":\"g\",\"artifactId\":\"a\",\"version\":\"2.3.4\",\"createdAt\":1234567890000,\"scope\":\"IMPORT\"}]"); - - sut = new RestMavenResolver("http://127.0.0.1:" + PORT + "/"); - } - - @Test - public void dependenciesCorrectMethod() { - var r = resolveSomeDependencies(); - assertEquals("POST", r.method); - } - - @Test - public void dependenciesCorrectPath() { - var r = resolveSomeDependencies(); - assertEquals("/depgraph/dependencies", r.path); - } - - @Test - public void dependenciesCorrectHeaders() { - var r = resolveSomeDependencies(); - assertTrue(r.headers.containsKey("Content-Type")); - assertEquals(APPLICATION_JSON, r.headers.get("Content-Type")); - assertTrue(r.headers.containsKey("Accept")); - assertEquals(APPLICATION_JSON, r.headers.get("Accept")); - } - - @Test - public void dependenciesCorrectTimestampDefault() { - var cfg = new ResolverConfig(); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of("resolveAt", Long.toString(cfg.resolveAt)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectTimestampExplicit() { - var cfg = new ResolverConfig().at(1234567); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of("resolveAt", Long.toString(1234567)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectNonDefaultScope() { - var cfg = new ResolverConfig().at(123).scope(TEST); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "scope", "TEST"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectDefaultDepth() { - var cfg = new ResolverConfig().at(123).includeTransitiveDeps(); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectNonDefaultDepth() { - var cfg = new ResolverConfig().at(123).excludeTransitiveDeps(); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "depth", "1"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectDefaultLimit() { - var cfg = new ResolverConfig().at(123); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectNonDefaultLimit() { - var cfg = new ResolverConfig().at(123).limit(234); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "limit", "234"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectNonDefaultCustomDepth() { - var cfg = new ResolverConfig().at(123).limitTransitiveDeps(13); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "depth", "13"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectIncludeProvided() { - var cfg = new ResolverConfig().at(123).alwaysIncludeProvided(true); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "alwaysIncludeProvided", "true"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectIncludeOptional() { - var cfg = new ResolverConfig().at(123).alwaysIncludeOptional(true); - var r = resolveSomeDependencies(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "alwaysIncludeOptional", "true"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependenciesCorrectBody() { - var r = resolveSomeDependencies(); - var actual = parseBody(r.body); - var expected = SOME_DEPS; - assertEquals(expected, actual); - } - - @Test - public void dependenciesSuccessfullyParsed() { - var expected = Set.of(DEFAULT_REVISION); - var actual = sut.resolveDependencies(SOME_DEPS, new ResolverConfig()); - assertEquals(expected, actual); - - var a = actual.iterator().next(); - assertEquals(0L, a.id); - assertEquals(IMPORT, a.scope); - } - - @Test - public void dependentsCorrectMethod() { - var r = resolveSomeDependents(); - assertEquals("GET", r.method); - } - - @Test - public void dependentsCorrectPath() { - var r = resolveSomeDependents(); - assertEquals("/depgraph/dependents/g/a/1.2.3", r.path); - } - - @Test - public void dependentsCorrectHeaders() { - var r = resolveSomeDependents(); - assertTrue(r.headers.containsKey("Accept")); - assertEquals(APPLICATION_JSON, r.headers.get("Accept")); - } - - @Test - public void dependentsCorrectTimestampDefault() { - var cfg = new ResolverConfig(); - var r = resolveSomeDependents(cfg); - Map expected = Map.of("resolveAt", Long.toString(cfg.resolveAt)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectTimestampExplicit() { - var cfg = new ResolverConfig().at(1234567); - var r = resolveSomeDependents(cfg); - Map expected = Map.of("resolveAt", Long.toString(1234567)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectNonDefaultScope() { - var cfg = new ResolverConfig().at(123).scope(TEST); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "scope", "TEST"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectDefaultDepth() { - var cfg = new ResolverConfig().at(123).includeTransitiveDeps(); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectNonDefaultDepth() { - var cfg = new ResolverConfig().at(123).excludeTransitiveDeps(); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "depth", "1"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectDefaultLimit() { - var cfg = new ResolverConfig().at(123); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123)); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectNonDefaultLimit() { - var cfg = new ResolverConfig().at(123).limit(234); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "limit", "234"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectNonDefaultCustomDepth() { - var cfg = new ResolverConfig().at(123).limitTransitiveDeps(13); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "depth", "13"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectIncludeProvided() { - var cfg = new ResolverConfig().at(123).alwaysIncludeProvided(true); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "alwaysIncludeProvided", "true"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectIncludeOptional() { - var cfg = new ResolverConfig().at(123).alwaysIncludeOptional(true); - var r = resolveSomeDependents(cfg); - Map expected = Map.of( // - "resolveAt", Long.toString(123), // - "alwaysIncludeOptional", "true"); - assertEquals(expected, r.queryParams); - } - - @Test - public void dependentsCorrectBody() { - var r = resolveSomeDependents(); - var actual = parseBody(r.body); - var expected = Set.of(); - assertEquals(expected, actual); - } - - @Test - public void dependentsSuccessfullyParsed() { - var expected = Set.of(DEFAULT_REVISION); - var actual = sut.resolveDependents("g", "a", "1", new ResolverConfig()); - assertEquals(expected, actual); - - var a = actual.iterator().next(); - assertEquals(0L, a.id); - assertEquals(IMPORT, a.scope); - } - - private Request resolveSomeDependencies() { - return resolveSomeDependencies(new ResolverConfig()); - } - - private Request resolveSomeDependencies(ResolverConfig cfg) { - sut.resolveDependencies(SOME_DEPS, cfg); - assertEquals(1, httpd.requests.size()); - return httpd.requests.get(0); - } - - private Request resolveSomeDependents() { - return resolveSomeDependents(new ResolverConfig()); - } - - private Request resolveSomeDependents(ResolverConfig cfg) { - sut.resolveDependents("g", "a", "1.2.3", cfg); - assertEquals(1, httpd.requests.size()); - return httpd.requests.get(0); - } - - private static Set parseBody(String body) { - if (body == null || body.isEmpty()) { - return Set.of(); - } - return Arrays.stream(body.substring(1, body.length() - 1).split(",")) // - .map(gav -> gav.trim().substring(1, gav.length() - 1)) // - .collect(Collectors.toSet()); - } -} \ No newline at end of file diff --git a/core/src/test/java/eu/fasten/core/maven/utils/MavenUtilitiesTest.java b/core/src/test/java/eu/fasten/core/maven/utils/MavenUtilitiesTest.java deleted file mode 100644 index a559f1ebf..000000000 --- a/core/src/test/java/eu/fasten/core/maven/utils/MavenUtilitiesTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 eu.fasten.core.maven.utils; - -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class MavenUtilitiesTest { - - @Test - public void getReposDefaultTest() { - var actual = MavenUtilities.getRepos(); - var expected = List.of("https://repo.maven.apache.org/maven2/"); - assertEquals(expected, actual); - } - - @Test - public void downloadValidPomTest() throws IOException { - var file = MavenUtilities.downloadPom("junit", "junit", "4.12"); - assertTrue(file.isPresent()); - } - - @Test - public void downloadInvalidPomTest() { - assertThrows(IllegalStateException.class, () -> { - MavenUtilities.downloadPom("fake", "fake", "4.12"); - }); - } - - @Test - public void downloadPomWithInvalidRepoTest() { - assertThrows(IllegalStateException.class, () -> { - MavenUtilities.downloadPom("junit", "junit", "4.12", List.of("https://google.com/")); - }); - } - - @Test - public void downloadPomWithSpaceInURL() throws IOException { - var file = MavenUtilities.downloadPom(" com.day.crx", "crx-journal-api ", " 1.4.2-load4"); - assertTrue(file.isPresent()); - } -} diff --git a/core/src/test/java/eu/fasten/core/opal/MavenArtifactDownloaderTest.java b/core/src/test/java/eu/fasten/core/opal/MavenArtifactDownloaderTest.java index cf69cf9af..7e8a5272b 100644 --- a/core/src/test/java/eu/fasten/core/opal/MavenArtifactDownloaderTest.java +++ b/core/src/test/java/eu/fasten/core/opal/MavenArtifactDownloaderTest.java @@ -10,7 +10,7 @@ import eu.fasten.core.data.opal.MavenArtifactDownloader; import eu.fasten.core.data.opal.MavenCoordinate; import eu.fasten.core.data.opal.exceptions.MissingArtifactException; -import eu.fasten.core.maven.utils.MavenUtilities; +import dev.c0ps.maven.MavenUtilities; public class MavenArtifactDownloaderTest { diff --git a/core/src/test/java/eu/fasten/core/utils/AssertsTest.java b/core/src/test/java/eu/fasten/core/utils/AssertsTest.java deleted file mode 100644 index dfaf0f94f..000000000 --- a/core/src/test/java/eu/fasten/core/utils/AssertsTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2021 Delft University of Technology - * - * Licensed 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 eu.fasten.core.utils; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -public class AssertsTest { - - @Test - public void assertNotNull_fail() { - assertThrows(IllegalStateException.class, () -> { - Asserts.assertNotNull(null); - }); - } - - @Test - public void assertNotNull_ok() { - Asserts.assertNotNull(""); - } - - @Test - public void assertContains_fail() { - assertThrows(IllegalStateException.class, () -> { - Asserts.assertContains(new String[] { "a", "b", "c" }, "x"); - }); - } - - @Test - public void assertContains_ok() { - Asserts.assertContains(new String[] { "a", "b", "c" }, "a"); - } - - @Test - public void assertContains_okForNull() { - Asserts.assertContains(new String[] { "a", null }, null); - } - - @Test - public void assertNotNullOrEmpty_failNull() { - assertThrows(IllegalStateException.class, () -> { - Asserts.assertNotNullOrEmpty(null); - }); - } - - @Test - public void assertNotNullOrEmpty_failEmpty() { - assertThrows(IllegalStateException.class, () -> { - Asserts.assertNotNullOrEmpty(""); - }); - } - - @Test - public void assertNotNullOrEmpty_ok() { - Asserts.assertNotNullOrEmpty("..."); - } - - @Test - public void assertTrue_okStd() { - Asserts.assertTrue(true); - } - - @Test - public void assertTrue_okCustom() { - Asserts.assertTrue(true, "..."); - } - - @Test - public void assertTrue_failStd() { - var e = assertThrows(IllegalStateException.class, () -> { - Asserts.assertTrue(false); - }); - assertEquals("Expected condition not met.", e.getMessage()); - } - - @Test - public void assertTrue_failCustom() { - var e = assertThrows(IllegalStateException.class, () -> { - Asserts.assertTrue(false, "abc"); - }); - assertEquals("abc", e.getMessage()); - } -} \ No newline at end of file diff --git a/pom.xml b/pom.xml index ecfad7f88..718389f3b 100644 --- a/pom.xml +++ b/pom.xml @@ -290,11 +290,8 @@ - github - https://maven.pkg.github.com/cops-lab/test-utils/ - - true - + github-cops + https://maven.pkg.github.com/cops-lab/packages/