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;
}
}
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;
}
}
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();
}
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());
}
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");
}
Aggregations