Search in sources :

Example 1 with RemoteRepository

use of org.apache.archiva.repository.RemoteRepository in project archiva by apache.

the class Maven2RepositoryStorage method readProjectVersionMetadata.

@Override
public ProjectVersionMetadata readProjectVersionMetadata(ReadMetadataRequest readMetadataRequest) throws RepositoryStorageMetadataNotFoundException, RepositoryStorageMetadataInvalidException, RepositoryStorageRuntimeException {
    try {
        ManagedRepository managedRepository = repositoryRegistry.getManagedRepository(readMetadataRequest.getRepositoryId());
        boolean isReleases = managedRepository.getActiveReleaseSchemes().contains(ReleaseScheme.RELEASE);
        boolean isSnapshots = managedRepository.getActiveReleaseSchemes().contains(ReleaseScheme.SNAPSHOT);
        String artifactVersion = readMetadataRequest.getProjectVersion();
        // olamy: in case of browsing via the ui we can mix repos (parent of a SNAPSHOT can come from release repo)
        if (!readMetadataRequest.isBrowsingRequest()) {
            if (VersionUtil.isSnapshot(artifactVersion)) {
                // skygo trying to improve speed by honoring managed configuration MRM-1658
                if (isReleases && !isSnapshots) {
                    throw new RepositoryStorageRuntimeException("lookforsnaponreleaseonly", "managed repo is configured for release only");
                }
            } else {
                if (!isReleases && isSnapshots) {
                    throw new RepositoryStorageRuntimeException("lookforsreleaseonsneponly", "managed repo is configured for snapshot only");
                }
            }
        }
        Path basedir = Paths.get(managedRepository.getLocation());
        if (VersionUtil.isSnapshot(artifactVersion)) {
            Path metadataFile = pathTranslator.toFile(basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), artifactVersion, METADATA_FILENAME);
            try {
                ArchivaRepositoryMetadata metadata = MavenMetadataReader.read(metadataFile);
                // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename
                SnapshotVersion snapshotVersion = metadata.getSnapshotVersion();
                if (snapshotVersion != null) {
                    artifactVersion = // remove SNAPSHOT from end
                    artifactVersion.substring(0, artifactVersion.length() - 8);
                    artifactVersion = artifactVersion + snapshotVersion.getTimestamp() + "-" + snapshotVersion.getBuildNumber();
                }
            } catch (XMLException e) {
                // unable to parse metadata - LOGGER it, and continue with the version as the original SNAPSHOT version
                LOGGER.warn("Invalid metadata: {} - {}", metadataFile, e.getMessage());
            }
        }
        // TODO: won't work well with some other layouts, might need to convert artifact parts to ID by path translator
        String id = readMetadataRequest.getProjectId() + "-" + artifactVersion + ".pom";
        Path file = pathTranslator.toFile(basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(), id);
        if (!Files.exists(file)) {
            // metadata could not be resolved
            throw new RepositoryStorageMetadataNotFoundException("The artifact's POM file '" + file.toAbsolutePath() + "' was missing");
        }
        // TODO: this is a workaround until we can properly resolve using proxies as well - this doesn't cache
        // anything locally!
        List<RemoteRepository> remoteRepositories = new ArrayList<>();
        Map<String, NetworkProxy> networkProxies = new HashMap<>();
        Map<String, List<ProxyConnector>> proxyConnectorsMap = proxyConnectorAdmin.getProxyConnectorAsMap();
        List<ProxyConnector> proxyConnectors = proxyConnectorsMap.get(readMetadataRequest.getRepositoryId());
        if (proxyConnectors != null) {
            for (ProxyConnector proxyConnector : proxyConnectors) {
                RemoteRepository remoteRepoConfig = repositoryRegistry.getRemoteRepository(proxyConnector.getTargetRepoId());
                if (remoteRepoConfig != null) {
                    remoteRepositories.add(remoteRepoConfig);
                    NetworkProxy networkProxyConfig = networkProxyAdmin.getNetworkProxy(proxyConnector.getProxyId());
                    if (networkProxyConfig != null) {
                        // key/value: remote repo ID/proxy info
                        networkProxies.put(proxyConnector.getTargetRepoId(), networkProxyConfig);
                    }
                }
            }
        }
        // can have released parent pom
        if (readMetadataRequest.isBrowsingRequest()) {
            remoteRepositories.addAll(repositoryRegistry.getRemoteRepositories());
        }
        ModelBuildingRequest req = new DefaultModelBuildingRequest().setProcessPlugins(false).setPomFile(file.toFile()).setTwoPhaseBuilding(false).setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
        // MRM-1607. olamy this will resolve jdk profiles on the current running archiva jvm
        req.setSystemProperties(System.getProperties());
        // MRM-1411
        req.setModelResolver(new RepositoryModelResolver(managedRepository, pathTranslator, wagonFactory, remoteRepositories, networkProxies, managedRepository));
        Model model;
        try {
            model = builder.build(req).getEffectiveModel();
        } catch (ModelBuildingException e) {
            String msg = "The artifact's POM file '" + file + "' was invalid: " + e.getMessage();
            List<ModelProblem> modelProblems = e.getProblems();
            for (ModelProblem problem : modelProblems) {
                // but setTwoPhaseBuilding(true) fix that
                if (((problem.getException() instanceof FileNotFoundException || problem.getException() instanceof NoSuchFileException) && e.getModelId() != null && !e.getModelId().equals(problem.getModelId()))) {
                    LOGGER.warn("The artifact's parent POM file '{}' cannot be resolved. " + "Using defaults for project version metadata..", file);
                    ProjectVersionMetadata metadata = new ProjectVersionMetadata();
                    metadata.setId(readMetadataRequest.getProjectVersion());
                    MavenProjectFacet facet = new MavenProjectFacet();
                    facet.setGroupId(readMetadataRequest.getNamespace());
                    facet.setArtifactId(readMetadataRequest.getProjectId());
                    facet.setPackaging("jar");
                    metadata.addFacet(facet);
                    String errMsg = "Error in resolving artifact's parent POM file. " + (problem.getException() == null ? problem.getMessage() : problem.getException().getMessage());
                    RepositoryProblemFacet repoProblemFacet = new RepositoryProblemFacet();
                    repoProblemFacet.setRepositoryId(readMetadataRequest.getRepositoryId());
                    repoProblemFacet.setId(readMetadataRequest.getRepositoryId());
                    repoProblemFacet.setMessage(errMsg);
                    repoProblemFacet.setProblem(errMsg);
                    repoProblemFacet.setProject(readMetadataRequest.getProjectId());
                    repoProblemFacet.setVersion(readMetadataRequest.getProjectVersion());
                    repoProblemFacet.setNamespace(readMetadataRequest.getNamespace());
                    metadata.addFacet(repoProblemFacet);
                    return metadata;
                }
            }
            throw new RepositoryStorageMetadataInvalidException("invalid-pom", msg, e);
        }
        // Check if the POM is in the correct location
        boolean correctGroupId = readMetadataRequest.getNamespace().equals(model.getGroupId());
        boolean correctArtifactId = readMetadataRequest.getProjectId().equals(model.getArtifactId());
        boolean correctVersion = readMetadataRequest.getProjectVersion().equals(model.getVersion());
        if (!correctGroupId || !correctArtifactId || !correctVersion) {
            StringBuilder message = new StringBuilder("Incorrect POM coordinates in '" + file + "':");
            if (!correctGroupId) {
                message.append("\nIncorrect group ID: ").append(model.getGroupId());
            }
            if (!correctArtifactId) {
                message.append("\nIncorrect artifact ID: ").append(model.getArtifactId());
            }
            if (!correctVersion) {
                message.append("\nIncorrect version: ").append(model.getVersion());
            }
            throw new RepositoryStorageMetadataInvalidException("mislocated-pom", message.toString());
        }
        ProjectVersionMetadata metadata = new ProjectVersionMetadata();
        metadata.setCiManagement(convertCiManagement(model.getCiManagement()));
        metadata.setDescription(model.getDescription());
        metadata.setId(readMetadataRequest.getProjectVersion());
        metadata.setIssueManagement(convertIssueManagement(model.getIssueManagement()));
        metadata.setLicenses(convertLicenses(model.getLicenses()));
        metadata.setMailingLists(convertMailingLists(model.getMailingLists()));
        metadata.setDependencies(convertDependencies(model.getDependencies()));
        metadata.setName(model.getName());
        metadata.setOrganization(convertOrganization(model.getOrganization()));
        metadata.setScm(convertScm(model.getScm()));
        metadata.setUrl(model.getUrl());
        metadata.setProperties(model.getProperties());
        MavenProjectFacet facet = new MavenProjectFacet();
        facet.setGroupId(model.getGroupId() != null ? model.getGroupId() : model.getParent().getGroupId());
        facet.setArtifactId(model.getArtifactId());
        facet.setPackaging(model.getPackaging());
        if (model.getParent() != null) {
            MavenProjectParent parent = new MavenProjectParent();
            parent.setGroupId(model.getParent().getGroupId());
            parent.setArtifactId(model.getParent().getArtifactId());
            parent.setVersion(model.getParent().getVersion());
            facet.setParent(parent);
        }
        metadata.addFacet(facet);
        return metadata;
    } catch (RepositoryAdminException e) {
        throw new RepositoryStorageRuntimeException("repo-admin", e.getMessage(), e);
    }
}
Also used : ModelBuildingRequest(org.apache.maven.model.building.ModelBuildingRequest) DefaultModelBuildingRequest(org.apache.maven.model.building.DefaultModelBuildingRequest) RepositoryStorageRuntimeException(org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException) ManagedRepository(org.apache.archiva.repository.ManagedRepository) HashMap(java.util.HashMap) ProjectVersionMetadata(org.apache.archiva.metadata.model.ProjectVersionMetadata) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) RemoteRepository(org.apache.archiva.repository.RemoteRepository) NetworkProxy(org.apache.archiva.admin.model.beans.NetworkProxy) RepositoryStorageMetadataInvalidException(org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException) RepositoryStorageMetadataNotFoundException(org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException) SnapshotVersion(org.apache.archiva.model.SnapshotVersion) ModelBuildingException(org.apache.maven.model.building.ModelBuildingException) List(java.util.List) ArrayList(java.util.ArrayList) MailingList(org.apache.maven.model.MailingList) ModelProblem(org.apache.maven.model.building.ModelProblem) ProxyConnector(org.apache.archiva.admin.model.beans.ProxyConnector) Path(java.nio.file.Path) RepositoryProblemFacet(org.apache.archiva.metadata.model.facets.RepositoryProblemFacet) DefaultModelBuildingRequest(org.apache.maven.model.building.DefaultModelBuildingRequest) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) XMLException(org.apache.archiva.xml.XMLException) Model(org.apache.maven.model.Model) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata)

Example 2 with RemoteRepository

use of org.apache.archiva.repository.RemoteRepository in project archiva by apache.

the class RepositoryModelResolver method connectToRepository.

/**
 * Using wagon, connect to the remote repository.
 *
 * @param wagon the wagon instance to establish the connection on.
 * @return true if the connection was successful. false if not connected.
 */
private boolean connectToRepository(Wagon wagon, RemoteRepository remoteRepository) {
    boolean connected;
    final NetworkProxy proxyConnector = this.networkProxyMap.get(remoteRepository.getId());
    ProxyInfo networkProxy = null;
    if (proxyConnector != null) {
        networkProxy = new ProxyInfo();
        networkProxy.setType(proxyConnector.getProtocol());
        networkProxy.setHost(proxyConnector.getHost());
        networkProxy.setPort(proxyConnector.getPort());
        networkProxy.setUserName(proxyConnector.getUsername());
        networkProxy.setPassword(proxyConnector.getPassword());
        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;
    RepositoryCredentials creds = remoteRepository.getLoginCredentials();
    String username = "";
    String password = "";
    if (creds instanceof UsernamePasswordCredentials) {
        UsernamePasswordCredentials c = (UsernamePasswordCredentials) creds;
        username = c.getUserName();
        password = c.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);
    }
    int timeoutInMilliseconds = ((int) remoteRepository.getTimeout().getSeconds()) * 1000;
    // FIXME olamy having 2 config values
    // Set timeout
    wagon.setReadTimeout(timeoutInMilliseconds);
    wagon.setTimeout(timeoutInMilliseconds);
    try {
        org.apache.maven.wagon.repository.Repository wagonRepository = new org.apache.maven.wagon.repository.Repository(remoteRepository.getId(), remoteRepository.getLocation().toString());
        if (networkProxy != null) {
            wagon.connect(wagonRepository, authInfo, networkProxy);
        } else {
            wagon.connect(wagonRepository, authInfo);
        }
        connected = true;
    } catch (ConnectionException | AuthenticationException e) {
        log.error("Could not connect to {}:{} ", remoteRepository.getName(), e.getMessage());
        connected = false;
    }
    return connected;
}
Also used : RepositoryCredentials(org.apache.archiva.repository.RepositoryCredentials) AuthenticationException(org.apache.maven.wagon.authentication.AuthenticationException) NetworkProxy(org.apache.archiva.admin.model.beans.NetworkProxy) AuthenticationInfo(org.apache.maven.wagon.authentication.AuthenticationInfo) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) ProxyInfo(org.apache.maven.wagon.proxy.ProxyInfo) Repository(org.apache.maven.model.Repository) RemoteRepository(org.apache.archiva.repository.RemoteRepository) ManagedRepository(org.apache.archiva.repository.ManagedRepository) ConnectionException(org.apache.maven.wagon.ConnectionException)

Example 3 with RemoteRepository

use of org.apache.archiva.repository.RemoteRepository in project archiva by apache.

the class DefaultRepositoryProxyConnectors 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.
 */
private boolean connectToRepository(ProxyConnector connector, Wagon wagon, RemoteRepositoryContent remoteRepository) {
    boolean connected = false;
    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.getURL();
            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.getRepository().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.getURL());
        authInfo = new AuthenticationInfo();
        authInfo.setUserName(username);
        authInfo.setPassword(password);
    }
    // Convert seconds to milliseconds
    long timeoutInMilliseconds = remoteRepository.getRepository().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.getURL().toString());
        wagon.connect(wagonRepository, authInfo, networkProxy);
        connected = true;
    } catch (ConnectionException | AuthenticationException e) {
        log.warn("Could not connect to {}: {}", remoteRepository.getRepository().getName(), e.getMessage());
        connected = false;
    }
    return connected;
}
Also used : ProxyInfo(org.apache.maven.wagon.proxy.ProxyInfo) RepositoryCredentials(org.apache.archiva.repository.RepositoryCredentials) PasswordCredentials(org.apache.archiva.repository.PasswordCredentials) Repository(org.apache.maven.wagon.repository.Repository) ManagedRepository(org.apache.archiva.repository.ManagedRepository) RemoteRepository(org.apache.archiva.repository.RemoteRepository) AuthenticationException(org.apache.maven.wagon.authentication.AuthenticationException) AuthenticationInfo(org.apache.maven.wagon.authentication.AuthenticationInfo) ConnectionException(org.apache.maven.wagon.ConnectionException)

Example 4 with RemoteRepository

use of org.apache.archiva.repository.RemoteRepository in project archiva by apache.

the class DefaultRemoteRepositoryAdmin method convertRepo.

/*
 * Conversion between the repository from the registry and the serialized DTO for the admin API
 */
private org.apache.archiva.admin.model.beans.RemoteRepository convertRepo(RemoteRepository repo) {
    if (repo == null) {
        return null;
    }
    org.apache.archiva.admin.model.beans.RemoteRepository adminRepo = new org.apache.archiva.admin.model.beans.RemoteRepository(getArchivaConfiguration().getDefaultLocale());
    setBaseRepoAttributes(adminRepo, repo);
    adminRepo.setUrl(convertUriToString(repo.getLocation()));
    adminRepo.setCronExpression(repo.getSchedulingDefinition());
    adminRepo.setCheckPath(repo.getCheckPath());
    adminRepo.setExtraHeaders(repo.getExtraHeaders());
    adminRepo.setExtraParameters(repo.getExtraParameters());
    adminRepo.setTimeout((int) repo.getTimeout().getSeconds());
    RepositoryCredentials creds = repo.getLoginCredentials();
    if (creds != null && creds instanceof PasswordCredentials) {
        PasswordCredentials pCreds = (PasswordCredentials) creds;
        adminRepo.setUserName(pCreds.getUsername());
        adminRepo.setPassword(new String(pCreds.getPassword() != null ? pCreds.getPassword() : new char[0]));
    }
    if (repo.supportsFeature(RemoteIndexFeature.class)) {
        RemoteIndexFeature rif = repo.getFeature(RemoteIndexFeature.class).get();
        adminRepo.setRemoteIndexUrl(convertUriToString(rif.getIndexUri()));
        adminRepo.setDownloadRemoteIndex(rif.isDownloadRemoteIndex());
        adminRepo.setRemoteDownloadNetworkProxyId(rif.getProxyId());
        adminRepo.setDownloadRemoteIndexOnStartup(rif.isDownloadRemoteIndexOnStartup());
        adminRepo.setRemoteDownloadTimeout((int) rif.getDownloadTimeout().getSeconds());
    }
    if (repo.supportsFeature(IndexCreationFeature.class)) {
        IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
        adminRepo.setIndexDirectory(PathUtil.getPathFromUri(icf.getIndexPath()).toString());
    }
    adminRepo.setDescription(repo.getDescription());
    return adminRepo;
}
Also used : RepositoryCredentials(org.apache.archiva.repository.RepositoryCredentials) PasswordCredentials(org.apache.archiva.repository.PasswordCredentials) RemoteRepository(org.apache.archiva.repository.RemoteRepository) IndexCreationFeature(org.apache.archiva.repository.features.IndexCreationFeature) RemoteIndexFeature(org.apache.archiva.repository.features.RemoteIndexFeature)

Example 5 with RemoteRepository

use of org.apache.archiva.repository.RemoteRepository in project archiva by apache.

the class ArchivaIndexManagerMock method createContext.

@Override
public ArchivaIndexingContext createContext(Repository repository) throws IndexCreationFailedException {
    log.debug("Creating context for repo {}, type: {}", repository.getId(), repository.getType());
    if (repository.getType() != RepositoryType.MAVEN) {
        throw new UnsupportedRepositoryTypeException(repository.getType());
    }
    IndexingContext mvnCtx = null;
    try {
        if (repository instanceof RemoteRepository) {
            mvnCtx = createRemoteContext((RemoteRepository) repository);
        } else if (repository instanceof ManagedRepository) {
            mvnCtx = createManagedContext((ManagedRepository) repository);
        }
    } catch (IOException e) {
        log.error("IOException during context creation " + e.getMessage(), e);
        throw new IndexCreationFailedException("Could not create index context for repository " + repository.getId() + (StringUtils.isNotEmpty(e.getMessage()) ? ": " + e.getMessage() : ""), e);
    }
    MavenIndexContextMock context = new MavenIndexContextMock(repository, mvnCtx);
    return context;
}
Also used : ManagedRepository(org.apache.archiva.repository.ManagedRepository) IndexCreationFailedException(org.apache.archiva.indexer.IndexCreationFailedException) ArchivaIndexingContext(org.apache.archiva.indexer.ArchivaIndexingContext) IndexingContext(org.apache.maven.index.context.IndexingContext) RemoteRepository(org.apache.archiva.repository.RemoteRepository) IOException(java.io.IOException) UnsupportedRepositoryTypeException(org.apache.archiva.repository.UnsupportedRepositoryTypeException)

Aggregations

RemoteRepository (org.apache.archiva.repository.RemoteRepository)18 IOException (java.io.IOException)8 RepositoryAdminException (org.apache.archiva.admin.model.RepositoryAdminException)7 ManagedRepository (org.apache.archiva.repository.ManagedRepository)7 PasswordCredentials (org.apache.archiva.repository.PasswordCredentials)7 RemoteIndexFeature (org.apache.archiva.repository.features.RemoteIndexFeature)7 ProxyInfo (org.apache.maven.wagon.proxy.ProxyInfo)7 Path (java.nio.file.Path)6 NetworkProxy (org.apache.archiva.admin.model.beans.NetworkProxy)6 ConnectionException (org.apache.maven.wagon.ConnectionException)6 AuthenticationException (org.apache.maven.wagon.authentication.AuthenticationException)6 AuthenticationInfo (org.apache.maven.wagon.authentication.AuthenticationInfo)6 IndexingContext (org.apache.maven.index.context.IndexingContext)5 WagonFactoryException (org.apache.archiva.proxy.common.WagonFactoryException)4 WagonFactoryRequest (org.apache.archiva.proxy.common.WagonFactoryRequest)4 IndexUpdateRequest (org.apache.maven.index.updater.IndexUpdateRequest)4 ResourceFetcher (org.apache.maven.index.updater.ResourceFetcher)4 MalformedURLException (java.net.MalformedURLException)3 URI (java.net.URI)3 Configuration (org.apache.archiva.configuration.Configuration)3