1 package org.apache.archiva.rest.services;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.admin.ArchivaAdministration;
24 import org.apache.archiva.admin.model.beans.ManagedRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.audit.AuditEvent;
27 import org.apache.archiva.checksum.ChecksumAlgorithm;
28 import org.apache.archiva.checksum.ChecksummedFile;
29 import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
31 import org.apache.archiva.common.utils.VersionComparator;
32 import org.apache.archiva.common.utils.VersionUtil;
33 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
34 import org.apache.archiva.maven2.model.Artifact;
35 import org.apache.archiva.metadata.model.ArtifactMetadata;
36 import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
37 import org.apache.archiva.metadata.repository.MetadataRepository;
38 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
39 import org.apache.archiva.metadata.repository.MetadataResolutionException;
40 import org.apache.archiva.metadata.repository.RepositorySession;
41 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
42 import org.apache.archiva.model.ArchivaRepositoryMetadata;
43 import org.apache.archiva.model.ArtifactReference;
44 import org.apache.archiva.model.VersionedReference;
45 import org.apache.archiva.redback.authentication.AuthenticationResult;
46 import org.apache.archiva.redback.authorization.AuthorizationException;
47 import org.apache.archiva.redback.components.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.UserManagerException;
53 import org.apache.archiva.redback.users.UserNotFoundException;
54 import org.apache.archiva.repository.ContentNotFoundException;
55 import org.apache.archiva.repository.ManagedRepositoryContent;
56 import org.apache.archiva.repository.RepositoryContentFactory;
57 import org.apache.archiva.repository.RepositoryException;
58 import org.apache.archiva.repository.RepositoryNotFoundException;
59 import org.apache.archiva.repository.events.RepositoryListener;
60 import org.apache.archiva.repository.metadata.MetadataTools;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
62 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
63 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
64 import org.apache.archiva.repository.scanner.RepositoryScanner;
65 import org.apache.archiva.repository.scanner.RepositoryScannerException;
66 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
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.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.archiva.xml.XMLException;
78 import org.apache.commons.io.FilenameUtils;
79 import org.apache.commons.io.IOUtils;
80 import org.apache.commons.lang.StringUtils;
81 import org.apache.maven.index.context.IndexingContext;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.springframework.stereotype.Service;
86 import javax.inject.Inject;
87 import javax.inject.Named;
88 import javax.ws.rs.core.Response;
90 import java.io.FileInputStream;
91 import java.io.FileOutputStream;
92 import java.io.IOException;
93 import java.text.DateFormat;
94 import java.text.SimpleDateFormat;
95 import java.util.ArrayList;
96 import java.util.Calendar;
97 import java.util.Collection;
98 import java.util.Collections;
99 import java.util.Date;
100 import java.util.List;
101 import java.util.Set;
102 import java.util.TimeZone;
105 * @author Olivier Lamy
108 @Service( "repositoriesService#rest" )
109 public class DefaultRepositoriesService
110 extends AbstractRestService
111 implements RepositoriesService
113 private Logger log = LoggerFactory.getLogger( getClass() );
116 @Named( value = "taskExecutor#indexing" )
117 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
120 private ManagedRepositoryAdmin managedRepositoryAdmin;
123 private PlexusSisuBridge plexusSisuBridge;
126 private MavenIndexerUtils mavenIndexerUtils;
129 private SecuritySystem securitySystem;
132 private RepositoryContentFactory repositoryFactory;
135 @Named( value = "archivaTaskScheduler#repository" )
136 private ArchivaTaskScheduler scheduler;
139 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
142 @Named( value = "repositorySessionFactory" )
143 protected RepositorySessionFactory repositorySessionFactory;
146 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
149 private RepositoryScanner repoScanner;
151 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
153 public Boolean scanRepository( String repositoryId, boolean fullScan )
155 return doScanRepository( repositoryId, fullScan );
158 public Boolean alreadyScanning( String repositoryId )
160 return repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId );
163 public Boolean removeScanningTaskFromQueue( String repositoryId )
165 RepositoryTask task = new RepositoryTask();
166 task.setRepositoryId( repositoryId );
169 return repositoryTaskScheduler.unQueueTask( task );
171 catch ( TaskQueueException e )
173 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
178 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
179 throws ArchivaRestServiceException
184 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
186 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
188 ArtifactIndexingTask task =
189 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
191 task.setExecuteOnEntireRepo( true );
192 task.setOnlyUpdate( !fullScan );
194 archivaIndexingTaskExecutor.executeTask( task );
197 catch ( Exception e )
199 log.error( e.getMessage(), e );
200 throw new ArchivaRestServiceException( e.getMessage(), e );
204 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
205 throws ArchivaRestServiceException
209 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
211 catch ( DownloadRemoteIndexException e )
213 log.error( e.getMessage(), e );
214 throw new ArchivaRestServiceException( e.getMessage(), e );
219 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
220 throws ArchivaRestServiceException
223 String userName = getAuditInformation().getUser().getUsername();
224 if ( StringUtils.isBlank( userName ) )
226 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
229 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
231 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
234 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
236 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
239 ManagedRepository source = null;
242 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
244 catch ( RepositoryAdminException e )
246 throw new ArchivaRestServiceException( e.getMessage(), e );
249 if ( source == null )
251 throw new ArchivaRestServiceException(
252 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
255 ManagedRepository target = null;
258 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
260 catch ( RepositoryAdminException e )
262 throw new ArchivaRestServiceException( e.getMessage(), e );
265 if ( target == null )
267 throw new ArchivaRestServiceException(
268 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
271 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
273 throw new ArchivaRestServiceException( "groupId is mandatory", null );
276 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
278 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
281 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
283 throw new ArchivaRestServiceException( "version is mandatory", null );
286 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
288 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
291 // end check parameters
296 user = securitySystem.getUserManager().findUser( userName );
298 catch ( UserNotFoundException e )
300 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
302 catch ( UserManagerException e )
304 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
307 // check karma on source : read
308 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
309 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
313 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
314 artifactTransferRequest.getRepositoryId() );
317 throw new ArchivaRestServiceException(
318 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
321 catch ( AuthorizationException e )
323 log.error( "error reading permission: " + e.getMessage(), e );
324 throw new ArchivaRestServiceException( e.getMessage(), e );
327 // check karma on target: write
331 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
332 artifactTransferRequest.getTargetRepositoryId() );
335 throw new ArchivaRestServiceException(
336 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
339 catch ( AuthorizationException e )
341 log.error( "error reading permission: " + e.getMessage(), e );
342 throw new ArchivaRestServiceException( e.getMessage(), e );
345 // sounds good we can continue !
347 ArtifactReference artifactReference = new ArtifactReference();
348 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
349 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
350 artifactReference.setVersion( artifactTransferRequest.getVersion() );
351 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
352 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
353 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
358 ManagedRepositoryContent sourceRepository =
359 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
361 String artifactSourcePath = sourceRepository.toPath( artifactReference );
363 if ( StringUtils.isEmpty( artifactSourcePath ) )
365 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
366 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
370 File artifactFile = new File( source.getLocation(), artifactSourcePath );
372 if ( !artifactFile.exists() )
374 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
375 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
379 ManagedRepositoryContent targetRepository =
380 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
382 String artifactPath = targetRepository.toPath( artifactReference );
384 int lastIndex = artifactPath.lastIndexOf( '/' );
386 String path = artifactPath.substring( 0, lastIndex );
387 File targetPath = new File( target.getLocation(), path );
389 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
390 int newBuildNumber = 1;
391 String timestamp = null;
393 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
394 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
396 if ( !targetPath.exists() )
401 String filename = artifactPath.substring( lastIndex + 1 );
403 boolean fixChecksums =
404 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
406 File targetFile = new File( targetPath, filename );
407 if ( targetFile.exists() && target.isBlockRedeployments() )
409 throw new ArchivaRestServiceException(
410 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
411 + " and redeployment blocked", null );
415 copyFile( artifactFile, targetPath, filename, fixChecksums );
416 queueRepositoryTask( target.getId(), targetFile );
419 // copy source pom to target repo
420 String pomFilename = filename;
421 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
423 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
425 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
427 File pomFile = new File(
428 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
431 if ( pomFile != null && pomFile.length() > 0 )
433 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
434 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
439 // explicitly update only if metadata-updater consumer is not enabled!
440 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
442 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
443 fixChecksums, artifactTransferRequest );
449 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
450 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
451 + artifactTransferRequest.getTargetRepositoryId() + "\'";
454 catch ( RepositoryException e )
456 log.error( "RepositoryException: " + e.getMessage(), e );
457 throw new ArchivaRestServiceException( e.getMessage(), e );
459 catch ( RepositoryAdminException e )
461 log.error( "RepositoryAdminException: " + e.getMessage(), e );
462 throw new ArchivaRestServiceException( e.getMessage(), e );
464 catch ( IOException e )
466 log.error( "IOException: " + e.getMessage(), e );
467 throw new ArchivaRestServiceException( e.getMessage(), e );
472 private void queueRepositoryTask( String repositoryId, File localFile )
474 RepositoryTask task = new RepositoryTask();
475 task.setRepositoryId( repositoryId );
476 task.setResourceFile( localFile );
477 task.setUpdateRelatedArtifacts( true );
478 //task.setScanAll( true );
482 scheduler.queueTask( task );
484 catch ( TaskQueueException e )
486 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
491 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
492 throws RepositoryMetadataException
494 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
495 if ( metadataFile.exists() )
499 metadata = MavenMetadataReader.read( metadataFile );
501 catch ( XMLException e )
503 throw new RepositoryMetadataException( e.getMessage(), e );
509 private File getMetadata( String targetPath )
511 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
513 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
516 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
519 FileOutputStream out = new FileOutputStream( new File( targetPath, targetFilename ) );
520 FileInputStream input = new FileInputStream( sourceFile );
524 IOUtils.copy( input, out );
528 IOUtils.closeQuietly( out );
529 IOUtils.closeQuietly( input );
534 fixChecksums( new File( targetPath, targetFilename ) );
538 private void fixChecksums( File file )
540 ChecksummedFile checksum = new ChecksummedFile( file );
541 checksum.fixChecksums( algorithms );
544 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
545 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
546 throws RepositoryMetadataException
548 List<String> availableVersions = new ArrayList<String>();
549 String latestVersion = artifactTransferRequest.getVersion();
551 File projectDir = new File( targetPath ).getParentFile();
552 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
554 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
556 if ( projectMetadataFile.exists() )
558 availableVersions = projectMetadata.getAvailableVersions();
560 Collections.sort( availableVersions, VersionComparator.getInstance() );
562 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
564 availableVersions.add( artifactTransferRequest.getVersion() );
567 latestVersion = availableVersions.get( availableVersions.size() - 1 );
571 availableVersions.add( artifactTransferRequest.getVersion() );
573 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
574 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
577 if ( projectMetadata.getGroupId() == null )
579 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
582 if ( projectMetadata.getArtifactId() == null )
584 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
587 projectMetadata.setLatestVersion( latestVersion );
588 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
589 projectMetadata.setAvailableVersions( availableVersions );
591 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
593 projectMetadata.setReleasedVersion( latestVersion );
596 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
600 fixChecksums( projectMetadataFile );
604 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
605 throws ArchivaRestServiceException
607 // if not a generic we can use the standard way to delete artifact
608 if ( !VersionUtil.isGenericSnapshot( version ) )
610 Artifact artifact = new Artifact( namespace, projectId, version );
611 return deleteArtifact( artifact );
614 if ( StringUtils.isEmpty( repositoryId ) )
616 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
619 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
621 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
624 if ( StringUtils.isEmpty( namespace ) )
626 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
629 if ( StringUtils.isEmpty( projectId ) )
631 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
634 if ( StringUtils.isEmpty( version ) )
636 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
639 RepositorySession repositorySession = repositorySessionFactory.createSession();
643 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
645 VersionedReference ref = new VersionedReference();
646 ref.setArtifactId( projectId );
647 ref.setGroupId( namespace );
648 ref.setVersion( version );
650 repository.deleteVersion( ref );
653 ProjectReference projectReference = new ProjectReference();
654 projectReference.setGroupId( namespace );
655 projectReference.setArtifactId( projectId );
657 repository.getVersions( )
660 ArtifactReference artifactReference = new ArtifactReference();
661 artifactReference.setGroupId( namespace );
662 artifactReference.setArtifactId( projectId );
663 artifactReference.setVersion( version );
665 MetadataRepository metadataRepository = repositorySession.getRepository();
667 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
668 log.debug( "related: {}", related );
669 for ( ArtifactReference artifactRef : related )
671 repository.deleteArtifact( artifactRef );
674 Collection<ArtifactMetadata> artifacts =
675 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
677 for ( ArtifactMetadata artifactMetadata : artifacts )
679 metadataRepository.removeArtifact( artifactMetadata, version );
682 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
684 catch ( MetadataRepositoryException e )
686 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
688 catch ( MetadataResolutionException e )
690 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
692 catch ( RepositoryException e )
694 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
699 repositorySession.save();
701 repositorySession.close();
707 public Boolean deleteArtifact( Artifact artifact )
708 throws ArchivaRestServiceException
711 String repositoryId = artifact.getContext();
712 if ( StringUtils.isEmpty( repositoryId ) )
714 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
717 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
719 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
722 if ( artifact == null )
724 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
727 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
729 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
732 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
734 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
737 // TODO more control on artifact fields
739 boolean snapshotVersion =
740 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
742 RepositorySession repositorySession = repositorySessionFactory.createSession();
745 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
747 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
748 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
749 fmt.setTimeZone( timezone );
750 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
752 VersionedReference ref = new VersionedReference();
753 ref.setArtifactId( artifact.getArtifactId() );
754 ref.setGroupId( artifact.getGroupId() );
755 ref.setVersion( artifact.getVersion() );
757 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
759 ArtifactReference artifactReference = new ArtifactReference();
760 artifactReference.setArtifactId( artifact.getArtifactId() );
761 artifactReference.setGroupId( artifact.getGroupId() );
762 artifactReference.setVersion( artifact.getVersion() );
763 artifactReference.setClassifier( artifact.getClassifier() );
764 artifactReference.setType( artifact.getPackaging() );
766 MetadataRepository metadataRepository = repositorySession.getRepository();
768 String path = repository.toMetadataPath( ref );
770 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
772 if ( StringUtils.isBlank( artifact.getPackaging() ) )
774 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
778 repository.deleteArtifact( artifactReference );
784 int index = path.lastIndexOf( '/' );
785 path = path.substring( 0, index );
786 File targetPath = new File( repoConfig.getLocation(), path );
788 if ( !targetPath.exists() )
790 //throw new ContentNotFoundException(
791 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
792 log.warn( "targetPath {} not found skip file deletion", targetPath );
795 // TODO: this should be in the storage mechanism so that it is all tied together
796 // delete from file system
797 if ( !snapshotVersion )
799 repository.deleteVersion( ref );
803 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
804 log.debug( "related: {}", related );
805 for ( ArtifactReference artifactRef : related )
807 repository.deleteArtifact( artifactRef );
810 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
811 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
813 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
815 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
817 if ( snapshotVersion )
819 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
821 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
827 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
828 artifact.getVersion() );
831 log.debug( "artifacts: {}", artifacts );
833 if ( artifacts.isEmpty() )
835 if ( !snapshotVersion )
837 // verify metata repository doesn't contains anymore the version
838 Collection<String> projectVersions =
839 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
840 artifact.getArtifactId() );
842 if ( projectVersions.contains( artifact.getVersion() ) )
844 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
845 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
846 artifact.getArtifactId(), artifact.getVersion() );
852 for ( ArtifactMetadata artifactMetadata : artifacts )
855 // TODO: mismatch between artifact (snapshot) version and project (base) version here
856 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
858 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
860 if ( StringUtils.isBlank( artifact.getPackaging() ) )
862 throw new ArchivaRestServiceException(
863 "You must configure a type/packaging when using classifier", 400, null );
865 // cleanup facet which contains classifier information
866 MavenArtifactFacet mavenArtifactFacet =
867 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
869 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
871 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
872 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
873 artifact.getVersion();
874 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
875 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
876 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
877 mavenArtifactFacetToCompare );
878 metadataRepository.save();
884 if ( snapshotVersion )
886 metadataRepository.removeArtifact( artifactMetadata,
887 VersionUtil.getBaseVersion( artifact.getVersion() ) );
891 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
892 artifactMetadata.getNamespace(),
893 artifactMetadata.getProject(), artifact.getVersion(),
894 artifactMetadata.getId() );
897 // TODO: move into the metadata repository proper - need to differentiate attachment of
898 // repository metadata to an artifact
899 for ( RepositoryListener listener : listeners )
901 listener.deleteArtifact( metadataRepository, repository.getId(),
902 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
903 artifactMetadata.getVersion(), artifactMetadata.getId() );
906 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
910 catch ( ContentNotFoundException e )
912 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
914 catch ( RepositoryNotFoundException e )
916 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
918 catch ( RepositoryException e )
920 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
922 catch ( MetadataResolutionException e )
924 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
926 catch ( MetadataRepositoryException e )
928 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
930 catch ( RepositoryAdminException e )
932 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
937 repositorySession.save();
939 repositorySession.close();
944 public Boolean deleteGroupId( String groupId, String repositoryId )
945 throws ArchivaRestServiceException
947 if ( StringUtils.isEmpty( repositoryId ) )
949 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
952 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
954 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
957 if ( StringUtils.isEmpty( groupId ) )
959 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
962 RepositorySession repositorySession = repositorySessionFactory.createSession();
966 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
968 repository.deleteGroupId( groupId );
970 MetadataRepository metadataRepository = repositorySession.getRepository();
972 metadataRepository.removeNamespace( repositoryId, groupId );
974 metadataRepository.save();
976 catch ( MetadataRepositoryException e )
978 log.error( e.getMessage(), e );
979 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
981 catch ( RepositoryException e )
983 log.error( e.getMessage(), e );
984 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
989 repositorySession.close();
994 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
995 throws ArchivaRestServiceException
997 if ( StringUtils.isEmpty( repositoryId ) )
999 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1002 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1004 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1007 if ( StringUtils.isEmpty( groupId ) )
1009 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1012 if ( StringUtils.isEmpty( projectId ) )
1014 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1017 RepositorySession repositorySession = repositorySessionFactory.createSession();
1021 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1023 repository.deleteProject( groupId, projectId );
1025 catch ( ContentNotFoundException e )
1027 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1029 catch ( RepositoryException e )
1031 log.error( e.getMessage(), e );
1032 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1038 MetadataRepository metadataRepository = repositorySession.getRepository();
1040 metadataRepository.removeProject( repositoryId, groupId, projectId );
1042 metadataRepository.save();
1044 catch ( MetadataRepositoryException e )
1046 log.error( e.getMessage(), e );
1047 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1052 repositorySession.close();
1058 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1059 throws ArchivaRestServiceException
1062 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1066 return 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;