Search in sources :

Example 11 with ArchivaRepositoryMetadata

use of org.apache.archiva.model.ArchivaRepositoryMetadata in project archiva by apache.

the class MetadataTransferTest method assertProjectMetadataContents.

/**
 * Test for the existance of the requestedResource in the default managed repository, and if it exists,
 * does it contain the specified list of expected versions?
 *
 * @param requestedResource the requested resource
 * @throws Exception
 */
private void assertProjectMetadataContents(String requestedResource, String[] expectedVersions, String latestVersion, String releaseVersion) throws Exception {
    Path actualFile = managedDefaultDir.resolve(requestedResource);
    assertTrue(Files.exists(actualFile));
    ProjectReference metadata = createProjectReference(requestedResource);
    // Build expected metadata XML
    StringWriter expectedMetadataXml = new StringWriter();
    ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
    m.setGroupId(metadata.getGroupId());
    m.setArtifactId(metadata.getArtifactId());
    m.setLatestVersion(latestVersion);
    m.setReleasedVersion(releaseVersion);
    if (expectedVersions != null) {
        m.getAvailableVersions().addAll(Arrays.asList(expectedVersions));
    }
    RepositoryMetadataWriter.write(m, expectedMetadataXml);
    // Compare the file to the actual contents.
    assertMetadataEquals(expectedMetadataXml.toString(), actualFile);
}
Also used : Path(java.nio.file.Path) ProjectReference(org.apache.archiva.model.ProjectReference) StringWriter(java.io.StringWriter) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata)

Example 12 with ArchivaRepositoryMetadata

use of org.apache.archiva.model.ArchivaRepositoryMetadata 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 13 with ArchivaRepositoryMetadata

use of org.apache.archiva.model.ArchivaRepositoryMetadata 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 14 with ArchivaRepositoryMetadata

use of org.apache.archiva.model.ArchivaRepositoryMetadata in project archiva by apache.

the class MetadataTools method updateMetadata.

/**
 * Update the metadata to represent the all versions/plugins of
 * the provided groupId:artifactId project or group reference,
 * based off of information present in the repository,
 * the maven-metadata.xml files, and the proxy/repository specific
 * metadata file contents.
 * <p>
 * We must treat this as a group or a project metadata file as there is no way to know in advance
 *
 * @param managedRepository the managed repository where the metadata is kept.
 * @param reference         the reference to update.
 * @throws LayoutException
 * @throws RepositoryMetadataException
 * @throws IOException
 * @throws ContentNotFoundException
 * @deprecated
 */
public void updateMetadata(ManagedRepositoryContent managedRepository, ProjectReference 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());
    // Gather up all versions found in the managed repository.
    Set<String> allVersions = managedRepository.getVersions(reference);
    // Gather up all plugins found in the managed repository.
    // TODO: do we know this information instead?
    // Set<Plugin> allPlugins = managedRepository.getPlugins( reference );
    Set<Plugin> allPlugins;
    if (Files.exists(metadataFile)) {
        try {
            allPlugins = new LinkedHashSet<Plugin>(MavenMetadataReader.read(metadataFile).getPlugins());
        } catch (XMLException e) {
            throw new RepositoryMetadataException(e.getMessage(), e);
        }
    } else {
        allPlugins = new LinkedHashSet<Plugin>();
    }
    // Does this repository have a set of remote proxied repositories?
    Set<String> proxiedRepoIds = this.proxies.get(managedRepository.getId());
    if (CollectionUtils.isNotEmpty(proxiedRepoIds)) {
        // Add in the proxied repo version ids too.
        Iterator<String> it = proxiedRepoIds.iterator();
        while (it.hasNext()) {
            String proxyId = it.next();
            ArchivaRepositoryMetadata proxyMetadata = readProxyMetadata(managedRepository, reference, proxyId);
            if (proxyMetadata != null) {
                allVersions.addAll(proxyMetadata.getAvailableVersions());
                allPlugins.addAll(proxyMetadata.getPlugins());
                long proxyLastUpdated = getLastUpdated(proxyMetadata);
                lastUpdated = Math.max(lastUpdated, proxyLastUpdated);
            }
        }
    }
    if (!allVersions.isEmpty()) {
        updateMetadataVersions(allVersions, metadata);
    } else {
        // Add the plugins to the metadata model.
        metadata.setPlugins(new ArrayList<>(allPlugins));
        // artifact ID was actually the last part of the group
        metadata.setGroupId(metadata.getGroupId() + "." + metadata.getArtifactId());
        metadata.setArtifactId(null);
    }
    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) ChecksummedFile(org.apache.archiva.checksum.ChecksummedFile) XMLException(org.apache.archiva.xml.XMLException) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata) Plugin(org.apache.archiva.model.Plugin)

Example 15 with ArchivaRepositoryMetadata

use of org.apache.archiva.model.ArchivaRepositoryMetadata in project archiva by apache.

the class MetadataTools method gatherSnapshotVersions.

/**
 * Gather the set of snapshot versions found in a particular versioned reference.
 *
 * @return the Set of snapshot artifact versions found.
 * @throws LayoutException
 * @throws ContentNotFoundException
 */
public Set<String> gatherSnapshotVersions(ManagedRepositoryContent managedRepository, VersionedReference reference) throws LayoutException, IOException, ContentNotFoundException {
    Set<String> foundVersions = managedRepository.getVersions(reference);
    // Next gather up the referenced 'latest' versions found in any proxied repositories
    // maven-metadata-${proxyId}.xml files that may be present.
    // Does this repository have a set of remote proxied repositories?
    Set<String> proxiedRepoIds = this.proxies.get(managedRepository.getId());
    if (CollectionUtils.isNotEmpty(proxiedRepoIds)) {
        String baseVersion = VersionUtil.getBaseVersion(reference.getVersion());
        baseVersion = baseVersion.substring(0, baseVersion.indexOf(VersionUtil.SNAPSHOT) - 1);
        // Add in the proxied repo version ids too.
        Iterator<String> it = proxiedRepoIds.iterator();
        while (it.hasNext()) {
            String proxyId = it.next();
            ArchivaRepositoryMetadata proxyMetadata = readProxyMetadata(managedRepository, reference, proxyId);
            if (proxyMetadata == null) {
                // There is no proxy metadata, skip it.
                continue;
            }
            // Is there some snapshot info?
            SnapshotVersion snapshot = proxyMetadata.getSnapshotVersion();
            if (snapshot != null) {
                String timestamp = snapshot.getTimestamp();
                int buildNumber = snapshot.getBuildNumber();
                // Only interested in the timestamp + buildnumber.
                if (StringUtils.isNotBlank(timestamp) && (buildNumber > 0)) {
                    foundVersions.add(baseVersion + "-" + timestamp + "-" + buildNumber);
                }
            }
        }
    }
    return foundVersions;
}
Also used : SnapshotVersion(org.apache.archiva.model.SnapshotVersion) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata)

Aggregations

ArchivaRepositoryMetadata (org.apache.archiva.model.ArchivaRepositoryMetadata)37 Path (java.nio.file.Path)29 StringWriter (java.io.StringWriter)8 XMLException (org.apache.archiva.xml.XMLException)8 ArrayList (java.util.ArrayList)7 SnapshotVersion (org.apache.archiva.model.SnapshotVersion)7 Test (org.junit.Test)7 IOException (java.io.IOException)5 RepositoryAdminException (org.apache.archiva.admin.model.RepositoryAdminException)5 ManagedRepository (org.apache.archiva.admin.model.beans.ManagedRepository)4 Plugin (org.apache.archiva.model.Plugin)4 ManagedRepositoryContent (org.apache.archiva.repository.ManagedRepositoryContent)4 Date (java.util.Date)3 ChecksummedFile (org.apache.archiva.checksum.ChecksummedFile)3 ArtifactReference (org.apache.archiva.model.ArtifactReference)3 RepositoryException (org.apache.archiva.repository.RepositoryException)3 ArchivaRestServiceException (org.apache.archiva.rest.api.services.ArchivaRestServiceException)3 DateFormat (java.text.DateFormat)2 SimpleDateFormat (java.text.SimpleDateFormat)2 TimeZone (java.util.TimeZone)2