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.admin.model.beans.ManagedRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.checksum.ChecksumAlgorithm;
27 import org.apache.archiva.checksum.ChecksummedFile;
28 import org.apache.archiva.common.utils.VersionComparator;
29 import org.apache.archiva.common.utils.VersionUtil;
30 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
31 import org.apache.archiva.maven2.model.Artifact;
32 import org.apache.archiva.metadata.model.ArtifactMetadata;
33 import org.apache.archiva.metadata.model.facets.AuditEvent;
34 import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
35 import org.apache.archiva.metadata.repository.MetadataRepository;
36 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
37 import org.apache.archiva.metadata.repository.MetadataResolutionException;
38 import org.apache.archiva.metadata.repository.RepositorySession;
39 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
40 import org.apache.archiva.model.ArchivaRepositoryMetadata;
41 import org.apache.archiva.model.ArtifactReference;
42 import org.apache.archiva.model.VersionedReference;
43 import org.apache.archiva.redback.authentication.AuthenticationResult;
44 import org.apache.archiva.redback.authorization.AuthorizationException;
45 import org.apache.archiva.redback.components.cache.Cache;
46 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
47 import org.apache.archiva.redback.system.DefaultSecuritySession;
48 import org.apache.archiva.redback.system.SecuritySession;
49 import org.apache.archiva.redback.system.SecuritySystem;
50 import org.apache.archiva.redback.users.User;
51 import org.apache.archiva.redback.users.UserManagerException;
52 import org.apache.archiva.redback.users.UserNotFoundException;
53 import org.apache.archiva.repository.ContentNotFoundException;
54 import org.apache.archiva.repository.ManagedRepositoryContent;
55 import org.apache.archiva.repository.RepositoryException;
56 import org.apache.archiva.repository.RepositoryNotFoundException;
57 import org.apache.archiva.repository.RepositoryRegistry;
58 import org.apache.archiva.repository.events.RepositoryListener;
59 import org.apache.archiva.repository.metadata.MetadataTools;
60 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
62 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
63 import org.apache.archiva.repository.scanner.RepositoryScanner;
64 import org.apache.archiva.repository.scanner.RepositoryScannerException;
65 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
66 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
67 import org.apache.archiva.rest.api.model.StringList;
68 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
69 import org.apache.archiva.rest.api.services.RepositoriesService;
70 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
71 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
72 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
73 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
74 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
75 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
76 import org.apache.archiva.security.ArchivaSecurityException;
77 import org.apache.archiva.security.common.ArchivaRoleConstants;
78 import org.apache.archiva.xml.XMLException;
79 import org.apache.commons.io.FilenameUtils;
80 import org.apache.commons.lang.StringUtils;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import org.springframework.beans.factory.annotation.Autowired;
84 import org.springframework.stereotype.Service;
86 import javax.inject.Inject;
87 import javax.inject.Named;
88 import javax.ws.rs.core.Response;
89 import java.io.IOException;
90 import java.nio.file.FileSystems;
91 import java.nio.file.Files;
92 import java.nio.file.Path;
93 import java.nio.file.Paths;
94 import java.nio.file.StandardCopyOption;
95 import java.text.DateFormat;
96 import java.text.SimpleDateFormat;
97 import java.util.ArrayList;
98 import java.util.Arrays;
99 import java.util.Calendar;
100 import java.util.Collection;
101 import java.util.Collections;
102 import java.util.Date;
103 import java.util.List;
104 import java.util.Set;
105 import java.util.TimeZone;
108 * @author Olivier Lamy
111 @Service("repositoriesService#rest")
112 public class DefaultRepositoriesService
113 extends AbstractRestService
114 implements RepositoriesService
116 private Logger log = LoggerFactory.getLogger( getClass() );
119 @Named(value = "taskExecutor#indexing")
120 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
123 private RepositoryRegistry repositoryRegistry;
126 private ManagedRepositoryAdmin managedRepositoryAdmin;
130 private SecuritySystem securitySystem;
133 @Named(value = "archivaTaskScheduler#repository")
134 private ArchivaTaskScheduler scheduler;
137 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
140 @Named(value = "repositorySessionFactory")
141 protected RepositorySessionFactory repositorySessionFactory;
144 @Autowired(required = false)
145 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
148 private RepositoryScanner repoScanner;
151 * Cache used for namespaces
154 @Named(value = "cache#namespaces")
155 private Cache<String, Collection<String>> namespacesCache;
157 private List<ChecksumAlgorithm> algorithms = Arrays.asList(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 );
160 public Boolean scanRepository( String repositoryId, boolean fullScan )
162 return doScanRepository( repositoryId, fullScan );
166 public Boolean alreadyScanning( String repositoryId )
168 // check queue first to make sure it doesn't get dequeued between calls
169 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
173 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
175 if ( scan.getRepository().getId().equals( repositoryId ) )
184 public Boolean removeScanningTaskFromQueue( String repositoryId )
186 RepositoryTask task = new RepositoryTask();
187 task.setRepositoryId( repositoryId );
190 return repositoryTaskScheduler.unQueueTask( task );
192 catch ( TaskQueueException e )
194 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
199 private ManagedRepositoryContent getManagedRepositoryContent(String id) throws RepositoryException
201 org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( id );
203 throw new RepositoryException( "Repository not found "+id );
205 return repo.getContent();
209 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
210 throws ArchivaRestServiceException
216 org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository( repositoryId );
219 ArtifactIndexingTask task =
220 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, repository.getIndexingContext() );
222 task.setExecuteOnEntireRepo( true );
223 task.setOnlyUpdate( !fullScan );
225 archivaIndexingTaskExecutor.executeTask( task );
227 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
231 catch ( Exception e )
233 log.error( e.getMessage(), e );
234 throw new ArchivaRestServiceException( e.getMessage(), e );
239 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
240 throws ArchivaRestServiceException
244 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
246 catch ( DownloadRemoteIndexException e )
248 log.error( e.getMessage(), e );
249 throw new ArchivaRestServiceException( e.getMessage(), e );
255 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
256 throws ArchivaRestServiceException
259 String userName = getAuditInformation().getUser().getUsername();
260 if ( StringUtils.isBlank( userName ) )
262 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
265 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
267 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
270 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
272 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
275 ManagedRepository source = null;
278 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
280 catch ( RepositoryAdminException e )
282 throw new ArchivaRestServiceException( e.getMessage(), e );
285 if ( source == null )
287 throw new ArchivaRestServiceException(
288 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
291 ManagedRepository target = null;
294 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
296 catch ( RepositoryAdminException e )
298 throw new ArchivaRestServiceException( e.getMessage(), e );
301 if ( target == null )
303 throw new ArchivaRestServiceException(
304 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
307 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
309 throw new ArchivaRestServiceException( "groupId is mandatory", null );
312 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
314 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
317 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
319 throw new ArchivaRestServiceException( "version is mandatory", null );
322 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
324 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
327 // end check parameters
332 user = securitySystem.getUserManager().findUser( userName );
334 catch ( UserNotFoundException e )
336 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
338 catch ( UserManagerException e )
340 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
343 // check karma on source : read
344 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
345 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
349 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
350 artifactTransferRequest.getRepositoryId() );
353 throw new ArchivaRestServiceException(
354 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
357 catch ( AuthorizationException e )
359 log.error( "error reading permission: {}", e.getMessage(), e );
360 throw new ArchivaRestServiceException( e.getMessage(), e );
363 // check karma on target: write
367 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
368 artifactTransferRequest.getTargetRepositoryId() );
371 throw new ArchivaRestServiceException(
372 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
375 catch ( AuthorizationException e )
377 log.error( "error reading permission: {}", e.getMessage(), e );
378 throw new ArchivaRestServiceException( e.getMessage(), e );
381 // sounds good we can continue !
383 ArtifactReference artifactReference = new ArtifactReference();
384 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
385 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
386 artifactReference.setVersion( artifactTransferRequest.getVersion() );
387 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
388 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
389 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
394 ManagedRepositoryContent sourceRepository =
395 getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
397 String artifactSourcePath = sourceRepository.toPath( artifactReference );
399 if ( StringUtils.isEmpty( artifactSourcePath ) )
401 log.error( "cannot find artifact {}", artifactTransferRequest );
402 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
406 Path artifactFile = Paths.get( source.getLocation(), artifactSourcePath );
408 if ( !Files.exists(artifactFile) )
410 log.error( "cannot find artifact {}", artifactTransferRequest );
411 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
415 ManagedRepositoryContent targetRepository =
416 getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
418 String artifactPath = targetRepository.toPath( artifactReference );
420 int lastIndex = artifactPath.lastIndexOf( '/' );
422 String path = artifactPath.substring( 0, lastIndex );
423 Path targetPath = Paths.get( target.getLocation(), path );
425 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
426 int newBuildNumber = 1;
427 String timestamp = null;
429 Path versionMetadataFile = targetPath.resolve( MetadataTools.MAVEN_METADATA );
430 /* unused */ getMetadata( versionMetadataFile );
432 if ( !Files.exists(targetPath) )
434 Files.createDirectories( targetPath );
437 String filename = artifactPath.substring( lastIndex + 1 );
439 boolean fixChecksums =
440 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
442 Path targetFile = targetPath.resolve( filename );
443 if ( Files.exists(targetFile) && target.isBlockRedeployments() )
445 throw new ArchivaRestServiceException(
446 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
447 + " and redeployment blocked", null
452 copyFile( artifactFile, targetPath, filename, fixChecksums );
453 queueRepositoryTask( target.getId(), targetFile );
456 // copy source pom to target repo
457 String pomFilename = filename;
458 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
460 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
462 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
464 Path pomFile = Paths.get(source.getLocation(),
465 artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ,
468 if ( pomFile != null && Files.size( pomFile ) > 0 )
470 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
471 queueRepositoryTask( target.getId(), targetPath.resolve( pomFilename ) );
476 // explicitly update only if metadata-updater consumer is not enabled!
477 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
479 updateProjectMetadata( targetPath.toAbsolutePath().toString(), lastUpdatedTimestamp, timestamp, newBuildNumber,
480 fixChecksums, artifactTransferRequest );
486 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
487 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
488 + artifactTransferRequest.getTargetRepositoryId() + "\'";
489 log.debug("copyArtifact {}", msg);
492 catch ( RepositoryException e )
494 log.error( "RepositoryException: {}", e.getMessage(), e );
495 throw new ArchivaRestServiceException( e.getMessage(), e );
497 catch ( RepositoryAdminException e )
499 log.error( "RepositoryAdminException: {}", e.getMessage(), e );
500 throw new ArchivaRestServiceException( e.getMessage(), e );
502 catch ( IOException e )
504 log.error( "IOException: {}", e.getMessage(), e );
505 throw new ArchivaRestServiceException( e.getMessage(), e );
510 private void queueRepositoryTask( String repositoryId, Path localFile )
512 RepositoryTask task = new RepositoryTask();
513 task.setRepositoryId( repositoryId );
514 task.setResourceFile( localFile );
515 task.setUpdateRelatedArtifacts( true );
516 //task.setScanAll( true );
520 scheduler.queueTask( task );
522 catch ( TaskQueueException e )
524 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
525 + "'].", localFile.getFileName());
529 private ArchivaRepositoryMetadata getMetadata( Path metadataFile )
530 throws RepositoryMetadataException
532 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
533 if ( Files.exists(metadataFile) )
537 metadata = MavenMetadataReader.read( metadataFile );
539 catch ( XMLException e )
541 throw new RepositoryMetadataException( e.getMessage(), e );
547 private Path getMetadata( String targetPath )
549 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( FileSystems.getDefault().getSeparator() ));
551 return Paths.get( artifactPath, MetadataTools.MAVEN_METADATA );
554 private void copyFile( Path sourceFile, Path targetPath, String targetFilename, boolean fixChecksums )
557 Files.copy( sourceFile, targetPath.resolve( targetFilename ), StandardCopyOption.REPLACE_EXISTING,
558 StandardCopyOption.COPY_ATTRIBUTES );
562 fixChecksums( targetPath.resolve( targetFilename ) );
566 private void fixChecksums( Path file )
568 ChecksummedFile checksum = new ChecksummedFile( file );
569 checksum.fixChecksums( algorithms );
572 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
573 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
574 throws RepositoryMetadataException
576 List<String> availableVersions = new ArrayList<>();
577 String latestVersion = artifactTransferRequest.getVersion();
579 Path projectDir = Paths.get( targetPath ).getParent();
580 Path projectMetadataFile = projectDir.resolve( MetadataTools.MAVEN_METADATA );
582 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
584 if ( Files.exists(projectMetadataFile) )
586 availableVersions = projectMetadata.getAvailableVersions();
588 Collections.sort( availableVersions, VersionComparator.getInstance() );
590 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
592 availableVersions.add( artifactTransferRequest.getVersion() );
595 latestVersion = availableVersions.get( availableVersions.size() - 1 );
599 availableVersions.add( artifactTransferRequest.getVersion() );
601 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
602 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
605 if ( projectMetadata.getGroupId() == null )
607 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
610 if ( projectMetadata.getArtifactId() == null )
612 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
615 projectMetadata.setLatestVersion( latestVersion );
616 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
617 projectMetadata.setAvailableVersions( availableVersions );
619 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
621 projectMetadata.setReleasedVersion( latestVersion );
624 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile);
628 fixChecksums( projectMetadataFile );
633 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
634 throws ArchivaRestServiceException
636 // if not a generic we can use the standard way to delete artifact
637 if ( !VersionUtil.isGenericSnapshot( version ) )
639 Artifact artifact = new Artifact( namespace, projectId, version );
640 artifact.setRepositoryId( repositoryId );
641 artifact.setContext( repositoryId );
642 return deleteArtifact( artifact );
645 if ( StringUtils.isEmpty( repositoryId ) )
647 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
650 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
652 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
655 if ( StringUtils.isEmpty( namespace ) )
657 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
660 if ( StringUtils.isEmpty( projectId ) )
662 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
665 if ( StringUtils.isEmpty( version ) )
667 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
670 RepositorySession repositorySession = repositorySessionFactory.createSession();
674 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
676 VersionedReference ref = new VersionedReference();
677 ref.setArtifactId( projectId );
678 ref.setGroupId( namespace );
679 ref.setVersion( version );
681 repository.deleteVersion( ref );
684 ProjectReference projectReference = new ProjectReference();
685 projectReference.setGroupId( namespace );
686 projectReference.setArtifactId( projectId );
688 repository.getVersions( )
691 ArtifactReference artifactReference = new ArtifactReference();
692 artifactReference.setGroupId( namespace );
693 artifactReference.setArtifactId( projectId );
694 artifactReference.setVersion( version );
696 MetadataRepository metadataRepository = repositorySession.getRepository();
698 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
699 log.debug( "related: {}", related );
700 for ( ArtifactReference artifactRef : related )
702 repository.deleteArtifact( artifactRef );
705 Collection<ArtifactMetadata> artifacts =
706 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
708 for ( ArtifactMetadata artifactMetadata : artifacts )
710 metadataRepository.removeArtifact( artifactMetadata, version );
713 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
715 catch ( MetadataRepositoryException e )
717 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
719 catch ( MetadataResolutionException e )
721 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
723 catch ( RepositoryException e )
725 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
730 repositorySession.save();
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 = repositorySessionFactory.createSession();
783 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
785 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
786 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
787 fmt.setTimeZone( timezone );
788 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
790 VersionedReference ref = new VersionedReference();
791 ref.setArtifactId( artifact.getArtifactId() );
792 ref.setGroupId( artifact.getGroupId() );
793 ref.setVersion( artifact.getVersion() );
795 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
797 ArtifactReference artifactReference = new ArtifactReference();
798 artifactReference.setArtifactId( artifact.getArtifactId() );
799 artifactReference.setGroupId( artifact.getGroupId() );
800 artifactReference.setVersion( artifact.getVersion() );
801 artifactReference.setClassifier( artifact.getClassifier() );
802 artifactReference.setType( artifact.getPackaging() );
804 MetadataRepository metadataRepository = repositorySession.getRepository();
806 String path = repository.toMetadataPath( ref );
808 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
810 if ( StringUtils.isBlank( artifact.getPackaging() ) )
812 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
816 repository.deleteArtifact( artifactReference );
822 int index = path.lastIndexOf( '/' );
823 path = path.substring( 0, index );
824 Path targetPath = Paths.get( repoConfig.getLocation(), path );
826 if ( !Files.exists(targetPath) )
828 //throw new ContentNotFoundException(
829 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
830 log.warn( "targetPath {} not found skip file deletion", targetPath );
833 // TODO: this should be in the storage mechanism so that it is all tied together
834 // delete from file system
835 if ( !snapshotVersion )
837 repository.deleteVersion( ref );
841 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
842 log.debug( "related: {}", related );
843 for ( ArtifactReference artifactRef : related )
845 repository.deleteArtifact( artifactRef );
848 Path metadataFile = getMetadata( targetPath.toAbsolutePath().toString() );
849 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
851 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
853 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
855 if ( snapshotVersion )
857 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
859 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
865 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
866 artifact.getVersion() );
869 log.debug( "artifacts: {}", artifacts );
871 if ( artifacts.isEmpty() )
873 if ( !snapshotVersion )
875 // verify metata repository doesn't contains anymore the version
876 Collection<String> projectVersions =
877 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
878 artifact.getArtifactId() );
880 if ( projectVersions.contains( artifact.getVersion() ) )
882 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
883 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
884 artifact.getArtifactId(), artifact.getVersion() );
890 for ( ArtifactMetadata artifactMetadata : artifacts )
893 // TODO: mismatch between artifact (snapshot) version and project (base) version here
894 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
896 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
898 if ( StringUtils.isBlank( artifact.getPackaging() ) )
900 throw new ArchivaRestServiceException(
901 "You must configure a type/packaging when using classifier", 400, null );
903 // cleanup facet which contains classifier information
904 MavenArtifactFacet mavenArtifactFacet =
905 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
907 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
909 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
910 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
911 artifact.getVersion();
912 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
913 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
914 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
915 mavenArtifactFacetToCompare );
916 metadataRepository.save();
922 if ( snapshotVersion )
924 metadataRepository.removeArtifact( artifactMetadata,
925 VersionUtil.getBaseVersion( artifact.getVersion() ) );
929 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
930 artifactMetadata.getNamespace(),
931 artifactMetadata.getProject(), artifact.getVersion(),
932 artifactMetadata.getId() );
935 // TODO: move into the metadata repository proper - need to differentiate attachment of
936 // repository metadata to an artifact
937 for ( RepositoryListener listener : listeners )
939 listener.deleteArtifact( metadataRepository, repository.getId(),
940 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
941 artifactMetadata.getVersion(), artifactMetadata.getId() );
944 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
948 catch ( ContentNotFoundException e )
950 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
952 catch ( RepositoryNotFoundException e )
954 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
956 catch ( RepositoryException e )
958 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
960 catch ( MetadataResolutionException e )
962 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
964 catch ( MetadataRepositoryException e )
966 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
968 catch ( RepositoryAdminException e )
970 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
975 repositorySession.save();
977 repositorySession.close();
983 public Boolean deleteGroupId( String groupId, String repositoryId )
984 throws ArchivaRestServiceException
986 if ( StringUtils.isEmpty( repositoryId ) )
988 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
991 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
993 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
996 if ( StringUtils.isEmpty( groupId ) )
998 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1001 RepositorySession repositorySession = repositorySessionFactory.createSession();
1005 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1007 repository.deleteGroupId( groupId );
1009 MetadataRepository metadataRepository = repositorySession.getRepository();
1011 metadataRepository.removeNamespace( repositoryId, groupId );
1013 // just invalidate cache entry
1014 String cacheKey = repositoryId + "-" + groupId;
1015 namespacesCache.remove( cacheKey );
1016 namespacesCache.remove( repositoryId );
1018 metadataRepository.save();
1020 catch ( MetadataRepositoryException e )
1022 log.error( e.getMessage(), e );
1023 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1025 catch ( RepositoryException e )
1027 log.error( e.getMessage(), e );
1028 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1033 repositorySession.close();
1039 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1040 throws ArchivaRestServiceException
1042 if ( StringUtils.isEmpty( repositoryId ) )
1044 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1047 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1049 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1052 if ( StringUtils.isEmpty( groupId ) )
1054 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1057 if ( StringUtils.isEmpty( projectId ) )
1059 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1062 RepositorySession repositorySession = repositorySessionFactory.createSession();
1066 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1068 repository.deleteProject( groupId, projectId );
1070 catch ( ContentNotFoundException e )
1072 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1074 catch ( RepositoryException e )
1076 log.error( e.getMessage(), e );
1077 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1083 MetadataRepository metadataRepository = repositorySession.getRepository();
1085 metadataRepository.removeProject( repositoryId, groupId, projectId );
1087 metadataRepository.save();
1089 catch ( MetadataRepositoryException e )
1091 log.error( e.getMessage(), e );
1092 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1097 repositorySession.close();
1104 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1105 throws ArchivaRestServiceException
1108 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1112 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1114 catch ( ArchivaSecurityException e )
1116 throw new ArchivaRestServiceException( e.getMessage(),
1117 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1122 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1123 throws ArchivaRestServiceException
1125 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1128 return repoScanner.scan( repositoryRegistry.getManagedRepository( repositoryId ), sinceWhen );
1130 catch ( RepositoryScannerException e )
1132 log.error( e.getMessage(), e );
1133 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1138 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1142 private void updateMetadata( ArchivaRepositoryMetadata metadata, Path metadataFile, Date lastUpdatedTimestamp,
1144 throws RepositoryMetadataException
1146 List<String> availableVersions = new ArrayList<>();
1147 String latestVersion = "";
1149 if ( Files.exists(metadataFile) )
1151 if ( metadata.getAvailableVersions() != null )
1153 availableVersions = metadata.getAvailableVersions();
1155 if ( availableVersions.size() > 0 )
1157 Collections.sort( availableVersions, VersionComparator.getInstance() );
1159 if ( availableVersions.contains( artifact.getVersion() ) )
1161 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1163 if ( availableVersions.size() > 0 )
1165 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1171 if ( metadata.getGroupId() == null )
1173 metadata.setGroupId( artifact.getGroupId() );
1175 if ( metadata.getArtifactId() == null )
1177 metadata.setArtifactId( artifact.getArtifactId() );
1180 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1182 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1183 artifact.getVersion() ) )
1185 metadata.setReleasedVersion( latestVersion );
1189 metadata.setLatestVersion( latestVersion );
1190 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1191 metadata.setAvailableVersions( availableVersions );
1193 RepositoryMetadataWriter.write( metadata, metadataFile);
1194 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1195 checksum.fixChecksums( algorithms );
1199 public StringList getRunningRemoteDownloadIds()
1201 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1204 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1206 return managedRepositoryAdmin;
1209 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1211 this.managedRepositoryAdmin = managedRepositoryAdmin;
1214 public RepositorySessionFactory getRepositorySessionFactory()
1216 return repositorySessionFactory;
1219 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1221 this.repositorySessionFactory = repositorySessionFactory;
1224 public List<RepositoryListener> getListeners()
1229 public void setListeners( List<RepositoryListener> listeners )
1231 this.listeners = listeners;
1234 public ArchivaAdministration getArchivaAdministration()
1236 return archivaAdministration;
1239 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1241 this.archivaAdministration = archivaAdministration;