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.metadata.model.facets.AuditEvent;
27 import org.apache.archiva.checksum.ChecksumAlgorithm;
28 import org.apache.archiva.checksum.ChecksummedFile;
29 import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
31 import org.apache.archiva.common.utils.VersionComparator;
32 import org.apache.archiva.common.utils.VersionUtil;
33 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
34 import org.apache.archiva.maven2.model.Artifact;
35 import org.apache.archiva.metadata.model.ArtifactMetadata;
36 import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
37 import org.apache.archiva.metadata.repository.MetadataRepository;
38 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
39 import org.apache.archiva.metadata.repository.MetadataResolutionException;
40 import org.apache.archiva.metadata.repository.RepositorySession;
41 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
42 import org.apache.archiva.model.ArchivaRepositoryMetadata;
43 import org.apache.archiva.model.ArtifactReference;
44 import org.apache.archiva.model.VersionedReference;
45 import org.apache.archiva.redback.authentication.AuthenticationResult;
46 import org.apache.archiva.redback.authorization.AuthorizationException;
47 import org.apache.archiva.redback.components.cache.Cache;
48 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
49 import org.apache.archiva.redback.system.DefaultSecuritySession;
50 import org.apache.archiva.redback.system.SecuritySession;
51 import org.apache.archiva.redback.system.SecuritySystem;
52 import org.apache.archiva.redback.users.User;
53 import org.apache.archiva.redback.users.UserManagerException;
54 import org.apache.archiva.redback.users.UserNotFoundException;
55 import org.apache.archiva.repository.ContentNotFoundException;
56 import org.apache.archiva.repository.ManagedRepositoryContent;
57 import org.apache.archiva.repository.RepositoryContentFactory;
58 import org.apache.archiva.repository.RepositoryException;
59 import org.apache.archiva.repository.RepositoryNotFoundException;
60 import org.apache.archiva.repository.events.RepositoryListener;
61 import org.apache.archiva.repository.metadata.MetadataTools;
62 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
63 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
64 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
65 import org.apache.archiva.repository.scanner.RepositoryScanner;
66 import org.apache.archiva.repository.scanner.RepositoryScannerException;
67 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
68 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
69 import org.apache.archiva.rest.api.model.StringList;
70 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
71 import org.apache.archiva.rest.api.services.RepositoriesService;
72 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
73 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
74 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
75 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
76 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
77 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
78 import org.apache.archiva.security.ArchivaSecurityException;
79 import org.apache.archiva.security.common.ArchivaRoleConstants;
80 import org.apache.archiva.xml.XMLException;
81 import org.apache.commons.io.FilenameUtils;
82 import org.apache.commons.lang.StringUtils;
83 import org.apache.maven.index.context.IndexingContext;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import org.springframework.beans.factory.annotation.Autowired;
87 import org.springframework.stereotype.Service;
89 import javax.inject.Inject;
90 import javax.inject.Named;
91 import javax.ws.rs.core.Response;
93 import java.io.IOException;
94 import java.nio.file.Files;
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 ManagedRepositoryAdmin managedRepositoryAdmin;
126 private PlexusSisuBridge plexusSisuBridge;
129 private MavenIndexerUtils mavenIndexerUtils;
132 private SecuritySystem securitySystem;
135 private RepositoryContentFactory repositoryFactory;
138 @Named(value = "archivaTaskScheduler#repository")
139 private ArchivaTaskScheduler scheduler;
142 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
145 @Named(value = "repositorySessionFactory")
146 protected RepositorySessionFactory repositorySessionFactory;
149 @Autowired(required = false)
150 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
153 private RepositoryScanner repoScanner;
156 * Cache used for namespaces
159 @Named(value = "cache#namespaces")
160 private Cache<String, Collection<String>> namespacesCache;
162 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
165 public Boolean scanRepository( String repositoryId, boolean fullScan )
167 return doScanRepository( repositoryId, fullScan );
171 public Boolean alreadyScanning( String repositoryId )
173 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
175 if ( scan.getRepository().getId().equals( repositoryId ) )
180 return repositoryTaskScheduler.isProcessingRepositoryTask( 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 );
200 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
201 throws ArchivaRestServiceException
206 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
208 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
210 ArtifactIndexingTask task =
211 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
213 task.setExecuteOnEntireRepo( true );
214 task.setOnlyUpdate( !fullScan );
216 archivaIndexingTaskExecutor.executeTask( task );
219 catch ( Exception e )
221 log.error( e.getMessage(), e );
222 throw new ArchivaRestServiceException( e.getMessage(), e );
227 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
228 throws ArchivaRestServiceException
232 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
234 catch ( DownloadRemoteIndexException e )
236 log.error( e.getMessage(), e );
237 throw new ArchivaRestServiceException( e.getMessage(), e );
243 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
244 throws ArchivaRestServiceException
247 String userName = getAuditInformation().getUser().getUsername();
248 if ( StringUtils.isBlank( userName ) )
250 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
253 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
255 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
258 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
260 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
263 ManagedRepository source = null;
266 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
268 catch ( RepositoryAdminException e )
270 throw new ArchivaRestServiceException( e.getMessage(), e );
273 if ( source == null )
275 throw new ArchivaRestServiceException(
276 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
279 ManagedRepository target = null;
282 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
284 catch ( RepositoryAdminException e )
286 throw new ArchivaRestServiceException( e.getMessage(), e );
289 if ( target == null )
291 throw new ArchivaRestServiceException(
292 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
295 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
297 throw new ArchivaRestServiceException( "groupId is mandatory", null );
300 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
302 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
305 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
307 throw new ArchivaRestServiceException( "version is mandatory", null );
310 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
312 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
315 // end check parameters
320 user = securitySystem.getUserManager().findUser( userName );
322 catch ( UserNotFoundException e )
324 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
326 catch ( UserManagerException e )
328 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
331 // check karma on source : read
332 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
333 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
337 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
338 artifactTransferRequest.getRepositoryId() );
341 throw new ArchivaRestServiceException(
342 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
345 catch ( AuthorizationException e )
347 log.error( "error reading permission: " + e.getMessage(), e );
348 throw new ArchivaRestServiceException( e.getMessage(), e );
351 // check karma on target: write
355 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
356 artifactTransferRequest.getTargetRepositoryId() );
359 throw new ArchivaRestServiceException(
360 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
363 catch ( AuthorizationException e )
365 log.error( "error reading permission: " + e.getMessage(), e );
366 throw new ArchivaRestServiceException( e.getMessage(), e );
369 // sounds good we can continue !
371 ArtifactReference artifactReference = new ArtifactReference();
372 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
373 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
374 artifactReference.setVersion( artifactTransferRequest.getVersion() );
375 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
376 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
377 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
382 ManagedRepositoryContent sourceRepository =
383 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
385 String artifactSourcePath = sourceRepository.toPath( artifactReference );
387 if ( StringUtils.isEmpty( artifactSourcePath ) )
389 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
390 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
394 File artifactFile = new File( source.getLocation(), artifactSourcePath );
396 if ( !artifactFile.exists() )
398 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
399 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
403 ManagedRepositoryContent targetRepository =
404 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
406 String artifactPath = targetRepository.toPath( artifactReference );
408 int lastIndex = artifactPath.lastIndexOf( '/' );
410 String path = artifactPath.substring( 0, lastIndex );
411 File targetPath = new File( target.getLocation(), path );
413 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
414 int newBuildNumber = 1;
415 String timestamp = null;
417 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
418 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
420 if ( !targetPath.exists() )
425 String filename = artifactPath.substring( lastIndex + 1 );
427 boolean fixChecksums =
428 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
430 File targetFile = new File( targetPath, filename );
431 if ( targetFile.exists() && target.isBlockRedeployments() )
433 throw new ArchivaRestServiceException(
434 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
435 + " and redeployment blocked", null
440 copyFile( artifactFile, targetPath, filename, fixChecksums );
441 queueRepositoryTask( target.getId(), targetFile );
444 // copy source pom to target repo
445 String pomFilename = filename;
446 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
448 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
450 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
452 File pomFile = new File(
453 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
456 if ( pomFile != null && pomFile.length() > 0 )
458 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
459 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
464 // explicitly update only if metadata-updater consumer is not enabled!
465 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
467 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
468 fixChecksums, artifactTransferRequest );
474 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
475 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
476 + artifactTransferRequest.getTargetRepositoryId() + "\'";
479 catch ( RepositoryException e )
481 log.error( "RepositoryException: " + e.getMessage(), e );
482 throw new ArchivaRestServiceException( e.getMessage(), e );
484 catch ( RepositoryAdminException e )
486 log.error( "RepositoryAdminException: " + e.getMessage(), e );
487 throw new ArchivaRestServiceException( e.getMessage(), e );
489 catch ( IOException e )
491 log.error( "IOException: " + e.getMessage(), e );
492 throw new ArchivaRestServiceException( e.getMessage(), e );
497 private void queueRepositoryTask( String repositoryId, File localFile )
499 RepositoryTask task = new RepositoryTask();
500 task.setRepositoryId( repositoryId );
501 task.setResourceFile( localFile );
502 task.setUpdateRelatedArtifacts( true );
503 //task.setScanAll( true );
507 scheduler.queueTask( task );
509 catch ( TaskQueueException e )
511 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
516 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
517 throws RepositoryMetadataException
519 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
520 if ( metadataFile.exists() )
524 metadata = MavenMetadataReader.read( metadataFile );
526 catch ( XMLException e )
528 throw new RepositoryMetadataException( e.getMessage(), e );
534 private File getMetadata( String targetPath )
536 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
538 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
541 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
544 Files.copy( sourceFile.toPath(), new File( targetPath, targetFilename ).toPath(), StandardCopyOption.REPLACE_EXISTING,
545 StandardCopyOption.COPY_ATTRIBUTES );
549 fixChecksums( new File( targetPath, targetFilename ) );
553 private void fixChecksums( File file )
555 ChecksummedFile checksum = new ChecksummedFile( file );
556 checksum.fixChecksums( algorithms );
559 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
560 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
561 throws RepositoryMetadataException
563 List<String> availableVersions = new ArrayList<>();
564 String latestVersion = artifactTransferRequest.getVersion();
566 File projectDir = new File( targetPath ).getParentFile();
567 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
569 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
571 if ( projectMetadataFile.exists() )
573 availableVersions = projectMetadata.getAvailableVersions();
575 Collections.sort( availableVersions, VersionComparator.getInstance() );
577 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
579 availableVersions.add( artifactTransferRequest.getVersion() );
582 latestVersion = availableVersions.get( availableVersions.size() - 1 );
586 availableVersions.add( artifactTransferRequest.getVersion() );
588 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
589 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
592 if ( projectMetadata.getGroupId() == null )
594 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
597 if ( projectMetadata.getArtifactId() == null )
599 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
602 projectMetadata.setLatestVersion( latestVersion );
603 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
604 projectMetadata.setAvailableVersions( availableVersions );
606 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
608 projectMetadata.setReleasedVersion( latestVersion );
611 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
615 fixChecksums( projectMetadataFile );
620 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
621 throws ArchivaRestServiceException
623 // if not a generic we can use the standard way to delete artifact
624 if ( !VersionUtil.isGenericSnapshot( version ) )
626 Artifact artifact = new Artifact( namespace, projectId, version );
627 artifact.setRepositoryId( repositoryId );
628 artifact.setContext( repositoryId );
629 return deleteArtifact( artifact );
632 if ( StringUtils.isEmpty( repositoryId ) )
634 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
637 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
639 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
642 if ( StringUtils.isEmpty( namespace ) )
644 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
647 if ( StringUtils.isEmpty( projectId ) )
649 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
652 if ( StringUtils.isEmpty( version ) )
654 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
657 RepositorySession repositorySession = repositorySessionFactory.createSession();
661 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
663 VersionedReference ref = new VersionedReference();
664 ref.setArtifactId( projectId );
665 ref.setGroupId( namespace );
666 ref.setVersion( version );
668 repository.deleteVersion( ref );
671 ProjectReference projectReference = new ProjectReference();
672 projectReference.setGroupId( namespace );
673 projectReference.setArtifactId( projectId );
675 repository.getVersions( )
678 ArtifactReference artifactReference = new ArtifactReference();
679 artifactReference.setGroupId( namespace );
680 artifactReference.setArtifactId( projectId );
681 artifactReference.setVersion( version );
683 MetadataRepository metadataRepository = repositorySession.getRepository();
685 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
686 log.debug( "related: {}", related );
687 for ( ArtifactReference artifactRef : related )
689 repository.deleteArtifact( artifactRef );
692 Collection<ArtifactMetadata> artifacts =
693 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
695 for ( ArtifactMetadata artifactMetadata : artifacts )
697 metadataRepository.removeArtifact( artifactMetadata, version );
700 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
702 catch ( MetadataRepositoryException e )
704 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
706 catch ( MetadataResolutionException e )
708 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
710 catch ( RepositoryException e )
712 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
717 repositorySession.save();
719 repositorySession.close();
726 public Boolean deleteArtifact( Artifact artifact )
727 throws ArchivaRestServiceException
730 String repositoryId = artifact.getContext();
731 // some rest call can use context or repositoryId
733 if ( StringUtils.isEmpty( repositoryId ) )
735 repositoryId = artifact.getRepositoryId();
737 if ( StringUtils.isEmpty( repositoryId ) )
739 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
742 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
744 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
747 if ( artifact == null )
749 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
752 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
754 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
757 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
759 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
762 // TODO more control on artifact fields
764 boolean snapshotVersion =
765 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
767 RepositorySession repositorySession = repositorySessionFactory.createSession();
770 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
772 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
773 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
774 fmt.setTimeZone( timezone );
775 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
777 VersionedReference ref = new VersionedReference();
778 ref.setArtifactId( artifact.getArtifactId() );
779 ref.setGroupId( artifact.getGroupId() );
780 ref.setVersion( artifact.getVersion() );
782 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
784 ArtifactReference artifactReference = new ArtifactReference();
785 artifactReference.setArtifactId( artifact.getArtifactId() );
786 artifactReference.setGroupId( artifact.getGroupId() );
787 artifactReference.setVersion( artifact.getVersion() );
788 artifactReference.setClassifier( artifact.getClassifier() );
789 artifactReference.setType( artifact.getPackaging() );
791 MetadataRepository metadataRepository = repositorySession.getRepository();
793 String path = repository.toMetadataPath( ref );
795 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
797 if ( StringUtils.isBlank( artifact.getPackaging() ) )
799 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
803 repository.deleteArtifact( artifactReference );
809 int index = path.lastIndexOf( '/' );
810 path = path.substring( 0, index );
811 File targetPath = new File( repoConfig.getLocation(), path );
813 if ( !targetPath.exists() )
815 //throw new ContentNotFoundException(
816 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
817 log.warn( "targetPath {} not found skip file deletion", targetPath );
820 // TODO: this should be in the storage mechanism so that it is all tied together
821 // delete from file system
822 if ( !snapshotVersion )
824 repository.deleteVersion( ref );
828 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
829 log.debug( "related: {}", related );
830 for ( ArtifactReference artifactRef : related )
832 repository.deleteArtifact( artifactRef );
835 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
836 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
838 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
840 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
842 if ( snapshotVersion )
844 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
846 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
852 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
853 artifact.getVersion() );
856 log.debug( "artifacts: {}", artifacts );
858 if ( artifacts.isEmpty() )
860 if ( !snapshotVersion )
862 // verify metata repository doesn't contains anymore the version
863 Collection<String> projectVersions =
864 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
865 artifact.getArtifactId() );
867 if ( projectVersions.contains( artifact.getVersion() ) )
869 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
870 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
871 artifact.getArtifactId(), artifact.getVersion() );
877 for ( ArtifactMetadata artifactMetadata : artifacts )
880 // TODO: mismatch between artifact (snapshot) version and project (base) version here
881 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
883 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
885 if ( StringUtils.isBlank( artifact.getPackaging() ) )
887 throw new ArchivaRestServiceException(
888 "You must configure a type/packaging when using classifier", 400, null );
890 // cleanup facet which contains classifier information
891 MavenArtifactFacet mavenArtifactFacet =
892 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
894 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
896 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
897 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
898 artifact.getVersion();
899 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
900 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
901 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
902 mavenArtifactFacetToCompare );
903 metadataRepository.save();
909 if ( snapshotVersion )
911 metadataRepository.removeArtifact( artifactMetadata,
912 VersionUtil.getBaseVersion( artifact.getVersion() ) );
916 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
917 artifactMetadata.getNamespace(),
918 artifactMetadata.getProject(), artifact.getVersion(),
919 artifactMetadata.getId() );
922 // TODO: move into the metadata repository proper - need to differentiate attachment of
923 // repository metadata to an artifact
924 for ( RepositoryListener listener : listeners )
926 listener.deleteArtifact( metadataRepository, repository.getId(),
927 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
928 artifactMetadata.getVersion(), artifactMetadata.getId() );
931 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
935 catch ( ContentNotFoundException e )
937 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
939 catch ( RepositoryNotFoundException e )
941 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
943 catch ( RepositoryException e )
945 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
947 catch ( MetadataResolutionException e )
949 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
951 catch ( MetadataRepositoryException e )
953 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
955 catch ( RepositoryAdminException e )
957 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
962 repositorySession.save();
964 repositorySession.close();
970 public Boolean deleteGroupId( String groupId, String repositoryId )
971 throws ArchivaRestServiceException
973 if ( StringUtils.isEmpty( repositoryId ) )
975 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
978 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
980 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
983 if ( StringUtils.isEmpty( groupId ) )
985 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
988 RepositorySession repositorySession = repositorySessionFactory.createSession();
992 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
994 repository.deleteGroupId( groupId );
996 MetadataRepository metadataRepository = repositorySession.getRepository();
998 metadataRepository.removeNamespace( repositoryId, groupId );
1000 // just invalidate cache entry
1001 String cacheKey = repositoryId + "-" + groupId;
1002 namespacesCache.remove( cacheKey );
1003 namespacesCache.remove( repositoryId );
1005 metadataRepository.save();
1007 catch ( MetadataRepositoryException e )
1009 log.error( e.getMessage(), e );
1010 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1012 catch ( RepositoryException e )
1014 log.error( e.getMessage(), e );
1015 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1020 repositorySession.close();
1026 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1027 throws ArchivaRestServiceException
1029 if ( StringUtils.isEmpty( repositoryId ) )
1031 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1034 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1036 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1039 if ( StringUtils.isEmpty( groupId ) )
1041 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1044 if ( StringUtils.isEmpty( projectId ) )
1046 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1049 RepositorySession repositorySession = repositorySessionFactory.createSession();
1053 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1055 repository.deleteProject( groupId, projectId );
1057 catch ( ContentNotFoundException e )
1059 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1061 catch ( RepositoryException e )
1063 log.error( e.getMessage(), e );
1064 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1070 MetadataRepository metadataRepository = repositorySession.getRepository();
1072 metadataRepository.removeProject( repositoryId, groupId, projectId );
1074 metadataRepository.save();
1076 catch ( MetadataRepositoryException e )
1078 log.error( e.getMessage(), e );
1079 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1084 repositorySession.close();
1091 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1092 throws ArchivaRestServiceException
1095 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1099 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1101 catch ( ArchivaSecurityException e )
1103 throw new ArchivaRestServiceException( e.getMessage(),
1104 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1109 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1110 throws ArchivaRestServiceException
1112 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1115 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1117 catch ( RepositoryScannerException e )
1119 log.error( e.getMessage(), e );
1120 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1122 catch ( RepositoryAdminException e )
1124 log.error( e.getMessage(), e );
1125 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1130 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1134 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
1136 throws RepositoryMetadataException
1138 List<String> availableVersions = new ArrayList<>();
1139 String latestVersion = "";
1141 if ( metadataFile.exists() )
1143 if ( metadata.getAvailableVersions() != null )
1145 availableVersions = metadata.getAvailableVersions();
1147 if ( availableVersions.size() > 0 )
1149 Collections.sort( availableVersions, VersionComparator.getInstance() );
1151 if ( availableVersions.contains( artifact.getVersion() ) )
1153 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1155 if ( availableVersions.size() > 0 )
1157 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1163 if ( metadata.getGroupId() == null )
1165 metadata.setGroupId( artifact.getGroupId() );
1167 if ( metadata.getArtifactId() == null )
1169 metadata.setArtifactId( artifact.getArtifactId() );
1172 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1174 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1175 artifact.getVersion() ) )
1177 metadata.setReleasedVersion( latestVersion );
1181 metadata.setLatestVersion( latestVersion );
1182 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1183 metadata.setAvailableVersions( availableVersions );
1185 RepositoryMetadataWriter.write( metadata, metadataFile );
1186 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1187 checksum.fixChecksums( algorithms );
1191 public StringList getRunningRemoteDownloadIds()
1193 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1196 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1198 return managedRepositoryAdmin;
1201 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1203 this.managedRepositoryAdmin = managedRepositoryAdmin;
1206 public RepositoryContentFactory getRepositoryFactory()
1208 return repositoryFactory;
1211 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1213 this.repositoryFactory = repositoryFactory;
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;