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.cache.Cache;
48 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
49 import org.apache.archiva.redback.system.DefaultSecuritySession;
50 import org.apache.archiva.redback.system.SecuritySession;
51 import org.apache.archiva.redback.system.SecuritySystem;
52 import org.apache.archiva.redback.users.User;
53 import org.apache.archiva.redback.users.UserManagerException;
54 import org.apache.archiva.redback.users.UserNotFoundException;
55 import org.apache.archiva.repository.ContentNotFoundException;
56 import org.apache.archiva.repository.ManagedRepositoryContent;
57 import org.apache.archiva.repository.RepositoryContentFactory;
58 import org.apache.archiva.repository.RepositoryException;
59 import org.apache.archiva.repository.RepositoryNotFoundException;
60 import org.apache.archiva.repository.events.RepositoryListener;
61 import org.apache.archiva.repository.metadata.MetadataTools;
62 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
63 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
64 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
65 import org.apache.archiva.repository.scanner.RepositoryScanner;
66 import org.apache.archiva.repository.scanner.RepositoryScannerException;
67 import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
68 import org.apache.archiva.rest.api.model.StringList;
69 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
70 import org.apache.archiva.rest.api.services.RepositoriesService;
71 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
72 import org.apache.archiva.scheduler.indexing.ArchivaIndexingTaskExecutor;
73 import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
74 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
75 import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
76 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
77 import org.apache.archiva.security.ArchivaSecurityException;
78 import org.apache.archiva.security.common.ArchivaRoleConstants;
79 import org.apache.archiva.xml.XMLException;
80 import org.apache.commons.io.FilenameUtils;
81 import org.apache.commons.lang.StringUtils;
82 import org.apache.maven.index.context.IndexingContext;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85 import org.springframework.beans.factory.annotation.Autowired;
86 import org.springframework.stereotype.Service;
88 import javax.inject.Inject;
89 import javax.inject.Named;
90 import javax.ws.rs.core.Response;
92 import java.io.IOException;
93 import java.nio.file.Files;
94 import java.nio.file.StandardCopyOption;
95 import java.text.DateFormat;
96 import java.text.SimpleDateFormat;
97 import java.util.ArrayList;
98 import java.util.Calendar;
99 import java.util.Collection;
100 import java.util.Collections;
101 import java.util.Date;
102 import java.util.List;
103 import java.util.Set;
104 import java.util.TimeZone;
107 * @author Olivier Lamy
110 @Service("repositoriesService#rest")
111 public class DefaultRepositoriesService
112 extends AbstractRestService
113 implements RepositoriesService
115 private Logger log = LoggerFactory.getLogger( getClass() );
118 @Named(value = "taskExecutor#indexing")
119 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
122 private ManagedRepositoryAdmin managedRepositoryAdmin;
125 private PlexusSisuBridge plexusSisuBridge;
128 private MavenIndexerUtils mavenIndexerUtils;
131 private SecuritySystem securitySystem;
134 private RepositoryContentFactory repositoryFactory;
137 @Named(value = "archivaTaskScheduler#repository")
138 private ArchivaTaskScheduler scheduler;
141 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
144 @Named(value = "repositorySessionFactory")
145 protected RepositorySessionFactory repositorySessionFactory;
148 @Autowired(required = false)
149 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
152 private RepositoryScanner repoScanner;
155 * Cache used for namespaces
158 @Named(value = "cache#namespaces")
159 private Cache<String, Collection<String>> namespacesCache;
161 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
164 public Boolean scanRepository( String repositoryId, boolean fullScan )
166 return doScanRepository( repositoryId, fullScan );
170 public Boolean alreadyScanning( String repositoryId )
172 return repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId );
176 public Boolean removeScanningTaskFromQueue( String repositoryId )
178 RepositoryTask task = new RepositoryTask();
179 task.setRepositoryId( repositoryId );
182 return repositoryTaskScheduler.unQueueTask( task );
184 catch ( TaskQueueException e )
186 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
192 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
193 throws ArchivaRestServiceException
198 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
200 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
202 ArtifactIndexingTask task =
203 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
205 task.setExecuteOnEntireRepo( true );
206 task.setOnlyUpdate( !fullScan );
208 archivaIndexingTaskExecutor.executeTask( task );
211 catch ( Exception e )
213 log.error( e.getMessage(), e );
214 throw new ArchivaRestServiceException( e.getMessage(), e );
219 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
220 throws ArchivaRestServiceException
224 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
226 catch ( DownloadRemoteIndexException e )
228 log.error( e.getMessage(), e );
229 throw new ArchivaRestServiceException( e.getMessage(), e );
235 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
236 throws ArchivaRestServiceException
239 String userName = getAuditInformation().getUser().getUsername();
240 if ( StringUtils.isBlank( userName ) )
242 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
245 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
247 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
250 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
252 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
255 ManagedRepository source = null;
258 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
260 catch ( RepositoryAdminException e )
262 throw new ArchivaRestServiceException( e.getMessage(), e );
265 if ( source == null )
267 throw new ArchivaRestServiceException(
268 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
271 ManagedRepository target = null;
274 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
276 catch ( RepositoryAdminException e )
278 throw new ArchivaRestServiceException( e.getMessage(), e );
281 if ( target == null )
283 throw new ArchivaRestServiceException(
284 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
287 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
289 throw new ArchivaRestServiceException( "groupId is mandatory", null );
292 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
294 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
297 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
299 throw new ArchivaRestServiceException( "version is mandatory", null );
302 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
304 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
307 // end check parameters
312 user = securitySystem.getUserManager().findUser( userName );
314 catch ( UserNotFoundException e )
316 throw new ArchivaRestServiceException( "user " + userName + " not found", e );
318 catch ( UserManagerException e )
320 throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
323 // check karma on source : read
324 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
325 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
329 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
330 artifactTransferRequest.getRepositoryId() );
333 throw new ArchivaRestServiceException(
334 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
337 catch ( AuthorizationException e )
339 log.error( "error reading permission: " + e.getMessage(), e );
340 throw new ArchivaRestServiceException( e.getMessage(), e );
343 // check karma on target: write
347 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
348 artifactTransferRequest.getTargetRepositoryId() );
351 throw new ArchivaRestServiceException(
352 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
355 catch ( AuthorizationException e )
357 log.error( "error reading permission: " + e.getMessage(), e );
358 throw new ArchivaRestServiceException( e.getMessage(), e );
361 // sounds good we can continue !
363 ArtifactReference artifactReference = new ArtifactReference();
364 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
365 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
366 artifactReference.setVersion( artifactTransferRequest.getVersion() );
367 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
368 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
369 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
374 ManagedRepositoryContent sourceRepository =
375 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
377 String artifactSourcePath = sourceRepository.toPath( artifactReference );
379 if ( StringUtils.isEmpty( artifactSourcePath ) )
381 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
382 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
386 File artifactFile = new File( source.getLocation(), artifactSourcePath );
388 if ( !artifactFile.exists() )
390 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
391 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
395 ManagedRepositoryContent targetRepository =
396 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
398 String artifactPath = targetRepository.toPath( artifactReference );
400 int lastIndex = artifactPath.lastIndexOf( '/' );
402 String path = artifactPath.substring( 0, lastIndex );
403 File targetPath = new File( target.getLocation(), path );
405 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
406 int newBuildNumber = 1;
407 String timestamp = null;
409 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
410 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
412 if ( !targetPath.exists() )
417 String filename = artifactPath.substring( lastIndex + 1 );
419 boolean fixChecksums =
420 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
422 File targetFile = new File( targetPath, filename );
423 if ( targetFile.exists() && target.isBlockRedeployments() )
425 throw new ArchivaRestServiceException(
426 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
427 + " and redeployment blocked", null
432 copyFile( artifactFile, targetPath, filename, fixChecksums );
433 queueRepositoryTask( target.getId(), targetFile );
436 // copy source pom to target repo
437 String pomFilename = filename;
438 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
440 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
442 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
444 File pomFile = new File(
445 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
448 if ( pomFile != null && pomFile.length() > 0 )
450 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
451 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
456 // explicitly update only if metadata-updater consumer is not enabled!
457 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
459 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
460 fixChecksums, artifactTransferRequest );
466 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
467 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
468 + artifactTransferRequest.getTargetRepositoryId() + "\'";
471 catch ( RepositoryException e )
473 log.error( "RepositoryException: " + e.getMessage(), e );
474 throw new ArchivaRestServiceException( e.getMessage(), e );
476 catch ( RepositoryAdminException e )
478 log.error( "RepositoryAdminException: " + e.getMessage(), e );
479 throw new ArchivaRestServiceException( e.getMessage(), e );
481 catch ( IOException e )
483 log.error( "IOException: " + e.getMessage(), e );
484 throw new ArchivaRestServiceException( e.getMessage(), e );
489 private void queueRepositoryTask( String repositoryId, File localFile )
491 RepositoryTask task = new RepositoryTask();
492 task.setRepositoryId( repositoryId );
493 task.setResourceFile( localFile );
494 task.setUpdateRelatedArtifacts( true );
495 //task.setScanAll( true );
499 scheduler.queueTask( task );
501 catch ( TaskQueueException e )
503 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
508 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
509 throws RepositoryMetadataException
511 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
512 if ( metadataFile.exists() )
516 metadata = MavenMetadataReader.read( metadataFile );
518 catch ( XMLException e )
520 throw new RepositoryMetadataException( e.getMessage(), e );
526 private File getMetadata( String targetPath )
528 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
530 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
533 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
536 Files.copy( sourceFile.toPath(), new File( targetPath, targetFilename ).toPath(), StandardCopyOption.REPLACE_EXISTING,
537 StandardCopyOption.COPY_ATTRIBUTES );
541 fixChecksums( new File( targetPath, targetFilename ) );
545 private void fixChecksums( File file )
547 ChecksummedFile checksum = new ChecksummedFile( file );
548 checksum.fixChecksums( algorithms );
551 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
552 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
553 throws RepositoryMetadataException
555 List<String> availableVersions = new ArrayList<>();
556 String latestVersion = artifactTransferRequest.getVersion();
558 File projectDir = new File( targetPath ).getParentFile();
559 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
561 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
563 if ( projectMetadataFile.exists() )
565 availableVersions = projectMetadata.getAvailableVersions();
567 Collections.sort( availableVersions, VersionComparator.getInstance() );
569 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
571 availableVersions.add( artifactTransferRequest.getVersion() );
574 latestVersion = availableVersions.get( availableVersions.size() - 1 );
578 availableVersions.add( artifactTransferRequest.getVersion() );
580 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
581 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
584 if ( projectMetadata.getGroupId() == null )
586 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
589 if ( projectMetadata.getArtifactId() == null )
591 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
594 projectMetadata.setLatestVersion( latestVersion );
595 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
596 projectMetadata.setAvailableVersions( availableVersions );
598 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
600 projectMetadata.setReleasedVersion( latestVersion );
603 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
607 fixChecksums( projectMetadataFile );
612 public Boolean removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
613 throws ArchivaRestServiceException
615 // if not a generic we can use the standard way to delete artifact
616 if ( !VersionUtil.isGenericSnapshot( version ) )
618 Artifact artifact = new Artifact( namespace, projectId, version );
619 artifact.setRepositoryId( repositoryId );
620 artifact.setContext( repositoryId );
621 return deleteArtifact( artifact );
624 if ( StringUtils.isEmpty( repositoryId ) )
626 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
629 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
631 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
634 if ( StringUtils.isEmpty( namespace ) )
636 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
639 if ( StringUtils.isEmpty( projectId ) )
641 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
644 if ( StringUtils.isEmpty( version ) )
646 throw new ArchivaRestServiceException( "version cannot be null", 400, null );
649 RepositorySession repositorySession = repositorySessionFactory.createSession();
653 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
655 VersionedReference ref = new VersionedReference();
656 ref.setArtifactId( projectId );
657 ref.setGroupId( namespace );
658 ref.setVersion( version );
660 repository.deleteVersion( ref );
663 ProjectReference projectReference = new ProjectReference();
664 projectReference.setGroupId( namespace );
665 projectReference.setArtifactId( projectId );
667 repository.getVersions( )
670 ArtifactReference artifactReference = new ArtifactReference();
671 artifactReference.setGroupId( namespace );
672 artifactReference.setArtifactId( projectId );
673 artifactReference.setVersion( version );
675 MetadataRepository metadataRepository = repositorySession.getRepository();
677 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
678 log.debug( "related: {}", related );
679 for ( ArtifactReference artifactRef : related )
681 repository.deleteArtifact( artifactRef );
684 Collection<ArtifactMetadata> artifacts =
685 metadataRepository.getArtifacts( repositoryId, namespace, projectId, version );
687 for ( ArtifactMetadata artifactMetadata : artifacts )
689 metadataRepository.removeArtifact( artifactMetadata, version );
692 metadataRepository.removeProjectVersion( repositoryId, namespace, projectId, version );
694 catch ( MetadataRepositoryException e )
696 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
698 catch ( MetadataResolutionException e )
700 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
702 catch ( RepositoryException e )
704 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
709 repositorySession.save();
711 repositorySession.close();
718 public Boolean deleteArtifact( Artifact artifact )
719 throws ArchivaRestServiceException
722 String repositoryId = artifact.getContext();
723 // some rest call can use context or repositoryId
725 if ( StringUtils.isEmpty( repositoryId ) )
727 repositoryId = artifact.getRepositoryId();
729 if ( StringUtils.isEmpty( repositoryId ) )
731 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
734 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
736 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
739 if ( artifact == null )
741 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
744 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
746 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
749 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
751 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
754 // TODO more control on artifact fields
756 boolean snapshotVersion =
757 VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
759 RepositorySession repositorySession = repositorySessionFactory.createSession();
762 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
764 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
765 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
766 fmt.setTimeZone( timezone );
767 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
769 VersionedReference ref = new VersionedReference();
770 ref.setArtifactId( artifact.getArtifactId() );
771 ref.setGroupId( artifact.getGroupId() );
772 ref.setVersion( artifact.getVersion() );
774 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
776 ArtifactReference artifactReference = new ArtifactReference();
777 artifactReference.setArtifactId( artifact.getArtifactId() );
778 artifactReference.setGroupId( artifact.getGroupId() );
779 artifactReference.setVersion( artifact.getVersion() );
780 artifactReference.setClassifier( artifact.getClassifier() );
781 artifactReference.setType( artifact.getPackaging() );
783 MetadataRepository metadataRepository = repositorySession.getRepository();
785 String path = repository.toMetadataPath( ref );
787 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
789 if ( StringUtils.isBlank( artifact.getPackaging() ) )
791 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
795 repository.deleteArtifact( artifactReference );
801 int index = path.lastIndexOf( '/' );
802 path = path.substring( 0, index );
803 File targetPath = new File( repoConfig.getLocation(), path );
805 if ( !targetPath.exists() )
807 //throw new ContentNotFoundException(
808 // artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
809 log.warn( "targetPath {} not found skip file deletion", targetPath );
812 // TODO: this should be in the storage mechanism so that it is all tied together
813 // delete from file system
814 if ( !snapshotVersion )
816 repository.deleteVersion( ref );
820 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
821 log.debug( "related: {}", related );
822 for ( ArtifactReference artifactRef : related )
824 repository.deleteArtifact( artifactRef );
827 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
828 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
830 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
832 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
834 if ( snapshotVersion )
836 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
838 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
844 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
845 artifact.getVersion() );
848 log.debug( "artifacts: {}", artifacts );
850 if ( artifacts.isEmpty() )
852 if ( !snapshotVersion )
854 // verify metata repository doesn't contains anymore the version
855 Collection<String> projectVersions =
856 metadataRepository.getProjectVersions( repositoryId, artifact.getGroupId(),
857 artifact.getArtifactId() );
859 if ( projectVersions.contains( artifact.getVersion() ) )
861 log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
862 metadataRepository.removeProjectVersion( repositoryId, artifact.getGroupId(),
863 artifact.getArtifactId(), artifact.getVersion() );
869 for ( ArtifactMetadata artifactMetadata : artifacts )
872 // TODO: mismatch between artifact (snapshot) version and project (base) version here
873 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
875 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
877 if ( StringUtils.isBlank( artifact.getPackaging() ) )
879 throw new ArchivaRestServiceException(
880 "You must configure a type/packaging when using classifier", 400, null );
882 // cleanup facet which contains classifier information
883 MavenArtifactFacet mavenArtifactFacet =
884 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
886 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
888 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
889 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
890 artifact.getVersion();
891 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
892 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
893 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
894 mavenArtifactFacetToCompare );
895 metadataRepository.save();
901 if ( snapshotVersion )
903 metadataRepository.removeArtifact( artifactMetadata,
904 VersionUtil.getBaseVersion( artifact.getVersion() ) );
908 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
909 artifactMetadata.getNamespace(),
910 artifactMetadata.getProject(), artifact.getVersion(),
911 artifactMetadata.getId() );
914 // TODO: move into the metadata repository proper - need to differentiate attachment of
915 // repository metadata to an artifact
916 for ( RepositoryListener listener : listeners )
918 listener.deleteArtifact( metadataRepository, repository.getId(),
919 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
920 artifactMetadata.getVersion(), artifactMetadata.getId() );
923 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
927 catch ( ContentNotFoundException e )
929 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
931 catch ( RepositoryNotFoundException e )
933 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
935 catch ( RepositoryException e )
937 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
939 catch ( MetadataResolutionException e )
941 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
943 catch ( MetadataRepositoryException e )
945 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
947 catch ( RepositoryAdminException e )
949 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
954 repositorySession.save();
956 repositorySession.close();
962 public Boolean deleteGroupId( String groupId, String repositoryId )
963 throws ArchivaRestServiceException
965 if ( StringUtils.isEmpty( repositoryId ) )
967 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
970 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
972 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
975 if ( StringUtils.isEmpty( groupId ) )
977 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
980 RepositorySession repositorySession = repositorySessionFactory.createSession();
984 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
986 repository.deleteGroupId( groupId );
988 MetadataRepository metadataRepository = repositorySession.getRepository();
990 metadataRepository.removeNamespace( repositoryId, groupId );
992 // just invalidate cache entry
993 String cacheKey = repositoryId + "-" + groupId;
994 namespacesCache.remove( cacheKey );
995 namespacesCache.remove( repositoryId );
997 metadataRepository.save();
999 catch ( MetadataRepositoryException e )
1001 log.error( e.getMessage(), e );
1002 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1004 catch ( RepositoryException e )
1006 log.error( e.getMessage(), e );
1007 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1012 repositorySession.close();
1018 public Boolean deleteProject( String groupId, String projectId, String repositoryId )
1019 throws ArchivaRestServiceException
1021 if ( StringUtils.isEmpty( repositoryId ) )
1023 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
1026 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
1028 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
1031 if ( StringUtils.isEmpty( groupId ) )
1033 throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
1036 if ( StringUtils.isEmpty( projectId ) )
1038 throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
1041 RepositorySession repositorySession = repositorySessionFactory.createSession();
1045 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
1047 repository.deleteProject( groupId, projectId );
1049 catch ( ContentNotFoundException e )
1051 log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
1053 catch ( RepositoryException e )
1055 log.error( e.getMessage(), e );
1056 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1062 MetadataRepository metadataRepository = repositorySession.getRepository();
1064 metadataRepository.removeProject( repositoryId, groupId, projectId );
1066 metadataRepository.save();
1068 catch ( MetadataRepositoryException e )
1070 log.error( e.getMessage(), e );
1071 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
1076 repositorySession.close();
1083 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
1084 throws ArchivaRestServiceException
1087 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
1091 return userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
1093 catch ( ArchivaSecurityException e )
1095 throw new ArchivaRestServiceException( e.getMessage(),
1096 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
1101 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
1102 throws ArchivaRestServiceException
1104 long sinceWhen = RepositoryScanner.FRESH_SCAN;
1107 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
1109 catch ( RepositoryScannerException e )
1111 log.error( e.getMessage(), e );
1112 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1114 catch ( RepositoryAdminException e )
1116 log.error( e.getMessage(), e );
1117 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
1122 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
1126 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
1128 throws RepositoryMetadataException
1130 List<String> availableVersions = new ArrayList<>();
1131 String latestVersion = "";
1133 if ( metadataFile.exists() )
1135 if ( metadata.getAvailableVersions() != null )
1137 availableVersions = metadata.getAvailableVersions();
1139 if ( availableVersions.size() > 0 )
1141 Collections.sort( availableVersions, VersionComparator.getInstance() );
1143 if ( availableVersions.contains( artifact.getVersion() ) )
1145 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
1147 if ( availableVersions.size() > 0 )
1149 latestVersion = availableVersions.get( availableVersions.size() - 1 );
1155 if ( metadata.getGroupId() == null )
1157 metadata.setGroupId( artifact.getGroupId() );
1159 if ( metadata.getArtifactId() == null )
1161 metadata.setArtifactId( artifact.getArtifactId() );
1164 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
1166 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
1167 artifact.getVersion() ) )
1169 metadata.setReleasedVersion( latestVersion );
1173 metadata.setLatestVersion( latestVersion );
1174 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
1175 metadata.setAvailableVersions( availableVersions );
1177 RepositoryMetadataWriter.write( metadata, metadataFile );
1178 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
1179 checksum.fixChecksums( algorithms );
1183 public StringList getRunningRemoteDownloadIds()
1185 return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
1188 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1190 return managedRepositoryAdmin;
1193 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1195 this.managedRepositoryAdmin = managedRepositoryAdmin;
1198 public RepositoryContentFactory getRepositoryFactory()
1200 return repositoryFactory;
1203 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1205 this.repositoryFactory = repositoryFactory;
1208 public RepositorySessionFactory getRepositorySessionFactory()
1210 return repositorySessionFactory;
1213 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
1215 this.repositorySessionFactory = repositorySessionFactory;
1218 public List<RepositoryListener> getListeners()
1223 public void setListeners( List<RepositoryListener> listeners )
1225 this.listeners = listeners;
1228 public ArchivaAdministration getArchivaAdministration()
1230 return archivaAdministration;
1233 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1235 this.archivaAdministration = archivaAdministration;