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.plexusbridge.PlexusSisuBridge;
29 import org.apache.archiva.common.utils.VersionComparator;
30 import org.apache.archiva.common.utils.VersionUtil;
31 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
32 import org.apache.archiva.maven2.model.Artifact;
33 import org.apache.archiva.metadata.model.ArtifactMetadata;
34 import org.apache.archiva.metadata.model.facets.AuditEvent;
35 import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
36 import org.apache.archiva.metadata.repository.MetadataRepository;
37 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
38 import org.apache.archiva.metadata.repository.MetadataResolutionException;
39 import org.apache.archiva.metadata.repository.RepositorySession;
40 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
41 import org.apache.archiva.model.ArchivaRepositoryMetadata;
42 import org.apache.archiva.model.ArtifactReference;
43 import org.apache.archiva.model.VersionedReference;
44 import org.apache.archiva.redback.authentication.AuthenticationResult;
45 import org.apache.archiva.redback.authorization.AuthorizationException;
46 import org.apache.archiva.redback.components.cache.Cache;
47 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
48 import org.apache.archiva.redback.system.DefaultSecuritySession;
49 import org.apache.archiva.redback.system.SecuritySession;
50 import org.apache.archiva.redback.system.SecuritySystem;
51 import org.apache.archiva.redback.users.User;
52 import org.apache.archiva.redback.users.UserManagerException;
53 import org.apache.archiva.redback.users.UserNotFoundException;
54 import org.apache.archiva.repository.ContentNotFoundException;
55 import org.apache.archiva.repository.ManagedRepositoryContent;
56 import org.apache.archiva.repository.RepositoryException;
57 import org.apache.archiva.repository.RepositoryNotFoundException;
58 import org.apache.archiva.repository.RepositoryRegistry;
59 import org.apache.archiva.repository.events.RepositoryListener;
60 import org.apache.archiva.repository.metadata.MetadataTools;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
62 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
63 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
64 import org.apache.archiva.repository.scanner.RepositoryScanner;
65 import org.apache.archiva.repository.scanner.RepositoryScannerException;
66 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
67 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
68 import org.apache.archiva.rest.api.model.StringList;
69 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
70 import org.apache.archiva.rest.api.services.RepositoriesService;
71 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
72 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
73 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
74 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
75 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
76 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
77 import org.apache.archiva.security.ArchivaSecurityException;
78 import org.apache.archiva.security.common.ArchivaRoleConstants;
79 import org.apache.archiva.xml.XMLException;
80 import org.apache.commons.io.FilenameUtils;
81 import org.apache.commons.lang.StringUtils;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.springframework.beans.factory.annotation.Autowired;
85 import org.springframework.stereotype.Service;
87 import javax.inject.Inject;
88 import javax.inject.Named;
89 import javax.ws.rs.core.Response;
90 import java.io.IOException;
91 import java.nio.file.FileSystems;
92 import java.nio.file.Files;
93 import java.nio.file.Path;
94 import java.nio.file.Paths;
95 import java.nio.file.StandardCopyOption;
96 import java.text.DateFormat;
97 import java.text.SimpleDateFormat;
98 import java.util.ArrayList;
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;
129 private PlexusSisuBridge plexusSisuBridge;
132 private SecuritySystem securitySystem;
135 @Named(value = "archivaTaskScheduler#repository")
136 private ArchivaTaskScheduler scheduler;
139 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
142 @Named(value = "repositorySessionFactory")
143 protected RepositorySessionFactory repositorySessionFactory;
146 @Autowired(required = false)
147 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
150 private RepositoryScanner repoScanner;
153 * Cache used for namespaces
156 @Named(value = "cache#namespaces")
157 private Cache<String, Collection<String>> namespacesCache;
159 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
162 public Boolean scanRepository( String repositoryId, boolean fullScan )
164 return doScanRepository( repositoryId, fullScan );
168 public Boolean alreadyScanning( String repositoryId )
170 // check queue first to make sure it doesn't get dequeued between calls
171 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
175 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
177 if ( scan.getRepository().getId().equals( repositoryId ) )
186 public Boolean removeScanningTaskFromQueue( String repositoryId )
188 RepositoryTask task = new RepositoryTask();
189 task.setRepositoryId( repositoryId );
192 return repositoryTaskScheduler.unQueueTask( task );
194 catch ( TaskQueueException e )
196 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
201 private ManagedRepositoryContent getManagedRepositoryContent(String id) throws RepositoryException
203 org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( id );
205 throw new RepositoryException( "Repository not found "+id );
207 return repo.getContent();
211 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
212 throws ArchivaRestServiceException
218 org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository( repositoryId );
221 ArtifactIndexingTask task =
222 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, repository.getIndexingContext() );
224 task.setExecuteOnEntireRepo( true );
225 task.setOnlyUpdate( !fullScan );
227 archivaIndexingTaskExecutor.executeTask( task );
229 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
233 catch ( Exception e )
235 log.error( e.getMessage(), e );
236 throw new ArchivaRestServiceException( e.getMessage(), e );
241 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
242 throws ArchivaRestServiceException
246 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
248 catch ( DownloadRemoteIndexException e )
250 log.error( e.getMessage(), e );
251 throw new ArchivaRestServiceException( e.getMessage(), e );
257 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
258 throws ArchivaRestServiceException
261 String userName = getAuditInformation().getUser().getUsername();
262 if ( StringUtils.isBlank( userName ) )
264 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
267 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
269 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
272 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
274 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
277 ManagedRepository source = null;
280 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
282 catch ( RepositoryAdminException e )
284 throw new ArchivaRestServiceException( e.getMessage(), e );
287 if ( source == null )
289 throw new ArchivaRestServiceException(
290 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
293 ManagedRepository target = null;
296 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
298 catch ( RepositoryAdminException e )
300 throw new ArchivaRestServiceException( e.getMessage(), e );
303 if ( target == null )
305 throw new ArchivaRestServiceException(
306 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
309 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
311 throw new ArchivaRestServiceException( "groupId is mandatory", null );
314 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
316 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
319 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
321 throw new ArchivaRestServiceException( "version is mandatory", null );
324 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
326 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
329 // end check parameters
334 user = securitySystem.getUserManager().findUser( userName );
336 catch ( UserNotFoundException e )
338 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
340 catch ( UserManagerException e )
342 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
345 // check karma on source : read
346 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
347 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
351 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
352 artifactTransferRequest.getRepositoryId() );
355 throw new ArchivaRestServiceException(
356 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
359 catch ( AuthorizationException e )
361 log.error( "error reading permission: {}", e.getMessage(), e );
362 throw new ArchivaRestServiceException( e.getMessage(), e );
365 // check karma on target: write
369 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
370 artifactTransferRequest.getTargetRepositoryId() );
373 throw new ArchivaRestServiceException(
374 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
377 catch ( AuthorizationException e )
379 log.error( "error reading permission: {}", e.getMessage(), e );
380 throw new ArchivaRestServiceException( e.getMessage(), e );
383 // sounds good we can continue !
385 ArtifactReference artifactReference = new ArtifactReference();
386 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
387 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
388 artifactReference.setVersion( artifactTransferRequest.getVersion() );
389 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
390 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
391 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
396 ManagedRepositoryContent sourceRepository =
397 getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
399 String artifactSourcePath = sourceRepository.toPath( artifactReference );
401 if ( StringUtils.isEmpty( artifactSourcePath ) )
403 log.error( "cannot find artifact {}", artifactTransferRequest );
404 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
408 Path artifactFile = Paths.get( source.getLocation(), artifactSourcePath );
410 if ( !Files.exists(artifactFile) )
412 log.error( "cannot find artifact {}", artifactTransferRequest );
413 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
417 ManagedRepositoryContent targetRepository =
418 getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
420 String artifactPath = targetRepository.toPath( artifactReference );
422 int lastIndex = artifactPath.lastIndexOf( '/' );
424 String path = artifactPath.substring( 0, lastIndex );
425 Path targetPath = Paths.get( target.getLocation(), path );
427 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
428 int newBuildNumber = 1;
429 String timestamp = null;
431 Path versionMetadataFile = targetPath.resolve( MetadataTools.MAVEN_METADATA );
432 /* unused */ getMetadata( versionMetadataFile );
434 if ( !Files.exists(targetPath) )
436 Files.createDirectories( targetPath );
439 String filename = artifactPath.substring( lastIndex + 1 );
441 boolean fixChecksums =
442 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
444 Path targetFile = targetPath.resolve( filename );
445 if ( Files.exists(targetFile) && target.isBlockRedeployments() )
447 throw new ArchivaRestServiceException(
448 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
449 + " and redeployment blocked", null
454 copyFile( artifactFile, targetPath, filename, fixChecksums );
455 queueRepositoryTask( target.getId(), targetFile );
458 // copy source pom to target repo
459 String pomFilename = filename;
460 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
462 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
464 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
466 Path pomFile = Paths.get(source.getLocation(),
467 artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ,
470 if ( pomFile != null && Files.size( pomFile ) > 0 )
472 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
473 queueRepositoryTask( target.getId(), targetPath.resolve( pomFilename ) );
478 // explicitly update only if metadata-updater consumer is not enabled!
479 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
481 updateProjectMetadata( targetPath.toAbsolutePath().toString(), lastUpdatedTimestamp, timestamp, newBuildNumber,
482 fixChecksums, artifactTransferRequest );
488 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
489 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
490 + artifactTransferRequest.getTargetRepositoryId() + "\'";
491 log.debug("copyArtifact {}", msg);
494 catch ( RepositoryException e )
496 log.error( "RepositoryException: {}", e.getMessage(), e );
497 throw new ArchivaRestServiceException( e.getMessage(), e );
499 catch ( RepositoryAdminException e )
501 log.error( "RepositoryAdminException: {}", e.getMessage(), e );
502 throw new ArchivaRestServiceException( e.getMessage(), e );
504 catch ( IOException e )
506 log.error( "IOException: {}", e.getMessage(), e );
507 throw new ArchivaRestServiceException( e.getMessage(), e );
512 private void queueRepositoryTask( String repositoryId, Path localFile )
514 RepositoryTask task = new RepositoryTask();
515 task.setRepositoryId( repositoryId );
516 task.setResourceFile( localFile );
517 task.setUpdateRelatedArtifacts( true );
518 //task.setScanAll( true );
522 scheduler.queueTask( task );
524 catch ( TaskQueueException e )
526 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
527 + "'].", localFile.getFileName());
531 private ArchivaRepositoryMetadata getMetadata( Path metadataFile )
532 throws RepositoryMetadataException
534 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
535 if ( Files.exists(metadataFile) )
539 metadata = MavenMetadataReader.read( metadataFile );
541 catch ( XMLException e )
543 throw new RepositoryMetadataException( e.getMessage(), e );
549 private Path getMetadata( String targetPath )
551 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( FileSystems.getDefault().getSeparator() ));
553 return Paths.get( artifactPath, MetadataTools.MAVEN_METADATA );
556 private void copyFile( Path sourceFile, Path targetPath, String targetFilename, boolean fixChecksums )
559 Files.copy( sourceFile, targetPath.resolve( targetFilename ), StandardCopyOption.REPLACE_EXISTING,
560 StandardCopyOption.COPY_ATTRIBUTES );
564 fixChecksums( targetPath.resolve( targetFilename ) );
568 private void fixChecksums( Path file )
570 ChecksummedFile checksum = new ChecksummedFile( file );
571 checksum.fixChecksums( algorithms );
574 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
575 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
576 throws RepositoryMetadataException
578 List<String> availableVersions = new ArrayList<>();
579 String latestVersion = artifactTransferRequest.getVersion();
581 Path projectDir = Paths.get( targetPath ).getParent();
582 Path projectMetadataFile = projectDir.resolve( MetadataTools.MAVEN_METADATA );
584 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
586 if ( Files.exists(projectMetadataFile) )
588 availableVersions = projectMetadata.getAvailableVersions();
590 Collections.sort( availableVersions, VersionComparator.getInstance() );
592 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
594 availableVersions.add( artifactTransferRequest.getVersion() );
597 latestVersion = availableVersions.get( availableVersions.size() - 1 );
601 availableVersions.add( artifactTransferRequest.getVersion() );
603 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
604 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
607 if ( projectMetadata.getGroupId() == null )
609 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
612 if ( projectMetadata.getArtifactId() == null )
614 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
617 projectMetadata.setLatestVersion( latestVersion );
618 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
619 projectMetadata.setAvailableVersions( availableVersions );
621 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
623 projectMetadata.setReleasedVersion( latestVersion );
626 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile);
630 fixChecksums( projectMetadataFile );
635 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
636 throws ArchivaRestServiceException
638 // if not a generic we can use the standard way to delete artifact
639 if ( !VersionUtil.isGenericSnapshot( version ) )
641 Artifact artifact = new Artifact( namespace, projectId, version );
642 artifact.setRepositoryId( repositoryId );
643 artifact.setContext( repositoryId );
644 return deleteArtifact( artifact );
647 if ( StringUtils.isEmpty( repositoryId ) )
649 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
652 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
654 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
657 if ( StringUtils.isEmpty( namespace ) )
659 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
662 if ( StringUtils.isEmpty( projectId ) )
664 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
667 if ( StringUtils.isEmpty( version ) )
669 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
672 RepositorySession repositorySession = repositorySessionFactory.createSession();
676 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
678 VersionedReference ref = new VersionedReference();
679 ref.setArtifactId( projectId );
680 ref.setGroupId( namespace );
681 ref.setVersion( version );
683 repository.deleteVersion( ref );
686 ProjectReference projectReference = new ProjectReference();
687 projectReference.setGroupId( namespace );
688 projectReference.setArtifactId( projectId );
690 repository.getVersions( )
693 ArtifactReference artifactReference = new ArtifactReference();
694 artifactReference.setGroupId( namespace );
695 artifactReference.setArtifactId( projectId );
696 artifactReference.setVersion( version );
698 MetadataRepository metadataRepository = repositorySession.getRepository();
700 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
701 log.debug( "related: {}", related );
702 for ( ArtifactReference artifactRef : related )
704 repository.deleteArtifact( artifactRef );
707 Collection<ArtifactMetadata> artifacts =
708 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
710 for ( ArtifactMetadata artifactMetadata : artifacts )
712 metadataRepository.removeArtifact( artifactMetadata, version );
715 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
717 catch ( MetadataRepositoryException e )
719 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
721 catch ( MetadataResolutionException e )
723 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
725 catch ( RepositoryException e )
727 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
732 repositorySession.save();
734 repositorySession.close();
741 public Boolean deleteArtifact( Artifact artifact )
742 throws ArchivaRestServiceException
745 String repositoryId = artifact.getContext();
746 // some rest call can use context or repositoryId
748 if ( StringUtils.isEmpty( repositoryId ) )
750 repositoryId = artifact.getRepositoryId();
752 if ( StringUtils.isEmpty( repositoryId ) )
754 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
757 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
759 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
762 if ( artifact == null )
764 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
767 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
769 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
772 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
774 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
777 // TODO more control on artifact fields
779 boolean snapshotVersion =
780 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
782 RepositorySession repositorySession = repositorySessionFactory.createSession();
785 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
787 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
788 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
789 fmt.setTimeZone( timezone );
790 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
792 VersionedReference ref = new VersionedReference();
793 ref.setArtifactId( artifact.getArtifactId() );
794 ref.setGroupId( artifact.getGroupId() );
795 ref.setVersion( artifact.getVersion() );
797 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
799 ArtifactReference artifactReference = new ArtifactReference();
800 artifactReference.setArtifactId( artifact.getArtifactId() );
801 artifactReference.setGroupId( artifact.getGroupId() );
802 artifactReference.setVersion( artifact.getVersion() );
803 artifactReference.setClassifier( artifact.getClassifier() );
804 artifactReference.setType( artifact.getPackaging() );
806 MetadataRepository metadataRepository = repositorySession.getRepository();
808 String path = repository.toMetadataPath( ref );
810 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
812 if ( StringUtils.isBlank( artifact.getPackaging() ) )
814 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
818 repository.deleteArtifact( artifactReference );
824 int index = path.lastIndexOf( '/' );
825 path = path.substring( 0, index );
826 Path targetPath = Paths.get( repoConfig.getLocation(), path );
828 if ( !Files.exists(targetPath) )
830 //throw new ContentNotFoundException(
831 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
832 log.warn( "targetPath {} not found skip file deletion", targetPath );
835 // TODO: this should be in the storage mechanism so that it is all tied together
836 // delete from file system
837 if ( !snapshotVersion )
839 repository.deleteVersion( ref );
843 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
844 log.debug( "related: {}", related );
845 for ( ArtifactReference artifactRef : related )
847 repository.deleteArtifact( artifactRef );
850 Path metadataFile = getMetadata( targetPath.toAbsolutePath().toString() );
851 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
853 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
855 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
857 if ( snapshotVersion )
859 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
861 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
867 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
868 artifact.getVersion() );
871 log.debug( "artifacts: {}", artifacts );
873 if ( artifacts.isEmpty() )
875 if ( !snapshotVersion )
877 // verify metata repository doesn't contains anymore the version
878 Collection<String> projectVersions =
879 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
880 artifact.getArtifactId() );
882 if ( projectVersions.contains( artifact.getVersion() ) )
884 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
885 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
886 artifact.getArtifactId(), artifact.getVersion() );
892 for ( ArtifactMetadata artifactMetadata : artifacts )
895 // TODO: mismatch between artifact (snapshot) version and project (base) version here
896 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
898 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
900 if ( StringUtils.isBlank( artifact.getPackaging() ) )
902 throw new ArchivaRestServiceException(
903 "You must configure a type/packaging when using classifier", 400, null );
905 // cleanup facet which contains classifier information
906 MavenArtifactFacet mavenArtifactFacet =
907 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
909 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
911 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
912 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
913 artifact.getVersion();
914 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
915 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
916 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
917 mavenArtifactFacetToCompare );
918 metadataRepository.save();
924 if ( snapshotVersion )
926 metadataRepository.removeArtifact( artifactMetadata,
927 VersionUtil.getBaseVersion( artifact.getVersion() ) );
931 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
932 artifactMetadata.getNamespace(),
933 artifactMetadata.getProject(), artifact.getVersion(),
934 artifactMetadata.getId() );
937 // TODO: move into the metadata repository proper - need to differentiate attachment of
938 // repository metadata to an artifact
939 for ( RepositoryListener listener : listeners )
941 listener.deleteArtifact( metadataRepository, repository.getId(),
942 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
943 artifactMetadata.getVersion(), artifactMetadata.getId() );
946 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
950 catch ( ContentNotFoundException e )
952 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
954 catch ( RepositoryNotFoundException e )
956 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
958 catch ( RepositoryException e )
960 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
962 catch ( MetadataResolutionException e )
964 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
966 catch ( MetadataRepositoryException e )
968 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
970 catch ( RepositoryAdminException e )
972 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
977 repositorySession.save();
979 repositorySession.close();
985 public Boolean deleteGroupId( String groupId, String repositoryId )
986 throws ArchivaRestServiceException
988 if ( StringUtils.isEmpty( repositoryId ) )
990 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
993 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
995 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
998 if ( StringUtils.isEmpty( groupId ) )
1000 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1003 RepositorySession repositorySession = repositorySessionFactory.createSession();
1007 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1009 repository.deleteGroupId( groupId );
1011 MetadataRepository metadataRepository = repositorySession.getRepository();
1013 metadataRepository.removeNamespace( repositoryId, groupId );
1015 // just invalidate cache entry
1016 String cacheKey = repositoryId + "-" + groupId;
1017 namespacesCache.remove( cacheKey );
1018 namespacesCache.remove( repositoryId );
1020 metadataRepository.save();
1022 catch ( MetadataRepositoryException e )
1024 log.error( e.getMessage(), e );
1025 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1027 catch ( RepositoryException e )
1029 log.error( e.getMessage(), e );
1030 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1035 repositorySession.close();
1041 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1042 throws ArchivaRestServiceException
1044 if ( StringUtils.isEmpty( repositoryId ) )
1046 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1049 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1051 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1054 if ( StringUtils.isEmpty( groupId ) )
1056 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1059 if ( StringUtils.isEmpty( projectId ) )
1061 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1064 RepositorySession repositorySession = repositorySessionFactory.createSession();
1068 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1070 repository.deleteProject( groupId, projectId );
1072 catch ( ContentNotFoundException e )
1074 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1076 catch ( RepositoryException e )
1078 log.error( e.getMessage(), e );
1079 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1085 MetadataRepository metadataRepository = repositorySession.getRepository();
1087 metadataRepository.removeProject( repositoryId, groupId, projectId );
1089 metadataRepository.save();
1091 catch ( MetadataRepositoryException e )
1093 log.error( e.getMessage(), e );
1094 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1099 repositorySession.close();
1106 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1107 throws ArchivaRestServiceException
1110 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1114 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1116 catch ( ArchivaSecurityException e )
1118 throw new ArchivaRestServiceException( e.getMessage(),
1119 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1124 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1125 throws ArchivaRestServiceException
1127 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1130 return repoScanner.scan( repositoryRegistry.getManagedRepository( repositoryId ), sinceWhen );
1132 catch ( RepositoryScannerException e )
1134 log.error( e.getMessage(), e );
1135 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1140 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1144 private void updateMetadata( ArchivaRepositoryMetadata metadata, Path metadataFile, Date lastUpdatedTimestamp,
1146 throws RepositoryMetadataException
1148 List<String> availableVersions = new ArrayList<>();
1149 String latestVersion = "";
1151 if ( Files.exists(metadataFile) )
1153 if ( metadata.getAvailableVersions() != null )
1155 availableVersions = metadata.getAvailableVersions();
1157 if ( availableVersions.size() > 0 )
1159 Collections.sort( availableVersions, VersionComparator.getInstance() );
1161 if ( availableVersions.contains( artifact.getVersion() ) )
1163 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1165 if ( availableVersions.size() > 0 )
1167 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1173 if ( metadata.getGroupId() == null )
1175 metadata.setGroupId( artifact.getGroupId() );
1177 if ( metadata.getArtifactId() == null )
1179 metadata.setArtifactId( artifact.getArtifactId() );
1182 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1184 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1185 artifact.getVersion() ) )
1187 metadata.setReleasedVersion( latestVersion );
1191 metadata.setLatestVersion( latestVersion );
1192 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1193 metadata.setAvailableVersions( availableVersions );
1195 RepositoryMetadataWriter.write( metadata, metadataFile);
1196 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1197 checksum.fixChecksums( algorithms );
1201 public StringList getRunningRemoteDownloadIds()
1203 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1206 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1208 return managedRepositoryAdmin;
1211 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1213 this.managedRepositoryAdmin = managedRepositoryAdmin;
1216 public RepositorySessionFactory getRepositorySessionFactory()
1218 return repositorySessionFactory;
1221 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1223 this.repositorySessionFactory = repositorySessionFactory;
1226 public List<RepositoryListener> getListeners()
1231 public void setListeners( List<RepositoryListener> listeners )
1233 this.listeners = listeners;
1236 public ArchivaAdministration getArchivaAdministration()
1238 return archivaAdministration;
1241 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1243 this.archivaAdministration = archivaAdministration;