Search in sources :

Example 1 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class Maven2RepositoryStorage method readArtifactsMetadata.

@Override
public Collection<ArtifactMetadata> readArtifactsMetadata(ReadMetadataRequest readMetadataRequest) throws RepositoryStorageRuntimeException {
    Path dir = pathTranslator.toFile(getRepositoryBasedir(readMetadataRequest.getRepositoryId()), readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion());
    if (!(Files.exists(dir) && Files.isDirectory(dir))) {
        return Collections.emptyList();
    }
    // all files that are not metadata and not a checksum / signature are considered artifacts
    final Predicate<Path> dFilter = new ArtifactDirectoryFilter(readMetadataRequest.getFilter());
    try (Stream<Path> stream = Files.list(dir)) {
        // Returns a map TRUE -> (success values), FALSE -> (Exceptions)
        Map<Boolean, List<Try<ArtifactMetadata>>> result = stream.filter(dFilter).map(path -> {
            try {
                return Try.success(getArtifactFromFile(readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(), path));
            } catch (Exception e) {
                LOGGER.debug("Could not create metadata for {}:  {}", path, e.getMessage(), e);
                return Try.<ArtifactMetadata>failure(e);
            }
        }).collect(Collectors.groupingBy(Try::isSuccess));
        if (result.containsKey(Boolean.FALSE) && result.get(Boolean.FALSE).size() > 0 && (!result.containsKey(Boolean.TRUE) || result.get(Boolean.TRUE).size() == 0)) {
            LOGGER.error("Could not get artifact metadata. Directory: {}. Number of errors {}.", dir, result.get(Boolean.FALSE).size());
            Try<ArtifactMetadata> failure = result.get(Boolean.FALSE).get(0);
            LOGGER.error("Sample exception {}", failure.getError().getMessage(), failure.getError());
            throw new RepositoryStorageRuntimeException(readMetadataRequest.getRepositoryId(), "Could not retrieve metadata of the files");
        } else {
            if (!result.containsKey(Boolean.TRUE) || result.get(Boolean.TRUE) == null) {
                return Collections.emptyList();
            }
            return result.get(Boolean.TRUE).stream().map(tr -> tr.get()).collect(Collectors.toList());
        }
    } catch (IOException e) {
        LOGGER.error("Could not read directory {}: {}", dir, e.getMessage(), e);
    }
    return Collections.emptyList();
}
Also used : Path(java.nio.file.Path) StringUtils(org.apache.commons.lang.StringUtils) NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata) Date(java.util.Date) RepositoryStorageRuntimeException(org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException) LoggerFactory(org.slf4j.LoggerFactory) RepositoryProxyConnectors(org.apache.archiva.proxy.model.RepositoryProxyConnectors) DefaultModelBuilderFactory(org.apache.maven.model.building.DefaultModelBuilderFactory) XMLException(org.apache.archiva.xml.XMLException) RepositoryProblemFacet(org.apache.archiva.metadata.model.facets.RepositoryProblemFacet) ReleaseScheme(org.apache.archiva.repository.ReleaseScheme) NetworkProxyAdmin(org.apache.archiva.admin.model.networkproxy.NetworkProxyAdmin) ModelBuilder(org.apache.maven.model.building.ModelBuilder) PathParser(org.apache.archiva.repository.content.PathParser) Map(java.util.Map) ProjectMetadata(org.apache.archiva.metadata.model.ProjectMetadata) Path(java.nio.file.Path) ProxyConnectorAdmin(org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin) Try(org.apache.archiva.common.Try) ArtifactMetadata(org.apache.archiva.metadata.model.ArtifactMetadata) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) Predicate(java.util.function.Predicate) Collection(java.util.Collection) RepositoryRegistry(org.apache.archiva.repository.RepositoryRegistry) ProxyDownloadException(org.apache.archiva.policies.ProxyDownloadException) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) ProxyConnector(org.apache.archiva.admin.model.beans.ProxyConnector) Filter(org.apache.archiva.metadata.repository.filter.Filter) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) Scm(org.apache.maven.model.Scm) FileNotFoundException(java.io.FileNotFoundException) ManagedRepository(org.apache.archiva.repository.ManagedRepository) Relocation(org.apache.maven.model.Relocation) Organization(org.apache.maven.model.Organization) List(java.util.List) DistributionManagement(org.apache.maven.model.DistributionManagement) Stream(java.util.stream.Stream) ReadMetadataRequest(org.apache.archiva.metadata.repository.storage.ReadMetadataRequest) ModelBuildingRequest(org.apache.maven.model.building.ModelBuildingRequest) PostConstruct(javax.annotation.PostConstruct) ArtifactReference(org.apache.archiva.model.ArtifactReference) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) Model(org.apache.maven.model.Model) RepositoryStorageMetadataNotFoundException(org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException) CiManagement(org.apache.maven.model.CiManagement) NetworkProxy(org.apache.archiva.admin.model.beans.NetworkProxy) RepositoryPathTranslator(org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator) RelocationException(org.apache.archiva.metadata.repository.storage.RelocationException) Dependency(org.apache.maven.model.Dependency) HashMap(java.util.HashMap) WagonFactory(org.apache.archiva.proxy.common.WagonFactory) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ProjectVersionMetadata(org.apache.archiva.metadata.model.ProjectVersionMetadata) RemoteRepository(org.apache.archiva.repository.RemoteRepository) Charset(java.nio.charset.Charset) Service(org.springframework.stereotype.Service) ChecksumAlgorithm(org.apache.archiva.checksum.ChecksumAlgorithm) MavenMetadataReader(org.apache.archiva.maven2.metadata.MavenMetadataReader) Named(javax.inject.Named) LayoutException(org.apache.archiva.repository.LayoutException) IssueManagement(org.apache.maven.model.IssueManagement) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) SnapshotVersion(org.apache.archiva.model.SnapshotVersion) Logger(org.slf4j.Logger) Files(java.nio.file.Files) ModelBuildingException(org.apache.maven.model.building.ModelBuildingException) VersionUtil(org.apache.archiva.common.utils.VersionUtil) IOException(java.io.IOException) License(org.apache.maven.model.License) ApplicationContext(org.springframework.context.ApplicationContext) ChecksummedFile(org.apache.archiva.checksum.ChecksummedFile) ModelProblem(org.apache.maven.model.building.ModelProblem) RepositoryStorageMetadataInvalidException(org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException) Paths(java.nio.file.Paths) DefaultModelBuildingRequest(org.apache.maven.model.building.DefaultModelBuildingRequest) MailingList(org.apache.maven.model.MailingList) Collections(java.util.Collections) RepositoryStorage(org.apache.archiva.metadata.repository.storage.RepositoryStorage) ArrayUtils(org.apache.commons.lang.ArrayUtils) RepositoryStorageRuntimeException(org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException) IOException(java.io.IOException) NoSuchFileException(java.nio.file.NoSuchFileException) RepositoryStorageRuntimeException(org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException) XMLException(org.apache.archiva.xml.XMLException) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) ProxyDownloadException(org.apache.archiva.policies.ProxyDownloadException) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) FileNotFoundException(java.io.FileNotFoundException) RepositoryStorageMetadataNotFoundException(org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException) RelocationException(org.apache.archiva.metadata.repository.storage.RelocationException) LayoutException(org.apache.archiva.repository.LayoutException) ModelBuildingException(org.apache.maven.model.building.ModelBuildingException) IOException(java.io.IOException) RepositoryStorageMetadataInvalidException(org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException) List(java.util.List) ArrayList(java.util.ArrayList) MailingList(org.apache.maven.model.MailingList) ArtifactMetadata(org.apache.archiva.metadata.model.ArtifactMetadata)

Example 2 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class DependencyTreeBuilderTestMaven3 method testBuilderDependencies.

@Test
public void testBuilderDependencies() throws Exception {
    List<TreeEntry> treeEntries = builder.buildDependencyTree(Collections.singletonList(TEST_REPO_ID), TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
    Artifact artifact = new Artifact(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION, "", "");
    artifact.setFileExtension("jar");
    assertThat(treeEntries).isNotNull().isNotEmpty().contains(new TreeEntry(artifact));
    artifact = new Artifact("commons-lang", "commons-lang", "2.2", "compile", "");
    artifact.setFileExtension("jar");
    assertThat(treeEntries.get(0).getChilds()).isNotNull().isNotEmpty().contains(new TreeEntry(artifact));
}
Also used : TreeEntry(org.apache.archiva.maven2.model.TreeEntry) Artifact(org.apache.archiva.maven2.model.Artifact) Test(org.junit.Test)

Example 3 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class DefaultSearchService method redirectToArtifactFile.

@Override
public Response redirectToArtifactFile(String repositoryId, String groupId, String artifactId, String version, String packaging, String classifier) throws ArchivaRestServiceException {
    try {
        if (StringUtils.isEmpty(groupId)) {
            return Response.status(new Response.StatusType() {

                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "groupId mandatory";
                }
            }).build();
        }
        if (StringUtils.isEmpty(version)) {
            return Response.status(new Response.StatusType() {

                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "version mandatory";
                }
            }).build();
        }
        if (StringUtils.isEmpty(artifactId)) {
            return Response.status(new Response.StatusType() {

                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "artifactId mandatory";
                }
            }).build();
        }
        SearchFields searchField = new SearchFields();
        searchField.setGroupId(groupId);
        searchField.setArtifactId(artifactId);
        searchField.setPackaging(StringUtils.isBlank(packaging) ? "jar" : packaging);
        if (!StringUtils.equals(version, LATEST_KEYWORD)) {
            searchField.setVersion(version);
        }
        searchField.setClassifier(classifier);
        List<String> userRepos = getObservablesRepoIds().getStrings();
        searchField.setRepositories(StringUtils.isEmpty(repositoryId) ? userRepos : Arrays.asList(repositoryId));
        searchField.setExactSearch(true);
        SearchResults searchResults = repositorySearch.search(getPrincipal(), searchField, null);
        List<Artifact> artifacts = getArtifacts(searchResults);
        if (artifacts.isEmpty()) {
            return Response.status(new Response.StatusType() {

                @Override
                public int getStatusCode() {
                    return Response.Status.NO_CONTENT.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.NO_CONTENT.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "your query doesn't return any artifact";
                }
            }).build();
        }
        // so simple loop and retain only artifact with null classifier
        if (classifier == null) {
            List<Artifact> filteredArtifacts = new ArrayList<>(artifacts.size());
            for (Artifact artifact : artifacts) {
                if (artifact.getClassifier() == null) {
                    filteredArtifacts.add(artifact);
                }
            }
            artifacts = filteredArtifacts;
        }
        // TODO return json result of the query ?
        if (artifacts.size() > 1 && !StringUtils.equals(version, LATEST_KEYWORD)) {
            return Response.status(new Response.StatusType() {

                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "your query return more than one artifact";
                }
            }).build();
        }
        // version is LATEST so we have to find the latest one from the result
        if (artifacts.size() > 1 && StringUtils.equals(version, LATEST_KEYWORD)) {
            TreeMap<String, Artifact> artifactPerVersion = new TreeMap<>(VersionComparator.getInstance());
            for (Artifact artifact : artifacts) {
                artifactPerVersion.put(artifact.getVersion(), artifact);
            }
            return Response.temporaryRedirect(new URI(artifactPerVersion.lastEntry().getValue().getUrl())).build();
        }
        Artifact artifact = artifacts.get(0);
        return Response.temporaryRedirect(new URI(artifact.getUrl())).build();
    } catch (Exception e) {
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
}
Also used : SearchFields(org.apache.archiva.indexer.search.SearchFields) ArrayList(java.util.ArrayList) SearchResults(org.apache.archiva.indexer.search.SearchResults) TreeMap(java.util.TreeMap) URI(java.net.URI) Artifact(org.apache.archiva.maven2.model.Artifact) RepositorySearchException(org.apache.archiva.indexer.search.RepositorySearchException) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException)

Example 4 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class DefaultSearchService method getArtifactByChecksum.

public List<Artifact> getArtifactByChecksum(ChecksumSearch checksumSearch) throws ArchivaRestServiceException {
    // if no repos set we use ones available for the user
    if (checksumSearch.getRepositories() == null || checksumSearch.getRepositories().isEmpty()) {
        checksumSearch.setRepositories(getObservableRepos());
    }
    RepositorySession repositorySession = repositorySessionFactory.createSession();
    MetadataRepository metadataRepository = repositorySession.getRepository();
    Set<Artifact> artifactSet = new HashSet<>();
    try {
        for (String repoId : checksumSearch.getRepositories()) {
            Collection<ArtifactMetadata> artifactMetadatas = metadataRepository.getArtifactsByChecksum(repoId, checksumSearch.getChecksum());
            artifactSet.addAll(buildArtifacts(artifactMetadatas, repoId));
        }
        return new ArrayList<>(artifactSet);
    } catch (MetadataRepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), e);
    } finally {
        repositorySession.closeQuietly();
    }
}
Also used : MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) MetadataRepository(org.apache.archiva.metadata.repository.MetadataRepository) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ArrayList(java.util.ArrayList) RepositorySession(org.apache.archiva.metadata.repository.RepositorySession) ArtifactMetadata(org.apache.archiva.metadata.model.ArtifactMetadata) Artifact(org.apache.archiva.maven2.model.Artifact) HashSet(java.util.HashSet)

Example 5 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class DefaultSearchService method getArtifacts.

// -------------------------------------
// internal
// -------------------------------------
protected List<Artifact> getArtifacts(SearchResults searchResults) throws ArchivaRestServiceException {
    if (searchResults == null || searchResults.isEmpty()) {
        return Collections.emptyList();
    }
    List<Artifact> artifacts = new ArrayList<>(searchResults.getReturnedHitsCount());
    for (SearchResultHit hit : searchResults.getHits()) {
        // duplicate Artifact one per available version
        if (hit.getVersions().size() > 0) {
            for (String version : hit.getVersions()) {
                Artifact versionned = getModelMapper().map(hit, Artifact.class);
                if (StringUtils.isNotBlank(version)) {
                    versionned.setVersion(version);
                    versionned.setUrl(getArtifactUrl(versionned));
                    artifacts.add(versionned);
                }
            }
        }
    }
    return artifacts;
}
Also used : SearchResultHit(org.apache.archiva.indexer.search.SearchResultHit) ArrayList(java.util.ArrayList) Artifact(org.apache.archiva.maven2.model.Artifact)

Aggregations

Artifact (org.apache.archiva.maven2.model.Artifact)37 Test (org.junit.Test)29 ArrayList (java.util.ArrayList)14 SearchService (org.apache.archiva.rest.api.services.SearchService)14 BrowseService (org.apache.archiva.rest.api.services.BrowseService)11 Path (java.nio.file.Path)10 SearchRequest (org.apache.archiva.rest.api.model.SearchRequest)9 Artifact (se.light.assembly64.model.Artifact)9 List (java.util.List)8 ManagedRepositoriesService (org.apache.archiva.rest.api.services.ManagedRepositoriesService)8 RepositoriesService (org.apache.archiva.rest.api.services.RepositoriesService)8 File (java.io.File)7 IOException (java.io.IOException)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ArchivaRestServiceException (org.apache.archiva.rest.api.services.ArchivaRestServiceException)6 Arrays (java.util.Arrays)5 HashSet (java.util.HashSet)5