1 package org.apache.archiva.rest.services;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.admin.ArchivaAdministration;
24 import org.apache.archiva.admin.model.beans.ManagedRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.audit.AuditEvent;
27 import org.apache.archiva.checksum.ChecksumAlgorithm;
28 import org.apache.archiva.checksum.ChecksummedFile;
29 import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
31 import org.apache.archiva.common.utils.VersionComparator;
32 import org.apache.archiva.common.utils.VersionUtil;
33 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
34 import org.apache.archiva.maven2.model.Artifact;
35 import org.apache.archiva.metadata.model.ArtifactMetadata;
36 import org.apache.archiva.metadata.repository.MetadataRepository;
37 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
38 import org.apache.archiva.metadata.repository.MetadataResolutionException;
39 import org.apache.archiva.metadata.repository.RepositorySession;
40 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
41 import org.apache.archiva.metadata.repository.storage.maven2.MavenArtifactFacet;
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.taskqueue.TaskQueueException;
48 import org.apache.archiva.redback.system.DefaultSecuritySession;
49 import org.apache.archiva.redback.system.SecuritySession;
50 import org.apache.archiva.redback.system.SecuritySystem;
51 import org.apache.archiva.redback.users.User;
52 import org.apache.archiva.redback.users.UserNotFoundException;
53 import org.apache.archiva.repository.ContentNotFoundException;
54 import org.apache.archiva.repository.ManagedRepositoryContent;
55 import org.apache.archiva.repository.RepositoryContentFactory;
56 import org.apache.archiva.repository.RepositoryException;
57 import org.apache.archiva.repository.RepositoryNotFoundException;
58 import org.apache.archiva.repository.events.RepositoryListener;
59 import org.apache.archiva.repository.metadata.MetadataTools;
60 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
62 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
63 import org.apache.archiva.repository.scanner.RepositoryScanner;
64 import org.apache.archiva.repository.scanner.RepositoryScannerException;
65 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
66 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
67 import org.apache.archiva.rest.api.services.RepositoriesService;
68 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
69 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
70 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
71 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
72 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
73 import org.apache.archiva.scheduler.repository.RepositoryTask;
74 import org.apache.archiva.security.ArchivaSecurityException;
75 import org.apache.archiva.security.common.ArchivaRoleConstants;
76 import org.apache.archiva.xml.XMLException;
77 import org.apache.commons.io.FilenameUtils;
78 import org.apache.commons.io.IOUtils;
79 import org.apache.commons.lang.StringUtils;
80 import org.apache.maven.index.context.IndexingContext;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import org.springframework.stereotype.Service;
85 import javax.inject.Inject;
86 import javax.inject.Named;
87 import javax.ws.rs.core.Response;
89 import java.io.FileInputStream;
90 import java.io.FileOutputStream;
91 import java.io.IOException;
92 import java.text.DateFormat;
93 import java.text.SimpleDateFormat;
94 import java.util.ArrayList;
95 import java.util.Calendar;
96 import java.util.Collection;
97 import java.util.Collections;
98 import java.util.Date;
99 import java.util.List;
100 import java.util.Set;
101 import java.util.TimeZone;
104 * @author Olivier Lamy
107 @Service ( "repositoriesService#rest" )
108 public class DefaultRepositoriesService
109 extends AbstractRestService
110 implements RepositoriesService
112 private Logger log = LoggerFactory.getLogger( getClass() );
115 @Named ( value = "taskExecutor#indexing" )
116 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
119 private ManagedRepositoryAdmin managedRepositoryAdmin;
122 private PlexusSisuBridge plexusSisuBridge;
125 private MavenIndexerUtils mavenIndexerUtils;
128 private SecuritySystem securitySystem;
131 private RepositoryContentFactory repositoryFactory;
134 @Named ( value = "archivaTaskScheduler#repository" )
135 private ArchivaTaskScheduler scheduler;
138 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
141 @Named ( value = "repositorySessionFactory" )
142 protected RepositorySessionFactory repositorySessionFactory;
145 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
148 private RepositoryScanner repoScanner;
150 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
152 public Boolean scanRepository( String repositoryId, boolean fullScan )
154 return doScanRepository( repositoryId, fullScan );
157 public Boolean alreadyScanning( String repositoryId )
159 return repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId );
162 public Boolean removeScanningTaskFromQueue( String repositoryId )
164 RepositoryTask task = new RepositoryTask();
165 task.setRepositoryId( repositoryId );
168 return repositoryTaskScheduler.unQueueTask( task );
170 catch ( TaskQueueException e )
172 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
177 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
178 throws ArchivaRestServiceException
183 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
185 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
187 ArtifactIndexingTask task =
188 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
190 task.setExecuteOnEntireRepo( true );
191 task.setOnlyUpdate( !fullScan );
193 archivaIndexingTaskExecutor.executeTask( task );
196 catch ( Exception e )
198 log.error( e.getMessage(), e );
199 throw new ArchivaRestServiceException( e.getMessage(), e );
203 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
204 throws ArchivaRestServiceException
208 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
210 catch ( DownloadRemoteIndexException e )
212 log.error( e.getMessage(), e );
213 throw new ArchivaRestServiceException( e.getMessage(), e );
218 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
219 throws ArchivaRestServiceException
222 String userName = getAuditInformation().getUser().getUsername();
223 if ( StringUtils.isBlank( userName ) )
225 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
228 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
230 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
233 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
235 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
238 ManagedRepository source = null;
241 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
243 catch ( RepositoryAdminException e )
245 throw new ArchivaRestServiceException( e.getMessage(), e );
248 if ( source == null )
250 throw new ArchivaRestServiceException(
251 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
254 ManagedRepository target = null;
257 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
259 catch ( RepositoryAdminException e )
261 throw new ArchivaRestServiceException( e.getMessage(), e );
264 if ( target == null )
266 throw new ArchivaRestServiceException(
267 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
270 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
272 throw new ArchivaRestServiceException( "groupId is mandatory", null );
275 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
277 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
280 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
282 throw new ArchivaRestServiceException( "version is mandatory", null );
285 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
287 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
290 // end check parameters
295 user = securitySystem.getUserManager().findUser( userName );
297 catch ( UserNotFoundException e )
299 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
302 // check karma on source : read
303 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
304 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
308 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
309 artifactTransferRequest.getRepositoryId() );
312 throw new ArchivaRestServiceException(
313 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
316 catch ( AuthorizationException e )
318 log.error( "error reading permission: " + e.getMessage(), e );
319 throw new ArchivaRestServiceException( e.getMessage(), e );
322 // check karma on target: write
326 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
327 artifactTransferRequest.getTargetRepositoryId() );
330 throw new ArchivaRestServiceException(
331 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
334 catch ( AuthorizationException e )
336 log.error( "error reading permission: " + e.getMessage(), e );
337 throw new ArchivaRestServiceException( e.getMessage(), e );
340 // sounds good we can continue !
342 ArtifactReference artifactReference = new ArtifactReference();
343 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
344 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
345 artifactReference.setVersion( artifactTransferRequest.getVersion() );
346 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
347 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
348 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
353 ManagedRepositoryContent sourceRepository =
354 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
356 String artifactSourcePath = sourceRepository.toPath( artifactReference );
358 if ( StringUtils.isEmpty( artifactSourcePath ) )
360 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
361 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
365 File artifactFile = new File( source.getLocation(), artifactSourcePath );
367 if ( !artifactFile.exists() )
369 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
370 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
374 ManagedRepositoryContent targetRepository =
375 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
377 String artifactPath = targetRepository.toPath( artifactReference );
379 int lastIndex = artifactPath.lastIndexOf( '/' );
381 String path = artifactPath.substring( 0, lastIndex );
382 File targetPath = new File( target.getLocation(), path );
384 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
385 int newBuildNumber = 1;
386 String timestamp = null;
388 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
389 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
391 if ( !targetPath.exists() )
396 String filename = artifactPath.substring( lastIndex + 1 );
398 // FIXME some dupe with uploadaction
400 boolean fixChecksums =
401 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
403 File targetFile = new File( targetPath, filename );
404 if ( targetFile.exists() && target.isBlockRedeployments() )
406 throw new ArchivaRestServiceException(
407 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
408 + " and redeployment blocked", null );
412 copyFile( artifactFile, targetPath, filename, fixChecksums );
413 queueRepositoryTask( target.getId(), targetFile );
416 // copy source pom to target repo
417 String pomFilename = filename;
418 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
420 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
422 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
424 File pomFile = new File(
425 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
428 if ( pomFile != null && pomFile.length() > 0 )
430 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
431 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
436 // explicitly update only if metadata-updater consumer is not enabled!
437 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
439 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
440 fixChecksums, artifactTransferRequest );
446 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
447 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
448 + artifactTransferRequest.getTargetRepositoryId() + "\'";
451 catch ( RepositoryException e )
453 log.error( "RepositoryException: " + e.getMessage(), e );
454 throw new ArchivaRestServiceException( e.getMessage(), e );
456 catch ( RepositoryAdminException e )
458 log.error( "RepositoryAdminException: " + e.getMessage(), e );
459 throw new ArchivaRestServiceException( e.getMessage(), e );
461 catch ( IOException e )
463 log.error( "IOException: " + e.getMessage(), e );
464 throw new ArchivaRestServiceException( e.getMessage(), e );
469 //FIXME some duplicate with UploadAction
471 private void queueRepositoryTask( String repositoryId, File localFile )
473 RepositoryTask task = new RepositoryTask();
474 task.setRepositoryId( repositoryId );
475 task.setResourceFile( localFile );
476 task.setUpdateRelatedArtifacts( true );
477 //task.setScanAll( true );
481 scheduler.queueTask( task );
483 catch ( TaskQueueException e )
485 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
490 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
491 throws RepositoryMetadataException
493 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
494 if ( metadataFile.exists() )
498 metadata = MavenMetadataReader.read( metadataFile );
500 catch ( XMLException e )
502 throw new RepositoryMetadataException( e.getMessage(), e );
508 private File getMetadata( String targetPath )
510 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
512 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
515 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
518 FileOutputStream out = new FileOutputStream( new File( targetPath, targetFilename ) );
519 FileInputStream input = new FileInputStream( sourceFile );
523 IOUtils.copy( input, out );
527 IOUtils.closeQuietly( out );
528 IOUtils.closeQuietly( input );
533 fixChecksums( new File( targetPath, targetFilename ) );
537 private void fixChecksums( File file )
539 ChecksummedFile checksum = new ChecksummedFile( file );
540 checksum.fixChecksums( algorithms );
543 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
544 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
545 throws RepositoryMetadataException
547 List<String> availableVersions = new ArrayList<String>();
548 String latestVersion = artifactTransferRequest.getVersion();
550 File projectDir = new File( targetPath ).getParentFile();
551 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
553 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
555 if ( projectMetadataFile.exists() )
557 availableVersions = projectMetadata.getAvailableVersions();
559 Collections.sort( availableVersions, VersionComparator.getInstance() );
561 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
563 availableVersions.add( artifactTransferRequest.getVersion() );
566 latestVersion = availableVersions.get( availableVersions.size() - 1 );
570 availableVersions.add( artifactTransferRequest.getVersion() );
572 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
573 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
576 if ( projectMetadata.getGroupId() == null )
578 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
581 if ( projectMetadata.getArtifactId() == null )
583 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
586 projectMetadata.setLatestVersion( latestVersion );
587 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
588 projectMetadata.setAvailableVersions( availableVersions );
590 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
592 projectMetadata.setReleasedVersion( latestVersion );
595 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
599 fixChecksums( projectMetadataFile );
603 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
604 throws ArchivaRestServiceException
606 // if not a generic we can use the standard way to delete artifact
607 if ( !VersionUtil.isGenericSnapshot( version ) )
609 Artifact artifact = new Artifact( namespace, projectId, version );
610 return deleteArtifact( artifact );
613 if ( StringUtils.isEmpty( repositoryId ) )
615 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
618 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
620 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
623 if ( StringUtils.isEmpty( namespace ) )
625 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
628 if ( StringUtils.isEmpty( projectId ) )
630 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
633 if ( StringUtils.isEmpty( version ) )
635 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
638 RepositorySession repositorySession = repositorySessionFactory.createSession();
642 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
644 VersionedReference ref = new VersionedReference();
645 ref.setArtifactId( projectId );
646 ref.setGroupId( namespace );
647 ref.setVersion( version );
649 repository.deleteVersion( ref );
652 ProjectReference projectReference = new ProjectReference();
653 projectReference.setGroupId( namespace );
654 projectReference.setArtifactId( projectId );
656 repository.getVersions( )
659 ArtifactReference artifactReference = new ArtifactReference();
660 artifactReference.setGroupId( namespace );
661 artifactReference.setArtifactId( projectId );
662 artifactReference.setVersion( version );
664 MetadataRepository metadataRepository = repositorySession.getRepository();
666 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
667 log.debug( "related: {}", related );
668 for ( ArtifactReference artifactRef : related )
670 repository.deleteArtifact( artifactRef );
673 Collection<ArtifactMetadata> artifacts =
674 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
676 for ( ArtifactMetadata artifactMetadata : artifacts )
678 metadataRepository.removeArtifact( artifactMetadata, version );
681 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
683 catch ( MetadataRepositoryException e )
685 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
687 catch ( MetadataResolutionException e )
689 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
691 catch ( RepositoryException e )
693 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
698 repositorySession.save();
700 repositorySession.close();
706 public Boolean deleteArtifact( Artifact artifact )
707 throws ArchivaRestServiceException
710 String repositoryId = artifact.getContext();
711 if ( StringUtils.isEmpty( repositoryId ) )
713 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
716 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
718 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
721 if ( artifact == null )
723 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
726 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
728 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
731 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
733 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
736 // TODO more control on artifact fields
738 boolean snapshotVersion =
739 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
741 RepositorySession repositorySession = repositorySessionFactory.createSession();
744 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
746 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
747 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
748 fmt.setTimeZone( timezone );
749 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
751 VersionedReference ref = new VersionedReference();
752 ref.setArtifactId( artifact.getArtifactId() );
753 ref.setGroupId( artifact.getGroupId() );
754 ref.setVersion( artifact.getVersion() );
756 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
758 ArtifactReference artifactReference = new ArtifactReference();
759 artifactReference.setArtifactId( artifact.getArtifactId() );
760 artifactReference.setGroupId( artifact.getGroupId() );
761 artifactReference.setVersion( artifact.getVersion() );
762 artifactReference.setClassifier( artifact.getClassifier() );
763 artifactReference.setType( artifact.getPackaging() );
765 MetadataRepository metadataRepository = repositorySession.getRepository();
767 String path = repository.toMetadataPath( ref );
769 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
771 if ( StringUtils.isBlank( artifact.getPackaging() ) )
773 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
777 repository.deleteArtifact( artifactReference );
783 int index = path.lastIndexOf( '/' );
784 path = path.substring( 0, index );
785 File targetPath = new File( repoConfig.getLocation(), path );
787 if ( !targetPath.exists() )
789 //throw new ContentNotFoundException(
790 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
791 log.warn( "targetPath {} not found skip file deletion", targetPath );
794 // TODO: this should be in the storage mechanism so that it is all tied together
795 // delete from file system
796 if ( !snapshotVersion )
798 repository.deleteVersion( ref );
802 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
803 log.debug( "related: {}", related );
804 for ( ArtifactReference artifactRef : related )
806 repository.deleteArtifact( artifactRef );
809 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
810 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
812 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
814 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
816 if ( snapshotVersion )
818 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
820 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
826 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
827 artifact.getVersion() );
830 log.debug( "artifacts: {}", artifacts );
832 if ( artifacts.isEmpty() )
834 if ( !snapshotVersion )
836 // verify metata repository doesn't contains anymore the version
837 Collection<String> projectVersions =
838 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
839 artifact.getArtifactId() );
841 if ( projectVersions.contains( artifact.getVersion() ) )
843 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
844 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
845 artifact.getArtifactId(), artifact.getVersion() );
851 for ( ArtifactMetadata artifactMetadata : artifacts )
854 // TODO: mismatch between artifact (snapshot) version and project (base) version here
855 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
857 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
859 if ( StringUtils.isBlank( artifact.getPackaging() ) )
861 throw new ArchivaRestServiceException(
862 "You must configure a type/packaging when using classifier", 400, null );
864 // cleanup facet which contains classifier information
865 MavenArtifactFacet mavenArtifactFacet =
866 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
868 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
870 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
871 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
872 artifact.getVersion();
873 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
874 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
875 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
876 mavenArtifactFacetToCompare );
877 metadataRepository.save();
883 if ( snapshotVersion )
885 metadataRepository.removeArtifact( artifactMetadata,
886 VersionUtil.getBaseVersion( artifact.getVersion() ) );
890 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
891 artifactMetadata.getNamespace(),
892 artifactMetadata.getProject(), artifact.getVersion(),
893 artifactMetadata.getId() );
896 // TODO: move into the metadata repository proper - need to differentiate attachment of
897 // repository metadata to an artifact
898 for ( RepositoryListener listener : listeners )
900 listener.deleteArtifact( metadataRepository, repository.getId(),
901 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
902 artifactMetadata.getVersion(), artifactMetadata.getId() );
905 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
909 catch ( ContentNotFoundException e )
911 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
913 catch ( RepositoryNotFoundException e )
915 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
917 catch ( RepositoryException e )
919 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
921 catch ( MetadataResolutionException e )
923 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
925 catch ( MetadataRepositoryException e )
927 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
929 catch ( RepositoryAdminException e )
931 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
936 repositorySession.save();
938 repositorySession.close();
943 public Boolean deleteGroupId( String groupId, String repositoryId )
944 throws ArchivaRestServiceException
946 if ( StringUtils.isEmpty( repositoryId ) )
948 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
951 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
953 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
956 if ( StringUtils.isEmpty( groupId ) )
958 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
961 RepositorySession repositorySession = repositorySessionFactory.createSession();
965 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
967 repository.deleteGroupId( groupId );
969 MetadataRepository metadataRepository = repositorySession.getRepository();
971 metadataRepository.removeNamespace( repositoryId, groupId );
973 metadataRepository.save();
975 catch ( MetadataRepositoryException e )
977 log.error( e.getMessage(), e );
978 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
980 catch ( RepositoryException e )
982 log.error( e.getMessage(), e );
983 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
988 repositorySession.close();
993 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
994 throws ArchivaRestServiceException
996 if ( StringUtils.isEmpty( repositoryId ) )
998 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1001 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1003 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1006 if ( StringUtils.isEmpty( groupId ) )
1008 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1011 if ( StringUtils.isEmpty( projectId ) )
1013 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1016 RepositorySession repositorySession = repositorySessionFactory.createSession();
1020 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1022 repository.deleteProject( groupId, projectId );
1024 catch ( ContentNotFoundException e )
1026 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1028 catch ( RepositoryException e )
1030 log.error( e.getMessage(), e );
1031 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1037 MetadataRepository metadataRepository = repositorySession.getRepository();
1039 metadataRepository.removeProject( repositoryId, groupId, projectId );
1041 metadataRepository.save();
1043 catch ( MetadataRepositoryException e )
1045 log.error( e.getMessage(), e );
1046 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1051 repositorySession.close();
1057 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1058 throws ArchivaRestServiceException
1061 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1065 boolean res = userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1068 catch ( ArchivaSecurityException e )
1070 throw new ArchivaRestServiceException( e.getMessage(),
1071 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1075 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1076 throws ArchivaRestServiceException
1078 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1081 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1083 catch ( RepositoryScannerException e )
1085 log.error( e.getMessage(), e );
1086 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1088 catch ( RepositoryAdminException e )
1090 log.error( e.getMessage(), e );
1091 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1096 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1100 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
1102 throws RepositoryMetadataException
1104 List<String> availableVersions = new ArrayList<String>();
1105 String latestVersion = "";
1107 if ( metadataFile.exists() )
1109 if ( metadata.getAvailableVersions() != null )
1111 availableVersions = metadata.getAvailableVersions();
1113 if ( availableVersions.size() > 0 )
1115 Collections.sort( availableVersions, VersionComparator.getInstance() );
1117 if ( availableVersions.contains( artifact.getVersion() ) )
1119 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1121 if ( availableVersions.size() > 0 )
1123 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1129 if ( metadata.getGroupId() == null )
1131 metadata.setGroupId( artifact.getGroupId() );
1133 if ( metadata.getArtifactId() == null )
1135 metadata.setArtifactId( artifact.getArtifactId() );
1138 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1140 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1141 artifact.getVersion() ) )
1143 metadata.setReleasedVersion( latestVersion );
1147 metadata.setLatestVersion( latestVersion );
1148 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1149 metadata.setAvailableVersions( availableVersions );
1151 RepositoryMetadataWriter.write( metadata, metadataFile );
1152 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1153 checksum.fixChecksums( algorithms );
1156 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1158 return managedRepositoryAdmin;
1161 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1163 this.managedRepositoryAdmin = managedRepositoryAdmin;
1166 public RepositoryContentFactory getRepositoryFactory()
1168 return repositoryFactory;
1171 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1173 this.repositoryFactory = repositoryFactory;
1176 public RepositorySessionFactory getRepositorySessionFactory()
1178 return repositorySessionFactory;
1181 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1183 this.repositorySessionFactory = repositorySessionFactory;
1186 public List<RepositoryListener> getListeners()
1191 public void setListeners( List<RepositoryListener> listeners )
1193 this.listeners = listeners;
1196 public ArchivaAdministration getArchivaAdministration()
1198 return archivaAdministration;
1201 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1203 this.archivaAdministration = archivaAdministration;