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.components.cache.Cache;
29 import org.apache.archiva.components.taskqueue.TaskQueueException;
30 import org.apache.archiva.maven2.model.Artifact;
31 import org.apache.archiva.metadata.audit.RepositoryListener;
32 import org.apache.archiva.metadata.maven.model.MavenArtifactFacet;
33 import org.apache.archiva.metadata.model.ArtifactMetadata;
34 import org.apache.archiva.metadata.model.facets.AuditEvent;
35 import org.apache.archiva.metadata.repository.MetadataRepository;
36 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
37 import org.apache.archiva.metadata.repository.MetadataResolutionException;
38 import org.apache.archiva.metadata.repository.MetadataSessionException;
39 import org.apache.archiva.metadata.repository.RepositorySession;
40 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
41 import org.apache.archiva.model.ArchivaRepositoryMetadata;
42 import org.apache.archiva.redback.authentication.AuthenticationResult;
43 import org.apache.archiva.redback.authorization.AuthorizationException;
44 import org.apache.archiva.redback.system.DefaultSecuritySession;
45 import org.apache.archiva.redback.system.SecuritySession;
46 import org.apache.archiva.redback.system.SecuritySystem;
47 import org.apache.archiva.redback.users.User;
48 import org.apache.archiva.redback.users.UserManagerException;
49 import org.apache.archiva.redback.users.UserNotFoundException;
50 import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
51 import org.apache.archiva.repository.content.ContentNotFoundException;
52 import org.apache.archiva.repository.content.LayoutException;
53 import org.apache.archiva.repository.ManagedRepository;
54 import org.apache.archiva.repository.ManagedRepositoryContent;
55 import org.apache.archiva.repository.RepositoryException;
56 import org.apache.archiva.repository.RepositoryNotFoundException;
57 import org.apache.archiva.repository.RepositoryRegistry;
58 import org.apache.archiva.repository.RepositoryType;
59 import org.apache.archiva.repository.content.ContentItem;
60 import org.apache.archiva.repository.content.ItemNotFoundException;
61 import org.apache.archiva.repository.content.ItemSelector;
62 import org.apache.archiva.repository.content.Version;
63 import org.apache.archiva.repository.content.base.ArchivaItemSelector;
64 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
65 import org.apache.archiva.repository.metadata.base.MetadataTools;
66 import org.apache.archiva.repository.metadata.base.RepositoryMetadataWriter;
67 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
68 import org.apache.archiva.repository.scanner.RepositoryScanner;
69 import org.apache.archiva.repository.scanner.RepositoryScannerException;
70 import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
71 import org.apache.archiva.repository.storage.RepositoryStorage;
72 import org.apache.archiva.repository.storage.StorageAsset;
73 import org.apache.archiva.repository.storage.fs.FsStorageUtil;
74 import org.apache.archiva.rest.api.model.ActionStatus;
75 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
76 import org.apache.archiva.rest.api.model.PermissionStatus;
77 import org.apache.archiva.rest.api.model.ScanStatus;
78 import org.apache.archiva.rest.api.model.StringList;
79 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
80 import org.apache.archiva.rest.api.services.RepositoriesService;
81 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
82 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
83 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
84 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
85 import org.apache.archiva.scheduler.indexing.maven.ArchivaIndexingTaskExecutor;
86 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
87 import org.apache.archiva.security.ArchivaSecurityException;
88 import org.apache.archiva.security.common.ArchivaRoleConstants;
89 import org.apache.commons.io.FilenameUtils;
90 import org.apache.commons.lang3.StringUtils;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.springframework.beans.factory.annotation.Autowired;
94 import org.springframework.stereotype.Service;
96 import javax.inject.Inject;
97 import javax.inject.Named;
98 import javax.ws.rs.core.Response;
99 import java.io.IOException;
100 import java.io.OutputStreamWriter;
101 import java.nio.file.Path;
102 import java.text.DateFormat;
103 import java.text.SimpleDateFormat;
104 import java.util.ArrayList;
105 import java.util.Arrays;
106 import java.util.Calendar;
107 import java.util.Collection;
108 import java.util.Collections;
109 import java.util.Date;
110 import java.util.List;
111 import java.util.TimeZone;
114 * @author Olivier Lamy
117 @Service("repositoriesService#rest")
118 public class DefaultRepositoriesService
119 extends AbstractRestService
120 implements RepositoriesService
122 private Logger log = LoggerFactory.getLogger( getClass() );
125 @Named(value = "taskExecutor#indexing")
126 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
129 private RepositoryRegistry repositoryRegistry;
132 private SecuritySystem securitySystem;
135 @Named(value = "archivaTaskScheduler#repository")
136 private ArchivaTaskScheduler<RepositoryTask> scheduler;
139 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
142 @Named(value = "repositorySessionFactory")
143 protected RepositorySessionFactory repositorySessionFactory;
146 @Autowired(required = false)
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 List<ChecksumAlgorithm> algorithms = Arrays.asList(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 );
162 public ActionStatus scanRepository( String repositoryId, boolean fullScan )
164 return new ActionStatus( doScanRepository( repositoryId, fullScan ) );
168 public ScanStatus getScanStatus( String repositoryId )
170 // check queue first to make sure it doesn't get dequeued between calls
171 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
173 return new ScanStatus( true );
175 for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
177 if ( scan.getRepository().getId().equals( repositoryId ) )
179 return new ScanStatus( true );
182 return new ScanStatus( false );
186 public ActionStatus removeScanningTaskFromQueue( String repositoryId )
188 RepositoryTask task = new RepositoryTask();
189 task.setRepositoryId( repositoryId );
192 return new ActionStatus( repositoryTaskScheduler.unQueueTask( task ) );
194 catch ( TaskQueueException e )
196 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
197 return ActionStatus.FAIL;
201 private ManagedRepositoryContent getManagedRepositoryContent( String id) throws RepositoryException
203 org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( id );
205 throw new RepositoryException( "Repository not found "+id );
207 return repo.getContent();
211 public ActionStatus scanRepositoryNow( String repositoryId, boolean fullScan )
212 throws ArchivaRestServiceException
218 org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository( repositoryId );
221 ArtifactIndexingTask task =
222 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, repository.getIndexingContext() );
224 task.setExecuteOnEntireRepo( true );
225 task.setOnlyUpdate( !fullScan );
227 archivaIndexingTaskExecutor.executeTask( task );
229 scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
231 return ActionStatus.SUCCESS;
233 catch ( Exception e )
235 log.error( e.getMessage(), e );
236 throw new ArchivaRestServiceException( e.getMessage(), e );
241 public ActionStatus scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
242 throws ArchivaRestServiceException
246 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
248 catch ( DownloadRemoteIndexException e )
250 log.error( e.getMessage(), e );
251 throw new ArchivaRestServiceException( e.getMessage(), e );
253 return ActionStatus.SUCCESS;
257 public ActionStatus copyArtifact( ArtifactTransferRequest artifactTransferRequest )
258 throws ArchivaRestServiceException
261 String userName = getAuditInformation().getUser().getUsername();
262 if ( StringUtils.isBlank( userName ) )
264 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
267 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
269 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
272 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
274 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
277 ManagedRepository source = null;
278 source = repositoryRegistry.getManagedRepository( artifactTransferRequest.getRepositoryId() );
280 if ( source == null )
282 throw new ArchivaRestServiceException(
283 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
286 ManagedRepository target = null;
287 target = repositoryRegistry.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
289 if ( target == null )
291 throw new ArchivaRestServiceException(
292 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
295 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
297 throw new ArchivaRestServiceException( "groupId is mandatory", null );
300 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
302 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
305 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
307 throw new ArchivaRestServiceException( "version is mandatory", null );
310 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
312 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
315 // end check parameters
320 user = securitySystem.getUserManager().findUser( userName );
322 catch ( UserNotFoundException e )
324 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
326 catch ( UserManagerException e )
328 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
331 // check karma on source : read
332 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
333 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
337 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
338 artifactTransferRequest.getRepositoryId() );
341 throw new ArchivaRestServiceException(
342 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
345 catch ( AuthorizationException e )
347 log.error( "error reading permission: {}", e.getMessage(), e );
348 throw new ArchivaRestServiceException( e.getMessage(), e );
351 // check karma on target: write
355 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
356 artifactTransferRequest.getTargetRepositoryId() );
359 throw new ArchivaRestServiceException(
360 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
363 catch ( AuthorizationException e )
365 log.error( "error reading permission: {}", e.getMessage(), e );
366 throw new ArchivaRestServiceException( e.getMessage(), e );
369 // sounds good we can continue !
371 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
372 ItemSelector selector = ArchivaItemSelector.builder( )
373 .withProjectId( artifactTransferRequest.getArtifactId( ) )
374 .withArtifactId( artifactTransferRequest.getArtifactId( ) )
375 .withNamespace( artifactTransferRequest.getGroupId( ) )
376 .withArtifactVersion( artifactTransferRequest.getVersion( ) )
377 .withClassifier( artifactTransferRequest.getClassifier( ) )
378 .withExtension( StringUtils.isEmpty( packaging ) ? "jar" : packaging )
385 ManagedRepositoryContent sourceRepository =
386 getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
387 BaseRepositoryContentLayout layout = sourceRepository.getLayout( BaseRepositoryContentLayout.class );
388 // String artifactSourcePath = sourceRepository.toPath( selector );
389 org.apache.archiva.repository.content.Artifact sourceArtifact = layout.getArtifact( selector );
391 if ( !sourceArtifact.exists() )
393 log.error( "cannot find artifact {}", artifactTransferRequest );
394 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
398 StorageAsset artifactFile = sourceArtifact.getAsset( );
400 ManagedRepositoryContent targetRepository =
401 getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
403 String artifactPath = artifactFile.getPath( );
405 int lastIndex = artifactPath.lastIndexOf( '/' );
407 String path = artifactPath.substring( 0, lastIndex );
408 StorageAsset targetDir = target.getAsset( path );
410 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
411 int newBuildNumber = 1;
412 String timestamp = null;
414 StorageAsset versionMetadataFile = target.getAsset(path + "/" + MetadataTools.MAVEN_METADATA );
415 /* unused */ getMetadata( targetRepository.getRepository().getType(), versionMetadataFile );
417 if ( !targetDir.exists() )
419 targetDir = target.addAsset(targetDir.getPath(), true);
423 String filename = artifactPath.substring( lastIndex + 1 );
425 boolean fixChecksums =
426 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
428 StorageAsset targetFile = target.getAsset(targetDir.getPath() + "/" + filename );
429 if ( targetFile.exists() && target.blocksRedeployments())
431 throw new ArchivaRestServiceException(
432 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
433 + " and redeployment blocked", null
438 copyFile(artifactFile, targetFile, fixChecksums );
439 queueRepositoryTask( target.getId(), targetFile );
442 // copy source pom to target repo
443 String pomFilename = filename;
444 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
446 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
448 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
450 StorageAsset pomFile = source.getAsset(
451 artifactPath.substring( 0, artifactPath.lastIndexOf( '/' ) )+"/"+ pomFilename );
453 if ( pomFile != null && pomFile.exists() )
455 StorageAsset targetPomFile = target.getAsset( targetDir.getPath() + "/" + pomFilename );
456 copyFile(pomFile, targetPomFile, fixChecksums );
457 queueRepositoryTask( target.getId(), targetPomFile );
462 // explicitly update only if metadata-updater consumer is not enabled!
463 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
465 updateProjectMetadata( target.getType(), target, targetDir, lastUpdatedTimestamp, timestamp, newBuildNumber,
466 fixChecksums, artifactTransferRequest );
472 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
473 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
474 + artifactTransferRequest.getTargetRepositoryId() + "\'";
475 log.debug("copyArtifact {}", msg);
478 catch ( RepositoryException | LayoutException e )
480 log.error( "RepositoryException: {}", e.getMessage(), e );
481 throw new ArchivaRestServiceException( e.getMessage(), e );
483 catch ( RepositoryAdminException e )
485 log.error( "RepositoryAdminException: {}", e.getMessage(), e );
486 throw new ArchivaRestServiceException( e.getMessage(), e );
488 catch ( IOException e )
490 log.error( "IOException: {}", e.getMessage(), e );
491 throw new ArchivaRestServiceException( e.getMessage(), e );
493 return ActionStatus.SUCCESS;
496 private void queueRepositoryTask( String repositoryId, StorageAsset localFile )
499 RepositoryTask task = new RepositoryTask();
500 task.setRepositoryId( repositoryId );
501 task.setResourceFile( localFile );
502 task.setUpdateRelatedArtifacts( true );
503 //task.setScanAll( true );
507 scheduler.queueTask( task );
509 catch ( TaskQueueException e )
511 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
512 + "'].", localFile.getName());
516 private ArchivaRepositoryMetadata getMetadata( RepositoryType repositoryType, StorageAsset metadataFile )
517 throws RepositoryMetadataException
519 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
520 if ( metadataFile.exists() )
522 metadata = repositoryRegistry.getMetadataReader( repositoryType ).read( metadataFile );
527 private StorageAsset getMetadata( RepositoryStorage storage, String targetPath )
529 return storage.getAsset( targetPath + "/" + MetadataTools.MAVEN_METADATA );
534 * Copies the asset to the new target.
536 private void copyFile(StorageAsset sourceFile, StorageAsset targetPath, boolean fixChecksums)
540 FsStorageUtil.copyAsset( sourceFile, targetPath, true );
543 fixChecksums( targetPath );
547 private void fixChecksums( StorageAsset file )
549 Path destinationFile = file.getFilePath();
550 if (destinationFile!=null)
552 ChecksummedFile checksum = new ChecksummedFile( destinationFile );
553 checksum.fixChecksums( algorithms );
557 private void updateProjectMetadata( RepositoryType repositoryType, RepositoryStorage storage, StorageAsset targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
558 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
559 throws RepositoryMetadataException
561 List<String> availableVersions = new ArrayList<>();
562 String latestVersion = artifactTransferRequest.getVersion();
564 StorageAsset projectDir = targetPath.getParent();
565 StorageAsset projectMetadataFile = storage.getAsset( projectDir.getPath()+"/"+MetadataTools.MAVEN_METADATA );
567 ArchivaRepositoryMetadata projectMetadata = getMetadata( repositoryType, projectMetadataFile );
569 if ( projectMetadataFile.exists() )
571 availableVersions = projectMetadata.getAvailableVersions();
573 Collections.sort( availableVersions, VersionComparator.getInstance() );
575 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
577 availableVersions.add( artifactTransferRequest.getVersion() );
580 latestVersion = availableVersions.get( availableVersions.size() - 1 );
584 availableVersions.add( artifactTransferRequest.getVersion() );
586 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
587 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
590 if ( projectMetadata.getGroupId() == null )
592 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
595 if ( projectMetadata.getArtifactId() == null )
597 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
600 projectMetadata.setLatestVersion( latestVersion );
601 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
602 projectMetadata.setAvailableVersions( availableVersions );
604 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
606 projectMetadata.setReleasedVersion( latestVersion );
609 try(OutputStreamWriter writer = new OutputStreamWriter(projectMetadataFile.getWriteStream(true))) {
610 RepositoryMetadataWriter.write(projectMetadata, writer);
611 } catch (IOException e) {
612 throw new RepositoryMetadataException(e);
617 fixChecksums( projectMetadataFile );
622 public ActionStatus removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
623 throws ArchivaRestServiceException
625 // if not a generic we can use the standard way to delete artifact
626 if ( !VersionUtil.isGenericSnapshot( version ) )
628 Artifact artifact = new Artifact( namespace, projectId, version );
629 artifact.setRepositoryId( repositoryId );
630 artifact.setContext( repositoryId );
631 return deleteArtifact( artifact );
634 if ( StringUtils.isEmpty( repositoryId ) )
636 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
639 if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
641 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
644 if ( StringUtils.isEmpty( namespace ) )
646 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
649 if ( StringUtils.isEmpty( projectId ) )
651 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
654 if ( StringUtils.isEmpty( version ) )
656 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
659 RepositorySession repositorySession = null;
662 repositorySession = repositorySessionFactory.createSession();
664 catch ( MetadataRepositoryException e )
666 e.printStackTrace( );
671 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
672 BaseRepositoryContentLayout layout = repository.getLayout( BaseRepositoryContentLayout.class );
674 ArchivaItemSelector selector = ArchivaItemSelector.builder( )
675 .withNamespace( namespace )
676 .withProjectId( projectId )
677 .withVersion( version )
679 Version versionItem = layout.getVersion( selector );
680 if (versionItem!=null && versionItem.exists()) {
681 repository.deleteItem( versionItem );
684 MetadataRepository metadataRepository = repositorySession.getRepository();
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 | ItemNotFoundException | 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();
713 return ActionStatus.SUCCESS;
717 public ActionStatus 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 ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
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() );
757 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion( ) );
759 RepositorySession repositorySession = null;
762 repositorySession = repositorySessionFactory.createSession();
764 catch ( MetadataRepositoryException e )
766 e.printStackTrace( );
770 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
772 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
773 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
774 fmt.setTimeZone( timezone );
775 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
777 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
778 BaseRepositoryContentLayout layout = repository.getLayout( BaseRepositoryContentLayout.class );
780 ArchivaItemSelector versionSelector = ArchivaItemSelector.builder( ).withNamespace( artifact.getGroupId( ) )
781 .withProjectId( artifact.getArtifactId( ) )
782 .withVersion( baseVersion ).build( );
784 Version version1 = layout.getVersion( versionSelector );
785 String path = repository.toPath( version1 );
787 ArchivaItemSelector selector = ArchivaItemSelector.builder( )
788 .withNamespace( artifact.getGroupId( ) )
789 .withProjectId( artifact.getArtifactId( ) )
790 .withVersion( baseVersion )
791 .withClassifier( artifact.getClassifier( ) )
792 .withArtifactId( artifact.getArtifactId( ) )
793 .withType( artifact.getType( ) )
794 .includeRelatedArtifacts()
797 MetadataRepository metadataRepository = repositorySession.getRepository();
799 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
801 if ( StringUtils.isBlank( artifact.getPackaging() ) )
803 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
806 List<? extends org.apache.archiva.repository.content.Artifact> artifactItems = layout.getArtifacts( selector );
807 for ( org.apache.archiva.repository.content.Artifact aRef : artifactItems ) {
810 repository.deleteItem( aRef );
812 catch ( ItemNotFoundException e )
814 log.error( "Could not delete item, seems to be deleted by other thread. {}, {} ", aRef, e.getMessage( ) );
822 int index = path.lastIndexOf( '/' );
823 path = path.substring( 0, index );
824 StorageAsset targetPath = repo.getAsset( path );
826 if ( !targetPath.exists() )
828 //throw new ContentNotFoundException(
829 // artifact.getNamespace() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
830 log.warn( "targetPath {} not found skip file deletion", targetPath );
831 return ActionStatus.FAIL;
834 // TODO: this should be in the storage mechanism so that it is all tied together
835 // delete from file system
836 if ( !snapshotVersion && version1.exists() )
840 repository.deleteItem( version1 );
842 catch ( ItemNotFoundException e )
844 log.error( "Could not delete version item {}", e.getMessage( ) );
849 // We are deleting all version related artifacts for a snapshot version
850 for ( org.apache.archiva.repository.content.Artifact delArtifact : layout.getArtifacts( selector )) {
853 repository.deleteItem( delArtifact );
855 catch ( ItemNotFoundException e )
857 log.warn( "Artifact that should be deleted, was not found: {}", delArtifact );
861 StorageAsset metadataFile = getMetadata( repo, targetPath.getPath() );
862 ArchivaRepositoryMetadata metadata = getMetadata( repository.getRepository().getType(), metadataFile );
863 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
866 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
868 if ( snapshotVersion )
871 metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
872 artifact.getArtifactId(), baseVersion );
877 metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
878 artifact.getArtifactId(), artifact.getVersion() );
881 log.debug( "artifacts: {}", artifacts );
883 if ( artifacts.isEmpty() )
885 if ( !snapshotVersion )
887 // verify metata repository doesn't contains anymore the version
888 Collection<String> projectVersions =
889 metadataRepository.getProjectVersions(repositorySession , repositoryId,
890 artifact.getGroupId(), artifact.getArtifactId() );
892 if ( projectVersions.contains( artifact.getVersion() ) )
894 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
895 metadataRepository.removeProjectVersion(repositorySession , repositoryId,
896 artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() );
902 for ( ArtifactMetadata artifactMetadata : artifacts )
905 // TODO: mismatch between artifact (snapshot) version and project (base) version here
906 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
908 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
910 if ( StringUtils.isBlank( artifact.getPackaging() ) )
912 throw new ArchivaRestServiceException(
913 "You must configure a type/packaging when using classifier", 400, null );
915 // cleanup facet which contains classifier information
916 MavenArtifactFacet mavenArtifactFacet =
917 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
919 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
921 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
922 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
923 artifact.getVersion();
924 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
925 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
926 metadataRepository.removeFacetFromArtifact(repositorySession , repositoryId, groupId, artifactId,
927 version, mavenArtifactFacetToCompare );
928 repositorySession.save();
934 if ( snapshotVersion )
936 metadataRepository.removeTimestampedArtifact(repositorySession ,
937 artifactMetadata, VersionUtil.getBaseVersion( artifact.getVersion() ) );
941 metadataRepository.removeArtifact(repositorySession ,
942 artifactMetadata.getRepositoryId(),
943 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
944 artifact.getVersion(), artifactMetadata.getId() );
947 // TODO: move into the metadata repository proper - need to differentiate attachment of
948 // repository metadata to an artifact
949 for ( RepositoryListener listener : listeners )
951 listener.deleteArtifact( metadataRepository, repository.getId(),
952 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
953 artifactMetadata.getVersion(), artifactMetadata.getId() );
956 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
960 catch ( ContentNotFoundException e )
962 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
964 catch ( RepositoryNotFoundException e )
966 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
968 catch ( RepositoryException e )
970 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
972 catch (MetadataResolutionException | MetadataSessionException | MetadataRepositoryException | LayoutException e )
974 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
980 repositorySession.save();
981 } catch (MetadataSessionException e) {
982 log.error("Could not save sesion {}", e.getMessage());
985 repositorySession.close();
987 return ActionStatus.SUCCESS;
991 public ActionStatus deleteGroupId( String groupId, String repositoryId )
992 throws ArchivaRestServiceException
994 if ( StringUtils.isEmpty( repositoryId ) )
996 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
999 if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
1001 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1004 if ( StringUtils.isEmpty( groupId ) )
1006 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1009 RepositorySession repositorySession = null;
1012 repositorySession = repositorySessionFactory.createSession();
1014 catch ( MetadataRepositoryException e )
1016 e.printStackTrace( );
1021 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1022 ArchivaItemSelector itemselector = ArchivaItemSelector.builder( ).withNamespace( groupId ).build();
1023 ContentItem item = repository.getItem( itemselector );
1024 repository.deleteItem( item );
1026 MetadataRepository metadataRepository = repositorySession.getRepository();
1028 metadataRepository.removeNamespace(repositorySession , repositoryId, groupId );
1030 // just invalidate cache entry
1031 String cacheKey = repositoryId + "-" + groupId;
1032 namespacesCache.remove( cacheKey );
1033 namespacesCache.remove( repositoryId );
1035 repositorySession.save();
1037 catch (MetadataRepositoryException | MetadataSessionException e )
1039 log.error( e.getMessage(), e );
1040 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1042 catch ( RepositoryException e )
1044 log.error( e.getMessage(), e );
1045 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1047 catch ( ItemNotFoundException e )
1049 log.error( "Item not found {}", e.getMessage(), e );
1050 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1055 repositorySession.close();
1057 return ActionStatus.SUCCESS;
1061 public ActionStatus deleteProject( String groupId, String projectId, String repositoryId )
1062 throws ArchivaRestServiceException
1064 if ( StringUtils.isEmpty( repositoryId ) )
1066 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1069 if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
1071 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1074 if ( StringUtils.isEmpty( groupId ) )
1076 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1079 if ( StringUtils.isEmpty( projectId ) )
1081 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1084 RepositorySession repositorySession = null;
1087 repositorySession = repositorySessionFactory.createSession();
1089 catch ( MetadataRepositoryException e )
1091 e.printStackTrace( );
1096 ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
1097 ArchivaItemSelector itemSelector = ArchivaItemSelector.builder( ).withNamespace( groupId )
1098 .withProjectId( projectId ).build( );
1099 ContentItem item = repository.getItem( itemSelector );
1101 repository.deleteItem( item );
1103 catch ( ContentNotFoundException e )
1105 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1107 catch ( RepositoryException e )
1109 log.error( e.getMessage(), e );
1110 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1112 catch ( ItemNotFoundException e )
1114 log.error( "Item not found {}", e.getMessage(), e );
1115 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1121 MetadataRepository metadataRepository = repositorySession.getRepository();
1123 metadataRepository.removeProject(repositorySession , repositoryId, groupId, projectId );
1125 repositorySession.save();
1127 catch (MetadataRepositoryException | MetadataSessionException e )
1129 log.error( e.getMessage(), e );
1130 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1135 repositorySession.close();
1137 return ActionStatus.SUCCESS;
1142 public PermissionStatus getPermissionStatus( String repoId )
1143 throws ArchivaRestServiceException
1146 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1150 return new PermissionStatus( userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId ) );
1152 catch ( ArchivaSecurityException e )
1154 throw new ArchivaRestServiceException( e.getMessage(),
1155 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1160 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1161 throws ArchivaRestServiceException
1163 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1166 return repoScanner.scan( repositoryRegistry.getManagedRepository( repositoryId ), sinceWhen );
1168 catch ( RepositoryScannerException e )
1170 log.error( e.getMessage(), e );
1171 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1176 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1180 private void updateMetadata( ArchivaRepositoryMetadata metadata, StorageAsset metadataFile, Date lastUpdatedTimestamp,
1182 throws RepositoryMetadataException
1184 List<String> availableVersions = new ArrayList<>();
1185 String latestVersion = "";
1187 if ( metadataFile.exists() )
1189 if ( metadata.getAvailableVersions() != null )
1191 availableVersions = metadata.getAvailableVersions();
1193 if ( availableVersions.size() > 0 )
1195 Collections.sort( availableVersions, VersionComparator.getInstance() );
1197 if ( availableVersions.contains( artifact.getVersion() ) )
1199 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1201 if ( availableVersions.size() > 0 )
1203 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1209 if ( metadata.getGroupId() == null )
1211 metadata.setGroupId( artifact.getGroupId() );
1213 if ( metadata.getArtifactId() == null )
1215 metadata.setArtifactId( artifact.getArtifactId() );
1218 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1220 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1221 artifact.getVersion() ) )
1223 metadata.setReleasedVersion( latestVersion );
1227 metadata.setLatestVersion( latestVersion );
1228 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1229 metadata.setAvailableVersions( availableVersions );
1231 try (OutputStreamWriter writer = new OutputStreamWriter(metadataFile.getWriteStream(true))) {
1232 RepositoryMetadataWriter.write(metadata, writer);
1233 } catch (IOException e) {
1234 throw new RepositoryMetadataException(e);
1236 ChecksummedFile checksum = new ChecksummedFile( metadataFile.getFilePath() );
1237 checksum.fixChecksums( algorithms );
1241 public StringList getRunningRemoteDownloadIds()
1243 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1246 public RepositorySessionFactory getRepositorySessionFactory()
1248 return repositorySessionFactory;
1251 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1253 this.repositorySessionFactory = repositorySessionFactory;
1256 public List<RepositoryListener> getListeners()
1261 public void setListeners( List<RepositoryListener> listeners )
1263 this.listeners = listeners;
1266 public ArchivaAdministration getArchivaAdministration()
1268 return archivaAdministration;
1271 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1273 this.archivaAdministration = archivaAdministration;