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 /* unused */ 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() + "\'";
485 log.debug("copyArtifact {}", msg);
488 catch ( RepositoryException e )
490 log.error( "RepositoryException: " + e.getMessage(), e );
491 throw new ArchivaRestServiceException( e.getMessage(), e );
493 catch ( RepositoryAdminException e )
495 log.error( "RepositoryAdminException: " + e.getMessage(), e );
496 throw new ArchivaRestServiceException( e.getMessage(), e );
498 catch ( IOException e )
500 log.error( "IOException: " + e.getMessage(), e );
501 throw new ArchivaRestServiceException( e.getMessage(), e );
506 private void queueRepositoryTask( String repositoryId, File localFile )
508 RepositoryTask task = new RepositoryTask();
509 task.setRepositoryId( repositoryId );
510 task.setResourceFile( localFile );
511 task.setUpdateRelatedArtifacts( true );
512 //task.setScanAll( true );
516 scheduler.queueTask( task );
518 catch ( TaskQueueException e )
520 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
525 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
526 throws RepositoryMetadataException
528 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
529 if ( metadataFile.exists() )
533 metadata = MavenMetadataReader.read( metadataFile );
535 catch ( XMLException e )
537 throw new RepositoryMetadataException( e.getMessage(), e );
543 private File getMetadata( String targetPath )
545 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
547 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
550 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
553 Files.copy( sourceFile.toPath(), new File( targetPath, targetFilename ).toPath(), StandardCopyOption.REPLACE_EXISTING,
554 StandardCopyOption.COPY_ATTRIBUTES );
558 fixChecksums( new File( targetPath, targetFilename ) );
562 private void fixChecksums( File file )
564 ChecksummedFile checksum = new ChecksummedFile( file );
565 checksum.fixChecksums( algorithms );
568 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
569 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
570 throws RepositoryMetadataException
572 List<String> availableVersions = new ArrayList<>();
573 String latestVersion = artifactTransferRequest.getVersion();
575 File projectDir = new File( targetPath ).getParentFile();
576 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
578 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
580 if ( projectMetadataFile.exists() )
582 availableVersions = projectMetadata.getAvailableVersions();
584 Collections.sort( availableVersions, VersionComparator.getInstance() );
586 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
588 availableVersions.add( artifactTransferRequest.getVersion() );
591 latestVersion = availableVersions.get( availableVersions.size() - 1 );
595 availableVersions.add( artifactTransferRequest.getVersion() );
597 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
598 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
601 if ( projectMetadata.getGroupId() == null )
603 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
606 if ( projectMetadata.getArtifactId() == null )
608 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
611 projectMetadata.setLatestVersion( latestVersion );
612 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
613 projectMetadata.setAvailableVersions( availableVersions );
615 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
617 projectMetadata.setReleasedVersion( latestVersion );
620 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
624 fixChecksums( projectMetadataFile );
629 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
630 throws ArchivaRestServiceException
632 // if not a generic we can use the standard way to delete artifact
633 if ( !VersionUtil.isGenericSnapshot( version ) )
635 Artifact artifact = new Artifact( namespace, projectId, version );
636 artifact.setRepositoryId( repositoryId );
637 artifact.setContext( repositoryId );
638 return deleteArtifact( artifact );
641 if ( StringUtils.isEmpty( repositoryId ) )
643 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
646 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
648 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
651 if ( StringUtils.isEmpty( namespace ) )
653 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
656 if ( StringUtils.isEmpty( projectId ) )
658 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
661 if ( StringUtils.isEmpty( version ) )
663 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
666 RepositorySession repositorySession = repositorySessionFactory.createSession();
670 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
672 VersionedReference ref = new VersionedReference();
673 ref.setArtifactId( projectId );
674 ref.setGroupId( namespace );
675 ref.setVersion( version );
677 repository.deleteVersion( ref );
680 ProjectReference projectReference = new ProjectReference();
681 projectReference.setGroupId( namespace );
682 projectReference.setArtifactId( projectId );
684 repository.getVersions( )
687 ArtifactReference artifactReference = new ArtifactReference();
688 artifactReference.setGroupId( namespace );
689 artifactReference.setArtifactId( projectId );
690 artifactReference.setVersion( version );
692 MetadataRepository metadataRepository = repositorySession.getRepository();
694 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
695 log.debug( "related: {}", related );
696 for ( ArtifactReference artifactRef : related )
698 repository.deleteArtifact( artifactRef );
701 Collection<ArtifactMetadata> artifacts =
702 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
704 for ( ArtifactMetadata artifactMetadata : artifacts )
706 metadataRepository.removeArtifact( artifactMetadata, version );
709 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
711 catch ( MetadataRepositoryException e )
713 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
715 catch ( MetadataResolutionException e )
717 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
719 catch ( RepositoryException e )
721 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
726 repositorySession.save();
728 repositorySession.close();
735 public Boolean deleteArtifact( Artifact artifact )
736 throws ArchivaRestServiceException
739 String repositoryId = artifact.getContext();
740 // some rest call can use context or repositoryId
742 if ( StringUtils.isEmpty( repositoryId ) )
744 repositoryId = artifact.getRepositoryId();
746 if ( StringUtils.isEmpty( repositoryId ) )
748 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
751 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
753 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
756 if ( artifact == null )
758 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
761 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
763 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
766 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
768 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
771 // TODO more control on artifact fields
773 boolean snapshotVersion =
774 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
776 RepositorySession repositorySession = repositorySessionFactory.createSession();
779 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
781 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
782 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
783 fmt.setTimeZone( timezone );
784 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
786 VersionedReference ref = new VersionedReference();
787 ref.setArtifactId( artifact.getArtifactId() );
788 ref.setGroupId( artifact.getGroupId() );
789 ref.setVersion( artifact.getVersion() );
791 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
793 ArtifactReference artifactReference = new ArtifactReference();
794 artifactReference.setArtifactId( artifact.getArtifactId() );
795 artifactReference.setGroupId( artifact.getGroupId() );
796 artifactReference.setVersion( artifact.getVersion() );
797 artifactReference.setClassifier( artifact.getClassifier() );
798 artifactReference.setType( artifact.getPackaging() );
800 MetadataRepository metadataRepository = repositorySession.getRepository();
802 String path = repository.toMetadataPath( ref );
804 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
806 if ( StringUtils.isBlank( artifact.getPackaging() ) )
808 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
812 repository.deleteArtifact( artifactReference );
818 int index = path.lastIndexOf( '/' );
819 path = path.substring( 0, index );
820 File targetPath = new File( repoConfig.getLocation(), path );
822 if ( !targetPath.exists() )
824 //throw new ContentNotFoundException(
825 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
826 log.warn( "targetPath {} not found skip file deletion", targetPath );
829 // TODO: this should be in the storage mechanism so that it is all tied together
830 // delete from file system
831 if ( !snapshotVersion )
833 repository.deleteVersion( ref );
837 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
838 log.debug( "related: {}", related );
839 for ( ArtifactReference artifactRef : related )
841 repository.deleteArtifact( artifactRef );
844 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
845 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
847 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
849 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
851 if ( snapshotVersion )
853 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
855 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
861 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
862 artifact.getVersion() );
865 log.debug( "artifacts: {}", artifacts );
867 if ( artifacts.isEmpty() )
869 if ( !snapshotVersion )
871 // verify metata repository doesn't contains anymore the version
872 Collection<String> projectVersions =
873 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
874 artifact.getArtifactId() );
876 if ( projectVersions.contains( artifact.getVersion() ) )
878 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
879 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
880 artifact.getArtifactId(), artifact.getVersion() );
886 for ( ArtifactMetadata artifactMetadata : artifacts )
889 // TODO: mismatch between artifact (snapshot) version and project (base) version here
890 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
892 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
894 if ( StringUtils.isBlank( artifact.getPackaging() ) )
896 throw new ArchivaRestServiceException(
897 "You must configure a type/packaging when using classifier", 400, null );
899 // cleanup facet which contains classifier information
900 MavenArtifactFacet mavenArtifactFacet =
901 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
903 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
905 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
906 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
907 artifact.getVersion();
908 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
909 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
910 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
911 mavenArtifactFacetToCompare );
912 metadataRepository.save();
918 if ( snapshotVersion )
920 metadataRepository.removeArtifact( artifactMetadata,
921 VersionUtil.getBaseVersion( artifact.getVersion() ) );
925 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
926 artifactMetadata.getNamespace(),
927 artifactMetadata.getProject(), artifact.getVersion(),
928 artifactMetadata.getId() );
931 // TODO: move into the metadata repository proper - need to differentiate attachment of
932 // repository metadata to an artifact
933 for ( RepositoryListener listener : listeners )
935 listener.deleteArtifact( metadataRepository, repository.getId(),
936 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
937 artifactMetadata.getVersion(), artifactMetadata.getId() );
940 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
944 catch ( ContentNotFoundException e )
946 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
948 catch ( RepositoryNotFoundException e )
950 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
952 catch ( RepositoryException e )
954 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
956 catch ( MetadataResolutionException e )
958 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
960 catch ( MetadataRepositoryException e )
962 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
964 catch ( RepositoryAdminException e )
966 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
971 repositorySession.save();
973 repositorySession.close();
979 public Boolean deleteGroupId( String groupId, String repositoryId )
980 throws ArchivaRestServiceException
982 if ( StringUtils.isEmpty( repositoryId ) )
984 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
987 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
989 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
992 if ( StringUtils.isEmpty( groupId ) )
994 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
997 RepositorySession repositorySession = repositorySessionFactory.createSession();
1001 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1003 repository.deleteGroupId( groupId );
1005 MetadataRepository metadataRepository = repositorySession.getRepository();
1007 metadataRepository.removeNamespace( repositoryId, groupId );
1009 // just invalidate cache entry
1010 String cacheKey = repositoryId + "-" + groupId;
1011 namespacesCache.remove( cacheKey );
1012 namespacesCache.remove( repositoryId );
1014 metadataRepository.save();
1016 catch ( MetadataRepositoryException e )
1018 log.error( e.getMessage(), e );
1019 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1021 catch ( RepositoryException e )
1023 log.error( e.getMessage(), e );
1024 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1029 repositorySession.close();
1035 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1036 throws ArchivaRestServiceException
1038 if ( StringUtils.isEmpty( repositoryId ) )
1040 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1043 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1045 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1048 if ( StringUtils.isEmpty( groupId ) )
1050 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1053 if ( StringUtils.isEmpty( projectId ) )
1055 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1058 RepositorySession repositorySession = repositorySessionFactory.createSession();
1062 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1064 repository.deleteProject( groupId, projectId );
1066 catch ( ContentNotFoundException e )
1068 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1070 catch ( RepositoryException e )
1072 log.error( e.getMessage(), e );
1073 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1079 MetadataRepository metadataRepository = repositorySession.getRepository();
1081 metadataRepository.removeProject( repositoryId, groupId, projectId );
1083 metadataRepository.save();
1085 catch ( MetadataRepositoryException e )
1087 log.error( e.getMessage(), e );
1088 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1093 repositorySession.close();
1100 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1101 throws ArchivaRestServiceException
1104 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1108 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1110 catch ( ArchivaSecurityException e )
1112 throw new ArchivaRestServiceException( e.getMessage(),
1113 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1118 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1119 throws ArchivaRestServiceException
1121 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1124 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1126 catch ( RepositoryScannerException e )
1128 log.error( e.getMessage(), e );
1129 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1131 catch ( RepositoryAdminException e )
1133 log.error( e.getMessage(), e );
1134 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1139 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1143 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
1145 throws RepositoryMetadataException
1147 List<String> availableVersions = new ArrayList<>();
1148 String latestVersion = "";
1150 if ( metadataFile.exists() )
1152 if ( metadata.getAvailableVersions() != null )
1154 availableVersions = metadata.getAvailableVersions();
1156 if ( availableVersions.size() > 0 )
1158 Collections.sort( availableVersions, VersionComparator.getInstance() );
1160 if ( availableVersions.contains( artifact.getVersion() ) )
1162 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1164 if ( availableVersions.size() > 0 )
1166 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1172 if ( metadata.getGroupId() == null )
1174 metadata.setGroupId( artifact.getGroupId() );
1176 if ( metadata.getArtifactId() == null )
1178 metadata.setArtifactId( artifact.getArtifactId() );
1181 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1183 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1184 artifact.getVersion() ) )
1186 metadata.setReleasedVersion( latestVersion );
1190 metadata.setLatestVersion( latestVersion );
1191 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1192 metadata.setAvailableVersions( availableVersions );
1194 RepositoryMetadataWriter.write( metadata, metadataFile );
1195 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1196 checksum.fixChecksums( algorithms );
1200 public StringList getRunningRemoteDownloadIds()
1202 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1205 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1207 return managedRepositoryAdmin;
1210 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1212 this.managedRepositoryAdmin = managedRepositoryAdmin;
1215 public RepositoryContentFactory getRepositoryFactory()
1217 return repositoryFactory;
1220 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1222 this.repositoryFactory = repositoryFactory;
1225 public RepositorySessionFactory getRepositorySessionFactory()
1227 return repositorySessionFactory;
1230 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1232 this.repositorySessionFactory = repositorySessionFactory;
1235 public List<RepositoryListener> getListeners()
1240 public void setListeners( List<RepositoryListener> listeners )
1242 this.listeners = listeners;
1245 public ArchivaAdministration getArchivaAdministration()
1247 return archivaAdministration;
1250 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1252 this.archivaAdministration = archivaAdministration;