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 // check queue first to make sure it doesn't get dequeued between calls
174 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
178 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
180 if ( scan.getRepository().getId().equals( repositoryId ) )
189 public Boolean removeScanningTaskFromQueue( String repositoryId )
191 RepositoryTask task = new RepositoryTask();
192 task.setRepositoryId( repositoryId );
195 return repositoryTaskScheduler.unQueueTask( task );
197 catch ( TaskQueueException e )
199 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
205 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
206 throws ArchivaRestServiceException
211 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
213 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
215 ArtifactIndexingTask task =
216 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
218 task.setExecuteOnEntireRepo( true );
219 task.setOnlyUpdate( !fullScan );
221 archivaIndexingTaskExecutor.executeTask( task );
223 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
227 catch ( Exception e )
229 log.error( e.getMessage(), e );
230 throw new ArchivaRestServiceException( e.getMessage(), e );
235 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
236 throws ArchivaRestServiceException
240 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
242 catch ( DownloadRemoteIndexException e )
244 log.error( e.getMessage(), e );
245 throw new ArchivaRestServiceException( e.getMessage(), e );
251 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
252 throws ArchivaRestServiceException
255 String userName = getAuditInformation().getUser().getUsername();
256 if ( StringUtils.isBlank( userName ) )
258 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
261 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
263 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
266 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
268 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
271 ManagedRepository source = null;
274 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
276 catch ( RepositoryAdminException e )
278 throw new ArchivaRestServiceException( e.getMessage(), e );
281 if ( source == null )
283 throw new ArchivaRestServiceException(
284 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
287 ManagedRepository target = null;
290 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
292 catch ( RepositoryAdminException e )
294 throw new ArchivaRestServiceException( e.getMessage(), e );
297 if ( target == null )
299 throw new ArchivaRestServiceException(
300 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
303 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
305 throw new ArchivaRestServiceException( "groupId is mandatory", null );
308 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
310 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
313 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
315 throw new ArchivaRestServiceException( "version is mandatory", null );
318 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
320 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
323 // end check parameters
328 user = securitySystem.getUserManager().findUser( userName );
330 catch ( UserNotFoundException e )
332 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
334 catch ( UserManagerException e )
336 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
339 // check karma on source : read
340 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
341 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
345 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
346 artifactTransferRequest.getRepositoryId() );
349 throw new ArchivaRestServiceException(
350 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
353 catch ( AuthorizationException e )
355 log.error( "error reading permission: " + e.getMessage(), e );
356 throw new ArchivaRestServiceException( e.getMessage(), e );
359 // check karma on target: write
363 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
364 artifactTransferRequest.getTargetRepositoryId() );
367 throw new ArchivaRestServiceException(
368 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
371 catch ( AuthorizationException e )
373 log.error( "error reading permission: " + e.getMessage(), e );
374 throw new ArchivaRestServiceException( e.getMessage(), e );
377 // sounds good we can continue !
379 ArtifactReference artifactReference = new ArtifactReference();
380 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
381 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
382 artifactReference.setVersion( artifactTransferRequest.getVersion() );
383 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
384 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
385 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
390 ManagedRepositoryContent sourceRepository =
391 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
393 String artifactSourcePath = sourceRepository.toPath( artifactReference );
395 if ( StringUtils.isEmpty( artifactSourcePath ) )
397 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
398 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
402 File artifactFile = new File( source.getLocation(), artifactSourcePath );
404 if ( !artifactFile.exists() )
406 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
407 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
411 ManagedRepositoryContent targetRepository =
412 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
414 String artifactPath = targetRepository.toPath( artifactReference );
416 int lastIndex = artifactPath.lastIndexOf( '/' );
418 String path = artifactPath.substring( 0, lastIndex );
419 File targetPath = new File( target.getLocation(), path );
421 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
422 int newBuildNumber = 1;
423 String timestamp = null;
425 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
426 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
428 if ( !targetPath.exists() )
433 String filename = artifactPath.substring( lastIndex + 1 );
435 boolean fixChecksums =
436 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
438 File targetFile = new File( targetPath, filename );
439 if ( targetFile.exists() && target.isBlockRedeployments() )
441 throw new ArchivaRestServiceException(
442 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
443 + " and redeployment blocked", null
448 copyFile( artifactFile, targetPath, filename, fixChecksums );
449 queueRepositoryTask( target.getId(), targetFile );
452 // copy source pom to target repo
453 String pomFilename = filename;
454 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
456 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
458 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
460 File pomFile = new File(
461 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
464 if ( pomFile != null && pomFile.length() > 0 )
466 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
467 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
472 // explicitly update only if metadata-updater consumer is not enabled!
473 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
475 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
476 fixChecksums, artifactTransferRequest );
482 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
483 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
484 + artifactTransferRequest.getTargetRepositoryId() + "\'";
487 catch ( RepositoryException e )
489 log.error( "RepositoryException: " + e.getMessage(), e );
490 throw new ArchivaRestServiceException( e.getMessage(), e );
492 catch ( RepositoryAdminException e )
494 log.error( "RepositoryAdminException: " + e.getMessage(), e );
495 throw new ArchivaRestServiceException( e.getMessage(), e );
497 catch ( IOException e )
499 log.error( "IOException: " + e.getMessage(), e );
500 throw new ArchivaRestServiceException( e.getMessage(), e );
505 private void queueRepositoryTask( String repositoryId, File localFile )
507 RepositoryTask task = new RepositoryTask();
508 task.setRepositoryId( repositoryId );
509 task.setResourceFile( localFile );
510 task.setUpdateRelatedArtifacts( true );
511 //task.setScanAll( true );
515 scheduler.queueTask( task );
517 catch ( TaskQueueException e )
519 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
524 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
525 throws RepositoryMetadataException
527 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
528 if ( metadataFile.exists() )
532 metadata = MavenMetadataReader.read( metadataFile );
534 catch ( XMLException e )
536 throw new RepositoryMetadataException( e.getMessage(), e );
542 private File getMetadata( String targetPath )
544 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
546 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
549 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
552 Files.copy( sourceFile.toPath(), new File( targetPath, targetFilename ).toPath(), StandardCopyOption.REPLACE_EXISTING,
553 StandardCopyOption.COPY_ATTRIBUTES );
557 fixChecksums( new File( targetPath, targetFilename ) );
561 private void fixChecksums( File file )
563 ChecksummedFile checksum = new ChecksummedFile( file );
564 checksum.fixChecksums( algorithms );
567 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
568 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
569 throws RepositoryMetadataException
571 List<String> availableVersions = new ArrayList<>();
572 String latestVersion = artifactTransferRequest.getVersion();
574 File projectDir = new File( targetPath ).getParentFile();
575 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
577 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
579 if ( projectMetadataFile.exists() )
581 availableVersions = projectMetadata.getAvailableVersions();
583 Collections.sort( availableVersions, VersionComparator.getInstance() );
585 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
587 availableVersions.add( artifactTransferRequest.getVersion() );
590 latestVersion = availableVersions.get( availableVersions.size() - 1 );
594 availableVersions.add( artifactTransferRequest.getVersion() );
596 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
597 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
600 if ( projectMetadata.getGroupId() == null )
602 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
605 if ( projectMetadata.getArtifactId() == null )
607 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
610 projectMetadata.setLatestVersion( latestVersion );
611 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
612 projectMetadata.setAvailableVersions( availableVersions );
614 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
616 projectMetadata.setReleasedVersion( latestVersion );
619 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
623 fixChecksums( projectMetadataFile );
628 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
629 throws ArchivaRestServiceException
631 // if not a generic we can use the standard way to delete artifact
632 if ( !VersionUtil.isGenericSnapshot( version ) )
634 Artifact artifact = new Artifact( namespace, projectId, version );
635 artifact.setRepositoryId( repositoryId );
636 artifact.setContext( repositoryId );
637 return deleteArtifact( artifact );
640 if ( StringUtils.isEmpty( repositoryId ) )
642 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
645 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
647 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
650 if ( StringUtils.isEmpty( namespace ) )
652 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
655 if ( StringUtils.isEmpty( projectId ) )
657 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
660 if ( StringUtils.isEmpty( version ) )
662 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
665 RepositorySession repositorySession = repositorySessionFactory.createSession();
669 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
671 VersionedReference ref = new VersionedReference();
672 ref.setArtifactId( projectId );
673 ref.setGroupId( namespace );
674 ref.setVersion( version );
676 repository.deleteVersion( ref );
679 ProjectReference projectReference = new ProjectReference();
680 projectReference.setGroupId( namespace );
681 projectReference.setArtifactId( projectId );
683 repository.getVersions( )
686 ArtifactReference artifactReference = new ArtifactReference();
687 artifactReference.setGroupId( namespace );
688 artifactReference.setArtifactId( projectId );
689 artifactReference.setVersion( version );
691 MetadataRepository metadataRepository = repositorySession.getRepository();
693 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
694 log.debug( "related: {}", related );
695 for ( ArtifactReference artifactRef : related )
697 repository.deleteArtifact( artifactRef );
700 Collection<ArtifactMetadata> artifacts =
701 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
703 for ( ArtifactMetadata artifactMetadata : artifacts )
705 metadataRepository.removeArtifact( artifactMetadata, version );
708 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
710 catch ( MetadataRepositoryException e )
712 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
714 catch ( MetadataResolutionException e )
716 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
718 catch ( RepositoryException e )
720 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
725 repositorySession.save();
727 repositorySession.close();
734 public Boolean deleteArtifact( Artifact artifact )
735 throws ArchivaRestServiceException
738 String repositoryId = artifact.getContext();
739 // some rest call can use context or repositoryId
741 if ( StringUtils.isEmpty( repositoryId ) )
743 repositoryId = artifact.getRepositoryId();
745 if ( StringUtils.isEmpty( repositoryId ) )
747 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
750 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
752 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
755 if ( artifact == null )
757 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
760 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
762 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
765 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
767 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
770 // TODO more control on artifact fields
772 boolean snapshotVersion =
773 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
775 RepositorySession repositorySession = repositorySessionFactory.createSession();
778 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
780 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
781 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
782 fmt.setTimeZone( timezone );
783 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
785 VersionedReference ref = new VersionedReference();
786 ref.setArtifactId( artifact.getArtifactId() );
787 ref.setGroupId( artifact.getGroupId() );
788 ref.setVersion( artifact.getVersion() );
790 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
792 ArtifactReference artifactReference = new ArtifactReference();
793 artifactReference.setArtifactId( artifact.getArtifactId() );
794 artifactReference.setGroupId( artifact.getGroupId() );
795 artifactReference.setVersion( artifact.getVersion() );
796 artifactReference.setClassifier( artifact.getClassifier() );
797 artifactReference.setType( artifact.getPackaging() );
799 MetadataRepository metadataRepository = repositorySession.getRepository();
801 String path = repository.toMetadataPath( ref );
803 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
805 if ( StringUtils.isBlank( artifact.getPackaging() ) )
807 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
811 repository.deleteArtifact( artifactReference );
817 int index = path.lastIndexOf( '/' );
818 path = path.substring( 0, index );
819 File targetPath = new File( repoConfig.getLocation(), path );
821 if ( !targetPath.exists() )
823 //throw new ContentNotFoundException(
824 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
825 log.warn( "targetPath {} not found skip file deletion", targetPath );
828 // TODO: this should be in the storage mechanism so that it is all tied together
829 // delete from file system
830 if ( !snapshotVersion )
832 repository.deleteVersion( ref );
836 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
837 log.debug( "related: {}", related );
838 for ( ArtifactReference artifactRef : related )
840 repository.deleteArtifact( artifactRef );
843 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
844 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
846 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
848 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
850 if ( snapshotVersion )
852 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
854 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
860 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
861 artifact.getVersion() );
864 log.debug( "artifacts: {}", artifacts );
866 if ( artifacts.isEmpty() )
868 if ( !snapshotVersion )
870 // verify metata repository doesn't contains anymore the version
871 Collection<String> projectVersions =
872 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
873 artifact.getArtifactId() );
875 if ( projectVersions.contains( artifact.getVersion() ) )
877 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
878 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
879 artifact.getArtifactId(), artifact.getVersion() );
885 for ( ArtifactMetadata artifactMetadata : artifacts )
888 // TODO: mismatch between artifact (snapshot) version and project (base) version here
889 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
891 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
893 if ( StringUtils.isBlank( artifact.getPackaging() ) )
895 throw new ArchivaRestServiceException(
896 "You must configure a type/packaging when using classifier", 400, null );
898 // cleanup facet which contains classifier information
899 MavenArtifactFacet mavenArtifactFacet =
900 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
902 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
904 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
905 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
906 artifact.getVersion();
907 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
908 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
909 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
910 mavenArtifactFacetToCompare );
911 metadataRepository.save();
917 if ( snapshotVersion )
919 metadataRepository.removeArtifact( artifactMetadata,
920 VersionUtil.getBaseVersion( artifact.getVersion() ) );
924 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
925 artifactMetadata.getNamespace(),
926 artifactMetadata.getProject(), artifact.getVersion(),
927 artifactMetadata.getId() );
930 // TODO: move into the metadata repository proper - need to differentiate attachment of
931 // repository metadata to an artifact
932 for ( RepositoryListener listener : listeners )
934 listener.deleteArtifact( metadataRepository, repository.getId(),
935 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
936 artifactMetadata.getVersion(), artifactMetadata.getId() );
939 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
943 catch ( ContentNotFoundException e )
945 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
947 catch ( RepositoryNotFoundException e )
949 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
951 catch ( RepositoryException e )
953 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
955 catch ( MetadataResolutionException e )
957 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
959 catch ( MetadataRepositoryException e )
961 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
963 catch ( RepositoryAdminException e )
965 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
970 repositorySession.save();
972 repositorySession.close();
978 public Boolean deleteGroupId( String groupId, String repositoryId )
979 throws ArchivaRestServiceException
981 if ( StringUtils.isEmpty( repositoryId ) )
983 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
986 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
988 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
991 if ( StringUtils.isEmpty( groupId ) )
993 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
996 RepositorySession repositorySession = repositorySessionFactory.createSession();
1000 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1002 repository.deleteGroupId( groupId );
1004 MetadataRepository metadataRepository = repositorySession.getRepository();
1006 metadataRepository.removeNamespace( repositoryId, groupId );
1008 // just invalidate cache entry
1009 String cacheKey = repositoryId + "-" + groupId;
1010 namespacesCache.remove( cacheKey );
1011 namespacesCache.remove( repositoryId );
1013 metadataRepository.save();
1015 catch ( MetadataRepositoryException e )
1017 log.error( e.getMessage(), e );
1018 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1020 catch ( RepositoryException e )
1022 log.error( e.getMessage(), e );
1023 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1028 repositorySession.close();
1034 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1035 throws ArchivaRestServiceException
1037 if ( StringUtils.isEmpty( repositoryId ) )
1039 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1042 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1044 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1047 if ( StringUtils.isEmpty( groupId ) )
1049 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1052 if ( StringUtils.isEmpty( projectId ) )
1054 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1057 RepositorySession repositorySession = repositorySessionFactory.createSession();
1061 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1063 repository.deleteProject( groupId, projectId );
1065 catch ( ContentNotFoundException e )
1067 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1069 catch ( RepositoryException e )
1071 log.error( e.getMessage(), e );
1072 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1078 MetadataRepository metadataRepository = repositorySession.getRepository();
1080 metadataRepository.removeProject( repositoryId, groupId, projectId );
1082 metadataRepository.save();
1084 catch ( MetadataRepositoryException e )
1086 log.error( e.getMessage(), e );
1087 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1092 repositorySession.close();
1099 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1100 throws ArchivaRestServiceException
1103 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1107 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1109 catch ( ArchivaSecurityException e )
1111 throw new ArchivaRestServiceException( e.getMessage(),
1112 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1117 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1118 throws ArchivaRestServiceException
1120 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1123 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1125 catch ( RepositoryScannerException e )
1127 log.error( e.getMessage(), e );
1128 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1130 catch ( RepositoryAdminException e )
1132 log.error( e.getMessage(), e );
1133 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1138 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1142 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
1144 throws RepositoryMetadataException
1146 List<String> availableVersions = new ArrayList<>();
1147 String latestVersion = "";
1149 if ( metadataFile.exists() )
1151 if ( metadata.getAvailableVersions() != null )
1153 availableVersions = metadata.getAvailableVersions();
1155 if ( availableVersions.size() > 0 )
1157 Collections.sort( availableVersions, VersionComparator.getInstance() );
1159 if ( availableVersions.contains( artifact.getVersion() ) )
1161 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1163 if ( availableVersions.size() > 0 )
1165 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1171 if ( metadata.getGroupId() == null )
1173 metadata.setGroupId( artifact.getGroupId() );
1175 if ( metadata.getArtifactId() == null )
1177 metadata.setArtifactId( artifact.getArtifactId() );
1180 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1182 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1183 artifact.getVersion() ) )
1185 metadata.setReleasedVersion( latestVersion );
1189 metadata.setLatestVersion( latestVersion );
1190 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1191 metadata.setAvailableVersions( availableVersions );
1193 RepositoryMetadataWriter.write( metadata, metadataFile );
1194 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1195 checksum.fixChecksums( algorithms );
1199 public StringList getRunningRemoteDownloadIds()
1201 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1204 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1206 return managedRepositoryAdmin;
1209 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1211 this.managedRepositoryAdmin = managedRepositoryAdmin;
1214 public RepositoryContentFactory getRepositoryFactory()
1216 return repositoryFactory;
1219 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1221 this.repositoryFactory = repositoryFactory;
1224 public RepositorySessionFactory getRepositorySessionFactory()
1226 return repositorySessionFactory;
1229 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1231 this.repositorySessionFactory = repositorySessionFactory;
1234 public List<RepositoryListener> getListeners()
1239 public void setListeners( List<RepositoryListener> listeners )
1241 this.listeners = listeners;
1244 public ArchivaAdministration getArchivaAdministration()
1246 return archivaAdministration;
1249 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1251 this.archivaAdministration = archivaAdministration;