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.metadata.model.ArtifactMetadata;
35 import org.apache.archiva.metadata.repository.MetadataRepository;
36 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
37 import org.apache.archiva.metadata.repository.MetadataResolutionException;
38 import org.apache.archiva.metadata.repository.RepositorySession;
39 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
40 import org.apache.archiva.metadata.repository.storage.maven2.MavenArtifactFacet;
41 import org.apache.archiva.model.ArchivaRepositoryMetadata;
42 import org.apache.archiva.model.ArtifactReference;
43 import org.apache.archiva.model.VersionedReference;
44 import org.apache.archiva.redback.authentication.AuthenticationResult;
45 import org.apache.archiva.redback.authorization.AuthorizationException;
46 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
47 import org.apache.archiva.redback.system.DefaultSecuritySession;
48 import org.apache.archiva.redback.system.SecuritySession;
49 import org.apache.archiva.redback.system.SecuritySystem;
50 import org.apache.archiva.redback.users.User;
51 import org.apache.archiva.redback.users.UserNotFoundException;
52 import org.apache.archiva.repository.ContentNotFoundException;
53 import org.apache.archiva.repository.ManagedRepositoryContent;
54 import org.apache.archiva.repository.RepositoryContentFactory;
55 import org.apache.archiva.repository.RepositoryException;
56 import org.apache.archiva.repository.RepositoryNotFoundException;
57 import org.apache.archiva.repository.events.RepositoryListener;
58 import org.apache.archiva.repository.metadata.MetadataTools;
59 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
60 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
61 import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
62 import org.apache.archiva.repository.scanner.RepositoryScanner;
63 import org.apache.archiva.repository.scanner.RepositoryScannerException;
64 import org.apache.archiva.rest.api.model.Artifact;
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.RepositoryArchivaTaskScheduler;
74 import org.apache.archiva.scheduler.repository.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 = "archivaTaskScheduler#repository" )
117 private RepositoryArchivaTaskScheduler repositoryTaskScheduler;
120 @Named( value = "taskExecutor#indexing" )
121 private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
124 private ManagedRepositoryAdmin managedRepositoryAdmin;
127 private PlexusSisuBridge plexusSisuBridge;
130 private MavenIndexerUtils mavenIndexerUtils;
133 private SecuritySystem securitySystem;
136 private RepositoryContentFactory repositoryFactory;
139 @Named( value = "archivaTaskScheduler#repository" )
140 private ArchivaTaskScheduler scheduler;
143 private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
146 @Named( value = "repositorySessionFactory" )
147 protected RepositorySessionFactory repositorySessionFactory;
150 protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
153 private RepositoryScanner repoScanner;
155 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
157 public Boolean scanRepository( String repositoryId, boolean fullScan )
159 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
161 log.info( "scanning of repository with id {} already scheduled", repositoryId );
162 return Boolean.FALSE;
164 RepositoryTask task = new RepositoryTask();
165 task.setRepositoryId( repositoryId );
166 task.setScanAll( fullScan );
169 repositoryTaskScheduler.queueTask( task );
171 catch ( TaskQueueException e )
173 log.error( "failed to schedule scanning of repo with id {}", repositoryId, e );
179 public Boolean alreadyScanning( String repositoryId )
181 return repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId );
184 public Boolean removeScanningTaskFromQueue( String repositoryId )
186 RepositoryTask task = new RepositoryTask();
187 task.setRepositoryId( repositoryId );
190 return repositoryTaskScheduler.unQueueTask( task );
192 catch ( TaskQueueException e )
194 log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
199 public Boolean scanRepositoryNow( String repositoryId, boolean fullScan )
200 throws ArchivaRestServiceException
205 ManagedRepository repository = managedRepositoryAdmin.getManagedRepository( repositoryId );
207 IndexingContext context = managedRepositoryAdmin.createIndexContext( repository );
209 ArtifactIndexingTask task =
210 new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, context );
212 task.setExecuteOnEntireRepo( true );
213 task.setOnlyUpdate( !fullScan );
215 archivaIndexingTaskExecutor.executeTask( task );
218 catch ( Exception e )
220 log.error( e.getMessage(), e );
221 throw new ArchivaRestServiceException( e.getMessage(), e );
225 public Boolean scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
226 throws ArchivaRestServiceException
230 downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
232 catch ( DownloadRemoteIndexException e )
234 log.error( e.getMessage(), e );
235 throw new ArchivaRestServiceException( e.getMessage(), e );
240 public Boolean copyArtifact( ArtifactTransferRequest artifactTransferRequest )
241 throws ArchivaRestServiceException
244 String userName = getAuditInformation().getUser().getUsername();
245 if ( StringUtils.isBlank( userName ) )
247 throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
250 if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
252 throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
255 if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
257 throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
260 ManagedRepository source = null;
263 source = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getRepositoryId() );
265 catch ( RepositoryAdminException e )
267 throw new ArchivaRestServiceException( e.getMessage(), e );
270 if ( source == null )
272 throw new ArchivaRestServiceException(
273 "cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
276 ManagedRepository target = null;
279 target = managedRepositoryAdmin.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
281 catch ( RepositoryAdminException e )
283 throw new ArchivaRestServiceException( e.getMessage(), e );
286 if ( target == null )
288 throw new ArchivaRestServiceException(
289 "cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
292 if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
294 throw new ArchivaRestServiceException( "groupId is mandatory", null );
297 if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
299 throw new ArchivaRestServiceException( "artifactId is mandatory", null );
302 if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
304 throw new ArchivaRestServiceException( "version is mandatory", null );
307 if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
309 throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
312 // end check parameters
317 user = securitySystem.getUserManager().findUser( userName );
319 catch ( UserNotFoundException e )
321 throw new ArchivaRestServiceException( "user " + userName + " not found", null );
324 // check karma on source : read
325 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
326 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
330 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
331 artifactTransferRequest.getRepositoryId() );
334 throw new ArchivaRestServiceException(
335 "not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
338 catch ( AuthorizationException e )
340 log.error( "error reading permission: " + e.getMessage(), e );
341 throw new ArchivaRestServiceException( e.getMessage(), e );
344 // check karma on target: write
348 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
349 artifactTransferRequest.getTargetRepositoryId() );
352 throw new ArchivaRestServiceException(
353 "not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
356 catch ( AuthorizationException e )
358 log.error( "error reading permission: " + e.getMessage(), e );
359 throw new ArchivaRestServiceException( e.getMessage(), e );
362 // sounds good we can continue !
364 ArtifactReference artifactReference = new ArtifactReference();
365 artifactReference.setArtifactId( artifactTransferRequest.getArtifactId() );
366 artifactReference.setGroupId( artifactTransferRequest.getGroupId() );
367 artifactReference.setVersion( artifactTransferRequest.getVersion() );
368 artifactReference.setClassifier( artifactTransferRequest.getClassifier() );
369 String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
370 artifactReference.setType( StringUtils.isEmpty( packaging ) ? "jar" : packaging );
375 ManagedRepositoryContent sourceRepository =
376 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
378 String artifactSourcePath = sourceRepository.toPath( artifactReference );
380 if ( StringUtils.isEmpty( artifactSourcePath ) )
382 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
383 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
387 File artifactFile = new File( source.getLocation(), artifactSourcePath );
389 if ( !artifactFile.exists() )
391 log.error( "cannot find artifact " + artifactTransferRequest.toString() );
392 throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
396 ManagedRepositoryContent targetRepository =
397 repositoryFactory.getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
399 String artifactPath = targetRepository.toPath( artifactReference );
401 int lastIndex = artifactPath.lastIndexOf( '/' );
403 String path = artifactPath.substring( 0, lastIndex );
404 File targetPath = new File( target.getLocation(), path );
406 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
407 int newBuildNumber = 1;
408 String timestamp = null;
410 File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
411 ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
413 if ( !targetPath.exists() )
418 String filename = artifactPath.substring( lastIndex + 1 );
420 // FIXME some dupe with uploadaction
422 boolean fixChecksums =
423 !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
425 File targetFile = new File( targetPath, filename );
426 if ( targetFile.exists() && target.isBlockRedeployments() )
428 throw new ArchivaRestServiceException(
429 "artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
430 + " and redeployment blocked", null );
434 copyFile( artifactFile, targetPath, filename, fixChecksums );
435 queueRepositoryTask( target.getId(), targetFile );
438 // copy source pom to target repo
439 String pomFilename = filename;
440 if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
442 pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
444 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
446 File pomFile = new File(
447 new File( source.getLocation(), artifactSourcePath.substring( 0, artifactPath.lastIndexOf( '/' ) ) ),
450 if ( pomFile != null && pomFile.length() > 0 )
452 copyFile( pomFile, targetPath, pomFilename, fixChecksums );
453 queueRepositoryTask( target.getId(), new File( targetPath, pomFilename ) );
458 // explicitly update only if metadata-updater consumer is not enabled!
459 if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
461 updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
462 fixChecksums, artifactTransferRequest );
468 "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
469 + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
470 + artifactTransferRequest.getTargetRepositoryId() + "\'";
473 catch ( RepositoryException e )
475 log.error( "RepositoryException: " + e.getMessage(), e );
476 throw new ArchivaRestServiceException( e.getMessage(), e );
478 catch ( RepositoryAdminException e )
480 log.error( "RepositoryAdminException: " + e.getMessage(), e );
481 throw new ArchivaRestServiceException( e.getMessage(), e );
483 catch ( IOException e )
485 log.error( "IOException: " + e.getMessage(), e );
486 throw new ArchivaRestServiceException( e.getMessage(), e );
491 //FIXME some duplicate with UploadAction
493 private void queueRepositoryTask( String repositoryId, File localFile )
495 RepositoryTask task = new RepositoryTask();
496 task.setRepositoryId( repositoryId );
497 task.setResourceFile( localFile );
498 task.setUpdateRelatedArtifacts( true );
499 //task.setScanAll( true );
503 scheduler.queueTask( task );
505 catch ( TaskQueueException e )
507 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
512 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
513 throws RepositoryMetadataException
515 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
516 if ( metadataFile.exists() )
520 metadata = MavenMetadataReader.read( metadataFile );
522 catch ( XMLException e )
524 throw new RepositoryMetadataException( e.getMessage(), e );
530 private File getMetadata( String targetPath )
532 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
534 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
537 private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
540 FileOutputStream out = new FileOutputStream( new File( targetPath, targetFilename ) );
541 FileInputStream input = new FileInputStream( sourceFile );
545 IOUtils.copy( input, out );
549 IOUtils.closeQuietly( out );
550 IOUtils.closeQuietly( input );
555 fixChecksums( new File( targetPath, targetFilename ) );
559 private void fixChecksums( File file )
561 ChecksummedFile checksum = new ChecksummedFile( file );
562 checksum.fixChecksums( algorithms );
565 private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
566 boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
567 throws RepositoryMetadataException
569 List<String> availableVersions = new ArrayList<String>();
570 String latestVersion = artifactTransferRequest.getVersion();
572 File projectDir = new File( targetPath ).getParentFile();
573 File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
575 ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
577 if ( projectMetadataFile.exists() )
579 availableVersions = projectMetadata.getAvailableVersions();
581 Collections.sort( availableVersions, VersionComparator.getInstance() );
583 if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
585 availableVersions.add( artifactTransferRequest.getVersion() );
588 latestVersion = availableVersions.get( availableVersions.size() - 1 );
592 availableVersions.add( artifactTransferRequest.getVersion() );
594 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
595 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
598 if ( projectMetadata.getGroupId() == null )
600 projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
603 if ( projectMetadata.getArtifactId() == null )
605 projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
608 projectMetadata.setLatestVersion( latestVersion );
609 projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
610 projectMetadata.setAvailableVersions( availableVersions );
612 if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
614 projectMetadata.setReleasedVersion( latestVersion );
617 RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
621 fixChecksums( projectMetadataFile );
625 public Boolean deleteArtifact( Artifact artifact )
626 throws ArchivaRestServiceException
629 String repositoryId = artifact.getContext();
630 if ( StringUtils.isEmpty( repositoryId ) )
632 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
635 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
637 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
640 if ( artifact == null )
642 throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
645 if ( StringUtils.isEmpty( artifact.getGroupId() ) )
647 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
650 if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
652 throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
655 // TODO more control on artifact fields
657 boolean snapshotVersion = VersionUtil.isSnapshot( artifact.getVersion() );
659 RepositorySession repositorySession = repositorySessionFactory.createSession();
662 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
664 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
665 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
666 fmt.setTimeZone( timezone );
667 ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
669 VersionedReference ref = new VersionedReference();
670 ref.setArtifactId( artifact.getArtifactId() );
671 ref.setGroupId( artifact.getGroupId() );
672 ref.setVersion( artifact.getVersion() );
674 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
676 ArtifactReference artifactReference = new ArtifactReference();
677 artifactReference.setArtifactId( artifact.getArtifactId() );
678 artifactReference.setGroupId( artifact.getGroupId() );
679 artifactReference.setVersion( artifact.getVersion() );
680 artifactReference.setClassifier( artifact.getClassifier() );
681 artifactReference.setType( artifact.getPackaging() );
683 MetadataRepository metadataRepository = repositorySession.getRepository();
685 String path = repository.toMetadataPath( ref );
687 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
689 if ( StringUtils.isBlank( artifact.getPackaging() ) )
691 throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
695 repository.deleteArtifact( artifactReference );
701 int index = path.lastIndexOf( '/' );
702 path = path.substring( 0, index );
703 File targetPath = new File( repoConfig.getLocation(), path );
705 if ( !targetPath.exists() )
707 throw new ContentNotFoundException(
708 artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
711 // TODO: this should be in the storage mechanism so that it is all tied together
712 // delete from file system
713 if ( !snapshotVersion )
715 repository.deleteVersion( ref );
719 Set<ArtifactReference> related = repository.getRelatedArtifacts( artifactReference );
720 log.debug( "related: {}", related );
721 for ( ArtifactReference artifactRef : related )
723 repository.deleteArtifact( artifactRef );
726 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
727 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
729 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
731 Collection<ArtifactMetadata> artifacts = Collections.emptyList();
733 if ( snapshotVersion )
735 String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion() );
737 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
743 metadataRepository.getArtifacts( repositoryId, artifact.getGroupId(), artifact.getArtifactId(),
744 artifact.getVersion() );
747 log.debug( "artifacts: {}", artifacts );
749 for ( ArtifactMetadata artifactMetadata : artifacts )
752 // TODO: mismatch between artifact (snapshot) version and project (base) version here
753 if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
755 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
757 if ( StringUtils.isBlank( artifact.getPackaging() ) )
759 throw new ArchivaRestServiceException(
760 "You must configure a type/packaging when using classifier", 400, null );
762 // cleanup facet which contains classifier information
763 MavenArtifactFacet mavenArtifactFacet =
764 (MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
766 if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
768 artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
769 String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
770 artifact.getVersion();
771 //metadataRepository.updateArtifact( repositoryId, groupId, artifactId, version,
772 // artifactMetadata );
773 // String repositoryId, String namespace, String project, String version, String projectId, MetadataFacet metadataFacet
774 MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
775 mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
776 metadataRepository.removeArtifact( repositoryId, groupId, artifactId, version,
777 mavenArtifactFacetToCompare );
778 metadataRepository.save();
784 metadataRepository.removeArtifact( artifactMetadata.getRepositoryId(),
785 artifactMetadata.getNamespace(),
786 artifactMetadata.getProject(), artifact.getVersion(),
787 artifactMetadata.getId() );
789 // TODO: move into the metadata repository proper - need to differentiate attachment of
790 // repository metadata to an artifact
791 for ( RepositoryListener listener : listeners )
793 listener.deleteArtifact( metadataRepository, repository.getId(),
794 artifactMetadata.getNamespace(), artifactMetadata.getProject(),
795 artifactMetadata.getVersion(), artifactMetadata.getId() );
798 triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
804 catch ( ContentNotFoundException e )
806 throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
808 catch ( RepositoryNotFoundException e )
810 throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
812 catch ( RepositoryException e )
814 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
816 catch ( MetadataResolutionException e )
818 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
820 catch ( MetadataRepositoryException e )
822 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
824 catch ( RepositoryAdminException e )
826 throw new ArchivaRestServiceException( "RepositoryAdmin exception: " + e.getMessage(), 500, e );
831 repositorySession.save();
833 repositorySession.close();
838 public Boolean deleteGroupId( String groupId, String repositoryId )
839 throws ArchivaRestServiceException
841 if ( StringUtils.isEmpty( repositoryId ) )
843 throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
846 if ( !isAuthorizedToDeleteArtifacts( repositoryId ) )
848 throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
851 if ( StringUtils.isEmpty( groupId ) )
853 throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
858 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
860 repository.deleteGroupId( groupId );
863 catch ( RepositoryException e )
865 log.error( e.getMessage(), e );
866 throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
871 public Boolean isAuthorizedToDeleteArtifacts( String repoId )
872 throws ArchivaRestServiceException
875 getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
879 boolean res = userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId );
882 catch ( ArchivaSecurityException e )
884 throw new ArchivaRestServiceException( e.getMessage(),
885 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
889 public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
890 throws ArchivaRestServiceException
892 long sinceWhen = RepositoryScanner.FRESH_SCAN;
895 return repoScanner.scan( getManagedRepositoryAdmin().getManagedRepository( repositoryId ), sinceWhen );
897 catch ( RepositoryScannerException e )
899 log.error( e.getMessage(), e );
900 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
902 catch ( RepositoryAdminException e )
904 log.error( e.getMessage(), e );
905 throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
910 * Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
914 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
916 throws RepositoryMetadataException
918 List<String> availableVersions = new ArrayList<String>();
919 String latestVersion = "";
921 if ( metadataFile.exists() )
923 if ( metadata.getAvailableVersions() != null )
925 availableVersions = metadata.getAvailableVersions();
927 if ( availableVersions.size() > 0 )
929 Collections.sort( availableVersions, VersionComparator.getInstance() );
931 if ( availableVersions.contains( artifact.getVersion() ) )
933 availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
935 if ( availableVersions.size() > 0 )
937 latestVersion = availableVersions.get( availableVersions.size() - 1 );
943 if ( metadata.getGroupId() == null )
945 metadata.setGroupId( artifact.getGroupId() );
947 if ( metadata.getArtifactId() == null )
949 metadata.setArtifactId( artifact.getArtifactId() );
952 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
954 if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
955 artifact.getVersion() ) )
957 metadata.setReleasedVersion( latestVersion );
961 metadata.setLatestVersion( latestVersion );
962 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
963 metadata.setAvailableVersions( availableVersions );
965 RepositoryMetadataWriter.write( metadata, metadataFile );
966 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
967 checksum.fixChecksums( algorithms );
970 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
972 return managedRepositoryAdmin;
975 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
977 this.managedRepositoryAdmin = managedRepositoryAdmin;
980 public RepositoryContentFactory getRepositoryFactory()
982 return repositoryFactory;
985 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
987 this.repositoryFactory = repositoryFactory;
990 public RepositorySessionFactory getRepositorySessionFactory()
992 return repositorySessionFactory;
995 public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
997 this.repositorySessionFactory = repositorySessionFactory;
1000 public List<RepositoryListener> getListeners()
1005 public void setListeners( List<RepositoryListener> listeners )
1007 this.listeners = listeners;
1010 public ArchivaAdministration getArchivaAdministration()
1012 return archivaAdministration;
1015 public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
1017 this.archivaAdministration = archivaAdministration;