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.*;
37 import org.apache.archiva.model.ArchivaRepositoryMetadata;
38 import org.apache.archiva.model.ArtifactReference;
39 import org.apache.archiva.model.VersionedReference;
40 import org.apache.archiva.redback.authentication.AuthenticationResult;
41 import org.apache.archiva.redback.authorization.AuthorizationException;
42 import org.apache.archiva.redback.components.cache.Cache;
43 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
44 import org.apache.archiva.redback.system.DefaultSecuritySession;
45 import org.apache.archiva.redback.system.SecuritySession;
46 import org.apache.archiva.redback.system.SecuritySystem;
47 import org.apache.archiva.redback.users.User;
48 import org.apache.archiva.redback.users.UserManagerException;
49 import org.apache.archiva.redback.users.UserNotFoundException;
50 import org.apache.archiva.repository.*;
51 import org.apache.archiva.repository.events.RepositoryListener;
52 import org.apache.archiva.repository.metadata.MetadataTools;
53 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
54 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
55 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
56 import org.apache.archiva.repository.scanner.RepositoryScanner;
57 import org.apache.archiva.repository.scanner.RepositoryScannerException;
58 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
59 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
60 import org.apache.archiva.rest.api.model.StringList;
61 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
62 import org.apache.archiva.rest.api.services.RepositoriesService;
63 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
64 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
65 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
66 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
67 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
68 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
69 import org.apache.archiva.security.ArchivaSecurityException;
70 import org.apache.archiva.security.common.ArchivaRoleConstants;
71 import org.apache.archiva.xml.XMLException;
72 import org.apache.commons.io.FilenameUtils;
73 import org.apache.commons.lang.StringUtils;
74 import org.apache.maven.index.context.IndexingContext;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.stereotype.Service;
80 import javax.inject.Inject;
81 import javax.inject.Named;
82 import javax.ws.rs.core.Response;
83 import java.io.IOException;
84 import java.nio.file.*;
85 import java.text.DateFormat;
86 import java.text.SimpleDateFormat;
90 * @author Olivier Lamy
93 @Service("repositoriesService#rest")
94 public class DefaultRepositoriesService
95 extends AbstractRestService
96 implements RepositoriesService
98 private Logger log = LoggerFactory.getLogger( getClass() );
101 @Named(value = "taskExecutor#indexing")
102 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
105 private ManagedRepositoryAdmin managedRepositoryAdmin;
108 private PlexusSisuBridge plexusSisuBridge;
111 private SecuritySystem securitySystem;
114 private RepositoryContentFactory repositoryFactory;
117 @Named(value = "archivaTaskScheduler#repository")
118 private ArchivaTaskScheduler scheduler;
121 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
124 @Named(value = "repositorySessionFactory")
125 protected RepositorySessionFactory repositorySessionFactory;
128 @Autowired(required = false)
129 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
132 private RepositoryScanner repoScanner;
135 * Cache used for namespaces
138 @Named(value = "cache#namespaces")
139 private Cache<String, Collection<String>> namespacesCache;
141 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
144 public Boolean scanRepository( String repositoryId, boolean fullScan )
146 return doScanRepository( repositoryId, fullScan );
150 public Boolean alreadyScanning( String repositoryId )
152 // check queue first to make sure it doesn't get dequeued between calls
153 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
157 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
159 if ( scan.getRepository().getId().equals( repositoryId ) )
168 public Boolean removeScanningTaskFromQueue( String repositoryId )
170 RepositoryTask task = new RepositoryTask();
171 task.setRepositoryId( repositoryId );
174 return repositoryTaskScheduler.unQueueTask( task );
176 catch ( TaskQueueException e )
178 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
184 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
185 throws ArchivaRestServiceException
190 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
192 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
194 ArtifactIndexingTask task =
195 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
197 task.setExecuteOnEntireRepo( true );
198 task.setOnlyUpdate( !fullScan );
200 archivaIndexingTaskExecutor.executeTask( task );
202 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
206 catch ( Exception e )
208 log.error( e.getMessage(), e );
209 throw new ArchivaRestServiceException( e.getMessage(), e );
214 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
215 throws ArchivaRestServiceException
219 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
221 catch ( DownloadRemoteIndexException e )
223 log.error( e.getMessage(), e );
224 throw new ArchivaRestServiceException( e.getMessage(), e );
230 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
231 throws ArchivaRestServiceException
234 String userName = getAuditInformation().getUser().getUsername();
235 if ( StringUtils.isBlank( userName ) )
237 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
240 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
242 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
245 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
247 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
250 ManagedRepository source = null;
253 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
255 catch ( RepositoryAdminException e )
257 throw new ArchivaRestServiceException( e.getMessage(), e );
260 if ( source == null )
262 throw new ArchivaRestServiceException(
263 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
266 ManagedRepository target = null;
269 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
271 catch ( RepositoryAdminException e )
273 throw new ArchivaRestServiceException( e.getMessage(), e );
276 if ( target == null )
278 throw new ArchivaRestServiceException(
279 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
282 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
284 throw new ArchivaRestServiceException( "groupId is mandatory", null );
287 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
289 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
292 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
294 throw new ArchivaRestServiceException( "version is mandatory", null );
297 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
299 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
302 // end check parameters
307 user = securitySystem.getUserManager().findUser( userName );
309 catch ( UserNotFoundException e )
311 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
313 catch ( UserManagerException e )
315 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
318 // check karma on source : read
319 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
320 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
324 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
325 artifactTransferRequest.getRepositoryId() );
328 throw new ArchivaRestServiceException(
329 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
332 catch ( AuthorizationException e )
334 log.error( "error reading permission: {}", e.getMessage(), e );
335 throw new ArchivaRestServiceException( e.getMessage(), e );
338 // check karma on target: write
342 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
343 artifactTransferRequest.getTargetRepositoryId() );
346 throw new ArchivaRestServiceException(
347 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
350 catch ( AuthorizationException e )
352 log.error( "error reading permission: {}", e.getMessage(), e );
353 throw new ArchivaRestServiceException( e.getMessage(), e );
356 // sounds good we can continue !
358 ArtifactReference artifactReference = new ArtifactReference();
359 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
360 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
361 artifactReference.setVersion( artifactTransferRequest.getVersion() );
362 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
363 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
364 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
369 ManagedRepositoryContent sourceRepository =
370 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
372 String artifactSourcePath = sourceRepository.toPath( artifactReference );
374 if ( StringUtils.isEmpty( artifactSourcePath ) )
376 log.error( "cannot find artifact {}", artifactTransferRequest );
377 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
381 Path artifactFile = Paths.get( source.getLocation(), artifactSourcePath );
383 if ( !Files.exists(artifactFile) )
385 log.error( "cannot find artifact {}", artifactTransferRequest );
386 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
390 ManagedRepositoryContent targetRepository =
391 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
393 String artifactPath = targetRepository.toPath( artifactReference );
395 int lastIndex = artifactPath.lastIndexOf( '/' );
397 String path = artifactPath.substring( 0, lastIndex );
398 Path targetPath = Paths.get( target.getLocation(), path );
400 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
401 int newBuildNumber = 1;
402 String timestamp = null;
404 Path versionMetadataFile = targetPath.resolve( MetadataTools.MAVEN_METADATA );
405 /* unused */ getMetadata( versionMetadataFile );
407 if ( !Files.exists(targetPath) )
409 Files.createDirectories( targetPath );
412 String filename = artifactPath.substring( lastIndex + 1 );
414 boolean fixChecksums =
415 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
417 Path targetFile = targetPath.resolve( filename );
418 if ( Files.exists(targetFile) && target.isBlockRedeployments() )
420 throw new ArchivaRestServiceException(
421 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
422 + " and redeployment blocked", null
427 copyFile( artifactFile, targetPath, filename, fixChecksums );
428 queueRepositoryTask( target.getId(), targetFile );
431 // copy source pom to target repo
432 String pomFilename = filename;
433 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
435 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
437 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
439 Path pomFile = Paths.get(source.getLocation(),
440 artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ,
443 if ( pomFile != null && Files.size( pomFile ) > 0 )
445 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
446 queueRepositoryTask( target.getId(), targetPath.resolve( pomFilename ) );
451 // explicitly update only if metadata-updater consumer is not enabled!
452 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
454 updateProjectMetadata( targetPath.toAbsolutePath().toString(), lastUpdatedTimestamp, timestamp, newBuildNumber,
455 fixChecksums, artifactTransferRequest );
461 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
462 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
463 + artifactTransferRequest.getTargetRepositoryId() + "\'";
464 log.debug("copyArtifact {}", msg);
467 catch ( RepositoryException e )
469 log.error( "RepositoryException: {}", e.getMessage(), e );
470 throw new ArchivaRestServiceException( e.getMessage(), e );
472 catch ( RepositoryAdminException e )
474 log.error( "RepositoryAdminException: {}", e.getMessage(), e );
475 throw new ArchivaRestServiceException( e.getMessage(), e );
477 catch ( IOException e )
479 log.error( "IOException: {}", e.getMessage(), e );
480 throw new ArchivaRestServiceException( e.getMessage(), e );
485 private void queueRepositoryTask( String repositoryId, Path localFile )
487 RepositoryTask task = new RepositoryTask();
488 task.setRepositoryId( repositoryId );
489 task.setResourceFile( localFile );
490 task.setUpdateRelatedArtifacts( true );
491 //task.setScanAll( true );
495 scheduler.queueTask( task );
497 catch ( TaskQueueException e )
499 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
500 + "'].", localFile.getFileName());
504 private ArchivaRepositoryMetadata getMetadata( Path metadataFile )
505 throws RepositoryMetadataException
507 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
508 if ( Files.exists(metadataFile) )
512 metadata = MavenMetadataReader.read( metadataFile );
514 catch ( XMLException e )
516 throw new RepositoryMetadataException( e.getMessage(), e );
522 private Path getMetadata( String targetPath )
524 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( FileSystems.getDefault().getSeparator() ));
526 return Paths.get( artifactPath, MetadataTools.MAVEN_METADATA );
529 private void copyFile( Path sourceFile, Path targetPath, String targetFilename, boolean fixChecksums )
532 Files.copy( sourceFile, targetPath.resolve( targetFilename ), StandardCopyOption.REPLACE_EXISTING,
533 StandardCopyOption.COPY_ATTRIBUTES );
537 fixChecksums( targetPath.resolve( targetFilename ) );
541 private void fixChecksums( Path file )
543 ChecksummedFile checksum = new ChecksummedFile( file );
544 checksum.fixChecksums( algorithms );
547 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
548 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
549 throws RepositoryMetadataException
551 List<String> availableVersions = new ArrayList<>();
552 String latestVersion = artifactTransferRequest.getVersion();
554 Path projectDir = Paths.get( targetPath ).getParent();
555 Path projectMetadataFile = projectDir.resolve( MetadataTools.MAVEN_METADATA );
557 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
559 if ( Files.exists(projectMetadataFile) )
561 availableVersions = projectMetadata.getAvailableVersions();
563 Collections.sort( availableVersions, VersionComparator.getInstance() );
565 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
567 availableVersions.add( artifactTransferRequest.getVersion() );
570 latestVersion = availableVersions.get( availableVersions.size() - 1 );
574 availableVersions.add( artifactTransferRequest.getVersion() );
576 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
577 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
580 if ( projectMetadata.getGroupId() == null )
582 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
585 if ( projectMetadata.getArtifactId() == null )
587 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
590 projectMetadata.setLatestVersion( latestVersion );
591 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
592 projectMetadata.setAvailableVersions( availableVersions );
594 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
596 projectMetadata.setReleasedVersion( latestVersion );
599 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile);
603 fixChecksums( projectMetadataFile );
608 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
609 throws ArchivaRestServiceException
611 // if not a generic we can use the standard way to delete artifact
612 if ( !VersionUtil.isGenericSnapshot( version ) )
614 Artifact artifact = new Artifact( namespace, projectId, version );
615 artifact.setRepositoryId( repositoryId );
616 artifact.setContext( repositoryId );
617 return deleteArtifact( artifact );
620 if ( StringUtils.isEmpty( repositoryId ) )
622 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
625 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
627 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
630 if ( StringUtils.isEmpty( namespace ) )
632 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
635 if ( StringUtils.isEmpty( projectId ) )
637 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
640 if ( StringUtils.isEmpty( version ) )
642 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
645 RepositorySession repositorySession = repositorySessionFactory.createSession();
649 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
651 VersionedReference ref = new VersionedReference();
652 ref.setArtifactId( projectId );
653 ref.setGroupId( namespace );
654 ref.setVersion( version );
656 repository.deleteVersion( ref );
659 ProjectReference projectReference = new ProjectReference();
660 projectReference.setGroupId( namespace );
661 projectReference.setArtifactId( projectId );
663 repository.getVersions( )
666 ArtifactReference artifactReference = new ArtifactReference();
667 artifactReference.setGroupId( namespace );
668 artifactReference.setArtifactId( projectId );
669 artifactReference.setVersion( version );
671 MetadataRepository metadataRepository = repositorySession.getRepository();
673 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
674 log.debug( "related: {}", related );
675 for ( ArtifactReference artifactRef : related )
677 repository.deleteArtifact( artifactRef );
680 Collection<ArtifactMetadata> artifacts =
681 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
683 for ( ArtifactMetadata artifactMetadata : artifacts )
685 metadataRepository.removeArtifact( artifactMetadata, version );
688 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
690 catch ( MetadataRepositoryException e )
692 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
694 catch ( MetadataResolutionException e )
696 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
698 catch ( RepositoryException e )
700 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
705 repositorySession.save();
707 repositorySession.close();
714 public Boolean deleteArtifact( Artifact artifact )
715 throws ArchivaRestServiceException
718 String repositoryId = artifact.getContext();
719 // some rest call can use context or repositoryId
721 if ( StringUtils.isEmpty( repositoryId ) )
723 repositoryId = artifact.getRepositoryId();
725 if ( StringUtils.isEmpty( repositoryId ) )
727 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
730 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
732 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
735 if ( artifact == null )
737 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
740 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
742 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
745 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
747 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
750 // TODO more control on artifact fields
752 boolean snapshotVersion =
753 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
755 RepositorySession repositorySession = repositorySessionFactory.createSession();
758 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
760 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
761 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
762 fmt.setTimeZone( timezone );
763 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
765 VersionedReference ref = new VersionedReference();
766 ref.setArtifactId( artifact.getArtifactId() );
767 ref.setGroupId( artifact.getGroupId() );
768 ref.setVersion( artifact.getVersion() );
770 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
772 ArtifactReference artifactReference = new ArtifactReference();
773 artifactReference.setArtifactId( artifact.getArtifactId() );
774 artifactReference.setGroupId( artifact.getGroupId() );
775 artifactReference.setVersion( artifact.getVersion() );
776 artifactReference.setClassifier( artifact.getClassifier() );
777 artifactReference.setType( artifact.getPackaging() );
779 MetadataRepository metadataRepository = repositorySession.getRepository();
781 String path = repository.toMetadataPath( ref );
783 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
785 if ( StringUtils.isBlank( artifact.getPackaging() ) )
787 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
791 repository.deleteArtifact( artifactReference );
797 int index = path.lastIndexOf( '/' );
798 path = path.substring( 0, index );
799 Path targetPath = Paths.get( repoConfig.getLocation(), path );
801 if ( !Files.exists(targetPath) )
803 //throw new ContentNotFoundException(
804 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
805 log.warn( "targetPath {} not found skip file deletion", targetPath );
808 // TODO: this should be in the storage mechanism so that it is all tied together
809 // delete from file system
810 if ( !snapshotVersion )
812 repository.deleteVersion( ref );
816 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
817 log.debug( "related: {}", related );
818 for ( ArtifactReference artifactRef : related )
820 repository.deleteArtifact( artifactRef );
823 Path metadataFile = getMetadata( targetPath.toAbsolutePath().toString() );
824 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
826 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
828 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
830 if ( snapshotVersion )
832 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
834 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
840 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
841 artifact.getVersion() );
844 log.debug( "artifacts: {}", artifacts );
846 if ( artifacts.isEmpty() )
848 if ( !snapshotVersion )
850 // verify metata repository doesn't contains anymore the version
851 Collection<String> projectVersions =
852 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
853 artifact.getArtifactId() );
855 if ( projectVersions.contains( artifact.getVersion() ) )
857 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
858 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
859 artifact.getArtifactId(), artifact.getVersion() );
865 for ( ArtifactMetadata artifactMetadata : artifacts )
868 // TODO: mismatch between artifact (snapshot) version and project (base) version here
869 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
871 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
873 if ( StringUtils.isBlank( artifact.getPackaging() ) )
875 throw new ArchivaRestServiceException(
876 "You must configure a type/packaging when using classifier", 400, null );
878 // cleanup facet which contains classifier information
879 MavenArtifactFacet mavenArtifactFacet =
880 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
882 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
884 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
885 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
886 artifact.getVersion();
887 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
888 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
889 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
890 mavenArtifactFacetToCompare );
891 metadataRepository.save();
897 if ( snapshotVersion )
899 metadataRepository.removeArtifact( artifactMetadata,
900 VersionUtil.getBaseVersion( artifact.getVersion() ) );
904 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
905 artifactMetadata.getNamespace(),
906 artifactMetadata.getProject(), artifact.getVersion(),
907 artifactMetadata.getId() );
910 // TODO: move into the metadata repository proper - need to differentiate attachment of
911 // repository metadata to an artifact
912 for ( RepositoryListener listener : listeners )
914 listener.deleteArtifact( metadataRepository, repository.getId(),
915 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
916 artifactMetadata.getVersion(), artifactMetadata.getId() );
919 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
923 catch ( ContentNotFoundException e )
925 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
927 catch ( RepositoryNotFoundException e )
929 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
931 catch ( RepositoryException e )
933 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
935 catch ( MetadataResolutionException e )
937 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
939 catch ( MetadataRepositoryException e )
941 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
943 catch ( RepositoryAdminException e )
945 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
950 repositorySession.save();
952 repositorySession.close();
958 public Boolean deleteGroupId( String groupId, String repositoryId )
959 throws ArchivaRestServiceException
961 if ( StringUtils.isEmpty( repositoryId ) )
963 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
966 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
968 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
971 if ( StringUtils.isEmpty( groupId ) )
973 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
976 RepositorySession repositorySession = repositorySessionFactory.createSession();
980 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
982 repository.deleteGroupId( groupId );
984 MetadataRepository metadataRepository = repositorySession.getRepository();
986 metadataRepository.removeNamespace( repositoryId, groupId );
988 // just invalidate cache entry
989 String cacheKey = repositoryId + "-" + groupId;
990 namespacesCache.remove( cacheKey );
991 namespacesCache.remove( repositoryId );
993 metadataRepository.save();
995 catch ( MetadataRepositoryException e )
997 log.error( e.getMessage(), e );
998 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1000 catch ( RepositoryException e )
1002 log.error( e.getMessage(), e );
1003 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1008 repositorySession.close();
1014 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1015 throws ArchivaRestServiceException
1017 if ( StringUtils.isEmpty( repositoryId ) )
1019 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1022 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1024 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1027 if ( StringUtils.isEmpty( groupId ) )
1029 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1032 if ( StringUtils.isEmpty( projectId ) )
1034 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1037 RepositorySession repositorySession = repositorySessionFactory.createSession();
1041 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1043 repository.deleteProject( groupId, projectId );
1045 catch ( ContentNotFoundException e )
1047 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1049 catch ( RepositoryException e )
1051 log.error( e.getMessage(), e );
1052 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1058 MetadataRepository metadataRepository = repositorySession.getRepository();
1060 metadataRepository.removeProject( repositoryId, groupId, projectId );
1062 metadataRepository.save();
1064 catch ( MetadataRepositoryException e )
1066 log.error( e.getMessage(), e );
1067 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1072 repositorySession.close();
1079 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1080 throws ArchivaRestServiceException
1083 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1087 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1089 catch ( ArchivaSecurityException e )
1091 throw new ArchivaRestServiceException( e.getMessage(),
1092 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1097 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1098 throws ArchivaRestServiceException
1100 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1103 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1105 catch ( RepositoryScannerException e )
1107 log.error( e.getMessage(), e );
1108 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1110 catch ( RepositoryAdminException e )
1112 log.error( e.getMessage(), e );
1113 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1118 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1122 private void updateMetadata( ArchivaRepositoryMetadata metadata, Path metadataFile, Date lastUpdatedTimestamp,
1124 throws RepositoryMetadataException
1126 List<String> availableVersions = new ArrayList<>();
1127 String latestVersion = "";
1129 if ( Files.exists(metadataFile) )
1131 if ( metadata.getAvailableVersions() != null )
1133 availableVersions = metadata.getAvailableVersions();
1135 if ( availableVersions.size() > 0 )
1137 Collections.sort( availableVersions, VersionComparator.getInstance() );
1139 if ( availableVersions.contains( artifact.getVersion() ) )
1141 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1143 if ( availableVersions.size() > 0 )
1145 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1151 if ( metadata.getGroupId() == null )
1153 metadata.setGroupId( artifact.getGroupId() );
1155 if ( metadata.getArtifactId() == null )
1157 metadata.setArtifactId( artifact.getArtifactId() );
1160 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1162 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1163 artifact.getVersion() ) )
1165 metadata.setReleasedVersion( latestVersion );
1169 metadata.setLatestVersion( latestVersion );
1170 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1171 metadata.setAvailableVersions( availableVersions );
1173 RepositoryMetadataWriter.write( metadata, metadataFile);
1174 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1175 checksum.fixChecksums( algorithms );
1179 public StringList getRunningRemoteDownloadIds()
1181 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1184 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1186 return managedRepositoryAdmin;
1189 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1191 this.managedRepositoryAdmin = managedRepositoryAdmin;
1194 public RepositoryContentFactory getRepositoryFactory()
1196 return repositoryFactory;
1199 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1201 this.repositoryFactory = repositoryFactory;
1204 public RepositorySessionFactory getRepositorySessionFactory()
1206 return repositorySessionFactory;
1209 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1211 this.repositorySessionFactory = repositorySessionFactory;
1214 public List<RepositoryListener> getListeners()
1219 public void setListeners( List<RepositoryListener> listeners )
1221 this.listeners = listeners;
1224 public ArchivaAdministration getArchivaAdministration()
1226 return archivaAdministration;
1229 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1231 this.archivaAdministration = archivaAdministration;