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.audit.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.rest.api.model.ArtifactTransferRequest;
68 import org.apache.archiva.rest.api.model.StringList;
69 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
70 import org.apache.archiva.rest.api.services.RepositoriesService;
71 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
72 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
73 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
74 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
75 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
76 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
77 import org.apache.archiva.security.ArchivaSecurityException;
78 import org.apache.archiva.security.common.ArchivaRoleConstants;
79 import org.apache.archiva.xml.XMLException;
80 import org.apache.commons.io.FilenameUtils;
81 import org.apache.commons.lang.StringUtils;
82 import org.apache.maven.index.context.IndexingContext;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85 import org.springframework.stereotype.Service;
87 import javax.inject.Inject;
88 import javax.inject.Named;
89 import javax.ws.rs.core.Response;
91 import java.io.IOException;
92 import java.nio.file.Files;
93 import java.nio.file.StandardCopyOption;
94 import java.text.DateFormat;
95 import java.text.SimpleDateFormat;
96 import java.util.ArrayList;
97 import java.util.Calendar;
98 import java.util.Collection;
99 import java.util.Collections;
100 import java.util.Date;
101 import java.util.List;
102 import java.util.Set;
103 import java.util.TimeZone;
106 * @author Olivier Lamy
109 @Service("repositoriesService#rest")
110 public class DefaultRepositoriesService
111 extends AbstractRestService
112 implements RepositoriesService
114 private Logger log = LoggerFactory.getLogger( getClass() );
117 @Named(value = "taskExecutor#indexing")
118 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
121 private ManagedRepositoryAdmin managedRepositoryAdmin;
124 private PlexusSisuBridge plexusSisuBridge;
127 private MavenIndexerUtils mavenIndexerUtils;
130 private SecuritySystem securitySystem;
133 private RepositoryContentFactory repositoryFactory;
136 @Named(value = "archivaTaskScheduler#repository")
137 private ArchivaTaskScheduler scheduler;
140 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
143 @Named(value = "repositorySessionFactory")
144 protected RepositorySessionFactory repositorySessionFactory;
147 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
150 private RepositoryScanner repoScanner;
153 * Cache used for namespaces
156 @Named(value = "cache#namespaces")
157 private Cache<String, Collection<String>> namespacesCache;
159 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
162 public Boolean scanRepository( String repositoryId, boolean fullScan )
164 return doScanRepository( repositoryId, fullScan );
168 public Boolean alreadyScanning( String repositoryId )
170 return repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId );
174 public Boolean removeScanningTaskFromQueue( String repositoryId )
176 RepositoryTask task = new RepositoryTask();
177 task.setRepositoryId( repositoryId );
180 return repositoryTaskScheduler.unQueueTask( task );
182 catch ( TaskQueueException e )
184 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
190 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
191 throws ArchivaRestServiceException
196 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
198 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
200 ArtifactIndexingTask task =
201 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
203 task.setExecuteOnEntireRepo( true );
204 task.setOnlyUpdate( !fullScan );
206 archivaIndexingTaskExecutor.executeTask( task );
209 catch ( Exception e )
211 log.error( e.getMessage(), e );
212 throw new ArchivaRestServiceException( e.getMessage(), e );
217 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
218 throws ArchivaRestServiceException
222 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
224 catch ( DownloadRemoteIndexException e )
226 log.error( e.getMessage(), e );
227 throw new ArchivaRestServiceException( e.getMessage(), e );
233 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
234 throws ArchivaRestServiceException
237 String userName = getAuditInformation().getUser().getUsername();
238 if ( StringUtils.isBlank( userName ) )
240 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
243 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
245 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
248 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
250 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
253 ManagedRepository source = null;
256 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
258 catch ( RepositoryAdminException e )
260 throw new ArchivaRestServiceException( e.getMessage(), e );
263 if ( source == null )
265 throw new ArchivaRestServiceException(
266 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
269 ManagedRepository target = null;
272 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
274 catch ( RepositoryAdminException e )
276 throw new ArchivaRestServiceException( e.getMessage(), e );
279 if ( target == null )
281 throw new ArchivaRestServiceException(
282 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
285 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
287 throw new ArchivaRestServiceException( "groupId is mandatory", null );
290 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
292 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
295 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
297 throw new ArchivaRestServiceException( "version is mandatory", null );
300 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
302 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
305 // end check parameters
310 user = securitySystem.getUserManager().findUser( userName );
312 catch ( UserNotFoundException e )
314 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
316 catch ( UserManagerException e )
318 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
321 // check karma on source : read
322 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
323 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
327 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
328 artifactTransferRequest.getRepositoryId() );
331 throw new ArchivaRestServiceException(
332 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
335 catch ( AuthorizationException e )
337 log.error( "error reading permission: " + e.getMessage(), e );
338 throw new ArchivaRestServiceException( e.getMessage(), e );
341 // check karma on target: write
345 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
346 artifactTransferRequest.getTargetRepositoryId() );
349 throw new ArchivaRestServiceException(
350 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
353 catch ( AuthorizationException e )
355 log.error( "error reading permission: " + e.getMessage(), e );
356 throw new ArchivaRestServiceException( e.getMessage(), e );
359 // sounds good we can continue !
361 ArtifactReference artifactReference = new ArtifactReference();
362 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
363 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
364 artifactReference.setVersion( artifactTransferRequest.getVersion() );
365 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
366 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
367 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
372 ManagedRepositoryContent sourceRepository =
373 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
375 String artifactSourcePath = sourceRepository.toPath( artifactReference );
377 if ( StringUtils.isEmpty( artifactSourcePath ) )
379 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
380 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
384 File artifactFile = new File( source.getLocation(), artifactSourcePath );
386 if ( !artifactFile.exists() )
388 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
389 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
393 ManagedRepositoryContent targetRepository =
394 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
396 String artifactPath = targetRepository.toPath( artifactReference );
398 int lastIndex = artifactPath.lastIndexOf( '/' );
400 String path = artifactPath.substring( 0, lastIndex );
401 File targetPath = new File( target.getLocation(), path );
403 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
404 int newBuildNumber = 1;
405 String timestamp = null;
407 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
408 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
410 if ( !targetPath.exists() )
415 String filename = artifactPath.substring( lastIndex + 1 );
417 boolean fixChecksums =
418 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
420 File targetFile = new File( targetPath, filename );
421 if ( targetFile.exists() && target.isBlockRedeployments() )
423 throw new ArchivaRestServiceException(
424 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
425 + " and redeployment blocked", null
430 copyFile( artifactFile, targetPath, filename, fixChecksums );
431 queueRepositoryTask( target.getId(), targetFile );
434 // copy source pom to target repo
435 String pomFilename = filename;
436 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
438 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
440 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
442 File pomFile = new File(
443 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
446 if ( pomFile != null && pomFile.length() > 0 )
448 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
449 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
454 // explicitly update only if metadata-updater consumer is not enabled!
455 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
457 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
458 fixChecksums, artifactTransferRequest );
464 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
465 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
466 + artifactTransferRequest.getTargetRepositoryId() + "\'";
469 catch ( RepositoryException e )
471 log.error( "RepositoryException: " + e.getMessage(), e );
472 throw new ArchivaRestServiceException( e.getMessage(), e );
474 catch ( RepositoryAdminException e )
476 log.error( "RepositoryAdminException: " + e.getMessage(), e );
477 throw new ArchivaRestServiceException( e.getMessage(), e );
479 catch ( IOException e )
481 log.error( "IOException: " + e.getMessage(), e );
482 throw new ArchivaRestServiceException( e.getMessage(), e );
487 private void queueRepositoryTask( String repositoryId, File localFile )
489 RepositoryTask task = new RepositoryTask();
490 task.setRepositoryId( repositoryId );
491 task.setResourceFile( localFile );
492 task.setUpdateRelatedArtifacts( true );
493 //task.setScanAll( true );
497 scheduler.queueTask( task );
499 catch ( TaskQueueException e )
501 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
506 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
507 throws RepositoryMetadataException
509 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
510 if ( metadataFile.exists() )
514 metadata = MavenMetadataReader.read( metadataFile );
516 catch ( XMLException e )
518 throw new RepositoryMetadataException( e.getMessage(), e );
524 private File getMetadata( String targetPath )
526 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
528 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
531 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
534 Files.copy( sourceFile.toPath(), new File( targetPath, targetFilename ).toPath(), StandardCopyOption.REPLACE_EXISTING,
535 StandardCopyOption.COPY_ATTRIBUTES );
539 fixChecksums( new File( targetPath, targetFilename ) );
543 private void fixChecksums( File file )
545 ChecksummedFile checksum = new ChecksummedFile( file );
546 checksum.fixChecksums( algorithms );
549 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
550 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
551 throws RepositoryMetadataException
553 List<String> availableVersions = new ArrayList<>();
554 String latestVersion = artifactTransferRequest.getVersion();
556 File projectDir = new File( targetPath ).getParentFile();
557 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
559 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
561 if ( projectMetadataFile.exists() )
563 availableVersions = projectMetadata.getAvailableVersions();
565 Collections.sort( availableVersions, VersionComparator.getInstance() );
567 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
569 availableVersions.add( artifactTransferRequest.getVersion() );
572 latestVersion = availableVersions.get( availableVersions.size() - 1 );
576 availableVersions.add( artifactTransferRequest.getVersion() );
578 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
579 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
582 if ( projectMetadata.getGroupId() == null )
584 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
587 if ( projectMetadata.getArtifactId() == null )
589 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
592 projectMetadata.setLatestVersion( latestVersion );
593 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
594 projectMetadata.setAvailableVersions( availableVersions );
596 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
598 projectMetadata.setReleasedVersion( latestVersion );
601 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
605 fixChecksums( projectMetadataFile );
610 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
611 throws ArchivaRestServiceException
613 // if not a generic we can use the standard way to delete artifact
614 if ( !VersionUtil.isGenericSnapshot( version ) )
616 Artifact artifact = new Artifact( namespace, projectId, version );
617 artifact.setRepositoryId( repositoryId );
618 artifact.setContext( repositoryId );
619 return deleteArtifact( artifact );
622 if ( StringUtils.isEmpty( repositoryId ) )
624 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
627 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
629 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
632 if ( StringUtils.isEmpty( namespace ) )
634 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
637 if ( StringUtils.isEmpty( projectId ) )
639 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
642 if ( StringUtils.isEmpty( version ) )
644 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
647 RepositorySession repositorySession = repositorySessionFactory.createSession();
651 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
653 VersionedReference ref = new VersionedReference();
654 ref.setArtifactId( projectId );
655 ref.setGroupId( namespace );
656 ref.setVersion( version );
658 repository.deleteVersion( ref );
661 ProjectReference projectReference = new ProjectReference();
662 projectReference.setGroupId( namespace );
663 projectReference.setArtifactId( projectId );
665 repository.getVersions( )
668 ArtifactReference artifactReference = new ArtifactReference();
669 artifactReference.setGroupId( namespace );
670 artifactReference.setArtifactId( projectId );
671 artifactReference.setVersion( version );
673 MetadataRepository metadataRepository = repositorySession.getRepository();
675 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
676 log.debug( "related: {}", related );
677 for ( ArtifactReference artifactRef : related )
679 repository.deleteArtifact( artifactRef );
682 Collection<ArtifactMetadata> artifacts =
683 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
685 for ( ArtifactMetadata artifactMetadata : artifacts )
687 metadataRepository.removeArtifact( artifactMetadata, version );
690 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
692 catch ( MetadataRepositoryException e )
694 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
696 catch ( MetadataResolutionException e )
698 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
700 catch ( RepositoryException e )
702 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
707 repositorySession.save();
709 repositorySession.close();
716 public Boolean deleteArtifact( Artifact artifact )
717 throws ArchivaRestServiceException
720 String repositoryId = artifact.getContext();
721 // some rest call can use context or repositoryId
723 if ( StringUtils.isEmpty( repositoryId ) )
725 repositoryId = artifact.getRepositoryId();
727 if ( StringUtils.isEmpty( repositoryId ) )
729 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
732 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
734 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
737 if ( artifact == null )
739 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
742 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
744 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
747 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
749 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
752 // TODO more control on artifact fields
754 boolean snapshotVersion =
755 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
757 RepositorySession repositorySession = repositorySessionFactory.createSession();
760 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
762 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
763 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
764 fmt.setTimeZone( timezone );
765 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
767 VersionedReference ref = new VersionedReference();
768 ref.setArtifactId( artifact.getArtifactId() );
769 ref.setGroupId( artifact.getGroupId() );
770 ref.setVersion( artifact.getVersion() );
772 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
774 ArtifactReference artifactReference = new ArtifactReference();
775 artifactReference.setArtifactId( artifact.getArtifactId() );
776 artifactReference.setGroupId( artifact.getGroupId() );
777 artifactReference.setVersion( artifact.getVersion() );
778 artifactReference.setClassifier( artifact.getClassifier() );
779 artifactReference.setType( artifact.getPackaging() );
781 MetadataRepository metadataRepository = repositorySession.getRepository();
783 String path = repository.toMetadataPath( ref );
785 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
787 if ( StringUtils.isBlank( artifact.getPackaging() ) )
789 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
793 repository.deleteArtifact( artifactReference );
799 int index = path.lastIndexOf( '/' );
800 path = path.substring( 0, index );
801 File targetPath = new File( repoConfig.getLocation(), path );
803 if ( !targetPath.exists() )
805 //throw new ContentNotFoundException(
806 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
807 log.warn( "targetPath {} not found skip file deletion", targetPath );
810 // TODO: this should be in the storage mechanism so that it is all tied together
811 // delete from file system
812 if ( !snapshotVersion )
814 repository.deleteVersion( ref );
818 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
819 log.debug( "related: {}", related );
820 for ( ArtifactReference artifactRef : related )
822 repository.deleteArtifact( artifactRef );
825 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
826 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
828 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
830 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
832 if ( snapshotVersion )
834 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
836 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
842 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
843 artifact.getVersion() );
846 log.debug( "artifacts: {}", artifacts );
848 if ( artifacts.isEmpty() )
850 if ( !snapshotVersion )
852 // verify metata repository doesn't contains anymore the version
853 Collection<String> projectVersions =
854 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
855 artifact.getArtifactId() );
857 if ( projectVersions.contains( artifact.getVersion() ) )
859 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
860 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
861 artifact.getArtifactId(), artifact.getVersion() );
867 for ( ArtifactMetadata artifactMetadata : artifacts )
870 // TODO: mismatch between artifact (snapshot) version and project (base) version here
871 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
873 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
875 if ( StringUtils.isBlank( artifact.getPackaging() ) )
877 throw new ArchivaRestServiceException(
878 "You must configure a type/packaging when using classifier", 400, null );
880 // cleanup facet which contains classifier information
881 MavenArtifactFacet mavenArtifactFacet =
882 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
884 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
886 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
887 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
888 artifact.getVersion();
889 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
890 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
891 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
892 mavenArtifactFacetToCompare );
893 metadataRepository.save();
899 if ( snapshotVersion )
901 metadataRepository.removeArtifact( artifactMetadata,
902 VersionUtil.getBaseVersion( artifact.getVersion() ) );
906 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
907 artifactMetadata.getNamespace(),
908 artifactMetadata.getProject(), artifact.getVersion(),
909 artifactMetadata.getId() );
912 // TODO: move into the metadata repository proper - need to differentiate attachment of
913 // repository metadata to an artifact
914 for ( RepositoryListener listener : listeners )
916 listener.deleteArtifact( metadataRepository, repository.getId(),
917 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
918 artifactMetadata.getVersion(), artifactMetadata.getId() );
921 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
925 catch ( ContentNotFoundException e )
927 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
929 catch ( RepositoryNotFoundException e )
931 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
933 catch ( RepositoryException e )
935 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
937 catch ( MetadataResolutionException e )
939 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
941 catch ( MetadataRepositoryException e )
943 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
945 catch ( RepositoryAdminException e )
947 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
952 repositorySession.save();
954 repositorySession.close();
960 public Boolean deleteGroupId( String groupId, String repositoryId )
961 throws ArchivaRestServiceException
963 if ( StringUtils.isEmpty( repositoryId ) )
965 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
968 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
970 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
973 if ( StringUtils.isEmpty( groupId ) )
975 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
978 RepositorySession repositorySession = repositorySessionFactory.createSession();
982 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
984 repository.deleteGroupId( groupId );
986 MetadataRepository metadataRepository = repositorySession.getRepository();
988 metadataRepository.removeNamespace( repositoryId, groupId );
990 // just invalidate cache entry
991 String cacheKey = repositoryId + "-" + groupId;
992 namespacesCache.remove( cacheKey );
993 namespacesCache.remove( repositoryId );
995 metadataRepository.save();
997 catch ( MetadataRepositoryException e )
999 log.error( e.getMessage(), e );
1000 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1002 catch ( RepositoryException e )
1004 log.error( e.getMessage(), e );
1005 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1010 repositorySession.close();
1016 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1017 throws ArchivaRestServiceException
1019 if ( StringUtils.isEmpty( repositoryId ) )
1021 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1024 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1026 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1029 if ( StringUtils.isEmpty( groupId ) )
1031 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1034 if ( StringUtils.isEmpty( projectId ) )
1036 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1039 RepositorySession repositorySession = repositorySessionFactory.createSession();
1043 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1045 repository.deleteProject( groupId, projectId );
1047 catch ( ContentNotFoundException e )
1049 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1051 catch ( RepositoryException e )
1053 log.error( e.getMessage(), e );
1054 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1060 MetadataRepository metadataRepository = repositorySession.getRepository();
1062 metadataRepository.removeProject( repositoryId, groupId, projectId );
1064 metadataRepository.save();
1066 catch ( MetadataRepositoryException e )
1068 log.error( e.getMessage(), e );
1069 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1074 repositorySession.close();
1081 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1082 throws ArchivaRestServiceException
1085 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1089 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1091 catch ( ArchivaSecurityException e )
1093 throw new ArchivaRestServiceException( e.getMessage(),
1094 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1099 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1100 throws ArchivaRestServiceException
1102 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1105 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1107 catch ( RepositoryScannerException e )
1109 log.error( e.getMessage(), e );
1110 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1112 catch ( RepositoryAdminException e )
1114 log.error( e.getMessage(), e );
1115 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1120 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1124 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
1126 throws RepositoryMetadataException
1128 List<String> availableVersions = new ArrayList<>();
1129 String latestVersion = "";
1131 if ( metadataFile.exists() )
1133 if ( metadata.getAvailableVersions() != null )
1135 availableVersions = metadata.getAvailableVersions();
1137 if ( availableVersions.size() > 0 )
1139 Collections.sort( availableVersions, VersionComparator.getInstance() );
1141 if ( availableVersions.contains( artifact.getVersion() ) )
1143 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1145 if ( availableVersions.size() > 0 )
1147 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1153 if ( metadata.getGroupId() == null )
1155 metadata.setGroupId( artifact.getGroupId() );
1157 if ( metadata.getArtifactId() == null )
1159 metadata.setArtifactId( artifact.getArtifactId() );
1162 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1164 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1165 artifact.getVersion() ) )
1167 metadata.setReleasedVersion( latestVersion );
1171 metadata.setLatestVersion( latestVersion );
1172 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1173 metadata.setAvailableVersions( availableVersions );
1175 RepositoryMetadataWriter.write( metadata, metadataFile );
1176 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1177 checksum.fixChecksums( algorithms );
1181 public StringList getRunningRemoteDownloadIds()
1183 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1186 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1188 return managedRepositoryAdmin;
1191 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1193 this.managedRepositoryAdmin = managedRepositoryAdmin;
1196 public RepositoryContentFactory getRepositoryFactory()
1198 return repositoryFactory;
1201 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1203 this.repositoryFactory = repositoryFactory;
1206 public RepositorySessionFactory getRepositorySessionFactory()
1208 return repositorySessionFactory;
1211 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1213 this.repositorySessionFactory = repositorySessionFactory;
1216 public List<RepositoryListener> getListeners()
1221 public void setListeners( List<RepositoryListener> listeners )
1223 this.listeners = listeners;
1226 public ArchivaAdministration getArchivaAdministration()
1228 return archivaAdministration;
1231 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1233 this.archivaAdministration = archivaAdministration;