[ 
https://issues.apache.org/jira/browse/MNG-6869?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17692676#comment-17692676
 ] 

ASF GitHub Bot commented on MNG-6869:
-------------------------------------

mthmulders commented on code in PR #995:
URL: https://github.com/apache/maven/pull/995#discussion_r1115676030


##########
maven-embedder/src/main/java/org/apache/maven/cli/RemoteRepositoryConnectionVerifier.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.cli;
+
+import java.net.URI;
+import java.util.Optional;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.maven.RepositoryUtils;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.codehaus.plexus.PlexusContainer;
+import 
org.codehaus.plexus.component.repository.exception.ComponentLookupException;
+import org.eclipse.aether.RepositorySystemSession;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.repository.RemoteRepository;
+import org.eclipse.aether.spi.connector.transport.GetTask;
+import org.eclipse.aether.spi.connector.transport.Transporter;
+import org.eclipse.aether.spi.connector.transport.TransporterProvider;
+import org.eclipse.aether.transfer.NoTransporterException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Helper class to verify connection to a remote repository.
+ */
+public class RemoteRepositoryConnectionVerifier {
+    private static final Artifact APACHE_MAVEN_ARTIFACT = 
MavenStatusCommand.APACHE_MAVEN_ARTIFACT;
+    private final Logger logger;
+    private final TransporterProvider transporterProvider;
+
+    public RemoteRepositoryConnectionVerifier(final PlexusContainer container) 
throws ComponentLookupException {
+        this.logger = 
LoggerFactory.getILoggerFactory().getLogger(RemoteRepositoryConnectionVerifier.class.getName());
+        this.transporterProvider = container.lookup(TransporterProvider.class);
+    }
+
+    private boolean isCentralOrMirrorOfCentral(final RemoteRepository 
remoteRepository) {
+        return "central".equals(remoteRepository.getId())
+                || remoteRepository.getMirroredRepositories().stream()
+                        .map(RemoteRepository::getId)
+                        .anyMatch("central"::equals);
+    }
+
+    public Optional<String> verifyConnectionToRemoteRepository(
+            final RepositorySystemSession session, final ArtifactRepository 
artifactRepository) {
+        final RemoteRepository repository = 
RepositoryUtils.toRepo(artifactRepository);
+
+        final String artifactPath;
+
+        if (isCentralOrMirrorOfCentral(repository)) {
+            // We can be sure the Apache Maven artifact should be resolvable.
+            artifactPath = 
artifactRepository.getLayout().pathOf(RepositoryUtils.toArtifact(APACHE_MAVEN_ARTIFACT));
+        } else {
+            // We cannot be sure about any artifact that lives here.
+            artifactPath = "";
+        }
+
+        try {
+            final Transporter transporter = 
transporterProvider.newTransporter(session, repository);
+            final Optional<String> maybeIssue = 
verifyConnectionUsingTransport(transporter, repository, artifactPath);
+
+            if (!maybeIssue.isPresent()) {
+                logger.info("Connection check for {} [{}] completed", 
repository.getId(), repository.getUrl());
+            }
+
+            return maybeIssue;
+        } catch (final NoTransporterException nte) {
+            final String message = String.format(
+                    "There is no compatible transport for remote repository %s 
with location %s",
+                    repository.getId(), repository.getUrl());
+            return Optional.of(message);
+        }
+    }
+
+    private Optional<String> verifyConnectionUsingTransport(
+            final Transporter transporter, final RemoteRepository 
remoteRepository, final String artifactPath) {
+        try {
+            final GetTask task = new GetTask(URI.create(artifactPath));
+            transporter.get(task);
+            return Optional.empty();
+        } catch (final Exception e) {
+            return classifyException(remoteRepository, e);
+        }
+    }
+
+    private Optional<String> classifyException(final RemoteRepository 
remoteRepository, final Exception e) {
+        final String message = e.getMessage();
+        final String repositoryId = remoteRepository.getId();
+        final String repositoryUrl = remoteRepository.getUrl();
+        final String repository = String.format("%s [%s]", repositoryId, 
repositoryUrl);
+
+        final boolean notFound = StringUtils.contains(message, "status code: 
404");
+        final boolean unauthorized = StringUtils.contains(message, "status 
code: 401");
+        final boolean forbidden = StringUtils.contains(message, "status code: 
403");

Review Comment:
   We now use 
[`transport#classify()`](https://maven.apache.org/resolver/apidocs/org/eclipse/aether/spi/connector/transport/Transporter.html#classify(java.lang.Throwable)).
 It does not provide a lot of detail, but it's transport-agnostic AFAICS, which 
is definitely a plus.





> New flag to verify the status
> -----------------------------
>
>                 Key: MNG-6869
>                 URL: https://issues.apache.org/jira/browse/MNG-6869
>             Project: Maven
>          Issue Type: New Feature
>            Reporter: Robert Scholte
>            Assignee: Maarten Mulders
>            Priority: Major
>
> While working on INFRA-19861 we had issues with invalid changes in the 
> settings.xml.
> This was detected too late. After installation {{mvn --version}} is called, 
> but it will only show the version of Maven.
> It would be better to have a flag that verifies it a bit more:
> - can Maven read/write to the local repository
> - can Maven access all predefined repositories? (does the proxy work?)
> This gives a much better feedback if Maven can do its job.
> Current workaround: call something like {{mvn help:evaluate 
> -Dexpression=settings.localRepository -q -DforceStdout}}



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to