Search in sources :

Example 11 with RepositoryException

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

the class DefaultBrowseService method artifactAvailable.

@Override
public Boolean artifactAvailable(String groupId, String artifactId, String version, String classifier, String repositoryId) throws ArchivaRestServiceException {
    List<String> selectedRepos = getSelectedRepos(repositoryId);
    boolean snapshot = VersionUtil.isSnapshot(version);
    try {
        for (String repoId : selectedRepos) {
            ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository(repoId);
            if ((snapshot && !managedRepository.isSnapshots()) || (!snapshot && managedRepository.isSnapshots())) {
                continue;
            }
            ManagedRepositoryContent managedRepositoryContent = getManagedRepositoryContent(repoId);
            // FIXME default to jar which can be wrong for war zip etc....
            ArchivaArtifact archivaArtifact = new ArchivaArtifact(groupId, artifactId, version, StringUtils.isEmpty(classifier) ? "" : classifier, "jar", repoId);
            Path file = managedRepositoryContent.toFile(archivaArtifact);
            if (file != null && Files.exists(file)) {
                return true;
            }
            // in case of SNAPSHOT we can have timestamped version locally !
            if (StringUtils.endsWith(version, VersionUtil.SNAPSHOT)) {
                Path metadataFile = file.getParent().resolve(MetadataTools.MAVEN_METADATA);
                if (Files.exists(metadataFile)) {
                    try {
                        ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read(metadataFile);
                        int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
                        String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
                        // rebuild file name with timestamped version and build number
                        String timeStampFileName = // 
                        new StringBuilder(artifactId).append('-').append(// 
                        StringUtils.remove(version, "-" + VersionUtil.SNAPSHOT)).append('-').append(// 
                        timeStamp).append('-').append(// 
                        Integer.toString(buildNumber)).append(// 
                        (StringUtils.isEmpty(classifier) ? "" : "-" + classifier)).append(".jar").toString();
                        Path timeStampFile = file.getParent().resolve(timeStampFileName);
                        log.debug("try to find timestamped snapshot version file: {}", timeStampFile.toAbsolutePath());
                        if (Files.exists(timeStampFile)) {
                            return true;
                        }
                    } catch (XMLException e) {
                        log.warn("skip fail to find timestamped snapshot file: {}", e.getMessage());
                    }
                }
            }
            String path = managedRepositoryContent.toPath(archivaArtifact);
            file = connectors.fetchFromProxies(managedRepositoryContent, path);
            if (file != null && Files.exists(file)) {
                // download pom now
                String pomPath = StringUtils.substringBeforeLast(path, ".jar") + ".pom";
                connectors.fetchFromProxies(managedRepositoryContent, pomPath);
                return true;
            }
        }
    } catch (RepositoryAdminException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
    return false;
}
Also used : Path(java.nio.file.Path) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) RepositoryException(org.apache.archiva.repository.RepositoryException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) ArchivaArtifact(org.apache.archiva.model.ArchivaArtifact) XMLException(org.apache.archiva.xml.XMLException) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata)

Example 12 with RepositoryException

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

the class AbstractRestService method buildArtifacts.

protected List<Artifact> buildArtifacts(Collection<ArtifactMetadata> artifactMetadatas, String repositoryId) throws ArchivaRestServiceException {
    try {
        if (artifactMetadatas != null && !artifactMetadatas.isEmpty()) {
            List<Artifact> artifacts = new ArrayList<>(artifactMetadatas.size());
            for (ArtifactMetadata artifact : artifactMetadatas) {
                String repoId = repositoryId != null ? repositoryId : artifact.getRepositoryId();
                if (repoId == null) {
                    throw new IllegalStateException("Repository Id is null");
                }
                ManagedRepository repo = repositoryRegistry.getManagedRepository(repoId);
                if (repo == null) {
                    throw new RepositoryException("Repository not found " + repoId);
                }
                ManagedRepositoryContent content = repo.getContent();
                ArtifactBuilder builder = new ArtifactBuilder().forArtifactMetadata(artifact).withManagedRepositoryContent(content);
                Artifact art = builder.build();
                art.setUrl(getArtifactUrl(art, repositoryId));
                artifacts.add(art);
            }
            return artifacts;
        }
        return Collections.emptyList();
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
}
Also used : ManagedRepository(org.apache.archiva.repository.ManagedRepository) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ArrayList(java.util.ArrayList) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) RepositoryException(org.apache.archiva.repository.RepositoryException) ArtifactMetadata(org.apache.archiva.metadata.model.ArtifactMetadata) ArtifactBuilder(org.apache.archiva.rest.services.utils.ArtifactBuilder) Artifact(org.apache.archiva.maven2.model.Artifact)

Example 13 with RepositoryException

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

the class DownloadRemoteIndexTask method run.

@Override
public void run() {
    // so short lock : not sure we need it
    synchronized (this.runningRemoteDownloadIds) {
        if (this.runningRemoteDownloadIds.contains(this.remoteRepository.getId())) {
            // skip it as it's running
            log.info("skip download index remote for repo {} it's already running", this.remoteRepository.getId());
            return;
        }
        this.runningRemoteDownloadIds.add(this.remoteRepository.getId());
    }
    Path tempIndexDirectory = null;
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    try {
        log.info("start download remote index for remote repository {}", this.remoteRepository.getId());
        if (this.remoteRepository.getIndexingContext() == null) {
            throw new IndexNotFoundException("No index context set for repository " + remoteRepository.getId());
        }
        if (this.remoteRepository.getType() != RepositoryType.MAVEN) {
            throw new RepositoryException("Bad repository type");
        }
        if (!this.remoteRepository.supportsFeature(RemoteIndexFeature.class)) {
            throw new RepositoryException("Repository does not support RemotIndexFeature " + remoteRepository.getId());
        }
        RemoteIndexFeature rif = this.remoteRepository.getFeature(RemoteIndexFeature.class).get();
        IndexingContext indexingContext = this.remoteRepository.getIndexingContext().getBaseContext(IndexingContext.class);
        // create a temp directory to download files
        tempIndexDirectory = Paths.get(indexingContext.getIndexDirectoryFile().getParent(), ".tmpIndex");
        Path indexCacheDirectory = Paths.get(indexingContext.getIndexDirectoryFile().getParent(), ".indexCache");
        Files.createDirectories(indexCacheDirectory);
        if (Files.exists(tempIndexDirectory)) {
            org.apache.archiva.common.utils.FileUtils.deleteDirectory(tempIndexDirectory);
        }
        Files.createDirectories(tempIndexDirectory);
        tempIndexDirectory.toFile().deleteOnExit();
        String baseIndexUrl = indexingContext.getIndexUpdateUrl();
        String wagonProtocol = this.remoteRepository.getLocation().getScheme();
        final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(new WagonFactoryRequest(wagonProtocol, this.remoteRepository.getExtraHeaders()).networkProxy(this.networkProxy));
        // FIXME olamy having 2 config values
        wagon.setReadTimeout((int) rif.getDownloadTimeout().toMillis());
        wagon.setTimeout((int) remoteRepository.getTimeout().toMillis());
        if (wagon instanceof AbstractHttpClientWagon) {
            HttpConfiguration httpConfiguration = new HttpConfiguration();
            HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration();
            httpMethodConfiguration.setUsePreemptive(true);
            httpMethodConfiguration.setReadTimeout((int) rif.getDownloadTimeout().toMillis());
            httpConfiguration.setGet(httpMethodConfiguration);
            AbstractHttpClientWagon.class.cast(wagon).setHttpConfiguration(httpConfiguration);
        }
        wagon.addTransferListener(new DownloadListener());
        ProxyInfo proxyInfo = null;
        if (this.networkProxy != null) {
            proxyInfo = new ProxyInfo();
            proxyInfo.setType(this.networkProxy.getProtocol());
            proxyInfo.setHost(this.networkProxy.getHost());
            proxyInfo.setPort(this.networkProxy.getPort());
            proxyInfo.setUserName(this.networkProxy.getUsername());
            proxyInfo.setPassword(this.networkProxy.getPassword());
        }
        AuthenticationInfo authenticationInfo = null;
        if (this.remoteRepository.getLoginCredentials() != null && this.remoteRepository.getLoginCredentials() instanceof PasswordCredentials) {
            PasswordCredentials creds = (PasswordCredentials) this.remoteRepository.getLoginCredentials();
            authenticationInfo = new AuthenticationInfo();
            authenticationInfo.setUserName(creds.getUsername());
            authenticationInfo.setPassword(new String(creds.getPassword()));
        }
        log.debug("Connection to {}, authInfo={}", this.remoteRepository.getId(), authenticationInfo);
        wagon.connect(new Repository(this.remoteRepository.getId(), baseIndexUrl), authenticationInfo, proxyInfo);
        Path indexDirectory = indexingContext.getIndexDirectoryFile().toPath();
        if (!Files.exists(indexDirectory)) {
            Files.createDirectories(indexDirectory);
        }
        log.debug("Downloading index file to {}", indexDirectory);
        log.debug("Index cache dir {}", indexCacheDirectory);
        ResourceFetcher resourceFetcher = new WagonResourceFetcher(log, tempIndexDirectory, wagon, remoteRepository);
        IndexUpdateRequest request = new IndexUpdateRequest(indexingContext, resourceFetcher);
        request.setForceFullUpdate(this.fullDownload);
        request.setLocalIndexCacheDir(indexCacheDirectory.toFile());
        IndexUpdateResult result = this.indexUpdater.fetchAndUpdateIndex(request);
        log.debug("Update result success: {}", result.isSuccessful());
        stopWatch.stop();
        log.info("time update index from remote for repository {}: {}ms", this.remoteRepository.getId(), (stopWatch.getTime()));
        // index packing optionnal ??
        // IndexPackingRequest indexPackingRequest =
        // new IndexPackingRequest( indexingContext, indexingContext.getIndexDirectoryFile() );
        // indexPacker.packIndex( indexPackingRequest );
        indexingContext.updateTimestamp(true);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        deleteDirectoryQuiet(tempIndexDirectory);
        this.runningRemoteDownloadIds.remove(this.remoteRepository.getId());
    }
    log.info("end download remote index for remote repository {}", this.remoteRepository.getId());
}
Also used : Path(java.nio.file.Path) AbstractHttpClientWagon(org.apache.maven.wagon.shared.http.AbstractHttpClientWagon) PasswordCredentials(org.apache.archiva.repository.PasswordCredentials) HttpMethodConfiguration(org.apache.maven.wagon.shared.http.HttpMethodConfiguration) ResourceFetcher(org.apache.maven.index.updater.ResourceFetcher) IndexUpdateRequest(org.apache.maven.index.updater.IndexUpdateRequest) RepositoryException(org.apache.archiva.repository.RepositoryException) HttpConfiguration(org.apache.maven.wagon.shared.http.HttpConfiguration) StreamWagon(org.apache.maven.wagon.StreamWagon) AuthenticationInfo(org.apache.maven.wagon.authentication.AuthenticationInfo) TransferFailedException(org.apache.maven.wagon.TransferFailedException) IndexNotFoundException(org.apache.maven.index_shaded.lucene.index.IndexNotFoundException) RepositoryException(org.apache.archiva.repository.RepositoryException) AuthorizationException(org.apache.maven.wagon.authorization.AuthorizationException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ResourceDoesNotExistException(org.apache.maven.wagon.ResourceDoesNotExistException) StopWatch(org.apache.commons.lang.time.StopWatch) IndexUpdateResult(org.apache.maven.index.updater.IndexUpdateResult) ProxyInfo(org.apache.maven.wagon.proxy.ProxyInfo) Repository(org.apache.maven.wagon.repository.Repository) RemoteRepository(org.apache.archiva.repository.RemoteRepository) WagonFactoryRequest(org.apache.archiva.proxy.common.WagonFactoryRequest) IndexNotFoundException(org.apache.maven.index_shaded.lucene.index.IndexNotFoundException) RemoteIndexFeature(org.apache.archiva.repository.features.RemoteIndexFeature) IndexingContext(org.apache.maven.index.context.IndexingContext)

Example 14 with RepositoryException

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

the class RepositoryProviderMock method updateManagedInstance.

@Override
public void updateManagedInstance(EditableManagedRepository managedRepository, ManagedRepositoryConfiguration configuration) throws RepositoryException {
    try {
        managedRepository.setName(managedRepository.getPrimaryLocale(), configuration.getName());
        managedRepository.setLocation(new URI(configuration.getLocation() == null ? "" : configuration.getLocation()));
        managedRepository.setBaseUri(new URI(""));
        managedRepository.setBlocksRedeployment(configuration.isBlockRedeployments());
        managedRepository.setDescription(managedRepository.getPrimaryLocale(), configuration.getDescription());
        managedRepository.setLayout(configuration.getLayout());
        managedRepository.setScanned(configuration.isScanned());
        managedRepository.setSchedulingDefinition(configuration.getRefreshCronExpression());
        if (configuration.isReleases()) {
            managedRepository.addActiveReleaseScheme(ReleaseScheme.RELEASE);
        }
        if (configuration.isSnapshots()) {
            managedRepository.addActiveReleaseScheme(ReleaseScheme.SNAPSHOT);
        }
        ArtifactCleanupFeature acf = managedRepository.getFeature(ArtifactCleanupFeature.class).get();
        acf.setRetentionPeriod(Period.ofDays(configuration.getRetentionPeriod()));
        acf.setDeleteReleasedSnapshots(configuration.isDeleteReleasedSnapshots());
        acf.setRetentionCount(configuration.getRetentionCount());
        IndexCreationFeature icf = managedRepository.getFeature(IndexCreationFeature.class).get();
        icf.setIndexPath(new URI(configuration.getIndexDir()));
        icf.setSkipPackedIndexCreation(configuration.isSkipPackedIndexCreation());
        StagingRepositoryFeature srf = managedRepository.getFeature(StagingRepositoryFeature.class).get();
        srf.setStageRepoNeeded(configuration.isStageRepoNeeded());
    } catch (Exception e) {
        throw new RepositoryException("Error", e);
    }
}
Also used : IndexCreationFeature(org.apache.archiva.repository.features.IndexCreationFeature) RepositoryException(org.apache.archiva.repository.RepositoryException) ArtifactCleanupFeature(org.apache.archiva.repository.features.ArtifactCleanupFeature) StagingRepositoryFeature(org.apache.archiva.repository.features.StagingRepositoryFeature) URI(java.net.URI) RepositoryException(org.apache.archiva.repository.RepositoryException)

Example 15 with RepositoryException

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

the class RepositoryProviderMock method updateManagedInstance.

@Override
public void updateManagedInstance(EditableManagedRepository managedRepository, ManagedRepositoryConfiguration configuration) throws RepositoryException {
    try {
        managedRepository.setName(managedRepository.getPrimaryLocale(), configuration.getName());
        managedRepository.setLocation(new URI(configuration.getLocation() == null ? "" : configuration.getLocation()));
        managedRepository.setBaseUri(new URI(""));
        managedRepository.setBlocksRedeployment(configuration.isBlockRedeployments());
        managedRepository.setDescription(managedRepository.getPrimaryLocale(), configuration.getDescription());
        managedRepository.setLayout(configuration.getLayout());
        managedRepository.setScanned(configuration.isScanned());
        managedRepository.setSchedulingDefinition(configuration.getRefreshCronExpression());
        if (configuration.isReleases()) {
            managedRepository.addActiveReleaseScheme(ReleaseScheme.RELEASE);
        }
        if (configuration.isSnapshots()) {
            managedRepository.addActiveReleaseScheme(ReleaseScheme.SNAPSHOT);
        }
        ArtifactCleanupFeature acf = managedRepository.getFeature(ArtifactCleanupFeature.class).get();
        acf.setRetentionPeriod(Period.ofDays(configuration.getRetentionPeriod()));
        acf.setDeleteReleasedSnapshots(configuration.isDeleteReleasedSnapshots());
        acf.setRetentionCount(configuration.getRetentionCount());
        IndexCreationFeature icf = managedRepository.getFeature(IndexCreationFeature.class).get();
        icf.setIndexPath(new URI(configuration.getIndexDir()));
        icf.setSkipPackedIndexCreation(configuration.isSkipPackedIndexCreation());
        StagingRepositoryFeature srf = managedRepository.getFeature(StagingRepositoryFeature.class).get();
        srf.setStageRepoNeeded(configuration.isStageRepoNeeded());
    } catch (Exception e) {
        throw new RepositoryException("Error", e);
    }
}
Also used : IndexCreationFeature(org.apache.archiva.repository.features.IndexCreationFeature) RepositoryException(org.apache.archiva.repository.RepositoryException) ArtifactCleanupFeature(org.apache.archiva.repository.features.ArtifactCleanupFeature) StagingRepositoryFeature(org.apache.archiva.repository.features.StagingRepositoryFeature) URI(java.net.URI) RepositoryException(org.apache.archiva.repository.RepositoryException)

Aggregations

RepositoryException (org.apache.archiva.repository.RepositoryException)33 MetadataRepositoryException (org.apache.archiva.metadata.repository.MetadataRepositoryException)14 RepositoryAdminException (org.apache.archiva.admin.model.RepositoryAdminException)13 Path (java.nio.file.Path)12 ManagedRepositoryContent (org.apache.archiva.repository.ManagedRepositoryContent)12 IOException (java.io.IOException)11 ArchivaRestServiceException (org.apache.archiva.rest.api.services.ArchivaRestServiceException)11 Configuration (org.apache.archiva.configuration.Configuration)7 ArtifactReference (org.apache.archiva.model.ArtifactReference)7 URI (java.net.URI)6 MetadataRepository (org.apache.archiva.metadata.repository.MetadataRepository)6 RepositorySession (org.apache.archiva.metadata.repository.RepositorySession)6 IndexCreationFeature (org.apache.archiva.repository.features.IndexCreationFeature)6 RemoteIndexFeature (org.apache.archiva.repository.features.RemoteIndexFeature)6 StagingRepositoryFeature (org.apache.archiva.repository.features.StagingRepositoryFeature)6 ManagedRepository (org.apache.archiva.admin.model.beans.ManagedRepository)5 PasswordCredentials (org.apache.archiva.repository.PasswordCredentials)5 ManagedRepositoryConfiguration (org.apache.archiva.configuration.ManagedRepositoryConfiguration)4 ProxyConnectorConfiguration (org.apache.archiva.configuration.ProxyConnectorConfiguration)4 RemoteRepositoryConfiguration (org.apache.archiva.configuration.RemoteRepositoryConfiguration)4