Search in sources :

Example 1 with MavenArtifactResolver

use of io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver in project quarkus by quarkusio.

the class ExtensionDescriptorMojo method resolver.

private MavenArtifactResolver resolver() throws MojoExecutionException {
    if (resolver == null) {
        final DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repoSession);
        session.setWorkspaceReader(workspaceProvider.workspace());
        try {
            final BootstrapMavenContext ctx = new BootstrapMavenContext(BootstrapMavenContext.config().setRepositorySystem(repoSystem).setRemoteRepositoryManager(remoteRepoManager).setRepositorySystemSession(session).setRemoteRepositories(repos).setPreferPomsFromWorkspace(true).setCurrentProject(workspaceProvider.origin()));
            resolver = new MavenArtifactResolver(ctx);
        } catch (BootstrapMavenException e) {
            throw new MojoExecutionException("Failed to initialize Maven artifact resolver", e);
        }
    }
    return resolver;
}
Also used : BootstrapMavenException(io.quarkus.bootstrap.resolver.maven.BootstrapMavenException) BootstrapMavenContext(io.quarkus.bootstrap.resolver.maven.BootstrapMavenContext) DefaultRepositorySystemSession(org.eclipse.aether.DefaultRepositorySystemSession) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MavenArtifactResolver(io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver)

Example 2 with MavenArtifactResolver

use of io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver in project quarkus by quarkusio.

the class MavenRegistryClientFactory method buildRegistryClient.

@Override
public RegistryClient buildRegistryClient(RegistryConfig config) throws RegistryResolutionException {
    Objects.requireNonNull(config, "The registry config is null");
    final RegistryDescriptorConfig descriptorConfig = config.getDescriptor();
    if (descriptorConfig == null) {
        throw new IllegalArgumentException("The registry descriptor configuration is missing for " + config.getId());
    }
    final ArtifactCoords originalDescrCoords = descriptorConfig.getArtifact();
    final Artifact registryDescriptorCoords = new DefaultArtifact(originalDescrCoords.getGroupId(), originalDescrCoords.getArtifactId(), originalDescrCoords.getClassifier(), originalDescrCoords.getType(), originalDescrCoords.getVersion());
    final boolean cleanupTimestampedArtifacts = isCleanupTimestampedArtifacts(config);
    // Determine the original registry Maven repository configuration
    // If the user settings already contain a Maven repository configuration with either an ID matching the registry ID
    // or a URL matching the registry URL, the original Maven resolver will be assumed to be already properly initialized.
    // Otherwise, a new registry Maven repository will be configured and a new resolver will be initialized for the registry.
    final List<RemoteRepository> registryRepos = determineRegistryRepos(config, originalResolver.getRepositories());
    MavenArtifactResolver resolver;
    ArtifactResult result;
    if (!registryRepos.isEmpty()) {
        // first, we try applying the mirrors and proxies found in the user settings
        final List<RemoteRepository> aggregatedRepos = originalResolver.getRemoteRepositoryManager().aggregateRepositories(originalResolver.getSession(), Collections.emptyList(), registryRepos, true);
        resolver = newResolver(originalResolver, aggregatedRepos, config, log);
        try {
            result = MavenRegistryArtifactResolverWithCleanup.resolveAndCleanupOldTimestampedVersions(resolver, registryDescriptorCoords, cleanupTimestampedArtifacts);
        } catch (BootstrapMavenException e) {
            if (areMatching(registryRepos, aggregatedRepos)) {
                // there is nothing to fallback to
                throw new RegistryResolutionException(getDescriptorResolutionFailureMessage(config, resolver, e), e);
            }
            // if the mirror and proxies in the user settings were configured w/o taking the extension registry into account
            // we will warn the user and try the original registry repos as a fallback
            log.warn(getDescriptorResolutionFailureFromMirrorMessage(config, resolver, e, registryRepos));
            resolver = newResolver(originalResolver, registryRepos, config, log);
            try {
                result = MavenRegistryArtifactResolverWithCleanup.resolveAndCleanupOldTimestampedVersions(resolver, registryDescriptorCoords, cleanupTimestampedArtifacts);
            } catch (BootstrapMavenException e1) {
                throw new RegistryResolutionException(getDescriptorResolutionFailureMessage(config, resolver, e));
            }
        }
    } else {
        resolver = newResolver(originalResolver, originalResolver.getRepositories(), config, log);
        try {
            result = MavenRegistryArtifactResolverWithCleanup.resolveAndCleanupOldTimestampedVersions(resolver, registryDescriptorCoords, cleanupTimestampedArtifacts);
        } catch (BootstrapMavenException e) {
            throw new RegistryResolutionException(getDescriptorResolutionFailureMessage(config, resolver, e));
        }
    }
    final String srcRepoId = result.getRepository() == null ? "n/a" : result.getRepository().getId();
    log.debug("Resolved registry descriptor %s from %s", registryDescriptorCoords, srcRepoId);
    if (!registryRepos.isEmpty()) {
        if (srcRepoId != null && !"local".equals(srcRepoId)) {
            String srcRepoUrl = null;
            for (RemoteRepository repo : resolver.getRepositories()) {
                if (repo.getId().equals(srcRepoId)) {
                    srcRepoUrl = repo.getUrl();
                    break;
                }
            }
            if (srcRepoUrl == null) {
                throw new IllegalStateException("Failed to locate the repository URL corresponding to repository " + srcRepoId);
            }
        } else {
            log.debug("Failed to determine the remote repository for %s registry descriptor %s", config.getId(), registryDescriptorCoords);
        }
    }
    final RegistryConfig.Mutable descriptor;
    try {
        // Do not fix or add any missing bits.
        descriptor = RegistryConfig.mutableFromFile(result.getArtifact().getFile().toPath());
    } catch (IOException e) {
        throw new IllegalStateException("Failed to deserialize registries descriptor " + result.getArtifact().getFile(), e);
    }
    if (!isComplete(config, descriptor)) {
        config = completeRegistryConfig(config, descriptor);
    }
    final MavenRegistryArtifactResolver defaultResolver = defaultResolver(resolver, cleanupTimestampedArtifacts);
    final RegistryNonPlatformExtensionsResolver nonPlatformExtensionsResolver;
    final RegistryNonPlatformExtensionsConfig nonPlatformExtensions = config.getNonPlatformExtensions();
    if (nonPlatformExtensions == null || nonPlatformExtensions.isDisabled()) {
        log.debug("Non-platform extension catalogs were disabled for registry %s", config.getId());
        nonPlatformExtensionsResolver = null;
    } else {
        nonPlatformExtensionsResolver = new MavenNonPlatformExtensionsResolver(nonPlatformExtensions, defaultResolver, log);
    }
    final RegistryPlatformsResolver platformsResolver;
    final RegistryPlatformsConfig platformsConfig = config.getPlatforms();
    if (platformsConfig == null || platformsConfig.isDisabled()) {
        log.debug("Platform catalogs were disabled for registry %s", config.getId());
        platformsResolver = null;
    } else {
        platformsResolver = new MavenPlatformsResolver(platformsConfig, defaultResolver, log);
    }
    return new RegistryClientDispatcher(config, platformsResolver, Boolean.TRUE.equals(platformsConfig == null ? Boolean.FALSE : platformsConfig.getExtensionCatalogsIncluded()) ? new MavenPlatformExtensionsResolver(defaultResolver, log) : new MavenPlatformExtensionsResolver(defaultResolver(originalResolver, cleanupTimestampedArtifacts), log), nonPlatformExtensionsResolver, new MavenRegistryCache(config, defaultResolver, log));
}
Also used : RegistryConfig(io.quarkus.registry.config.RegistryConfig) ArtifactCoords(io.quarkus.maven.ArtifactCoords) RemoteRepository(org.eclipse.aether.repository.RemoteRepository) RegistryPlatformsConfig(io.quarkus.registry.config.RegistryPlatformsConfig) RegistryNonPlatformExtensionsConfig(io.quarkus.registry.config.RegistryNonPlatformExtensionsConfig) RegistryClientDispatcher(io.quarkus.registry.client.RegistryClientDispatcher) RegistryNonPlatformExtensionsResolver(io.quarkus.registry.client.RegistryNonPlatformExtensionsResolver) IOException(java.io.IOException) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact) Artifact(org.eclipse.aether.artifact.Artifact) ArtifactResult(org.eclipse.aether.resolution.ArtifactResult) BootstrapMavenException(io.quarkus.bootstrap.resolver.maven.BootstrapMavenException) RegistryResolutionException(io.quarkus.registry.RegistryResolutionException) RegistryDescriptorConfig(io.quarkus.registry.config.RegistryDescriptorConfig) RegistryPlatformsResolver(io.quarkus.registry.client.RegistryPlatformsResolver) MavenArtifactResolver(io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact)

Example 3 with MavenArtifactResolver

use of io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver in project quarkus by quarkusio.

the class PlatformCatalogLastUpdatedTest method testLastUpdated.

@Test
void testLastUpdated() throws Exception {
    final Path registryWorkDir = Paths.get("target").resolve("test-registry").normalize().toAbsolutePath();
    Files.createDirectories(registryWorkDir);
    final Path registryRepoDir = registryWorkDir.resolve("repo");
    Files.createDirectories(registryRepoDir);
    final MavenArtifactResolver mvn = MavenArtifactResolver.builder().setWorkspaceDiscovery(false).setLocalRepository(registryRepoDir.toString()).build();
    RegistriesConfig.Mutable registriesConfig = RegistriesConfig.builder();
    registriesConfig.addRegistry(configureRegistry("foo", registryWorkDir, mvn));
    final String fooTimestamp = "20210101010101";
    setLastUpdated("foo", fooTimestamp, registryRepoDir, mvn);
    PlatformCatalog platformCatalog = newCatalogResolver(registriesConfig.build(), mvn).resolvePlatformCatalog();
    assertThat(platformCatalog).isNotNull();
    assertThat(platformCatalog.getPlatforms()).hasSize(1);
    assertThat(platformCatalog.getPlatforms().iterator().next().getPlatformKey()).isEqualTo(toPlatformKey("foo"));
    assertThat(platformCatalog.getMetadata().get(Constants.LAST_UPDATED)).isEqualTo(fooTimestamp);
    registriesConfig.addRegistry(configureRegistry("bar", registryWorkDir, mvn));
    final String barTimestamp = "20210101010102";
    setLastUpdated("bar", barTimestamp, registryRepoDir, mvn);
    platformCatalog = newCatalogResolver(registriesConfig, mvn).resolvePlatformCatalog();
    assertThat(platformCatalog).isNotNull();
    assertThat(platformCatalog.getPlatforms()).hasSize(2);
    final Iterator<Platform> platforms = platformCatalog.getPlatforms().iterator();
    assertThat(platforms.next().getPlatformKey()).isEqualTo(toPlatformKey("foo"));
    assertThat(platforms.next().getPlatformKey()).isEqualTo(toPlatformKey("bar"));
    assertThat(platformCatalog.getMetadata().get(Constants.LAST_UPDATED)).isEqualTo(barTimestamp);
}
Also used : Path(java.nio.file.Path) RegistriesConfig(io.quarkus.registry.config.RegistriesConfig) Platform(io.quarkus.registry.catalog.Platform) PlatformCatalog(io.quarkus.registry.catalog.PlatformCatalog) MavenArtifactResolver(io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver) Test(org.junit.jupiter.api.Test)

Example 4 with MavenArtifactResolver

use of io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver in project quarkus by quarkusio.

the class CreateProjectMojo method execute.

@Override
public void execute() throws MojoExecutionException {
    // We detect the Maven version during the project generation to indicate the user immediately that the installed
    // version may not be supported.
    mavenVersionEnforcer.ensureMavenVersion(getLog(), session);
    try {
        Files.createDirectories(outputDirectory.toPath());
    } catch (IOException e) {
        throw new MojoExecutionException("Could not create directory " + outputDirectory, e);
    }
    final MavenArtifactResolver mvn;
    try {
        mvn = MavenArtifactResolver.builder().setRepositorySystem(repoSystem).setRepositorySystemSession(getLog().isDebugEnabled() ? repoSession : MojoUtils.muteTransferListener(repoSession)).setRemoteRepositories(repos).setRemoteRepositoryManager(remoteRepoManager).build();
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to initialize Maven artifact resolver", e);
    }
    final MojoMessageWriter log = new MojoMessageWriter(getLog());
    ExtensionCatalogResolver catalogResolver;
    try {
        catalogResolver = QuarkusProjectHelper.isRegistryClientEnabled() ? QuarkusProjectHelper.getCatalogResolver(mvn, log) : ExtensionCatalogResolver.empty();
    } catch (RegistryResolutionException e) {
        // fall back to the default platform
        catalogResolver = ExtensionCatalogResolver.empty();
    }
    ExtensionCatalog catalog = resolveExtensionsCatalog(this, bomGroupId, bomArtifactId, bomVersion, catalogResolver, mvn, log);
    File projectRoot = outputDirectory;
    File pom = project != null ? project.getFile() : null;
    Model parentPomModel = null;
    boolean containsAtLeastOneGradleFile = false;
    for (String gradleFile : Arrays.asList("build.gradle", "settings.gradle", "build.gradle.kts", "settings.gradle.kts")) {
        containsAtLeastOneGradleFile |= new File(projectRoot, gradleFile).isFile();
    }
    BuildTool buildToolEnum = BuildTool.findTool(buildTool);
    if (buildToolEnum == null) {
        String validBuildTools = String.join(",", Arrays.asList(BuildTool.values()).stream().map(BuildTool::toString).collect(Collectors.toList()));
        throw new IllegalArgumentException("Choose a valid build tool. Accepted values are: " + validBuildTools);
    }
    if (BuildTool.MAVEN.equals(buildToolEnum)) {
        if (pom != null && pom.isFile()) {
            try {
                parentPomModel = MojoUtils.readPom(pom);
                if (!"pom".equals(parentPomModel.getPackaging())) {
                    throw new MojoExecutionException("The parent project must have a packaging type of POM. Current packaging: " + parentPomModel.getPackaging());
                }
            } catch (IOException e) {
                throw new MojoExecutionException("Could not access parent pom.", e);
            }
        } else if (containsAtLeastOneGradleFile) {
            throw new MojoExecutionException("You are trying to create a Maven project in a directory that contains only Gradle build files.");
        }
    } else if (BuildTool.GRADLE.equals(buildToolEnum) || BuildTool.GRADLE_KOTLIN_DSL.equals(buildToolEnum)) {
        if (containsAtLeastOneGradleFile) {
            throw new MojoExecutionException("Adding subprojects to gradle projects is not implemented.");
        } else if (pom != null && pom.isFile()) {
            throw new MojoExecutionException("You are trying to create gradle project in a directory that contains only maven build files.");
        }
    }
    askTheUserForMissingValues();
    projectRoot = new File(outputDirectory, projectArtifactId);
    if (projectRoot.exists()) {
        throw new MojoExecutionException("Unable to create the project, " + "the directory " + projectRoot.getAbsolutePath() + " already exists");
    }
    boolean success;
    final Path projectDirPath = projectRoot.toPath();
    try {
        extensions = CreateProjectHelper.sanitizeExtensions(extensions);
        catalog = CreateProjectHelper.completeCatalog(catalog, extensions, mvn);
        final SourceType sourceType = CreateProjectHelper.determineSourceType(extensions);
        sanitizeOptions(sourceType);
        final List<ResourceLoader> codestartsResourceLoader = codestartLoadersBuilder().catalog(catalog).artifactResolver(mvn).build();
        QuarkusProject newProject = QuarkusProject.of(projectDirPath, catalog, codestartsResourceLoader, log, buildToolEnum);
        final CreateProject createProject = new CreateProject(newProject).groupId(projectGroupId).artifactId(projectArtifactId).version(projectVersion).sourceType(sourceType).javaTarget(javaVersion).className(className).packageName(packageName).extensions(extensions).example(example).noCode(noCode).appConfig(appConfig);
        if (path != null) {
            createProject.setValue("path", path);
        }
        success = createProject.execute().isSuccess();
        if (success && parentPomModel != null && BuildTool.MAVEN.equals(buildToolEnum)) {
            // Write to parent pom and submodule pom if project creation is successful
            if (!parentPomModel.getModules().contains(this.projectArtifactId)) {
                parentPomModel.addModule(this.projectArtifactId);
            }
            File subModulePomFile = new File(projectRoot, buildToolEnum.getDependenciesFile());
            Model subModulePomModel = MojoUtils.readPom(subModulePomFile);
            Parent parent = new Parent();
            parent.setGroupId(parentPomModel.getGroupId());
            parent.setArtifactId(parentPomModel.getArtifactId());
            parent.setVersion(parentPomModel.getVersion());
            subModulePomModel.setParent(parent);
            MojoUtils.write(parentPomModel, pom);
            MojoUtils.write(subModulePomModel, subModulePomFile);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to generate Quarkus project", e);
    }
    if (success) {
        printUserInstructions(projectRoot);
    } else {
        throw new MojoExecutionException("The project was created but (some of) the requested extensions couldn't be added.");
    }
}
Also used : Path(java.nio.file.Path) ResourceLoader(io.quarkus.platform.descriptor.loader.json.ResourceLoader) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Parent(org.apache.maven.model.Parent) SourceType(io.quarkus.devtools.project.codegen.SourceType) IOException(java.io.IOException) ExtensionCatalog(io.quarkus.registry.catalog.ExtensionCatalog) CreateProject(io.quarkus.devtools.commands.CreateProject) MojoMessageWriter(io.quarkus.platform.tools.maven.MojoMessageWriter) RegistryResolutionException(io.quarkus.registry.RegistryResolutionException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) RegistryResolutionException(io.quarkus.registry.RegistryResolutionException) BuildTool(io.quarkus.devtools.project.BuildTool) Model(org.apache.maven.model.Model) QuarkusProject(io.quarkus.devtools.project.QuarkusProject) MavenArtifactResolver(io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver) File(java.io.File) ExtensionCatalogResolver(io.quarkus.registry.ExtensionCatalogResolver)

Example 5 with MavenArtifactResolver

use of io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver in project quarkus by quarkusio.

the class GoOfflineMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    final Artifact pom = new DefaultArtifact(project.getArtifact().getGroupId(), project.getArtifactId(), ArtifactCoords.TYPE_POM, project.getVersion());
    final MavenArtifactResolver resolver = getResolver();
    final DependencyNode root;
    try {
        root = resolver.collectDependencies(pom, Collections.emptyList()).getRoot();
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to collect dependencies of " + pom, e);
    }
    final List<Path> createdDirs = new ArrayList<>();
    try {
        ensureResolvableModule(root, resolver.getMavenContext().getWorkspace(), createdDirs);
        final ArtifactCoords appArtifact = new GACTV(pom.getGroupId(), pom.getArtifactId(), pom.getClassifier(), pom.getExtension(), pom.getVersion());
        resolveAppModel(resolver, appArtifact, LaunchMode.NORMAL);
        resolveAppModel(resolver, appArtifact, LaunchMode.DEVELOPMENT);
        resolveAppModel(resolver, appArtifact, LaunchMode.TEST);
    } finally {
        for (Path d : createdDirs) {
            IoUtils.recursiveDelete(d);
        }
    }
}
Also used : Path(java.nio.file.Path) ArtifactCoords(io.quarkus.maven.dependency.ArtifactCoords) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DependencyNode(org.eclipse.aether.graph.DependencyNode) ArrayList(java.util.ArrayList) MavenArtifactResolver(io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver) GACTV(io.quarkus.maven.dependency.GACTV) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact) Artifact(org.eclipse.aether.artifact.Artifact) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact) BootstrapMavenException(io.quarkus.bootstrap.resolver.maven.BootstrapMavenException) AppModelResolverException(io.quarkus.bootstrap.resolver.AppModelResolverException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Aggregations

MavenArtifactResolver (io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver)23 IOException (java.io.IOException)15 Path (java.nio.file.Path)12 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)11 DefaultArtifact (org.eclipse.aether.artifact.DefaultArtifact)11 BootstrapMavenContext (io.quarkus.bootstrap.resolver.maven.BootstrapMavenContext)9 BootstrapMavenException (io.quarkus.bootstrap.resolver.maven.BootstrapMavenException)9 File (java.io.File)9 Artifact (org.eclipse.aether.artifact.Artifact)9 ArrayList (java.util.ArrayList)6 RegistryResolutionException (io.quarkus.registry.RegistryResolutionException)5 ExtensionCatalog (io.quarkus.registry.catalog.ExtensionCatalog)5 Model (org.apache.maven.model.Model)5 GACTV (io.quarkus.maven.dependency.GACTV)4 ResourceLoader (io.quarkus.platform.descriptor.loader.json.ResourceLoader)4 MojoMessageWriter (io.quarkus.platform.tools.maven.MojoMessageWriter)4 CuratedApplication (io.quarkus.bootstrap.app.CuratedApplication)3 QuarkusBootstrap (io.quarkus.bootstrap.app.QuarkusBootstrap)3 AppModelResolverException (io.quarkus.bootstrap.resolver.AppModelResolverException)3 ArtifactCoords (io.quarkus.maven.dependency.ArtifactCoords)3