Search in sources :

Example 11 with Repository

use of org.apache.maven.wagon.repository.Repository in project archiva by apache.

the class MavenRepositoryProxyHandler method connectToRepository.

/**
 * Using wagon, connect to the remote repository.
 *
 * @param connector        the connector configuration to utilize (for obtaining network proxy configuration from)
 * @param wagon            the wagon instance to establish the connection on.
 * @param remoteRepository the remote repository to connect to.
 * @return true if the connection was successful. false if not connected.
 */
protected boolean connectToRepository(ProxyConnector connector, Wagon wagon, RemoteRepository remoteRepository) {
    final ProxyInfo networkProxy = connector.getProxyId() == null ? null : this.networkProxyMap.get(connector.getProxyId());
    if (log.isDebugEnabled()) {
        if (networkProxy != null) {
            // TODO: move to proxyInfo.toString()
            String msg = "Using network proxy " + networkProxy.getHost() + ":" + networkProxy.getPort() + " to connect to remote repository " + remoteRepository.getLocation();
            if (networkProxy.getNonProxyHosts() != null) {
                msg += "; excluding hosts: " + networkProxy.getNonProxyHosts();
            }
            if (StringUtils.isNotBlank(networkProxy.getUserName())) {
                msg += "; as user: " + networkProxy.getUserName();
            }
            log.debug(msg);
        }
    }
    AuthenticationInfo authInfo = null;
    String username = "";
    String password = "";
    RepositoryCredentials repCred = remoteRepository.getLoginCredentials();
    if (repCred != null && repCred instanceof PasswordCredentials) {
        PasswordCredentials pwdCred = (PasswordCredentials) repCred;
        username = pwdCred.getUsername();
        password = pwdCred.getPassword() == null ? "" : new String(pwdCred.getPassword());
    }
    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        log.debug("Using username {} to connect to remote repository {}", username, remoteRepository.getLocation());
        authInfo = new AuthenticationInfo();
        authInfo.setUserName(username);
        authInfo.setPassword(password);
    }
    // Convert seconds to milliseconds
    long timeoutInMilliseconds = remoteRepository.getTimeout().toMillis();
    // Set timeout  read and connect
    // FIXME olamy having 2 config values
    wagon.setReadTimeout((int) timeoutInMilliseconds);
    wagon.setTimeout((int) timeoutInMilliseconds);
    try {
        Repository wagonRepository = new Repository(remoteRepository.getId(), remoteRepository.getLocation().toString());
        wagon.connect(wagonRepository, authInfo, networkProxy);
        return true;
    } catch (ConnectionException | AuthenticationException e) {
        log.warn("Could not connect to {}: {}", remoteRepository.getId(), e.getMessage());
        return false;
    }
}
Also used : ProxyInfo(org.apache.maven.wagon.proxy.ProxyInfo) RepositoryCredentials(org.apache.archiva.repository.RepositoryCredentials) PasswordCredentials(org.apache.archiva.repository.base.PasswordCredentials) Repository(org.apache.maven.wagon.repository.Repository) RemoteRepository(org.apache.archiva.repository.RemoteRepository) ManagedRepository(org.apache.archiva.repository.ManagedRepository) AuthenticationException(org.apache.maven.wagon.authentication.AuthenticationException) AuthenticationInfo(org.apache.maven.wagon.authentication.AuthenticationInfo) ConnectionException(org.apache.maven.wagon.ConnectionException)

Example 12 with Repository

use of org.apache.maven.wagon.repository.Repository in project archiva by apache.

the class DefaultRemoteRepositoriesService method checkRemoteConnectivity.

@Override
public ActionStatus checkRemoteConnectivity(String repositoryId) throws ArchivaRestServiceException {
    try {
        RemoteRepository remoteRepository = remoteRepositoryAdmin.getRemoteRepository(repositoryId);
        if (remoteRepository == null) {
            log.warn("Remote repository {} does not exist. Connectivity check returns false.", repositoryId);
            return ActionStatus.FAIL;
        }
        NetworkProxy networkProxy = null;
        if (StringUtils.isNotBlank(remoteRepository.getRemoteDownloadNetworkProxyId())) {
            networkProxy = proxyRegistry.getNetworkProxy(remoteRepository.getRemoteDownloadNetworkProxyId());
            if (networkProxy == null) {
                log.warn("A network proxy {} was configured for repository {}. But the proxy with the given id does not exist.", remoteRepository.getRemoteDownloadNetworkProxyId(), repositoryId);
            }
        }
        String wagonProtocol = new URL(remoteRepository.getUrl()).getProtocol();
        final Wagon wagon = wagonFactory.getWagon(// 
        new WagonFactoryRequest(wagonProtocol, remoteRepository.getExtraHeaders()).networkProxy(networkProxy));
        // hardcoded value as it's a check of the remote repo connectivity
        wagon.setReadTimeout(checkReadTimeout);
        wagon.setTimeout(checkTimeout);
        if (wagon instanceof AbstractHttpClientWagon) {
            HttpMethodConfiguration httpMethodConfiguration = // 
            new HttpMethodConfiguration().setUsePreemptive(// 
            true).setReadTimeout(checkReadTimeout);
            HttpConfiguration httpConfiguration = new HttpConfiguration().setGet(httpMethodConfiguration);
            AbstractHttpClientWagon.class.cast(wagon).setHttpConfiguration(httpConfiguration);
        }
        ProxyInfo proxyInfo = null;
        if (networkProxy != null) {
            proxyInfo = new ProxyInfo();
            proxyInfo.setType(networkProxy.getProtocol());
            proxyInfo.setHost(networkProxy.getHost());
            proxyInfo.setPort(networkProxy.getPort());
            proxyInfo.setUserName(networkProxy.getUsername());
            proxyInfo.setPassword(new String(networkProxy.getPassword()));
        }
        String url = StringUtils.stripEnd(remoteRepository.getUrl(), "/");
        wagon.connect(new Repository(remoteRepository.getId(), url), proxyInfo);
        // MRM-1933, there are certain servers that do not allow browsing
        if (!(StringUtils.isEmpty(remoteRepository.getCheckPath()) || "/".equals(remoteRepository.getCheckPath()))) {
            return new ActionStatus(wagon.resourceExists(remoteRepository.getCheckPath()));
        } else {
            // we only check connectivity as remote repo can be empty
            // MRM-1909: Wagon implementation appends a slash already
            wagon.getFileList("");
        }
        return ActionStatus.SUCCESS;
    } catch (TransferFailedException e) {
        log.info("TransferFailedException :{}", e.getMessage());
        return ActionStatus.FAIL;
    } catch (Exception e) {
        // This service returns either true or false, Exception cannot be handled by the clients
        log.debug("Exception occured on connectivity test.", e);
        log.info("Connection exception: {}", e.getMessage());
        return ActionStatus.FAIL;
    }
}
Also used : AbstractHttpClientWagon(org.apache.maven.wagon.shared.http.AbstractHttpClientWagon) HttpMethodConfiguration(org.apache.maven.wagon.shared.http.HttpMethodConfiguration) RemoteRepository(org.apache.archiva.admin.model.beans.RemoteRepository) AbstractHttpClientWagon(org.apache.maven.wagon.shared.http.AbstractHttpClientWagon) Wagon(org.apache.maven.wagon.Wagon) HttpConfiguration(org.apache.maven.wagon.shared.http.HttpConfiguration) NetworkProxy(org.apache.archiva.proxy.model.NetworkProxy) URL(java.net.URL) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) TransferFailedException(org.apache.maven.wagon.TransferFailedException) ActionStatus(org.apache.archiva.rest.api.model.ActionStatus) ProxyInfo(org.apache.maven.wagon.proxy.ProxyInfo) Repository(org.apache.maven.wagon.repository.Repository) RemoteRepository(org.apache.archiva.admin.model.beans.RemoteRepository) WagonFactoryRequest(org.apache.archiva.maven.common.proxy.WagonFactoryRequest) TransferFailedException(org.apache.maven.wagon.TransferFailedException)

Example 13 with Repository

use of org.apache.maven.wagon.repository.Repository in project archiva by apache.

the class DownloadSnapshotTest method downloadSNAPSHOT.

@Test
public void downloadSNAPSHOT() throws Exception {
    String id = Long.toString(System.currentTimeMillis());
    Path srcRep = getProjectDirectory().resolve("src/test/repositories/snapshot-repo");
    Path testRep = getBasedir().resolve("target").resolve("snapshot-repo-" + id).toAbsolutePath();
    FileUtils.copyDirectory(srcRep.toFile(), testRep.toFile());
    createdPaths.add(testRep);
    ManagedRepository managedRepository = new ManagedRepository(Locale.getDefault());
    managedRepository.setId(id);
    managedRepository.setName("name of " + id);
    managedRepository.setLocation(testRep.toString());
    managedRepository.setIndexDirectory(indexDir.resolve("index-" + id).toString());
    managedRepository.setPackedIndexDirectory(indexDir.resolve("indexpacked-" + id).toString());
    ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
    if (managedRepositoriesService.getManagedRepository(id) != null) {
        managedRepositoriesService.deleteManagedRepository(id, false);
    }
    getManagedRepositoriesService().addManagedRepository(managedRepository);
    RoleManagementService roleManagementService = getRoleManagementService(authorizationHeader);
    if (!roleManagementService.templatedRoleExists(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id)) {
        roleManagementService.createTemplatedRole(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id);
    }
    getUserService(authorizationHeader).createGuestUser();
    roleManagementService.assignRole(ArchivaRoleConstants.TEMPLATE_GUEST, "guest");
    roleManagementService.assignTemplatedRole(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id, "guest");
    getUserService(authorizationHeader).removeFromCache("guest");
    Path file = Paths.get("target/archiva-model-1.4-M4-SNAPSHOT.jar");
    Files.deleteIfExists(file);
    HttpWagon httpWagon = new HttpWagon();
    httpWagon.connect(new Repository("foo", "http://localhost:" + port));
    httpWagon.get("/repository/" + id + "/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-SNAPSHOT.jar", file.toFile());
    ZipFile zipFile = new ZipFile(file.toFile());
    List<String> entries = getZipEntriesNames(zipFile);
    ZipEntry zipEntry = zipFile.getEntry("org/apache/archiva/model/ArchivaArtifact.class");
    assertNotNull("cannot find zipEntry org/apache/archiva/model/ArchivaArtifact.class, entries: " + entries + ", content is: " + FileUtils.readFileToString(file.toFile(), Charset.forName("UTF-8")), zipEntry);
    zipFile.close();
    file.toFile().deleteOnExit();
}
Also used : Path(java.nio.file.Path) Repository(org.apache.maven.wagon.repository.Repository) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) ManagedRepositoriesService(org.apache.archiva.rest.api.services.ManagedRepositoriesService) HttpWagon(org.apache.maven.wagon.providers.http.HttpWagon) ZipFile(java.util.zip.ZipFile) RoleManagementService(org.apache.archiva.redback.rest.api.services.RoleManagementService) ZipEntry(java.util.zip.ZipEntry) Test(org.junit.Test)

Example 14 with Repository

use of org.apache.maven.wagon.repository.Repository in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryWagonTest method testAuthenticatedGet.

@Test
public void testAuthenticatedGet() throws Exception {
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse().setContent("test content")).build();
    ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
    wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
    wagon.setHttpTransportFactory(() -> transport);
    wagon.connect(new Repository("my-repo", REPO_URL));
    File f = FileTestUtils.createUniqueFile("my/artifact/dir", "test");
    wagon.get("my/resource", f);
    assertFileContains(f, "test content");
    String authHeader = transport.getLowLevelHttpRequest().getFirstHeaderValue("Authorization");
    Assert.assertEquals("Bearer test-access-token", authHeader);
    Assert.assertEquals("https://maven.pkg.dev/my-project/my-repo/my/resource", transport.getLowLevelHttpRequest().getUrl());
}
Also used : Repository(org.apache.maven.wagon.repository.Repository) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) AccessToken(com.google.auth.oauth2.AccessToken) File(java.io.File) Test(org.junit.Test)

Example 15 with Repository

use of org.apache.maven.wagon.repository.Repository in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryWagonTest method testPutPermissionDenied.

@Test
public void testPutPermissionDenied() throws Exception {
    MockHttpTransport transport = failingTransportWithStatus(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
    ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
    wagon.setCredentialProvider(new FailingCredentialProvider(new IOException("failed to get access token")));
    wagon.setHttpTransportFactory(() -> transport);
    wagon.connect(new Repository("my-repo", REPO_URL));
    File f = FileTestUtils.createUniqueFile("my/artifact/dir", "test");
    Files.asCharSink(f, Charset.defaultCharset()).write("test content");
    expectedException.expect(AuthorizationException.class);
    expectedException.expectMessage(CoreMatchers.containsString("Permission denied on remote repository (or it may not exist)"));
    expectedException.expectMessage(CoreMatchers.containsString("The request had no credentials"));
    wagon.put(f, "my/resource");
}
Also used : Repository(org.apache.maven.wagon.repository.Repository) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) IOException(java.io.IOException) File(java.io.File) Test(org.junit.Test)

Aggregations

Repository (org.apache.maven.wagon.repository.Repository)30 Test (org.junit.Test)13 IOException (java.io.IOException)11 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)9 File (java.io.File)9 ProxyInfo (org.apache.maven.wagon.proxy.ProxyInfo)7 Path (java.nio.file.Path)6 ArtifactRepository (org.apache.maven.artifact.repository.ArtifactRepository)6 Wagon (org.apache.maven.wagon.Wagon)6 AuthenticationException (org.apache.maven.wagon.authentication.AuthenticationException)6 TransferFailedException (org.apache.maven.wagon.TransferFailedException)5 AuthenticationInfo (org.apache.maven.wagon.authentication.AuthenticationInfo)5 AccessToken (com.google.auth.oauth2.AccessToken)4 ZipEntry (java.util.zip.ZipEntry)4 ZipFile (java.util.zip.ZipFile)4 RoleManagementService (org.apache.archiva.redback.rest.api.services.RoleManagementService)4 RemoteRepository (org.apache.archiva.repository.RemoteRepository)4 ConnectionException (org.apache.maven.wagon.ConnectionException)4 AuthorizationException (org.apache.maven.wagon.authorization.AuthorizationException)4 HttpWagon (org.apache.maven.wagon.providers.http.HttpWagon)4