1 package org.apache.archiva.rest.services;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.admin.ArchivaAdministration;
24 import org.apache.archiva.checksum.ChecksumAlgorithm;
25 import org.apache.archiva.checksum.ChecksummedFile;
26 import org.apache.archiva.common.utils.VersionComparator;
27 import org.apache.archiva.common.utils.VersionUtil;
28 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
29 import org.apache.archiva.maven2.model.Artifact;
30 import org.apache.archiva.metadata.model.ArtifactMetadata;
31 import org.apache.archiva.metadata.model.facets.AuditEvent;
32 import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
33 import org.apache.archiva.metadata.repository.*;
34 import org.apache.archiva.model.ArchivaRepositoryMetadata;
35 import org.apache.archiva.model.ArtifactReference;
36 import org.apache.archiva.model.VersionedReference;
37 import org.apache.archiva.redback.authentication.AuthenticationResult;
38 import org.apache.archiva.redback.authorization.AuthorizationException;
39 import org.apache.archiva.components.cache.Cache;
40 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
41 import org.apache.archiva.redback.system.DefaultSecuritySession;
42 import org.apache.archiva.redback.system.SecuritySession;
43 import org.apache.archiva.redback.system.SecuritySystem;
44 import org.apache.archiva.redback.users.User;
45 import org.apache.archiva.redback.users.UserManagerException;
46 import org.apache.archiva.redback.users.UserNotFoundException;
47 import org.apache.archiva.repository.ContentNotFoundException;
48 import org.apache.archiva.repository.ManagedRepository;
49 import org.apache.archiva.repository.ManagedRepositoryContent;
50 import org.apache.archiva.repository.RepositoryException;
51 import org.apache.archiva.repository.RepositoryNotFoundException;
52 import org.apache.archiva.repository.RepositoryRegistry;
53 import org.apache.archiva.repository.storage.RepositoryStorage;
54 import org.apache.archiva.repository.storage.StorageAsset;
55 import org.apache.archiva.repository.storage.StorageUtil;
56 import org.apache.archiva.metadata.audit.RepositoryListener;
57 import org.apache.archiva.repository.metadata.base.MetadataTools;
58 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
59 import org.apache.archiva.repository.metadata.base.RepositoryMetadataWriter;
60 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
61 import org.apache.archiva.repository.scanner.RepositoryScanner;
62 import org.apache.archiva.repository.scanner.RepositoryScannerException;
63 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
64 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
65 import org.apache.archiva.rest.api.model.StringList;
66 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
67 import org.apache.archiva.rest.api.services.RepositoriesService;
68 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
69 import org.apache.archiva.scheduler.indexing.maven.ArchivaIndexingTaskExecutor;
70 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
71 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
72 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
73 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
74 import org.apache.archiva.security.ArchivaSecurityException;
75 import org.apache.archiva.security.common.ArchivaRoleConstants;
76 import org.apache.archiva.xml.XMLException;
77 import org.apache.commons.io.FilenameUtils;
78 import org.apache.commons.lang3.StringUtils;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.stereotype.Service;
84 import javax.inject.Inject;
85 import javax.inject.Named;
86 import javax.ws.rs.core.Response;
87 import java.io.IOException;
88 import java.io.OutputStreamWriter;
89 import java.nio.file.Path;
90 import java.text.DateFormat;
91 import java.text.SimpleDateFormat;
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.Calendar;
95 import java.util.Collection;
96 import java.util.Collections;
97 import java.util.Date;
98 import java.util.List;
100 import java.util.TimeZone;
103 * @author Olivier Lamy
106 @Service("repositoriesService#rest")
107 public class DefaultRepositoriesService
108 extends AbstractRestService
109 implements RepositoriesService
111 private Logger log = LoggerFactory.getLogger( getClass() );
114 @Named(value = "taskExecutor#indexing")
115 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
118 private RepositoryRegistry repositoryRegistry;
121 private SecuritySystem securitySystem;
124 @Named(value = "archivaTaskScheduler#repository")
125 private ArchivaTaskScheduler<RepositoryTask> scheduler;
128 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
131 @Named(value = "repositorySessionFactory")
132 protected RepositorySessionFactory repositorySessionFactory;
135 @Autowired(required = false)
136 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
139 private RepositoryScanner repoScanner;
142 * Cache used for namespaces
145 @Named(value = "cache#namespaces")
146 private Cache<String, Collection<String>> namespacesCache;
148 private List<ChecksumAlgorithm> algorithms = Arrays.asList(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 );
151 public Boolean scanRepository( String repositoryId, boolean fullScan )
153 return doScanRepository( repositoryId, fullScan );
157 public Boolean alreadyScanning( String repositoryId )
159 // check queue first to make sure it doesn't get dequeued between calls
160 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
164 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
166 if ( scan.getRepository().getId().equals( repositoryId ) )
175 public Boolean removeScanningTaskFromQueue( String repositoryId )
177 RepositoryTask task = new RepositoryTask();
178 task.setRepositoryId( repositoryId );
181 return repositoryTaskScheduler.unQueueTask( task );
183 catch ( TaskQueueException e )
185 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
190 private ManagedRepositoryContent getManagedRepositoryContent(String id) throws RepositoryException
192 org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( id );
194 throw new RepositoryException( "Repository not found "+id );
196 return repo.getContent();
200 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
201 throws ArchivaRestServiceException
207 org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository( repositoryId );
210 ArtifactIndexingTask task =
211 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, repository.getIndexingContext() );
213 task.setExecuteOnEntireRepo( true );
214 task.setOnlyUpdate( !fullScan );
216 archivaIndexingTaskExecutor.executeTask( task );
218 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
222 catch ( Exception e )
224 log.error( e.getMessage(), e );
225 throw new ArchivaRestServiceException( e.getMessage(), e );
230 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
231 throws ArchivaRestServiceException
235 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
237 catch ( DownloadRemoteIndexException e )
239 log.error( e.getMessage(), e );
240 throw new ArchivaRestServiceException( e.getMessage(), e );
246 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
247 throws ArchivaRestServiceException
250 String userName = getAuditInformation().getUser().getUsername();
251 if ( StringUtils.isBlank( userName ) )
253 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
256 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
258 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
261 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
263 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
266 ManagedRepository source = null;
267 source = repositoryRegistry.getManagedRepository( artifactTransferRequest.getRepositoryId() );
269 if ( source == null )
271 throw new ArchivaRestServiceException(
272 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
275 ManagedRepository target = null;
276 target = repositoryRegistry.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
278 if ( target == null )
280 throw new ArchivaRestServiceException(
281 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
284 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
286 throw new ArchivaRestServiceException( "groupId is mandatory", null );
289 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
291 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
294 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
296 throw new ArchivaRestServiceException( "version is mandatory", null );
299 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
301 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
304 // end check parameters
309 user = securitySystem.getUserManager().findUser( userName );
311 catch ( UserNotFoundException e )
313 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
315 catch ( UserManagerException e )
317 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
320 // check karma on source : read
321 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
322 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
326 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
327 artifactTransferRequest.getRepositoryId() );
330 throw new ArchivaRestServiceException(
331 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
334 catch ( AuthorizationException e )
336 log.error( "error reading permission: {}", e.getMessage(), e );
337 throw new ArchivaRestServiceException( e.getMessage(), e );
340 // check karma on target: write
344 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
345 artifactTransferRequest.getTargetRepositoryId() );
348 throw new ArchivaRestServiceException(
349 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
352 catch ( AuthorizationException e )
354 log.error( "error reading permission: {}", e.getMessage(), e );
355 throw new ArchivaRestServiceException( e.getMessage(), e );
358 // sounds good we can continue !
360 ArtifactReference artifactReference = new ArtifactReference();
361 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
362 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
363 artifactReference.setVersion( artifactTransferRequest.getVersion() );
364 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
365 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
366 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
371 ManagedRepositoryContent sourceRepository =
372 getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
374 String artifactSourcePath = sourceRepository.toPath( artifactReference );
376 if ( StringUtils.isEmpty( artifactSourcePath ) )
378 log.error( "cannot find artifact {}", artifactTransferRequest );
379 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
383 StorageAsset artifactFile = source.getAsset( artifactSourcePath );
385 if ( !artifactFile.exists() )
387 log.error( "cannot find artifact {}", artifactTransferRequest );
388 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
392 ManagedRepositoryContent targetRepository =
393 getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
395 String artifactPath = targetRepository.toPath( artifactReference );
397 int lastIndex = artifactPath.lastIndexOf( '/' );
399 String path = artifactPath.substring( 0, lastIndex );
400 StorageAsset targetDir = target.getAsset( path );
402 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
403 int newBuildNumber = 1;
404 String timestamp = null;
406 StorageAsset versionMetadataFile = target.getAsset(path + "/" + MetadataTools.MAVEN_METADATA );
407 /* unused */ getMetadata( versionMetadataFile );
409 if ( !targetDir.exists() )
411 targetDir = target.addAsset(targetDir.getPath(), true);
415 String filename = artifactPath.substring( lastIndex + 1 );
417 boolean fixChecksums =
418 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
420 StorageAsset targetFile = target.getAsset(targetDir.getPath() + "/" + filename );
421 if ( targetFile.exists() && target.blocksRedeployments())
423 throw new ArchivaRestServiceException(
424 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
425 + " and redeployment blocked", null
430 copyFile(artifactFile, targetFile, fixChecksums );
431 queueRepositoryTask( target.getId(), targetFile );
434 // copy source pom to target repo
435 String pomFilename = filename;
436 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
438 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
440 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
442 StorageAsset pomFile = source.getAsset(
443 artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) )+"/"+ pomFilename );
445 if ( pomFile != null && pomFile.exists() )
447 StorageAsset targetPomFile = target.getAsset( targetDir.getPath() + "/" + pomFilename );
448 copyFile(pomFile, targetPomFile, fixChecksums );
449 queueRepositoryTask( target.getId(), targetPomFile );
454 // explicitly update only if metadata-updater consumer is not enabled!
455 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
457 updateProjectMetadata( target, targetDir, lastUpdatedTimestamp, timestamp, newBuildNumber,
458 fixChecksums, artifactTransferRequest );
464 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
465 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
466 + artifactTransferRequest.getTargetRepositoryId() + "\'";
467 log.debug("copyArtifact {}", msg);
470 catch ( RepositoryException e )
472 log.error( "RepositoryException: {}", e.getMessage(), e );
473 throw new ArchivaRestServiceException( e.getMessage(), e );
475 catch ( RepositoryAdminException e )
477 log.error( "RepositoryAdminException: {}", e.getMessage(), e );
478 throw new ArchivaRestServiceException( e.getMessage(), e );
480 catch ( IOException e )
482 log.error( "IOException: {}", e.getMessage(), e );
483 throw new ArchivaRestServiceException( e.getMessage(), e );
488 private void queueRepositoryTask( String repositoryId, StorageAsset localFile )
491 RepositoryTask task = new RepositoryTask();
492 task.setRepositoryId( repositoryId );
493 task.setResourceFile( localFile );
494 task.setUpdateRelatedArtifacts( true );
495 //task.setScanAll( true );
499 scheduler.queueTask( task );
501 catch ( TaskQueueException e )
503 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
504 + "'].", localFile.getName());
508 private ArchivaRepositoryMetadata getMetadata( StorageAsset metadataFile )
509 throws RepositoryMetadataException
511 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
512 if ( metadataFile.exists() )
516 metadata = MavenMetadataReader.read( metadataFile.getFilePath() );
518 catch (XMLException e )
520 throw new RepositoryMetadataException( e.getMessage(), e );
526 private StorageAsset getMetadata( RepositoryStorage storage, String targetPath )
528 return storage.getAsset( targetPath + "/" + MetadataTools.MAVEN_METADATA );
533 * Copies the asset to the new target.
535 private void copyFile(StorageAsset sourceFile, StorageAsset targetPath, boolean fixChecksums)
539 StorageUtil.copyAsset( sourceFile, targetPath, true );
542 fixChecksums( targetPath );
546 private void fixChecksums( StorageAsset file )
548 Path destinationFile = file.getFilePath();
549 if (destinationFile!=null)
551 ChecksummedFile checksum = new ChecksummedFile( destinationFile );
552 checksum.fixChecksums( algorithms );
556 private void updateProjectMetadata( RepositoryStorage storage, StorageAsset targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
557 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
558 throws RepositoryMetadataException
560 List<String> availableVersions = new ArrayList<>();
561 String latestVersion = artifactTransferRequest.getVersion();
563 StorageAsset projectDir = targetPath.getParent();
564 StorageAsset projectMetadataFile = storage.getAsset( projectDir.getPath()+"/"+MetadataTools.MAVEN_METADATA );
566 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
568 if ( projectMetadataFile.exists() )
570 availableVersions = projectMetadata.getAvailableVersions();
572 Collections.sort( availableVersions, VersionComparator.getInstance() );
574 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
576 availableVersions.add( artifactTransferRequest.getVersion() );
579 latestVersion = availableVersions.get( availableVersions.size() - 1 );
583 availableVersions.add( artifactTransferRequest.getVersion() );
585 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
586 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
589 if ( projectMetadata.getGroupId() == null )
591 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
594 if ( projectMetadata.getArtifactId() == null )
596 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
599 projectMetadata.setLatestVersion( latestVersion );
600 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
601 projectMetadata.setAvailableVersions( availableVersions );
603 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
605 projectMetadata.setReleasedVersion( latestVersion );
608 try(OutputStreamWriter writer = new OutputStreamWriter(projectMetadataFile.getWriteStream(true))) {
609 RepositoryMetadataWriter.write(projectMetadata, writer);
610 } catch (IOException e) {
611 throw new RepositoryMetadataException(e);
616 fixChecksums( projectMetadataFile );
621 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
622 throws ArchivaRestServiceException
624 // if not a generic we can use the standard way to delete artifact
625 if ( !VersionUtil.isGenericSnapshot( version ) )
627 Artifact artifact = new Artifact( namespace, projectId, version );
628 artifact.setRepositoryId( repositoryId );
629 artifact.setContext( repositoryId );
630 return deleteArtifact( artifact );
633 if ( StringUtils.isEmpty( repositoryId ) )
635 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
638 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
640 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
643 if ( StringUtils.isEmpty( namespace ) )
645 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
648 if ( StringUtils.isEmpty( projectId ) )
650 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
653 if ( StringUtils.isEmpty( version ) )
655 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
658 RepositorySession repositorySession = null;
661 repositorySession = repositorySessionFactory.createSession();
663 catch ( MetadataRepositoryException e )
665 e.printStackTrace( );
670 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
672 VersionedReference ref = new VersionedReference();
673 ref.setArtifactId( projectId );
674 ref.setGroupId( namespace );
675 ref.setVersion( version );
677 repository.deleteVersion( ref );
680 ProjectReference projectReference = new ProjectReference();
681 projectReference.setGroupId( namespace );
682 projectReference.setArtifactId( projectId );
684 repository.getVersions( )
687 ArtifactReference artifactReference = new ArtifactReference();
688 artifactReference.setGroupId( namespace );
689 artifactReference.setArtifactId( projectId );
690 artifactReference.setVersion( version );
692 MetadataRepository metadataRepository = repositorySession.getRepository();
694 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
695 log.debug( "related: {}", related );
696 for ( ArtifactReference artifactRef : related )
698 repository.deleteArtifact( artifactRef );
701 Collection<ArtifactMetadata> artifacts =
702 metadataRepository.getArtifacts(repositorySession , repositoryId, namespace, projectId, version );
704 for ( ArtifactMetadata artifactMetadata : artifacts )
706 metadataRepository.removeTimestampedArtifact(repositorySession , artifactMetadata, version );
709 metadataRepository.removeProjectVersion(repositorySession , repositoryId, namespace, projectId, version );
711 catch ( MetadataRepositoryException e )
713 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
715 catch ( MetadataResolutionException e )
717 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
719 catch ( RepositoryException e )
721 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
727 repositorySession.save();
728 } catch (MetadataSessionException e) {
729 log.error("Session save failed {}", e.getMessage());
732 repositorySession.close();
739 public Boolean deleteArtifact( Artifact artifact )
740 throws ArchivaRestServiceException
743 String repositoryId = artifact.getContext();
744 // some rest call can use context or repositoryId
746 if ( StringUtils.isEmpty( repositoryId ) )
748 repositoryId = artifact.getRepositoryId();
750 if ( StringUtils.isEmpty( repositoryId ) )
752 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
755 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
757 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
760 if ( artifact == null )
762 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
765 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
767 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
770 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
772 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
775 // TODO more control on artifact fields
777 boolean snapshotVersion =
778 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
780 RepositorySession repositorySession = null;
783 repositorySession = repositorySessionFactory.createSession();
785 catch ( MetadataRepositoryException e )
787 e.printStackTrace( );
791 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
793 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
794 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
795 fmt.setTimeZone( timezone );
796 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
798 VersionedReference ref = new VersionedReference();
799 ref.setArtifactId( artifact.getArtifactId() );
800 ref.setGroupId( artifact.getGroupId() );
801 ref.setVersion( artifact.getVersion() );
803 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
805 ArtifactReference artifactReference = new ArtifactReference();
806 artifactReference.setArtifactId( artifact.getArtifactId() );
807 artifactReference.setGroupId( artifact.getGroupId() );
808 artifactReference.setVersion( artifact.getVersion() );
809 artifactReference.setClassifier( artifact.getClassifier() );
810 artifactReference.setType( artifact.getPackaging() );
812 MetadataRepository metadataRepository = repositorySession.getRepository();
814 String path = repository.toMetadataPath( ref );
816 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
818 if ( StringUtils.isBlank( artifact.getPackaging() ) )
820 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
824 repository.deleteArtifact( artifactReference );
830 int index = path.lastIndexOf( '/' );
831 path = path.substring( 0, index );
832 StorageAsset targetPath = repo.getAsset( path );
834 if ( !targetPath.exists() )
836 //throw new ContentNotFoundException(
837 // artifact.getNamespace() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
838 log.warn( "targetPath {} not found skip file deletion", targetPath );
842 // TODO: this should be in the storage mechanism so that it is all tied together
843 // delete from file system
844 if ( !snapshotVersion )
846 repository.deleteVersion( ref );
850 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
851 log.debug( "related: {}", related );
852 for ( ArtifactReference artifactRef : related )
854 repository.deleteArtifact( artifactRef );
856 StorageAsset metadataFile = getMetadata( repo, targetPath.getPath() );
857 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
859 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
862 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
864 if ( snapshotVersion )
866 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
868 metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
869 artifact.getArtifactId(), baseVersion );
874 metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
875 artifact.getArtifactId(), artifact.getVersion() );
878 log.debug( "artifacts: {}", artifacts );
880 if ( artifacts.isEmpty() )
882 if ( !snapshotVersion )
884 // verify metata repository doesn't contains anymore the version
885 Collection<String> projectVersions =
886 metadataRepository.getProjectVersions(repositorySession , repositoryId,
887 artifact.getGroupId(), artifact.getArtifactId() );
889 if ( projectVersions.contains( artifact.getVersion() ) )
891 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
892 metadataRepository.removeProjectVersion(repositorySession , repositoryId,
893 artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() );
899 for ( ArtifactMetadata artifactMetadata : artifacts )
902 // TODO: mismatch between artifact (snapshot) version and project (base) version here
903 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
905 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
907 if ( StringUtils.isBlank( artifact.getPackaging() ) )
909 throw new ArchivaRestServiceException(
910 "You must configure a type/packaging when using classifier", 400, null );
912 // cleanup facet which contains classifier information
913 MavenArtifactFacet mavenArtifactFacet =
914 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
916 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
918 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
919 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
920 artifact.getVersion();
921 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
922 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
923 metadataRepository.removeFacetFromArtifact(repositorySession , repositoryId, groupId, artifactId,
924 version, mavenArtifactFacetToCompare );
925 repositorySession.save();
931 if ( snapshotVersion )
933 metadataRepository.removeTimestampedArtifact(repositorySession ,
934 artifactMetadata, VersionUtil.getBaseVersion( artifact.getVersion() ) );
938 metadataRepository.removeArtifact(repositorySession ,
939 artifactMetadata.getRepositoryId(),
940 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
941 artifact.getVersion(), artifactMetadata.getId() );
944 // TODO: move into the metadata repository proper - need to differentiate attachment of
945 // repository metadata to an artifact
946 for ( RepositoryListener listener : listeners )
948 listener.deleteArtifact( metadataRepository, repository.getId(),
949 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
950 artifactMetadata.getVersion(), artifactMetadata.getId() );
953 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
957 catch ( ContentNotFoundException e )
959 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
961 catch ( RepositoryNotFoundException e )
963 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
965 catch ( RepositoryException e )
967 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
969 catch (MetadataResolutionException | MetadataSessionException e )
971 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
973 catch ( MetadataRepositoryException e )
975 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
981 repositorySession.save();
982 } catch (MetadataSessionException e) {
983 log.error("Could not save sesion {}", e.getMessage());
986 repositorySession.close();
992 public Boolean deleteGroupId( String groupId, String repositoryId )
993 throws ArchivaRestServiceException
995 if ( StringUtils.isEmpty( repositoryId ) )
997 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1000 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1002 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1005 if ( StringUtils.isEmpty( groupId ) )
1007 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1010 RepositorySession repositorySession = null;
1013 repositorySession = repositorySessionFactory.createSession();
1015 catch ( MetadataRepositoryException e )
1017 e.printStackTrace( );
1022 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1024 repository.deleteGroupId( groupId );
1026 MetadataRepository metadataRepository = repositorySession.getRepository();
1028 metadataRepository.removeNamespace(repositorySession , repositoryId, groupId );
1030 // just invalidate cache entry
1031 String cacheKey = repositoryId + "-" + groupId;
1032 namespacesCache.remove( cacheKey );
1033 namespacesCache.remove( repositoryId );
1035 repositorySession.save();
1037 catch (MetadataRepositoryException | MetadataSessionException e )
1039 log.error( e.getMessage(), e );
1040 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1042 catch ( RepositoryException e )
1044 log.error( e.getMessage(), e );
1045 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1050 repositorySession.close();
1056 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1057 throws ArchivaRestServiceException
1059 if ( StringUtils.isEmpty( repositoryId ) )
1061 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1064 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1066 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1069 if ( StringUtils.isEmpty( groupId ) )
1071 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1074 if ( StringUtils.isEmpty( projectId ) )
1076 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1079 RepositorySession repositorySession = null;
1082 repositorySession = repositorySessionFactory.createSession();
1084 catch ( MetadataRepositoryException e )
1086 e.printStackTrace( );
1091 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1093 repository.deleteProject( groupId, projectId );
1095 catch ( ContentNotFoundException e )
1097 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1099 catch ( RepositoryException e )
1101 log.error( e.getMessage(), e );
1102 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1108 MetadataRepository metadataRepository = repositorySession.getRepository();
1110 metadataRepository.removeProject(repositorySession , repositoryId, groupId, projectId );
1112 repositorySession.save();
1114 catch (MetadataRepositoryException | MetadataSessionException e )
1116 log.error( e.getMessage(), e );
1117 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1122 repositorySession.close();
1129 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1130 throws ArchivaRestServiceException
1133 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1137 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1139 catch ( ArchivaSecurityException e )
1141 throw new ArchivaRestServiceException( e.getMessage(),
1142 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1147 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1148 throws ArchivaRestServiceException
1150 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1153 return repoScanner.scan( repositoryRegistry.getManagedRepository( repositoryId ), sinceWhen );
1155 catch ( RepositoryScannerException e )
1157 log.error( e.getMessage(), e );
1158 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1163 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1167 private void updateMetadata( ArchivaRepositoryMetadata metadata, StorageAsset metadataFile, Date lastUpdatedTimestamp,
1169 throws RepositoryMetadataException
1171 List<String> availableVersions = new ArrayList<>();
1172 String latestVersion = "";
1174 if ( metadataFile.exists() )
1176 if ( metadata.getAvailableVersions() != null )
1178 availableVersions = metadata.getAvailableVersions();
1180 if ( availableVersions.size() > 0 )
1182 Collections.sort( availableVersions, VersionComparator.getInstance() );
1184 if ( availableVersions.contains( artifact.getVersion() ) )
1186 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1188 if ( availableVersions.size() > 0 )
1190 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1196 if ( metadata.getGroupId() == null )
1198 metadata.setGroupId( artifact.getGroupId() );
1200 if ( metadata.getArtifactId() == null )
1202 metadata.setArtifactId( artifact.getArtifactId() );
1205 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1207 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1208 artifact.getVersion() ) )
1210 metadata.setReleasedVersion( latestVersion );
1214 metadata.setLatestVersion( latestVersion );
1215 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1216 metadata.setAvailableVersions( availableVersions );
1218 try (OutputStreamWriter writer = new OutputStreamWriter(metadataFile.getWriteStream(true))) {
1219 RepositoryMetadataWriter.write(metadata, writer);
1220 } catch (IOException e) {
1221 throw new RepositoryMetadataException(e);
1223 ChecksummedFile checksum = new ChecksummedFile( metadataFile.getFilePath() );
1224 checksum.fixChecksums( algorithms );
1228 public StringList getRunningRemoteDownloadIds()
1230 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1233 public RepositorySessionFactory getRepositorySessionFactory()
1235 return repositorySessionFactory;
1238 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1240 this.repositorySessionFactory = repositorySessionFactory;
1243 public List<RepositoryListener> getListeners()
1248 public void setListeners( List<RepositoryListener> listeners )
1250 this.listeners = listeners;
1253 public ArchivaAdministration getArchivaAdministration()
1255 return archivaAdministration;
1258 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1260 this.archivaAdministration = archivaAdministration;