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.checksum.ChecksumAlgorithm;
25 import org.apache.archiva.checksum.ChecksummedFile;
26 import org.apache.archiva.common.utils.VersionComparator;
27 import org.apache.archiva.common.utils.VersionUtil;
28 import org.apache.archiva.maven2.model.Artifact;
29 import org.apache.archiva.metadata.model.ArtifactMetadata;
30 import org.apache.archiva.metadata.model.facets.AuditEvent;
31 import org.apache.archiva.metadata.maven.model.MavenArtifactFacet;
32 import org.apache.archiva.metadata.repository.*;
33 import org.apache.archiva.model.ArchivaRepositoryMetadata;
34 import org.apache.archiva.model.ArtifactReference;
35 import org.apache.archiva.model.VersionedReference;
36 import org.apache.archiva.redback.authentication.AuthenticationResult;
37 import org.apache.archiva.redback.authorization.AuthorizationException;
38 import org.apache.archiva.components.cache.Cache;
39 import org.apache.archiva.components.taskqueue.TaskQueueException;
40 import org.apache.archiva.redback.system.DefaultSecuritySession;
41 import org.apache.archiva.redback.system.SecuritySession;
42 import org.apache.archiva.redback.system.SecuritySystem;
43 import org.apache.archiva.redback.users.User;
44 import org.apache.archiva.redback.users.UserManagerException;
45 import org.apache.archiva.redback.users.UserNotFoundException;
46 import org.apache.archiva.repository.ContentNotFoundException;
47 import org.apache.archiva.repository.LayoutException;
48 import org.apache.archiva.repository.ManagedRepository;
49 import org.apache.archiva.repository.ManagedRepositoryContent;
50 import org.apache.archiva.repository.RepositoryException;
51 import org.apache.archiva.repository.RepositoryNotFoundException;
52 import org.apache.archiva.repository.RepositoryRegistry;
53 import org.apache.archiva.repository.RepositoryType;
54 import org.apache.archiva.repository.storage.fs.FsStorageUtil;
55 import org.apache.archiva.repository.storage.RepositoryStorage;
56 import org.apache.archiva.repository.storage.StorageAsset;
57 import org.apache.archiva.metadata.audit.RepositoryListener;
58 import org.apache.archiva.repository.metadata.base.MetadataTools;
59 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
60 import org.apache.archiva.repository.metadata.base.RepositoryMetadataWriter;
61 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
62 import org.apache.archiva.repository.scanner.RepositoryScanner;
63 import org.apache.archiva.repository.scanner.RepositoryScannerException;
64 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
65 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
66 import org.apache.archiva.rest.api.model.StringList;
67 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
68 import org.apache.archiva.rest.api.services.RepositoriesService;
69 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
70 import org.apache.archiva.scheduler.indexing.maven.ArchivaIndexingTaskExecutor;
71 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
72 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
73 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
74 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
75 import org.apache.archiva.security.ArchivaSecurityException;
76 import org.apache.archiva.security.common.ArchivaRoleConstants;
77 import org.apache.commons.io.FilenameUtils;
78 import org.apache.commons.lang3.StringUtils;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.stereotype.Service;
84 import javax.inject.Inject;
85 import javax.inject.Named;
86 import javax.ws.rs.core.Response;
87 import java.io.IOException;
88 import java.io.OutputStreamWriter;
89 import java.nio.file.Path;
90 import java.text.DateFormat;
91 import java.text.SimpleDateFormat;
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.Calendar;
95 import java.util.Collection;
96 import java.util.Collections;
97 import java.util.Date;
98 import java.util.List;
99 import java.util.TimeZone;
102 * @author Olivier Lamy
105 @Service("repositoriesService#rest")
106 public class DefaultRepositoriesService
107 extends AbstractRestService
108 implements RepositoriesService
110 private Logger log = LoggerFactory.getLogger( getClass() );
113 @Named(value = "taskExecutor#indexing")
114 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
117 private RepositoryRegistry repositoryRegistry;
120 private SecuritySystem securitySystem;
123 @Named(value = "archivaTaskScheduler#repository")
124 private ArchivaTaskScheduler<RepositoryTask> scheduler;
127 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
130 @Named(value = "repositorySessionFactory")
131 protected RepositorySessionFactory repositorySessionFactory;
134 @Autowired(required = false)
135 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
138 private RepositoryScanner repoScanner;
141 * Cache used for namespaces
144 @Named(value = "cache#namespaces")
145 private Cache<String, Collection<String>> namespacesCache;
147 private List<ChecksumAlgorithm> algorithms = Arrays.asList(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 );
150 public Boolean scanRepository( String repositoryId, boolean fullScan )
152 return doScanRepository( repositoryId, fullScan );
156 public Boolean alreadyScanning( String repositoryId )
158 // check queue first to make sure it doesn't get dequeued between calls
159 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
163 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
165 if ( scan.getRepository().getId().equals( 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 );
189 private ManagedRepositoryContent getManagedRepositoryContent(String id) throws RepositoryException
191 org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( id );
193 throw new RepositoryException( "Repository not found "+id );
195 return repo.getContent();
199 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
200 throws ArchivaRestServiceException
206 org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository( repositoryId );
209 ArtifactIndexingTask task =
210 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, repository.getIndexingContext() );
212 task.setExecuteOnEntireRepo( true );
213 task.setOnlyUpdate( !fullScan );
215 archivaIndexingTaskExecutor.executeTask( task );
217 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
221 catch ( Exception e )
223 log.error( e.getMessage(), e );
224 throw new ArchivaRestServiceException( e.getMessage(), e );
229 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
230 throws ArchivaRestServiceException
234 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
236 catch ( DownloadRemoteIndexException e )
238 log.error( e.getMessage(), e );
239 throw new ArchivaRestServiceException( e.getMessage(), e );
245 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
246 throws ArchivaRestServiceException
249 String userName = getAuditInformation().getUser().getUsername();
250 if ( StringUtils.isBlank( userName ) )
252 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
255 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
257 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
260 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
262 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
265 ManagedRepository source = null;
266 source = repositoryRegistry.getManagedRepository( artifactTransferRequest.getRepositoryId() );
268 if ( source == null )
270 throw new ArchivaRestServiceException(
271 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
274 ManagedRepository target = null;
275 target = repositoryRegistry.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
277 if ( target == null )
279 throw new ArchivaRestServiceException(
280 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
283 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
285 throw new ArchivaRestServiceException( "groupId is mandatory", null );
288 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
290 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
293 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
295 throw new ArchivaRestServiceException( "version is mandatory", null );
298 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
300 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
303 // end check parameters
308 user = securitySystem.getUserManager().findUser( userName );
310 catch ( UserNotFoundException e )
312 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
314 catch ( UserManagerException e )
316 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
319 // check karma on source : read
320 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
321 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
325 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
326 artifactTransferRequest.getRepositoryId() );
329 throw new ArchivaRestServiceException(
330 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
333 catch ( AuthorizationException e )
335 log.error( "error reading permission: {}", e.getMessage(), e );
336 throw new ArchivaRestServiceException( e.getMessage(), e );
339 // check karma on target: write
343 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
344 artifactTransferRequest.getTargetRepositoryId() );
347 throw new ArchivaRestServiceException(
348 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
351 catch ( AuthorizationException e )
353 log.error( "error reading permission: {}", e.getMessage(), e );
354 throw new ArchivaRestServiceException( e.getMessage(), e );
357 // sounds good we can continue !
359 ArtifactReference artifactReference = new ArtifactReference();
360 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
361 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
362 artifactReference.setVersion( artifactTransferRequest.getVersion() );
363 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
364 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
365 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
370 ManagedRepositoryContent sourceRepository =
371 getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
373 String artifactSourcePath = sourceRepository.toPath( artifactReference );
375 if ( StringUtils.isEmpty( artifactSourcePath ) )
377 log.error( "cannot find artifact {}", artifactTransferRequest );
378 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
382 StorageAsset artifactFile = source.getAsset( artifactSourcePath );
384 if ( !artifactFile.exists() )
386 log.error( "cannot find artifact {}", artifactTransferRequest );
387 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
391 ManagedRepositoryContent targetRepository =
392 getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
394 String artifactPath = targetRepository.toPath( artifactReference );
396 int lastIndex = artifactPath.lastIndexOf( '/' );
398 String path = artifactPath.substring( 0, lastIndex );
399 StorageAsset targetDir = target.getAsset( path );
401 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
402 int newBuildNumber = 1;
403 String timestamp = null;
405 StorageAsset versionMetadataFile = target.getAsset(path + "/" + MetadataTools.MAVEN_METADATA );
406 /* unused */ getMetadata( targetRepository.getRepository().getType(), versionMetadataFile );
408 if ( !targetDir.exists() )
410 targetDir = target.addAsset(targetDir.getPath(), true);
414 String filename = artifactPath.substring( lastIndex + 1 );
416 boolean fixChecksums =
417 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
419 StorageAsset targetFile = target.getAsset(targetDir.getPath() + "/" + filename );
420 if ( targetFile.exists() && target.blocksRedeployments())
422 throw new ArchivaRestServiceException(
423 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
424 + " and redeployment blocked", null
429 copyFile(artifactFile, targetFile, fixChecksums );
430 queueRepositoryTask( target.getId(), targetFile );
433 // copy source pom to target repo
434 String pomFilename = filename;
435 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
437 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
439 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
441 StorageAsset pomFile = source.getAsset(
442 artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) )+"/"+ pomFilename );
444 if ( pomFile != null && pomFile.exists() )
446 StorageAsset targetPomFile = target.getAsset( targetDir.getPath() + "/" + pomFilename );
447 copyFile(pomFile, targetPomFile, fixChecksums );
448 queueRepositoryTask( target.getId(), targetPomFile );
453 // explicitly update only if metadata-updater consumer is not enabled!
454 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
456 updateProjectMetadata( target.getType(), target, targetDir, lastUpdatedTimestamp, timestamp, newBuildNumber,
457 fixChecksums, artifactTransferRequest );
463 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
464 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
465 + artifactTransferRequest.getTargetRepositoryId() + "\'";
466 log.debug("copyArtifact {}", msg);
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, StorageAsset localFile )
490 RepositoryTask task = new RepositoryTask();
491 task.setRepositoryId( repositoryId );
492 task.setResourceFile( localFile );
493 task.setUpdateRelatedArtifacts( true );
494 //task.setScanAll( true );
498 scheduler.queueTask( task );
500 catch ( TaskQueueException e )
502 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
503 + "'].", localFile.getName());
507 private ArchivaRepositoryMetadata getMetadata( RepositoryType repositoryType, StorageAsset metadataFile )
508 throws RepositoryMetadataException
510 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
511 if ( metadataFile.exists() )
513 metadata = repositoryRegistry.getMetadataReader( repositoryType ).read( metadataFile );
518 private StorageAsset getMetadata( RepositoryStorage storage, String targetPath )
520 return storage.getAsset( targetPath + "/" + MetadataTools.MAVEN_METADATA );
525 * Copies the asset to the new target.
527 private void copyFile(StorageAsset sourceFile, StorageAsset targetPath, boolean fixChecksums)
531 FsStorageUtil.copyAsset( sourceFile, targetPath, true );
534 fixChecksums( targetPath );
538 private void fixChecksums( StorageAsset file )
540 Path destinationFile = file.getFilePath();
541 if (destinationFile!=null)
543 ChecksummedFile checksum = new ChecksummedFile( destinationFile );
544 checksum.fixChecksums( algorithms );
548 private void updateProjectMetadata( RepositoryType repositoryType, RepositoryStorage storage, StorageAsset targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
549 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
550 throws RepositoryMetadataException
552 List<String> availableVersions = new ArrayList<>();
553 String latestVersion = artifactTransferRequest.getVersion();
555 StorageAsset projectDir = targetPath.getParent();
556 StorageAsset projectMetadataFile = storage.getAsset( projectDir.getPath()+"/"+MetadataTools.MAVEN_METADATA );
558 ArchivaRepositoryMetadata projectMetadata = getMetadata( repositoryType, projectMetadataFile );
560 if ( projectMetadataFile.exists() )
562 availableVersions = projectMetadata.getAvailableVersions();
564 Collections.sort( availableVersions, VersionComparator.getInstance() );
566 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
568 availableVersions.add( artifactTransferRequest.getVersion() );
571 latestVersion = availableVersions.get( availableVersions.size() - 1 );
575 availableVersions.add( artifactTransferRequest.getVersion() );
577 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
578 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
581 if ( projectMetadata.getGroupId() == null )
583 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
586 if ( projectMetadata.getArtifactId() == null )
588 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
591 projectMetadata.setLatestVersion( latestVersion );
592 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
593 projectMetadata.setAvailableVersions( availableVersions );
595 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
597 projectMetadata.setReleasedVersion( latestVersion );
600 try(OutputStreamWriter writer = new OutputStreamWriter(projectMetadataFile.getWriteStream(true))) {
601 RepositoryMetadataWriter.write(projectMetadata, writer);
602 } catch (IOException e) {
603 throw new RepositoryMetadataException(e);
608 fixChecksums( projectMetadataFile );
613 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
614 throws ArchivaRestServiceException
616 // if not a generic we can use the standard way to delete artifact
617 if ( !VersionUtil.isGenericSnapshot( version ) )
619 Artifact artifact = new Artifact( namespace, projectId, version );
620 artifact.setRepositoryId( repositoryId );
621 artifact.setContext( repositoryId );
622 return deleteArtifact( artifact );
625 if ( StringUtils.isEmpty( repositoryId ) )
627 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
630 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
632 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
635 if ( StringUtils.isEmpty( namespace ) )
637 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
640 if ( StringUtils.isEmpty( projectId ) )
642 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
645 if ( StringUtils.isEmpty( version ) )
647 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
650 RepositorySession repositorySession = null;
653 repositorySession = repositorySessionFactory.createSession();
655 catch ( MetadataRepositoryException e )
657 e.printStackTrace( );
662 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
664 VersionedReference ref = new VersionedReference();
665 ref.setArtifactId( projectId );
666 ref.setGroupId( namespace );
667 ref.setVersion( version );
669 repository.deleteVersion( ref );
672 ArtifactReference artifactReference = new ArtifactReference();
673 artifactReference.setGroupId( namespace );
674 artifactReference.setArtifactId( projectId );
675 artifactReference.setVersion( version );
677 MetadataRepository metadataRepository = repositorySession.getRepository();
679 List<ArtifactReference> related = repository.getRelatedArtifacts( repository.toVersion(artifactReference) );
680 log.debug( "related: {}", related );
681 for ( ArtifactReference artifactRef : related )
683 repository.deleteArtifact( artifactRef );
686 Collection<ArtifactMetadata> artifacts =
687 metadataRepository.getArtifacts(repositorySession , repositoryId, namespace, projectId, version );
689 for ( ArtifactMetadata artifactMetadata : artifacts )
691 metadataRepository.removeTimestampedArtifact(repositorySession , artifactMetadata, version );
694 metadataRepository.removeProjectVersion(repositorySession , repositoryId, namespace, projectId, version );
696 catch ( MetadataRepositoryException | MetadataResolutionException | RepositoryException | LayoutException e )
698 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
704 repositorySession.save();
705 } catch (MetadataSessionException e) {
706 log.error("Session save failed {}", e.getMessage());
709 repositorySession.close();
717 public Boolean deleteArtifact( Artifact artifact )
718 throws ArchivaRestServiceException
721 String repositoryId = artifact.getContext();
722 // some rest call can use context or repositoryId
724 if ( StringUtils.isEmpty( repositoryId ) )
726 repositoryId = artifact.getRepositoryId();
728 if ( StringUtils.isEmpty( repositoryId ) )
730 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
733 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
735 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
738 if ( artifact == null )
740 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
743 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
745 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
748 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
750 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
753 // TODO more control on artifact fields
755 boolean snapshotVersion =
756 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
758 RepositorySession repositorySession = null;
761 repositorySession = repositorySessionFactory.createSession();
763 catch ( MetadataRepositoryException e )
765 e.printStackTrace( );
769 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
771 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
772 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
773 fmt.setTimeZone( timezone );
774 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
776 VersionedReference ref = new VersionedReference();
777 ref.setArtifactId( artifact.getArtifactId() );
778 ref.setGroupId( artifact.getGroupId() );
779 ref.setVersion( artifact.getVersion() );
781 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
783 ArtifactReference artifactReference = new ArtifactReference();
784 artifactReference.setArtifactId( artifact.getArtifactId() );
785 artifactReference.setGroupId( artifact.getGroupId() );
786 artifactReference.setVersion( artifact.getVersion() );
787 artifactReference.setClassifier( artifact.getClassifier() );
788 artifactReference.setType( artifact.getType() );
790 MetadataRepository metadataRepository = repositorySession.getRepository();
792 String path = repository.toMetadataPath( ref );
794 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
796 if ( StringUtils.isBlank( artifact.getPackaging() ) )
798 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
801 List<ArtifactReference> artifacts = repository.getRelatedArtifacts( artifactReference );
802 for (ArtifactReference aRef : artifacts ) {
803 repository.deleteArtifact( aRef );
810 int index = path.lastIndexOf( '/' );
811 path = path.substring( 0, index );
812 StorageAsset targetPath = repo.getAsset( path );
814 if ( !targetPath.exists() )
816 //throw new ContentNotFoundException(
817 // artifact.getNamespace() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
818 log.warn( "targetPath {} not found skip file deletion", targetPath );
822 // TODO: this should be in the storage mechanism so that it is all tied together
823 // delete from file system
824 if ( !snapshotVersion )
826 repository.deleteVersion( ref );
830 // We are deleting all version related artifacts for a snapshot version
831 VersionedReference versionRef = repository.toVersion( artifactReference );
832 List<ArtifactReference> related = repository.getRelatedArtifacts( versionRef );
833 log.debug( "related: {}", related );
834 for ( ArtifactReference artifactRef : related )
838 repository.deleteArtifact( artifactRef );
839 } catch (ContentNotFoundException e) {
840 log.warn( "Artifact that should be deleted, was not found: {}", artifactRef );
843 StorageAsset metadataFile = getMetadata( repo, targetPath.getPath() );
844 ArchivaRepositoryMetadata metadata = getMetadata( repository.getRepository().getType(), metadataFile );
846 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
849 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
851 if ( snapshotVersion )
853 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
855 metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
856 artifact.getArtifactId(), baseVersion );
861 metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
862 artifact.getArtifactId(), 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(repositorySession , repositoryId,
874 artifact.getGroupId(), 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(repositorySession , repositoryId,
880 artifact.getGroupId(), 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.removeFacetFromArtifact(repositorySession , repositoryId, groupId, artifactId,
911 version, mavenArtifactFacetToCompare );
912 repositorySession.save();
918 if ( snapshotVersion )
920 metadataRepository.removeTimestampedArtifact(repositorySession ,
921 artifactMetadata, VersionUtil.getBaseVersion( artifact.getVersion() ) );
925 metadataRepository.removeArtifact(repositorySession ,
926 artifactMetadata.getRepositoryId(),
927 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
928 artifact.getVersion(), 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 | MetadataSessionException | MetadataRepositoryException | LayoutException e )
958 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
964 repositorySession.save();
965 } catch (MetadataSessionException e) {
966 log.error("Could not save sesion {}", e.getMessage());
969 repositorySession.close();
975 public Boolean deleteGroupId( String groupId, String repositoryId )
976 throws ArchivaRestServiceException
978 if ( StringUtils.isEmpty( repositoryId ) )
980 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
983 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
985 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
988 if ( StringUtils.isEmpty( groupId ) )
990 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
993 RepositorySession repositorySession = null;
996 repositorySession = repositorySessionFactory.createSession();
998 catch ( MetadataRepositoryException e )
1000 e.printStackTrace( );
1005 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1007 repository.deleteGroupId( groupId );
1009 MetadataRepository metadataRepository = repositorySession.getRepository();
1011 metadataRepository.removeNamespace(repositorySession , repositoryId, groupId );
1013 // just invalidate cache entry
1014 String cacheKey = repositoryId + "-" + groupId;
1015 namespacesCache.remove( cacheKey );
1016 namespacesCache.remove( repositoryId );
1018 repositorySession.save();
1020 catch (MetadataRepositoryException | MetadataSessionException e )
1022 log.error( e.getMessage(), e );
1023 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1025 catch ( RepositoryException e )
1027 log.error( e.getMessage(), e );
1028 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1033 repositorySession.close();
1039 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1040 throws ArchivaRestServiceException
1042 if ( StringUtils.isEmpty( repositoryId ) )
1044 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1047 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1049 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1052 if ( StringUtils.isEmpty( groupId ) )
1054 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1057 if ( StringUtils.isEmpty( projectId ) )
1059 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1062 RepositorySession repositorySession = null;
1065 repositorySession = repositorySessionFactory.createSession();
1067 catch ( MetadataRepositoryException e )
1069 e.printStackTrace( );
1074 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1076 repository.deleteProject( groupId, projectId );
1078 catch ( ContentNotFoundException e )
1080 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1082 catch ( RepositoryException e )
1084 log.error( e.getMessage(), e );
1085 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1091 MetadataRepository metadataRepository = repositorySession.getRepository();
1093 metadataRepository.removeProject(repositorySession , repositoryId, groupId, projectId );
1095 repositorySession.save();
1097 catch (MetadataRepositoryException | MetadataSessionException e )
1099 log.error( e.getMessage(), e );
1100 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1105 repositorySession.close();
1112 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1113 throws ArchivaRestServiceException
1116 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1120 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1122 catch ( ArchivaSecurityException e )
1124 throw new ArchivaRestServiceException( e.getMessage(),
1125 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1130 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1131 throws ArchivaRestServiceException
1133 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1136 return repoScanner.scan( repositoryRegistry.getManagedRepository( repositoryId ), sinceWhen );
1138 catch ( RepositoryScannerException e )
1140 log.error( e.getMessage(), e );
1141 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1146 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1150 private void updateMetadata( ArchivaRepositoryMetadata metadata, StorageAsset metadataFile, Date lastUpdatedTimestamp,
1152 throws RepositoryMetadataException
1154 List<String> availableVersions = new ArrayList<>();
1155 String latestVersion = "";
1157 if ( metadataFile.exists() )
1159 if ( metadata.getAvailableVersions() != null )
1161 availableVersions = metadata.getAvailableVersions();
1163 if ( availableVersions.size() > 0 )
1165 Collections.sort( availableVersions, VersionComparator.getInstance() );
1167 if ( availableVersions.contains( artifact.getVersion() ) )
1169 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1171 if ( availableVersions.size() > 0 )
1173 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1179 if ( metadata.getGroupId() == null )
1181 metadata.setGroupId( artifact.getGroupId() );
1183 if ( metadata.getArtifactId() == null )
1185 metadata.setArtifactId( artifact.getArtifactId() );
1188 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1190 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1191 artifact.getVersion() ) )
1193 metadata.setReleasedVersion( latestVersion );
1197 metadata.setLatestVersion( latestVersion );
1198 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1199 metadata.setAvailableVersions( availableVersions );
1201 try (OutputStreamWriter writer = new OutputStreamWriter(metadataFile.getWriteStream(true))) {
1202 RepositoryMetadataWriter.write(metadata, writer);
1203 } catch (IOException e) {
1204 throw new RepositoryMetadataException(e);
1206 ChecksummedFile checksum = new ChecksummedFile( metadataFile.getFilePath() );
1207 checksum.fixChecksums( algorithms );
1211 public StringList getRunningRemoteDownloadIds()
1213 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1216 public RepositorySessionFactory getRepositorySessionFactory()
1218 return repositorySessionFactory;
1221 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1223 this.repositorySessionFactory = repositorySessionFactory;
1226 public List<RepositoryListener> getListeners()
1231 public void setListeners( List<RepositoryListener> listeners )
1233 this.listeners = listeners;
1236 public ArchivaAdministration getArchivaAdministration()
1238 return archivaAdministration;
1241 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1243 this.archivaAdministration = archivaAdministration;