Search in sources :

Example 6 with ContentNotFoundException

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

the class DefaultRepositoriesService method deleteProject.

@Override
public Boolean deleteProject(String groupId, String projectId, String repositoryId) throws ArchivaRestServiceException {
    if (StringUtils.isEmpty(repositoryId)) {
        throw new ArchivaRestServiceException("repositoryId cannot be null", 400, null);
    }
    if (!isAuthorizedToDeleteArtifacts(repositoryId)) {
        throw new ArchivaRestServiceException("not authorized to delete artifacts", 403, null);
    }
    if (StringUtils.isEmpty(groupId)) {
        throw new ArchivaRestServiceException("groupId cannot be null", 400, null);
    }
    if (StringUtils.isEmpty(projectId)) {
        throw new ArchivaRestServiceException("artifactId cannot be null", 400, null);
    }
    RepositorySession repositorySession = repositorySessionFactory.createSession();
    try {
        ManagedRepositoryContent repository = getManagedRepositoryContent(repositoryId);
        repository.deleteProject(groupId, projectId);
    } catch (ContentNotFoundException e) {
        log.warn("skip ContentNotFoundException: {}", e.getMessage());
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    }
    try {
        MetadataRepository metadataRepository = repositorySession.getRepository();
        metadataRepository.removeProject(repositoryId, groupId, projectId);
        metadataRepository.save();
    } catch (MetadataRepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } finally {
        repositorySession.close();
    }
    return true;
}
Also used : MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) MetadataRepository(org.apache.archiva.metadata.repository.MetadataRepository) ContentNotFoundException(org.apache.archiva.repository.ContentNotFoundException) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) RepositoryException(org.apache.archiva.repository.RepositoryException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) RepositorySession(org.apache.archiva.metadata.repository.RepositorySession)

Example 7 with ContentNotFoundException

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

the class DefaultRepositoriesService method deleteArtifact.

@Override
public Boolean deleteArtifact(Artifact artifact) throws ArchivaRestServiceException {
    String repositoryId = artifact.getContext();
    // so try both!!
    if (StringUtils.isEmpty(repositoryId)) {
        repositoryId = artifact.getRepositoryId();
    }
    if (StringUtils.isEmpty(repositoryId)) {
        throw new ArchivaRestServiceException("repositoryId cannot be null", 400, null);
    }
    if (!isAuthorizedToDeleteArtifacts(repositoryId)) {
        throw new ArchivaRestServiceException("not authorized to delete artifacts", 403, null);
    }
    if (artifact == null) {
        throw new ArchivaRestServiceException("artifact cannot be null", 400, null);
    }
    if (StringUtils.isEmpty(artifact.getGroupId())) {
        throw new ArchivaRestServiceException("artifact.groupId cannot be null", 400, null);
    }
    if (StringUtils.isEmpty(artifact.getArtifactId())) {
        throw new ArchivaRestServiceException("artifact.artifactId cannot be null", 400, null);
    }
    // TODO more control on artifact fields
    boolean snapshotVersion = VersionUtil.isSnapshot(artifact.getVersion()) | VersionUtil.isGenericSnapshot(artifact.getVersion());
    RepositorySession repositorySession = repositorySessionFactory.createSession();
    try {
        Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
        TimeZone timezone = TimeZone.getTimeZone("UTC");
        DateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss");
        fmt.setTimeZone(timezone);
        ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository(repositoryId);
        VersionedReference ref = new VersionedReference();
        ref.setArtifactId(artifact.getArtifactId());
        ref.setGroupId(artifact.getGroupId());
        ref.setVersion(artifact.getVersion());
        ManagedRepositoryContent repository = getManagedRepositoryContent(repositoryId);
        ArtifactReference artifactReference = new ArtifactReference();
        artifactReference.setArtifactId(artifact.getArtifactId());
        artifactReference.setGroupId(artifact.getGroupId());
        artifactReference.setVersion(artifact.getVersion());
        artifactReference.setClassifier(artifact.getClassifier());
        artifactReference.setType(artifact.getPackaging());
        MetadataRepository metadataRepository = repositorySession.getRepository();
        String path = repository.toMetadataPath(ref);
        if (StringUtils.isNotBlank(artifact.getClassifier())) {
            if (StringUtils.isBlank(artifact.getPackaging())) {
                throw new ArchivaRestServiceException("You must configure a type/packaging when using classifier", 400, null);
            }
            repository.deleteArtifact(artifactReference);
        } else {
            int index = path.lastIndexOf('/');
            path = path.substring(0, index);
            Path targetPath = Paths.get(repoConfig.getLocation(), path);
            if (!Files.exists(targetPath)) {
                // throw new ContentNotFoundException(
                // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
                log.warn("targetPath {} not found skip file deletion", targetPath);
            }
            // delete from file system
            if (!snapshotVersion) {
                repository.deleteVersion(ref);
            } else {
                Set<ArtifactReference> related = repository.getRelatedArtifacts(artifactReference);
                log.debug("related: {}", related);
                for (ArtifactReference artifactRef : related) {
                    repository.deleteArtifact(artifactRef);
                }
            }
            Path metadataFile = getMetadata(targetPath.toAbsolutePath().toString());
            ArchivaRepositoryMetadata metadata = getMetadata(metadataFile);
            updateMetadata(metadata, metadataFile, lastUpdatedTimestamp, artifact);
        }
        Collection<ArtifactMetadata> artifacts = Collections.emptyList();
        if (snapshotVersion) {
            String baseVersion = VersionUtil.getBaseVersion(artifact.getVersion());
            artifacts = metadataRepository.getArtifacts(repositoryId, artifact.getGroupId(), artifact.getArtifactId(), baseVersion);
        } else {
            artifacts = metadataRepository.getArtifacts(repositoryId, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
        }
        log.debug("artifacts: {}", artifacts);
        if (artifacts.isEmpty()) {
            if (!snapshotVersion) {
                // verify metata repository doesn't contains anymore the version
                Collection<String> projectVersions = metadataRepository.getProjectVersions(repositoryId, artifact.getGroupId(), artifact.getArtifactId());
                if (projectVersions.contains(artifact.getVersion())) {
                    log.warn("artifact not found when deleted but version still here ! so force cleanup");
                    metadataRepository.removeProjectVersion(repositoryId, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
                }
            }
        }
        for (ArtifactMetadata artifactMetadata : artifacts) {
            // TODO: mismatch between artifact (snapshot) version and project (base) version here
            if (artifactMetadata.getVersion().equals(artifact.getVersion())) {
                if (StringUtils.isNotBlank(artifact.getClassifier())) {
                    if (StringUtils.isBlank(artifact.getPackaging())) {
                        throw new ArchivaRestServiceException("You must configure a type/packaging when using classifier", 400, null);
                    }
                    // cleanup facet which contains classifier information
                    MavenArtifactFacet mavenArtifactFacet = (MavenArtifactFacet) artifactMetadata.getFacet(MavenArtifactFacet.FACET_ID);
                    if (StringUtils.equals(artifact.getClassifier(), mavenArtifactFacet.getClassifier())) {
                        artifactMetadata.removeFacet(MavenArtifactFacet.FACET_ID);
                        String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version = artifact.getVersion();
                        MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
                        mavenArtifactFacetToCompare.setClassifier(artifact.getClassifier());
                        metadataRepository.removeArtifact(repositoryId, groupId, artifactId, version, mavenArtifactFacetToCompare);
                        metadataRepository.save();
                    }
                } else {
                    if (snapshotVersion) {
                        metadataRepository.removeArtifact(artifactMetadata, VersionUtil.getBaseVersion(artifact.getVersion()));
                    } else {
                        metadataRepository.removeArtifact(artifactMetadata.getRepositoryId(), artifactMetadata.getNamespace(), artifactMetadata.getProject(), artifact.getVersion(), artifactMetadata.getId());
                    }
                }
                // repository metadata to an artifact
                for (RepositoryListener listener : listeners) {
                    listener.deleteArtifact(metadataRepository, repository.getId(), artifactMetadata.getNamespace(), artifactMetadata.getProject(), artifactMetadata.getVersion(), artifactMetadata.getId());
                }
                triggerAuditEvent(repositoryId, path, AuditEvent.REMOVE_FILE);
            }
        }
    } catch (ContentNotFoundException e) {
        throw new ArchivaRestServiceException("Artifact does not exist: " + e.getMessage(), 400, e);
    } catch (RepositoryNotFoundException e) {
        throw new ArchivaRestServiceException("Target repository cannot be found: " + e.getMessage(), 400, e);
    } catch (RepositoryException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (MetadataResolutionException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (MetadataRepositoryException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException("RepositoryAdmin exception: " + e.getMessage(), 500, e);
    } finally {
        repositorySession.save();
        repositorySession.close();
    }
    return Boolean.TRUE;
}
Also used : ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) MavenArtifactFacet(org.apache.archiva.metadata.model.maven2.MavenArtifactFacet) RepositorySession(org.apache.archiva.metadata.repository.RepositorySession) MetadataRepository(org.apache.archiva.metadata.repository.MetadataRepository) VersionedReference(org.apache.archiva.model.VersionedReference) ArtifactMetadata(org.apache.archiva.metadata.model.ArtifactMetadata) Path(java.nio.file.Path) RepositoryListener(org.apache.archiva.repository.events.RepositoryListener) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) ContentNotFoundException(org.apache.archiva.repository.ContentNotFoundException) RepositoryException(org.apache.archiva.repository.RepositoryException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) RepositoryNotFoundException(org.apache.archiva.repository.RepositoryNotFoundException) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) Date(java.util.Date) MetadataResolutionException(org.apache.archiva.metadata.repository.MetadataResolutionException) TimeZone(java.util.TimeZone) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata) SimpleDateFormat(java.text.SimpleDateFormat) ArtifactReference(org.apache.archiva.model.ArtifactReference)

Example 8 with ContentNotFoundException

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

the class DaysOldRepositoryPurge method process.

@Override
public void process(String path) throws RepositoryPurgeException {
    try {
        Path artifactFile = Paths.get(repository.getRepoRoot(), path);
        if (!Files.exists(artifactFile)) {
            return;
        }
        ArtifactReference artifact = repository.toArtifactReference(path);
        Calendar olderThanThisDate = Calendar.getInstance(DateUtils.UTC_TIME_ZONE);
        olderThanThisDate.add(Calendar.DATE, -retentionPeriod);
        // respect retention count
        VersionedReference reference = new VersionedReference();
        reference.setGroupId(artifact.getGroupId());
        reference.setArtifactId(artifact.getArtifactId());
        reference.setVersion(artifact.getVersion());
        List<String> versions = new ArrayList<>(repository.getVersions(reference));
        Collections.sort(versions, VersionComparator.getInstance());
        if (retentionCount > versions.size()) {
            // Done. nothing to do here. skip it.
            return;
        }
        int countToPurge = versions.size() - retentionCount;
        Set<ArtifactReference> artifactsToDelete = new HashSet<>();
        for (String version : versions) {
            if (countToPurge-- <= 0) {
                break;
            }
            ArtifactReference newArtifactReference = repository.toArtifactReference(artifactFile.toAbsolutePath().toString());
            newArtifactReference.setVersion(version);
            Path newArtifactFile = repository.toFile(newArtifactReference);
            // Is this a generic snapshot "1.0-SNAPSHOT" ?
            if (VersionUtil.isGenericSnapshot(newArtifactReference.getVersion())) {
                if (Files.getLastModifiedTime(newArtifactFile).toMillis() < olderThanThisDate.getTimeInMillis()) {
                    artifactsToDelete.addAll(repository.getRelatedArtifacts(newArtifactReference));
                }
            } else // Is this a timestamp snapshot "1.0-20070822.123456-42" ?
            if (VersionUtil.isUniqueSnapshot(newArtifactReference.getVersion())) {
                Calendar timestampCal = uniqueSnapshotToCalendar(newArtifactReference.getVersion());
                if (timestampCal.getTimeInMillis() < olderThanThisDate.getTimeInMillis()) {
                    artifactsToDelete.addAll(repository.getRelatedArtifacts(newArtifactReference));
                }
            }
        }
        purge(artifactsToDelete);
    } catch (ContentNotFoundException | IOException e) {
        throw new RepositoryPurgeException(e.getMessage(), e);
    } catch (LayoutException e) {
        log.debug("Not processing file that is not an artifact: {}", e.getMessage());
    }
}
Also used : Path(java.nio.file.Path) ContentNotFoundException(org.apache.archiva.repository.ContentNotFoundException) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) IOException(java.io.IOException) VersionedReference(org.apache.archiva.model.VersionedReference) LayoutException(org.apache.archiva.repository.LayoutException) ArtifactReference(org.apache.archiva.model.ArtifactReference) HashSet(java.util.HashSet)

Example 9 with ContentNotFoundException

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

the class MetadataTools method updateMetadata.

/**
 * Update the metadata based on the following rules.
 * <p>
 * 1) If this is a SNAPSHOT reference, then utilize the proxy/repository specific
 * metadata files to represent the current / latest SNAPSHOT available.
 * 2) If this is a RELEASE reference, and the metadata file does not exist, then
 * create the metadata file with contents required of the VersionedReference
 *
 * @param managedRepository the managed repository where the metadata is kept.
 * @param reference         the versioned reference to update
 * @throws LayoutException
 * @throws RepositoryMetadataException
 * @throws IOException
 * @throws ContentNotFoundException
 * @deprecated
 */
public void updateMetadata(ManagedRepositoryContent managedRepository, VersionedReference reference) throws LayoutException, RepositoryMetadataException, IOException, ContentNotFoundException {
    Path metadataFile = Paths.get(managedRepository.getRepoRoot(), toPath(reference));
    long lastUpdated = getExistingLastUpdated(metadataFile);
    ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
    metadata.setGroupId(reference.getGroupId());
    metadata.setArtifactId(reference.getArtifactId());
    if (VersionUtil.isSnapshot(reference.getVersion())) {
        // Do SNAPSHOT handling.
        metadata.setVersion(VersionUtil.getBaseVersion(reference.getVersion()));
        // Gather up all of the versions found in the reference dir, and any
        // proxied maven-metadata.xml files.
        Set<String> snapshotVersions = gatherSnapshotVersions(managedRepository, reference);
        if (snapshotVersions.isEmpty()) {
            throw new ContentNotFoundException("No snapshot versions found on reference [" + VersionedReference.toKey(reference) + "].");
        }
        // sort the list to determine to aide in determining the Latest version.
        List<String> sortedVersions = new ArrayList<>();
        sortedVersions.addAll(snapshotVersions);
        Collections.sort(sortedVersions, new VersionComparator());
        String latestVersion = sortedVersions.get(sortedVersions.size() - 1);
        if (VersionUtil.isUniqueSnapshot(latestVersion)) {
            // The latestVersion will contain the full version string "1.0-alpha-5-20070821.213044-8"
            // This needs to be broken down into ${base}-${timestamp}-${build_number}
            Matcher m = VersionUtil.UNIQUE_SNAPSHOT_PATTERN.matcher(latestVersion);
            if (m.matches()) {
                metadata.setSnapshotVersion(new SnapshotVersion());
                int buildNumber = NumberUtils.toInt(m.group(3), -1);
                metadata.getSnapshotVersion().setBuildNumber(buildNumber);
                Matcher mtimestamp = VersionUtil.TIMESTAMP_PATTERN.matcher(m.group(2));
                if (mtimestamp.matches()) {
                    String tsDate = mtimestamp.group(1);
                    String tsTime = mtimestamp.group(2);
                    long snapshotLastUpdated = toLastUpdatedLong(tsDate + tsTime);
                    lastUpdated = Math.max(lastUpdated, snapshotLastUpdated);
                    metadata.getSnapshotVersion().setTimestamp(m.group(2));
                }
            }
        } else if (VersionUtil.isGenericSnapshot(latestVersion)) {
            // The latestVersion ends with the generic version string.
            // Example: 1.0-alpha-5-SNAPSHOT
            metadata.setSnapshotVersion(new SnapshotVersion());
        /* Disabled due to decision in [MRM-535].
                 * Do not set metadata.lastUpdated to file.lastModified.
                 * 
                 * Should this be the last updated timestamp of the file, or in the case of an 
                 * archive, the most recent timestamp in the archive?
                 * 
                ArtifactReference artifact = getFirstArtifact( managedRepository, reference );

                if ( artifact == null )
                {
                    throw new IOException( "Not snapshot artifact found to reference in " + reference );
                }

                File artifactFile = managedRepository.toFile( artifact );

                if ( artifactFile.exists() )
                {
                    Date lastModified = new Date( artifactFile.lastModified() );
                    metadata.setLastUpdatedTimestamp( lastModified );
                }
                */
        } else {
            throw new RepositoryMetadataException("Unable to process snapshot version <" + latestVersion + "> reference <" + reference + ">");
        }
    } else {
        // Do RELEASE handling.
        metadata.setVersion(reference.getVersion());
    }
    // Set last updated
    if (lastUpdated > 0) {
        metadata.setLastUpdatedTimestamp(toLastUpdatedDate(lastUpdated));
    }
    // Save the metadata model to disk.
    RepositoryMetadataWriter.write(metadata, metadataFile);
    ChecksummedFile checksum = new ChecksummedFile(metadataFile);
    checksum.fixChecksums(algorithms);
}
Also used : Path(java.nio.file.Path) ContentNotFoundException(org.apache.archiva.repository.ContentNotFoundException) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) ChecksummedFile(org.apache.archiva.checksum.ChecksummedFile) SnapshotVersion(org.apache.archiva.model.SnapshotVersion) VersionComparator(org.apache.archiva.common.utils.VersionComparator) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata)

Example 10 with ContentNotFoundException

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

the class ManagedDefaultRepositoryContent method getVersions.

@Override
public Set<String> getVersions(VersionedReference reference) throws ContentNotFoundException {
    String path = toMetadataPath(reference);
    int idx = path.lastIndexOf('/');
    if (idx > 0) {
        path = path.substring(0, idx);
    }
    Path repoBase = PathUtil.getPathFromUri(repository.getLocation());
    Path repoDir = repoBase.resolve(path);
    if (!Files.exists(repoDir)) {
        throw new ContentNotFoundException("Unable to get versions on a non-existant directory: " + repoDir.toAbsolutePath());
    }
    if (!Files.isDirectory(repoDir)) {
        throw new ContentNotFoundException("Unable to get versions on a non-directory: " + repoDir.toAbsolutePath());
    }
    Set<String> foundVersions = new HashSet<>();
    try (Stream<Path> stream = Files.list(repoDir)) {
        return stream.filter(Files::isRegularFile).map(p -> repoBase.relativize(p).toString()).filter(p -> !filetypes.matchesDefaultExclusions(p)).filter(filetypes::matchesArtifactPattern).map(path1 -> {
            try {
                return toArtifactReference(path1);
            } catch (LayoutException e) {
                log.debug("Not processing file that is not an artifact: {}", e.getMessage());
                return null;
            }
        }).filter(Objects::nonNull).map(ar -> ar.getVersion()).collect(Collectors.toSet());
    } catch (IOException e) {
        log.error("Could not read directory {}: {}", repoDir, e.getMessage(), e);
    }
    return Collections.emptySet();
}
Also used : Path(java.nio.file.Path) StringUtils(org.apache.commons.lang.StringUtils) PathUtil(org.apache.archiva.common.utils.PathUtil) ArtifactMappingProvider(org.apache.archiva.metadata.repository.storage.maven2.ArtifactMappingProvider) DefaultArtifactMappingProvider(org.apache.archiva.metadata.repository.storage.maven2.DefaultArtifactMappingProvider) ProjectReference(org.apache.archiva.model.ProjectReference) HashSet(java.util.HashSet) URI(java.net.URI) LayoutException(org.apache.archiva.repository.LayoutException) Path(java.nio.file.Path) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) VersionedReference(org.apache.archiva.model.VersionedReference) Files(java.nio.file.Files) RepositoryException(org.apache.archiva.repository.RepositoryException) Set(java.util.Set) FileTypes(org.apache.archiva.configuration.FileTypes) IOException(java.io.IOException) ContentNotFoundException(org.apache.archiva.repository.ContentNotFoundException) ArchivaArtifact(org.apache.archiva.model.ArchivaArtifact) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) ArtifactReference(org.apache.archiva.model.ArtifactReference) Collections(java.util.Collections) ContentNotFoundException(org.apache.archiva.repository.ContentNotFoundException) LayoutException(org.apache.archiva.repository.LayoutException) Objects(java.util.Objects) IOException(java.io.IOException) HashSet(java.util.HashSet)

Aggregations

ContentNotFoundException (org.apache.archiva.repository.ContentNotFoundException)12 Path (java.nio.file.Path)10 ArtifactReference (org.apache.archiva.model.ArtifactReference)9 VersionedReference (org.apache.archiva.model.VersionedReference)8 IOException (java.io.IOException)7 LayoutException (org.apache.archiva.repository.LayoutException)7 RepositoryException (org.apache.archiva.repository.RepositoryException)7 ManagedRepositoryContent (org.apache.archiva.repository.ManagedRepositoryContent)6 HashSet (java.util.HashSet)5 ProjectReference (org.apache.archiva.model.ProjectReference)5 ArrayList (java.util.ArrayList)4 MetadataRepository (org.apache.archiva.metadata.repository.MetadataRepository)4 URI (java.net.URI)3 Files (java.nio.file.Files)3 Paths (java.nio.file.Paths)3 Collections (java.util.Collections)3 List (java.util.List)3 Objects (java.util.Objects)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3