1 package org.apache.archiva.repository.maven.content;
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
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
21 import org.apache.archiva.common.filelock.FileLockManager;
22 import org.apache.archiva.common.utils.FileUtils;
23 import org.apache.archiva.configuration.FileTypes;
24 import org.apache.archiva.metadata.maven.MavenMetadataReader;
25 import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
26 import org.apache.archiva.model.ArtifactReference;
27 import org.apache.archiva.model.ProjectReference;
28 import org.apache.archiva.model.VersionedReference;
29 import org.apache.archiva.repository.ContentAccessException;
30 import org.apache.archiva.repository.ContentNotFoundException;
31 import org.apache.archiva.repository.EditableManagedRepository;
32 import org.apache.archiva.repository.ManagedRepositoryContent;
33 import org.apache.archiva.repository.ItemDeleteStatus;
34 import org.apache.archiva.repository.LayoutException;
35 import org.apache.archiva.repository.ManagedRepository;
36 import org.apache.archiva.repository.BaseRepositoryContentLayout;
37 import org.apache.archiva.repository.ManagedRepositoryContentLayout;
38 import org.apache.archiva.repository.content.Artifact;
39 import org.apache.archiva.repository.content.ArtifactType;
40 import org.apache.archiva.repository.content.BaseArtifactTypes;
41 import org.apache.archiva.repository.content.ContentItem;
42 import org.apache.archiva.repository.content.DataItem;
43 import org.apache.archiva.repository.content.ItemNotFoundException;
44 import org.apache.archiva.repository.content.ItemSelector;
45 import org.apache.archiva.repository.content.Namespace;
46 import org.apache.archiva.repository.content.Project;
47 import org.apache.archiva.repository.content.Version;
48 import org.apache.archiva.repository.content.base.ArchivaContentItem;
49 import org.apache.archiva.repository.content.base.ArchivaItemSelector;
50 import org.apache.archiva.repository.content.base.ArchivaNamespace;
51 import org.apache.archiva.repository.content.base.ArchivaProject;
52 import org.apache.archiva.repository.content.base.ArchivaVersion;
53 import org.apache.archiva.repository.content.base.builder.ArtifactOptBuilder;
54 import org.apache.archiva.repository.maven.metadata.storage.ArtifactMappingProvider;
55 import org.apache.archiva.repository.maven.metadata.storage.DefaultArtifactMappingProvider;
56 import org.apache.archiva.repository.storage.RepositoryStorage;
57 import org.apache.archiva.repository.storage.StorageAsset;
58 import org.apache.archiva.repository.storage.util.StorageUtil;
59 import org.apache.commons.collections4.map.ReferenceMap;
60 import org.apache.commons.lang3.StringUtils;
62 import javax.inject.Inject;
63 import javax.inject.Named;
64 import java.io.IOException;
66 import java.nio.file.Files;
67 import java.nio.file.Path;
68 import java.nio.file.Paths;
69 import java.util.Arrays;
70 import java.util.Collections;
71 import java.util.List;
72 import java.util.Objects;
73 import java.util.function.Consumer;
74 import java.util.function.Predicate;
75 import java.util.regex.Matcher;
76 import java.util.regex.Pattern;
77 import java.util.stream.Collectors;
78 import java.util.stream.Stream;
81 * ManagedDefaultRepositoryContent
83 public class ManagedDefaultRepositoryContent
84 extends AbstractDefaultRepositoryContent
85 implements ManagedRepositoryContent, BaseRepositoryContentLayout
88 // attribute flag that marks version objects that point to a snapshot artifact version
89 public static final String SNAPSHOT_ARTIFACT_VERSION = "maven.snav";
91 private FileTypes filetypes;
93 public void setFileTypes( FileTypes fileTypes )
95 this.filetypes = fileTypes;
98 private ManagedRepository repository;
100 private FileLockManager lockManager;
103 @Named( "repositoryPathTranslator#maven2" )
104 private RepositoryPathTranslator pathTranslator;
107 @Named( "metadataReader#maven" )
108 MavenMetadataReader metadataReader;
111 @Named( "MavenContentHelper" )
112 MavenContentHelper mavenContentHelper;
114 public static final String SNAPSHOT = "SNAPSHOT";
116 public static final Pattern UNIQUE_SNAPSHOT_PATTERN = Pattern.compile( "^(SNAPSHOT|[0-9]{8}\\.[0-9]{6}-[0-9]+)(.*)" );
117 public static final Pattern CLASSIFIER_PATTERN = Pattern.compile( "^-([^.]+)(\\..*)" );
118 public static final Pattern COMMON_EXTENSIONS = Pattern.compile( "^(jar|war|ear|dar|tar|zip|pom|xml)$" );
120 public static final Pattern TIMESTAMP_PATTERN = Pattern.compile( "^([0-9]{8})\\.([0-9]{6})$" );
122 public static final Pattern GENERIC_SNAPSHOT_PATTERN = Pattern.compile( "^(.*)-" + SNAPSHOT );
125 * We are caching content items in a weak reference map. To avoid always recreating the
126 * the hierarchical structure.
127 * TODO: Better use a object cache? E.g. our spring cache implementation?
129 private ReferenceMap<StorageAsset, ContentItem> itemMap = new ReferenceMap<>( );
130 private ReferenceMap<StorageAsset, DataItem> dataItemMap = new ReferenceMap<>( );
132 public ManagedDefaultRepositoryContent( )
134 super( Collections.singletonList( new DefaultArtifactMappingProvider( ) ) );
137 public ManagedDefaultRepositoryContent( ManagedRepository repository, FileTypes fileTypes, FileLockManager lockManager )
139 super( Collections.singletonList( new DefaultArtifactMappingProvider( ) ) );
140 setFileTypes( fileTypes );
141 this.lockManager = lockManager;
142 setRepository( repository );
145 public ManagedDefaultRepositoryContent( ManagedRepository repository, List<? extends ArtifactMappingProvider> artifactMappingProviders, FileTypes fileTypes, FileLockManager lockManager )
147 super( artifactMappingProviders == null ? Collections.singletonList( new DefaultArtifactMappingProvider( ) ) : artifactMappingProviders );
148 setFileTypes( fileTypes );
149 this.lockManager = lockManager;
150 setRepository( repository );
154 private StorageAsset getAssetByPath( String assetPath )
156 return getStorage( ).getAsset( assetPath );
159 private StorageAsset getAsset( String namespace )
161 String namespacePath = formatAsDirectory( namespace.trim( ) );
162 if ( StringUtils.isEmpty( namespacePath ) )
166 return getAssetByPath( namespacePath );
169 private StorageAsset getAsset( String namespace, String project )
171 return getAsset( namespace ).resolve( project );
174 private StorageAsset getAsset( String namespace, String project, String version )
176 return getAsset( namespace, project ).resolve( version );
179 private StorageAsset getAsset( String namespace, String project, String version, String fileName )
181 return getAsset( namespace, project, version ).resolve( fileName );
185 /// ************* Start of new generation interface ******************
189 public <T extends ContentItem> T adaptItem( Class<T> clazz, ContentItem item ) throws LayoutException
191 if (clazz.isAssignableFrom( Version.class ))
193 if ( !item.hasCharacteristic( Version.class ) )
195 item.setCharacteristic( Version.class, createVersionFromPath( item.getAsset() ) );
197 return (T) item.adapt( Version.class );
198 } else if ( clazz.isAssignableFrom( Project.class )) {
199 if ( !item.hasCharacteristic( Project.class ) )
201 item.setCharacteristic( Project.class, createProjectFromPath( item.getAsset() ) );
203 return (T) item.adapt( Project.class );
204 } else if ( clazz.isAssignableFrom( Namespace.class )) {
205 if ( !item.hasCharacteristic( Namespace.class ) )
207 item.setCharacteristic( Namespace.class, createNamespaceFromPath( item.getAsset() ) );
209 return (T) item.adapt( Namespace.class );
210 } else if ( clazz.isAssignableFrom( Artifact.class )) {
211 if (!item.hasCharacteristic( Artifact.class )) {
212 item.setCharacteristic( Artifact.class, createArtifactFromPath( item.getAsset( ) ) );
214 return (T) item.adapt( Artifact.class );
216 throw new LayoutException( "Could not convert item to class " + clazz);
221 public void deleteAllItems( ItemSelector selector, Consumer<ItemDeleteStatus> consumer ) throws ContentAccessException, IllegalArgumentException
223 try ( Stream<? extends ContentItem> stream = newItemStream( selector, false ) )
225 stream.forEach( item -> {
229 consumer.accept( new ItemDeleteStatus( item ) );
231 catch ( ItemNotFoundException e )
233 consumer.accept( new ItemDeleteStatus( item, ItemDeleteStatus.ITEM_NOT_FOUND, e ) );
235 catch ( Exception e )
237 consumer.accept( new ItemDeleteStatus( item, ItemDeleteStatus.DELETION_FAILED, e ) );
239 catch ( Throwable e )
241 consumer.accept( new ItemDeleteStatus( item, ItemDeleteStatus.UNKNOWN, e ) );
248 * Removes the item from the filesystem. For namespaces, projects and versions it deletes
250 * For namespaces you have to be careful, because maven repositories may have sub namespaces
251 * parallel to projects. Which means deleting a namespaces also deletes the sub namespaces and
252 * not only the projects of the given namespace. Better run the delete for each project of
255 * Artifacts are deleted as provided. No related artifacts will be deleted.
257 * @param item the item that should be removed
258 * @throws ItemNotFoundException if the item does not exist
259 * @throws ContentAccessException if some error occurred while accessing the filesystem
262 public void deleteItem( ContentItem item ) throws ItemNotFoundException, ContentAccessException
264 final Path baseDirectory = getRepoDir( );
265 final Path itemPath = item.getAsset( ).getFilePath( );
266 if ( !Files.exists( itemPath ) )
268 throw new ItemNotFoundException( "The item " + item.toString( ) + "does not exist in the repository " + getId( ) );
270 if ( !itemPath.toAbsolutePath( ).startsWith( baseDirectory.toAbsolutePath( ) ) )
272 log.error( "The namespace {} to delete from repository {} is not a subdirectory of the repository base.", item, getId( ) );
273 log.error( "Namespace directory: {}", itemPath );
274 log.error( "Repository directory: {}", baseDirectory );
275 throw new ContentAccessException( "Inconsistent directories found. Could not delete namespace." );
279 if ( Files.isDirectory( itemPath ) )
281 FileUtils.deleteDirectory( itemPath );
285 Files.deleteIfExists( itemPath );
288 catch ( IOException e )
290 log.error( "Could not delete item from path {}: {}", itemPath, e.getMessage( ), e );
291 throw new ContentAccessException( "Error occured while deleting item " + item + ": " + e.getMessage( ), e );
296 public ContentItem getItem( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
298 if ( selector.hasVersion( ) && selector.hasArtifactId( ) )
300 return getArtifact( selector );
302 else if ( selector.hasProjectId( ) && selector.hasVersion( ) )
304 return getVersion( selector );
306 else if ( selector.hasProjectId( ) )
308 return getProject( selector );
312 return getNamespace( selector );
317 public Namespace getNamespace( final ItemSelector namespaceSelector ) throws ContentAccessException, IllegalArgumentException
319 StorageAsset nsPath = getAsset( namespaceSelector.getNamespace() );
320 return getNamespaceFromPath( nsPath );
325 public Project getProject( final ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
327 if ( !selector.hasProjectId( ) )
329 throw new IllegalArgumentException( "Project id must be set" );
331 final StorageAsset path = getAsset( selector.getNamespace( ), selector.getProjectId( ) );
332 return getProjectFromPath( path );
337 public Version getVersion( final ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
339 if ( !selector.hasProjectId( ) )
341 throw new IllegalArgumentException( "Project id must be set" );
343 if ( !selector.hasVersion( ) )
345 throw new IllegalArgumentException( "Version must be set" );
347 final StorageAsset path = getAsset( selector.getNamespace( ), selector.getProjectId( ), selector.getVersion( ) );
348 return getVersionFromPath( path );
352 public Artifact createArtifact( final StorageAsset artifactPath, final ItemSelector selector,
353 final String classifier, final String extension )
355 Version version = getVersion( selector );
356 ArtifactOptBuilder builder = org.apache.archiva.repository.content.base.ArchivaArtifact.withAsset( artifactPath )
357 .withVersion( version )
358 .withId( selector.getArtifactId( ) )
359 .withArtifactVersion( mavenContentHelper.getArtifactVersion( artifactPath, selector ) )
360 .withClassifier( classifier );
361 if ( selector.hasType( ) )
363 builder.withType( selector.getType( ) );
365 return builder.build( );
368 public Namespace getNamespaceFromArtifactPath( final StorageAsset artifactPath )
370 final StorageAsset namespacePath = artifactPath.getParent( ).getParent( ).getParent( );
371 return getNamespaceFromPath( namespacePath );
374 public Namespace getNamespaceFromPath( final StorageAsset nsPath )
376 ContentItem item = itemMap.computeIfAbsent( nsPath,
377 path -> createNamespaceFromPath( nsPath ) );
378 if (!item.hasCharacteristic( Namespace.class )) {
379 item.setCharacteristic( Namespace.class, createNamespaceFromPath( nsPath ) );
381 return item.adapt( Namespace.class );
384 public Namespace createNamespaceFromPath( final StorageAsset namespacePath) {
385 final String namespace = MavenContentHelper.getNamespaceFromNamespacePath( namespacePath );
386 return ArchivaNamespace.withRepository( this )
387 .withAsset( namespacePath )
388 .withNamespace( namespace )
392 private Project getProjectFromPath( final StorageAsset path )
394 ContentItem item = itemMap.computeIfAbsent( path, projectPath ->
395 createProjectFromPath( projectPath )
397 if (!item.hasCharacteristic( Project.class )) {
398 item.setCharacteristic( Project.class, createProjectFromPath( path ) );
400 return item.adapt( Project.class );
403 private Project createProjectFromPath( final StorageAsset projectPath ) {
404 Namespace namespace = getNamespaceFromPath( projectPath.getParent( ) );
405 return ArchivaProject.withRepository( this ).withAsset( projectPath )
406 .withNamespace( namespace )
407 .withId( projectPath.getName( ) ).build( );
410 private Project getProjectFromArtifactPath( final StorageAsset artifactPath )
412 final StorageAsset projectPath = artifactPath.getParent( ).getParent( );
413 return getProjectFromPath( projectPath );
416 private Version getVersionFromArtifactPath( final StorageAsset artifactPath )
418 final StorageAsset versionPath = artifactPath.getParent( );
419 return getVersionFromPath( versionPath );
422 private Version getVersionFromPath( StorageAsset path )
424 ContentItem item = itemMap.computeIfAbsent( path, versionPath ->
425 createVersionFromPath( versionPath )
427 if (!item.hasCharacteristic( Version.class )) {
428 item.setCharacteristic( Version.class, createVersionFromPath( path ) );
430 return item.adapt( Version.class );
433 private Version createVersionFromPath(StorageAsset path) {
434 Project proj = getProjectFromPath( path.getParent( ) );
435 return ArchivaVersion.withRepository( this ).withAsset( path )
436 .withProject( proj ).withVersion(path.getName()).build();
439 private Artifact getArtifactFromPath( final StorageAsset artifactPath )
441 DataItem item = dataItemMap.computeIfAbsent( artifactPath, myArtifactPath ->
442 createArtifactFromPath( myArtifactPath )
444 if (!item.hasCharacteristic( Artifact.class )) {
445 item.setCharacteristic( Artifact.class, createArtifactFromPath( artifactPath ) );
447 return item.adapt( Artifact.class );
450 private Artifact createArtifactFromPath( final StorageAsset artifactPath ) {
451 final Version version = getVersionFromArtifactPath( artifactPath );
452 final ArtifactInfo info = getArtifactInfoFromPath( version.getVersion( ), artifactPath );
453 return org.apache.archiva.repository.content.base.ArchivaArtifact.withAsset( artifactPath )
454 .withVersion( version )
456 .withClassifier( info.classifier )
457 .withRemainder( info.remainder )
458 .withType( info.type )
459 .withArtifactVersion( info.version )
460 .withContentType( info.contentType )
461 .withArtifactType( info.artifactType )
465 private String getContentType(StorageAsset artifactPath) {
468 return Files.probeContentType( artifactPath.getFilePath( ) );
471 catch ( IOException e )
477 private DataItem getDataItemFromPath( final StorageAsset artifactPath )
479 final String extension = StringUtils.substringAfterLast( artifactPath.getName( ), "." );
480 final String contentType = getContentType( artifactPath );
481 return dataItemMap.computeIfAbsent( artifactPath, myArtifactPath ->
482 org.apache.archiva.repository.content.base.ArchivaDataItem.withAsset( artifactPath )
483 .withId( artifactPath.getName( ) )
484 .withContentType( contentType )
490 private ContentItem getItemFromPath( final StorageAsset itemPath )
492 if ( itemPath.isLeaf( ) )
494 if (dataItemMap.containsKey( itemPath )) {
495 return dataItemMap.get( itemPath );
497 return getDataItemFromPath( itemPath );
501 if (itemMap.containsKey( itemPath )) {
502 return itemMap.get( itemPath );
504 return ArchivaContentItem.withRepository( this ).withAsset( itemPath ).build();
510 public ManagedRepositoryContent getGenericContent( )
515 // Simple object to hold artifact information
516 private class ArtifactInfo
519 private String version;
520 private String extension;
521 private String remainder;
523 private String classifier;
524 private String contentType;
525 private StorageAsset asset;
526 private ArtifactType artifactType = BaseArtifactTypes.MAIN;
529 private ArtifactInfo getArtifactInfoFromPath( String genericVersion, StorageAsset path )
531 final ArtifactInfo info = new ArtifactInfo( );
533 info.id = path.getParent( ).getParent( ).getName( );
534 final String fileName = path.getName( );
535 if ( genericVersion.endsWith( "-" + SNAPSHOT ) )
537 String baseVersion = StringUtils.substringBeforeLast( genericVersion, "-" + SNAPSHOT );
538 String prefix = info.id + "-" + baseVersion + "-";
539 if ( fileName.startsWith( prefix ) )
541 String versionPostfix = StringUtils.removeStart( fileName, prefix );
542 Matcher matcher = UNIQUE_SNAPSHOT_PATTERN.matcher( versionPostfix );
543 if ( matcher.matches( ) )
545 info.version = baseVersion + "-" + matcher.group( 1 );
546 String newPrefix = info.id + "-" + info.version;
547 if ( fileName.startsWith( newPrefix ) )
549 String classPostfix = StringUtils.removeStart( fileName, newPrefix );
550 Matcher cMatch = CLASSIFIER_PATTERN.matcher( classPostfix );
551 if ( cMatch.matches( ) )
553 info.classifier = cMatch.group( 1 );
554 info.remainder = cMatch.group( 2 );
558 info.classifier = "";
559 info.remainder = classPostfix;
564 log.debug( "Artifact does not match the maven name pattern {}", path );
565 info.artifactType = BaseArtifactTypes.UNKNOWN;
566 info.classifier = "";
567 info.remainder = StringUtils.substringAfter( fileName, prefix );
572 log.debug( "Artifact does not match the snapshot version pattern {}", path );
574 info.artifactType = BaseArtifactTypes.UNKNOWN;
575 // This is just a guess. No guarantee to the get a usable version.
576 info.version = StringUtils.removeStart( fileName, info.id + '-' );
577 String postfix = StringUtils.substringAfterLast( info.version, "." ).toLowerCase( );
578 while ( COMMON_EXTENSIONS.matcher( postfix ).matches( ) )
580 info.version = StringUtils.substringBeforeLast( info.version, "." );
581 postfix = StringUtils.substringAfterLast( info.version, "." ).toLowerCase( );
583 info.classifier = "";
584 info.remainder = StringUtils.substringAfter( fileName, prefix );
589 log.debug( "Artifact does not match the maven name pattern: {}", path );
590 if ( fileName.contains( "-" + baseVersion ) )
592 info.id = StringUtils.substringBefore( fileName, "-" + baseVersion );
598 info.artifactType = BaseArtifactTypes.UNKNOWN;
600 info.classifier = "";
601 info.remainder = StringUtils.substringAfterLast( fileName, "." );
606 String prefix = info.id + "-" + genericVersion;
607 if ( fileName.startsWith( prefix ) )
609 info.version = genericVersion;
610 String classPostfix = StringUtils.removeStart( fileName, prefix );
611 Matcher cMatch = CLASSIFIER_PATTERN.matcher( classPostfix );
612 if ( cMatch.matches( ) )
614 info.classifier = cMatch.group( 1 );
615 info.remainder = cMatch.group( 2 );
619 info.classifier = "";
620 info.remainder = classPostfix;
625 if ( fileName.contains( "-" + genericVersion ) )
627 info.id = StringUtils.substringBefore( fileName, "-" + genericVersion );
633 log.debug( "Artifact does not match the version pattern {}", path );
634 info.artifactType = BaseArtifactTypes.UNKNOWN;
636 info.classifier = "";
637 info.remainder = StringUtils.substringAfterLast( fileName, "." );
640 info.extension = StringUtils.substringAfterLast( fileName, "." );
641 info.type = MavenContentHelper.getTypeFromClassifierAndExtension( info.classifier, info.extension );
644 info.contentType = Files.probeContentType( path.getFilePath( ) );
646 catch ( IOException e )
648 info.contentType = "";
651 if ( MavenContentHelper.METADATA_FILENAME.equalsIgnoreCase( fileName ) )
653 info.artifactType = BaseArtifactTypes.METADATA;
655 else if ( MavenContentHelper.METADATA_REPOSITORY_FILENAME.equalsIgnoreCase( fileName ) )
657 info.artifactType = MavenTypes.REPOSITORY_METADATA;
659 else if ( StringUtils.isNotEmpty( info.remainder ) && StringUtils.countMatches( info.remainder, "." ) >= 2 )
661 String mainFile = StringUtils.substringBeforeLast( fileName, "." );
662 if ( path.getParent( ).resolve( mainFile ).exists( ) )
664 info.artifactType = BaseArtifactTypes.RELATED;
672 public Artifact getArtifact( final ItemSelector selector ) throws ContentAccessException
674 if ( !selector.hasProjectId( ) )
676 throw new IllegalArgumentException( "Project id must be set" );
678 if ( !selector.hasVersion( ) )
680 throw new IllegalArgumentException( "Version must be set" );
682 if ( !selector.hasArtifactId( ) )
684 throw new IllegalArgumentException( "Artifact id must be set" );
686 final StorageAsset artifactDir = getAsset( selector.getNamespace( ), selector.getProjectId( ),
687 selector.getVersion( ) );
688 final String artifactVersion = mavenContentHelper.getArtifactVersion( artifactDir, selector );
689 final String classifier = MavenContentHelper.getClassifier( selector );
690 final String extension = MavenContentHelper.getArtifactExtension( selector );
691 final String artifactId = StringUtils.isEmpty( selector.getArtifactId( ) ) ? selector.getProjectId( ) : selector.getArtifactId( );
692 final String fileName = MavenContentHelper.getArtifactFileName( artifactId, artifactVersion, classifier, extension );
693 final StorageAsset path = getAsset( selector.getNamespace( ), selector.getProjectId( ),
694 selector.getVersion( ), fileName );
695 return getArtifactFromPath( path );
699 * Returns all the subdirectories of the given namespace directory as project.
702 public List<? extends Project> getProjects( Namespace namespace )
704 return namespace.getAsset( ).list( ).stream( )
705 .filter( a -> a.isContainer( ) )
706 .map( a -> getProjectFromPath( a ) )
707 .collect( Collectors.toList( ) );
711 public List<? extends Project> getProjects( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
713 return getProjects( getNamespace( selector ) );
717 * Returns a version object for each directory that is a direct child of the project directory.
719 * @param project the project for which the versions should be returned
720 * @return the list of versions or a empty list, if not version was found
723 public List<? extends Version> getVersions( final Project project )
725 StorageAsset asset = getAsset( project.getNamespace( ).getNamespace( ), project.getId( ) );
726 return asset.list( ).stream( ).filter( a -> a.isContainer( ) )
727 .map( a -> ArchivaVersion.withAsset( a )
728 .withProject( project )
729 .withVersion( a.getName( ) ).build( ) )
730 .collect( Collectors.toList( ) );
734 * Returns the versions that can be found for the given selector.
736 * @param selector the item selector. At least namespace and projectId must be set.
737 * @return the list of version objects or a empty list, if the selector does not match a version
738 * @throws ContentAccessException if the access to the underlying backend failed
739 * @throws IllegalArgumentException if the selector has no projectId specified
742 public List<? extends Version> getVersions( final ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
744 if ( !selector.hasProjectId( ) )
746 log.error( "Bad item selector for version list: {}", selector );
747 throw new IllegalArgumentException( "Project id not set, while retrieving versions." );
749 final Project project = getProject( selector );
750 if ( selector.hasVersion( ) )
752 final StorageAsset asset = getAsset( selector.getNamespace( ), selector.getProjectId( ), selector.getVersion( ) );
753 return asset.list( ).stream( ).map( a -> getArtifactInfoFromPath( selector.getVersion( ), a ) )
754 .filter( ai -> StringUtils.isNotEmpty( ai.version ) )
755 .map( v -> getVersionFromArtifactPath( v.asset ) )
757 .collect( Collectors.toList( ) );
761 return getVersions( project );
765 public List<String> getArtifactVersions( final ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
767 if ( !selector.hasProjectId( ) )
769 log.error( "Bad item selector for version list: {}", selector );
770 throw new IllegalArgumentException( "Project id not set, while retrieving versions." );
772 final Project project = getProject( selector );
773 if ( selector.hasVersion( ) )
775 final StorageAsset asset = getAsset( selector.getNamespace( ), selector.getProjectId( ), selector.getVersion( ) );
776 return asset.list( ).stream( ).map( a -> getArtifactInfoFromPath( selector.getVersion( ), a ) )
777 .filter( ai -> StringUtils.isNotEmpty( ai.version ) )
778 .map( v -> v.version )
780 .collect( Collectors.toList( ) );
784 return project.getAsset( ).list( ).stream( ).map( a -> getVersionFromPath( a ) )
785 .flatMap( v -> v.getAsset( ).list( ).stream( ).map( a -> getArtifactInfoFromPath( v.getVersion( ), a ) ) )
786 .filter( ai -> StringUtils.isNotEmpty( ai.version ) )
787 .map( v -> v.version )
789 .collect( Collectors.toList( ) );
795 * See {@link #newArtifactStream(ItemSelector)}. This method collects the stream into a list.
797 * @param selector the selector for the artifacts
798 * @return the list of artifacts
799 * @throws ContentAccessException if the access to the underlying filesystem failed
802 public List<? extends Artifact> getArtifacts( ItemSelector selector ) throws ContentAccessException
804 try ( Stream<? extends Artifact> stream = newArtifactStream( selector ) )
806 return stream.collect( Collectors.toList( ) );
812 * File filter to select certain artifacts using the selector data.
814 private Predicate<StorageAsset> getArtifactFileFilterFromSelector( final ItemSelector selector )
816 Predicate<StorageAsset> p = a -> a.isLeaf( );
817 StringBuilder fileNamePattern = new StringBuilder( "^" );
818 if ( selector.hasArtifactId( ) )
820 fileNamePattern.append( Pattern.quote( selector.getArtifactId( ) ) ).append( "-" );
824 fileNamePattern.append( "[A-Za-z0-9_\\-.]+-" );
826 if ( selector.hasArtifactVersion( ) )
828 if ( selector.getArtifactVersion( ).contains( "*" ) )
830 String[] tokens = StringUtils.splitByWholeSeparator( selector.getArtifactVersion( ), "*" );
831 for ( String currentToken : tokens )
833 if ( !currentToken.equals( "" ) )
835 fileNamePattern.append( Pattern.quote( currentToken ) );
837 fileNamePattern.append( "[A-Za-z0-9_\\-.]*" );
842 fileNamePattern.append( Pattern.quote( selector.getArtifactVersion( ) ) );
847 fileNamePattern.append( "[A-Za-z0-9_\\-.]+" );
849 String classifier = selector.hasClassifier( ) ? selector.getClassifier( ) :
850 ( selector.hasType( ) ? MavenContentHelper.getClassifierFromType( selector.getType( ) ) : null );
851 if ( classifier != null )
853 if ( "*".equals( classifier ) )
855 fileNamePattern.append( "(-[A-Za-z0-9]+)?\\." );
859 fileNamePattern.append( "-" ).append( Pattern.quote( classifier ) ).append( "\\." );
864 fileNamePattern.append( "\\." );
866 String extension = selector.hasExtension( ) ? selector.getExtension( ) :
867 ( selector.hasType( ) ? MavenContentHelper.getArtifactExtension( selector ) : null );
868 if ( extension != null )
870 if ( selector.includeRelatedArtifacts( ) )
872 fileNamePattern.append( Pattern.quote( extension ) ).append( "(\\.[A-Za-z0-9]+)?" );
876 fileNamePattern.append( Pattern.quote( extension ) );
881 fileNamePattern.append( "[A-Za-z0-9.]+" );
883 final Pattern pattern = Pattern.compile( fileNamePattern.toString( ) );
884 return p.and( a -> pattern.matcher( a.getName( ) ).matches( ) );
889 * Returns the artifacts. The number of artifacts returned depend on the selector.
890 * If the selector sets the flag {@link ItemSelector#includeRelatedArtifacts()} to <code>true</code>,
891 * additional to the matching artifacts, related artifacts like hash values or signatures are included in the artifact
893 * If the selector sets the flag {@link ItemSelector#recurse()} to <code>true</code>, artifacts of the given
894 * namespace and from all sub namespaces that start with the given namespace are returned.
896 * <li>If only a namespace is given, all artifacts with the given namespace or starting with the given
897 * namespace (see {@link ItemSelector#recurse()} are returned.</li>
898 * <li>If a namespace and a project id, or artifact id is given, the artifacts of all versions of the given
899 * namespace and project are returned.</li>
900 * <li>If a namespace and a project id or artifact id and a version is given, the artifacts of the given
901 * version are returned</li>
902 * <li>If no artifact version or artifact id is given, it will return all "artifacts" found in the directory.
903 * To select only artifacts that match the layout you should add the artifact id and artifact version
904 * (can contain a '*' pattern).</li>
907 * The '*' pattern can be used in classifiers and artifact versions and match zero or more characters.
909 * There is no determinate order of the elements in the stream.
911 * Returned streams are auto closable and should be used in a try-with-resources statement.
913 * @param selector the item selector
914 * @throws ContentAccessException if the access to the underlying filesystem failed
917 public Stream<? extends Artifact> newArtifactStream( ItemSelector selector ) throws ContentAccessException
919 String projectId = selector.hasProjectId( ) ? selector.getProjectId( ) : ( selector.hasArtifactId( ) ? selector.getArtifactId( )
921 final Predicate<StorageAsset> filter = getArtifactFileFilterFromSelector( selector );
922 if ( projectId != null && selector.hasVersion( ) )
924 return getAsset( selector.getNamespace( ), projectId, selector.getVersion( ) )
925 .list( ).stream( ).filter( filter )
926 .map( this::getArtifactFromPath );
928 else if ( projectId != null )
930 final StorageAsset projDir = getAsset( selector.getNamespace( ), projectId );
931 return projDir.list( ).stream( )
932 .map( a -> a.isContainer( ) ? a.list( ) : Arrays.asList( a ) )
933 .flatMap( List::stream )
935 .map( this::getArtifactFromPath );
939 StorageAsset namespaceDir = getAsset( selector.getNamespace( ) );
940 if ( selector.recurse( ) )
942 return StorageUtil.newAssetStream( namespaceDir, true )
944 .map( this::getArtifactFromPath );
949 // We descend into 2 subdirectories (project and version)
950 return namespaceDir.list( ).stream( )
951 .map( a -> a.isContainer( ) ? a.list( ) : Arrays.asList( a ) )
952 .flatMap( List::stream )
953 .map( a -> a.isContainer( ) ? a.list( ) : Arrays.asList( a ) )
954 .flatMap( List::stream )
956 .map( this::getArtifactFromPath );
962 * Same as {@link #newArtifactStream(ContentItem)} but returns the collected stream as list.
964 * @param item the item the parent item
965 * @return the list of artifacts or a empty list of no artifacts where found
968 public List<? extends Artifact> getArtifacts( ContentItem item )
970 try ( Stream<? extends Artifact> stream = newArtifactStream( item ) )
972 return stream.collect( Collectors.toList( ) );
977 * Returns all artifacts
981 * @throws ContentAccessException
983 public Stream<? extends Artifact> newArtifactStream( Namespace item ) throws ContentAccessException
985 return newArtifactStream( ArchivaItemSelector.builder( ).withNamespace( item.getNamespace( ) ).build( ) );
988 public Stream<? extends Artifact> newArtifactStream( Project item ) throws ContentAccessException
990 return newArtifactStream( ArchivaItemSelector.builder( ).withNamespace( item.getNamespace( ).getNamespace( ) )
991 .withProjectId( item.getId( ) ).build( ) );
994 public Stream<? extends Artifact> newArtifactStream( Version item ) throws ContentAccessException
996 return newArtifactStream( ArchivaItemSelector.builder( ).withNamespace( item.getProject( ).getNamespace( ).getNamespace( ) )
997 .withProjectId( item.getProject( ).getId( ) )
998 .withVersion( item.getVersion( ) ).build( ) );
1002 * Returns all related artifacts that match the given artifact. That means all artifacts that have
1003 * the same filename plus an additional extension, e.g. ${fileName}.sha2
1005 * @param item the artifact
1006 * @return the stream of artifacts
1007 * @throws ContentAccessException
1009 public Stream<? extends Artifact> newArtifactStream( Artifact item ) throws ContentAccessException
1011 final Version v = item.getVersion( );
1012 final String fileName = item.getFileName( );
1013 final Predicate<StorageAsset> filter = ( StorageAsset a ) ->
1014 a.getName( ).startsWith( fileName + "." );
1015 return v.getAsset( ).list( ).stream( ).filter( filter )
1016 .map( a -> getArtifactFromPath( a ) );
1020 * Returns the stream of artifacts that are children of the given item.
1022 * @param item the item from where the artifacts should be returned
1024 * @throws ContentAccessException
1027 public Stream<? extends Artifact> newArtifactStream( ContentItem item ) throws ContentAccessException
1029 if ( item instanceof Namespace )
1031 return newArtifactStream( ( (Namespace) item ) );
1033 else if ( item instanceof Project )
1035 return newArtifactStream( (Project) item );
1037 else if ( item instanceof Version )
1039 return newArtifactStream( (Version) item );
1041 else if ( item instanceof Artifact )
1043 return newArtifactStream( (Artifact) item );
1047 log.warn( "newArtifactStream for unsupported item requested: {}", item.getClass( ).getName( ) );
1048 return Stream.empty( );
1052 private void appendPatternRegex( StringBuilder builder, String name )
1054 String[] patternArray = name.split( "[*]" );
1055 for ( int i = 0; i < patternArray.length - 1; i++ )
1057 builder.append( Pattern.quote( patternArray[i] ) )
1058 .append( "[A-Za-z0-9_\\-]*" );
1060 builder.append( Pattern.quote( patternArray[patternArray.length - 1] ) );
1063 Predicate<StorageAsset> getItemFileFilterFromSelector( ItemSelector selector )
1065 if ( !selector.hasNamespace( ) && !selector.hasProjectId( ) )
1067 throw new IllegalArgumentException( "Selector must have at least namespace and projectid" );
1069 StringBuilder pathMatcher = new StringBuilder( "^" );
1070 if ( selector.hasNamespace( ) )
1072 String path = "/" + String.join( "/", selector.getNamespace( ).split( "\\." ) );
1073 if ( path.contains( "*" ) )
1075 appendPatternRegex( pathMatcher, path );
1079 pathMatcher.append( Pattern.quote( path ) );
1083 if ( selector.hasProjectId( ) )
1085 pathMatcher.append( "/" );
1086 if ( selector.getProjectId( ).contains( "*" ) )
1088 appendPatternRegex( pathMatcher, selector.getProjectId( ) );
1092 pathMatcher.append( Pattern.quote( selector.getProjectId( ) ) );
1095 if ( selector.hasVersion( ) )
1097 pathMatcher.append( "/" );
1098 if ( selector.getVersion( ).contains( "*" ) )
1100 appendPatternRegex( pathMatcher, selector.getVersion( ) );
1104 pathMatcher.append( Pattern.quote( selector.getVersion( ) ) );
1107 pathMatcher.append( ".*" );
1108 final Pattern pathPattern = Pattern.compile( pathMatcher.toString( ) );
1109 final Predicate<StorageAsset> pathPredicate = ( StorageAsset asset ) -> pathPattern.matcher( asset.getPath( ) ).matches( );
1110 if ( selector.hasArtifactId( ) || selector.hasArtifactVersion( ) || selector.hasClassifier( )
1111 || selector.hasType( ) || selector.hasExtension( ) )
1113 return getArtifactFileFilterFromSelector( selector ).and( pathPredicate );
1117 return pathPredicate;
1122 * Returns a concatenation of the asset and its children as stream, if they exist.
1123 * It descends <code>level+1</code> levels down.
1125 * @param a the asset to start from
1126 * @param level the number of child levels to descend. 0 means only the children of the given asset, 1 means the children of childrens of the given asset, ...
1127 * @return the stream of storage assets
1129 private Stream<StorageAsset> getChildrenDF( StorageAsset a, int level )
1131 if ( a.isContainer( ) )
1134 return Stream.concat( a.list().stream( ).flatMap( ch -> getChildrenDF( ch, level - 1 ) ), Stream.of( a ) );
1137 return Stream.concat( a.list( ).stream( ), Stream.of( a ) );
1142 return Stream.of( a );
1147 public Stream<? extends ContentItem> newItemStream( ItemSelector selector, boolean parallel ) throws ContentAccessException, IllegalArgumentException
1149 final Predicate<StorageAsset> filter = getItemFileFilterFromSelector( selector );
1150 StorageAsset startDir;
1151 if (selector.getNamespace().contains("*")) {
1152 startDir = getAsset( "" );
1153 } else if ( selector.hasProjectId( ) && selector.getProjectId().contains("*") )
1155 startDir = getAsset( selector.getNamespace( ) );
1156 } else if ( selector.hasProjectId() && selector.hasVersion() && selector.getVersion().contains("*")) {
1157 startDir = getAsset( selector.getNamespace( ), selector.getProjectId( ) );
1159 else if ( selector.hasProjectId( ) && selector.hasVersion( ) )
1161 startDir = getAsset( selector.getNamespace( ), selector.getProjectId( ), selector.getVersion() );
1163 else if ( selector.hasProjectId( ) )
1165 startDir = getAsset( selector.getNamespace( ), selector.getProjectId( ) );
1169 startDir = getAsset( selector.getNamespace( ) );
1170 if ( !selector.recurse( ) )
1172 // We descend into 2 subdirectories (project and version)
1173 return startDir.list( ).stream( )
1174 .flatMap( a -> getChildrenDF( a, 1 ) )
1175 .map( this::getItemFromPath );
1179 return StorageUtil.newAssetStream( startDir, parallel )
1181 .map( this::getItemFromPath );
1186 * Checks, if the asset/file queried by the given selector exists.
1189 public boolean hasContent( ItemSelector selector )
1191 return getItem( selector ).getAsset( ).exists( );
1195 public ContentItem getParent( ContentItem item )
1197 return getItemFromPath( item.getAsset( ).getParent( ) );
1201 public List<? extends ContentItem> getChildren( ContentItem item )
1203 if (item.getAsset().isLeaf()) {
1204 return Collections.emptyList( );
1206 return item.getAsset( ).list( ).stream( ).map( a -> getItemFromPath( a ) ).collect( Collectors.toList( ) );
1211 public <T extends ContentItem> T applyCharacteristic( Class<T> clazz, ContentItem item ) throws LayoutException
1213 if (item.getAsset().isLeaf()) {
1214 if (clazz.isAssignableFrom( Artifact.class )) {
1215 Artifact artifact = getArtifactFromPath( item.getAsset( ) );
1216 item.setCharacteristic( Artifact.class, artifact );
1217 return (T) artifact;
1219 throw new LayoutException( "Could not adapt file to clazz " + clazz );
1222 if (clazz.isAssignableFrom( Version.class )) {
1223 Version version = getVersionFromPath( item.getAsset( ) );
1224 item.setCharacteristic( Version.class, version );
1226 } else if (clazz.isAssignableFrom( Project.class )) {
1227 Project project = getProjectFromPath( item.getAsset( ) );
1228 item.setCharacteristic( Project.class, project );
1230 } else if (clazz.isAssignableFrom( Namespace.class )) {
1231 Namespace ns = getNamespaceFromPath( item.getAsset( ) );
1232 item.setCharacteristic( Namespace.class, ns );
1235 throw new LayoutException( "Cannot adapt directory to clazz " + clazz );
1241 public <T extends ManagedRepositoryContentLayout> T getLayout( Class<T> clazz ) throws LayoutException
1243 if (clazz.isAssignableFrom( this.getClass() )) {
1246 throw new LayoutException( "Cannot convert to layout " + clazz );
1251 public <T extends ManagedRepositoryContentLayout> boolean supportsLayout( Class<T> clazz )
1253 return clazz.isAssignableFrom( this.getClass( ) );
1257 * Moves the file to the artifact destination
1260 public void addArtifact( Path sourceFile, Artifact destination ) throws IllegalArgumentException, ContentAccessException
1264 StorageAsset asset = destination.getAsset( );
1265 if ( !asset.exists( ) )
1269 asset.replaceDataFromFile( sourceFile );
1271 catch ( IOException e )
1273 log.error( "Could not push data to asset source={} destination={}. {}", sourceFile, destination.getAsset( ).getFilePath( ), e.getMessage( ) );
1274 throw new ContentAccessException( e.getMessage( ), e );
1279 public ContentItem toItem( String path ) throws LayoutException
1281 StorageAsset asset = getRepository( ).getAsset( path );
1282 if ( asset.isLeaf( ) )
1284 ItemSelector selector = getPathParser( ).toItemSelector( path );
1285 return getItem( selector );
1289 return getItemFromPath( asset );
1294 public ContentItem toItem( StorageAsset assetPath ) throws LayoutException
1296 return toItem( assetPath.getPath( ) );
1299 /// ************* End of new generation interface ******************
1302 * Returns a version reference from the coordinates
1304 * @param groupId the group id
1305 * @param artifactId the artifact id
1306 * @param version the version
1307 * @return the versioned reference object
1310 public VersionedReference toVersion( String groupId, String artifactId, String version )
1312 return new VersionedReference( ).groupId( groupId ).artifactId( artifactId ).version( version );
1316 * Return the version the artifact is part of
1318 * @param artifactReference
1321 public VersionedReference toVersion( ArtifactReference artifactReference )
1323 return toVersion( artifactReference.getGroupId( ), artifactReference.getArtifactId( ), artifactReference.getVersion( ) );
1327 public String toPath( ContentItem item ) {
1328 return item.getAsset( ).getPath( );
1332 public DataItem getMetadataItem( Version version ) {
1333 StorageAsset metaPath = version.getAsset( ).resolve( MAVEN_METADATA );
1334 return getDataItemFromPath( metaPath );
1338 public DataItem getMetadataItem( Project project )
1340 StorageAsset metaPath = project.getAsset( ).resolve( MAVEN_METADATA );
1341 return getDataItemFromPath( metaPath );
1346 public void deleteVersion( VersionedReference ref ) throws ContentNotFoundException, ContentAccessException
1348 final String path = toPath( ref );
1349 final Path deleteTarget = getRepoDir( ).resolve( path );
1350 if ( !Files.exists( deleteTarget ) )
1352 log.warn( "Version path for repository {} does not exist: {}", getId( ), deleteTarget );
1353 throw new ContentNotFoundException( "Version not found for repository " + getId( ) + ": " + path );
1355 if ( Files.isDirectory( deleteTarget ) )
1359 org.apache.archiva.common.utils.FileUtils.deleteDirectory( deleteTarget );
1361 catch ( IOException e )
1363 log.error( "Could not delete file path {}: {}", deleteTarget, e.getMessage( ), e );
1364 throw new ContentAccessException( "Error while trying to delete path " + path + " from repository " + getId( ) + ": " + e.getMessage( ), e );
1369 log.warn( "Version path for repository {} is not a directory {}", getId( ), deleteTarget );
1370 throw new ContentNotFoundException( "Version path for repository " + getId( ) + " is not directory: " + path );
1375 public void deleteProject( ProjectReference ref )
1376 throws ContentNotFoundException, ContentAccessException
1378 final String path = toPath( ref );
1379 final Path deleteTarget = getRepoDir( ).resolve( path );
1380 if ( !Files.exists( deleteTarget ) )
1382 log.warn( "Project path for repository {} does not exist: {}", getId( ), deleteTarget );
1383 throw new ContentNotFoundException( "Project not found for repository " + getId( ) + ": " + path );
1385 if ( Files.isDirectory( deleteTarget ) )
1389 org.apache.archiva.common.utils.FileUtils.deleteDirectory( deleteTarget );
1391 catch ( IOException e )
1393 log.error( "Could not delete file path {}: {}", deleteTarget, e.getMessage( ), e );
1394 throw new ContentAccessException( "Error while trying to delete path " + path + " from repository " + getId( ) + ": " + e.getMessage( ), e );
1399 log.warn( "Project path for repository {} is not a directory {}", getId( ), deleteTarget );
1400 throw new ContentNotFoundException( "Project path for repository " + getId( ) + " is not directory: " + path );
1406 public void deleteProject( String namespace, String projectId ) throws ContentNotFoundException, ContentAccessException
1408 this.deleteProject( new ProjectReference( ).groupId( namespace ).artifactId( projectId ) );
1412 public void deleteArtifact( ArtifactReference ref ) throws ContentNotFoundException, ContentAccessException
1414 final String path = toPath( ref );
1415 final Path repoDir = getRepoDir( );
1416 Path deleteTarget = repoDir.resolve( path );
1417 if ( Files.exists( deleteTarget ) )
1421 if ( Files.isDirectory( deleteTarget ) )
1423 org.apache.archiva.common.utils.FileUtils.deleteDirectory( deleteTarget );
1427 Files.delete( deleteTarget );
1430 catch ( IOException e )
1432 log.error( "Could not delete file path {}: {}", deleteTarget, e.getMessage( ), e );
1433 throw new ContentAccessException( "Error while trying to delete path " + path + " from repository " + getId( ) + ": " + e.getMessage( ), e );
1438 log.warn( "Artifact path for repository {} does not exist: {}", getId( ), deleteTarget );
1439 throw new ContentNotFoundException( "Artifact not found for repository " + getId( ) + ": " + path );
1445 public void deleteGroupId( String groupId )
1446 throws ContentNotFoundException, ContentAccessException
1448 final String path = toPath( groupId );
1449 final Path deleteTarget = getRepoDir( ).resolve( path );
1450 if ( !Files.exists( deleteTarget ) )
1452 log.warn( "Namespace path for repository {} does not exist: {}", getId( ), deleteTarget );
1453 throw new ContentNotFoundException( "Namespace not found for repository " + getId( ) + ": " + path );
1455 if ( Files.isDirectory( deleteTarget ) )
1459 org.apache.archiva.common.utils.FileUtils.deleteDirectory( deleteTarget );
1461 catch ( IOException e )
1463 log.error( "Could not delete file path {}: {}", deleteTarget, e.getMessage( ), e );
1464 throw new ContentAccessException( "Error while trying to delete path " + path + " from repository " + getId( ) + ": " + e.getMessage( ), e );
1469 log.warn( "Namespace path for repository {} is not a directory {}", getId( ), deleteTarget );
1470 throw new ContentNotFoundException( "Namespace path for repository " + getId( ) + " is not directory: " + path );
1476 public String getId( )
1478 return repository.getId( );
1482 public List<ArtifactReference> getRelatedArtifacts( VersionedReference reference )
1483 throws ContentNotFoundException, LayoutException, ContentAccessException
1485 StorageAsset artifactDir = toFile( reference );
1486 if ( !artifactDir.exists( ) )
1488 throw new ContentNotFoundException(
1489 "Unable to get related artifacts using a non-existant directory: " + artifactDir.getPath( ) );
1492 if ( !artifactDir.isContainer( ) )
1494 throw new ContentNotFoundException(
1495 "Unable to get related artifacts using a non-directory: " + artifactDir.getPath( ) );
1498 // First gather up the versions found as artifacts in the managed repository.
1500 try ( Stream<? extends StorageAsset> stream = artifactDir.list( ).stream( ) )
1502 return stream.filter( asset -> !asset.isContainer( ) ).map( path -> {
1505 ArtifactReference artifact = toArtifactReference( path.getPath( ) );
1506 if ( artifact.getGroupId( ).equals( reference.getGroupId( ) ) && artifact.getArtifactId( ).equals(
1507 reference.getArtifactId( ) ) && artifact.getVersion( ).equals( reference.getVersion( ) ) )
1516 catch ( LayoutException e )
1518 log.debug( "Not processing file that is not an artifact: {}", e.getMessage( ) );
1521 } ).filter( Objects::nonNull ).collect( Collectors.toList( ) );
1523 catch ( RuntimeException e )
1525 Throwable cause = e.getCause( );
1526 if ( cause != null )
1528 if ( cause instanceof LayoutException )
1530 throw (LayoutException) cause;
1534 throw new ContentAccessException( cause.getMessage( ), cause );
1539 throw new ContentAccessException( e.getMessage( ), e );
1545 * Create the filter for various combinations of classifier and type
1547 private Predicate<ArtifactReference> getChecker( ArtifactReference referenceObject, String extension )
1549 // TODO: Check, if extension is the correct parameter here
1550 // We compare type with extension which works for artifacts like .jar.md5 but may
1551 // be not the best way.
1553 if ( referenceObject.getClassifier( ) != null && referenceObject.getType( ) != null )
1555 return ( ( ArtifactReference a ) ->
1556 referenceObject.getGroupId( ).equals( a.getGroupId( ) )
1557 && referenceObject.getArtifactId( ).equals( a.getArtifactId( ) )
1558 && referenceObject.getVersion( ).equals( a.getVersion( ) )
1559 && ( ( a.getType( ) == null )
1560 || referenceObject.getType( ).equals( a.getType( ) )
1561 || a.getType( ).startsWith( extension ) )
1562 && referenceObject.getClassifier( ).equals( a.getClassifier( ) )
1565 else if ( referenceObject.getClassifier( ) != null && referenceObject.getType( ) == null )
1567 return ( ( ArtifactReference a ) ->
1568 referenceObject.getGroupId( ).equals( a.getGroupId( ) )
1569 && referenceObject.getArtifactId( ).equals( a.getArtifactId( ) )
1570 && referenceObject.getVersion( ).equals( a.getVersion( ) )
1571 && referenceObject.getClassifier( ).equals( a.getClassifier( ) )
1574 else if ( referenceObject.getClassifier( ) == null && referenceObject.getType( ) != null )
1576 return ( ( ArtifactReference a ) ->
1577 referenceObject.getGroupId( ).equals( a.getGroupId( ) )
1578 && referenceObject.getArtifactId( ).equals( a.getArtifactId( ) )
1579 && referenceObject.getVersion( ).equals( a.getVersion( ) )
1580 && ( ( a.getType( ) == null )
1581 || referenceObject.getType( ).equals( a.getType( ) )
1582 || a.getType( ).startsWith( extension ) )
1587 return ( ( ArtifactReference a ) ->
1588 referenceObject.getGroupId( ).equals( a.getGroupId( ) )
1589 && referenceObject.getArtifactId( ).equals( a.getArtifactId( ) )
1590 && referenceObject.getVersion( ).equals( a.getVersion( ) )
1598 public String getRepoRoot( )
1600 return convertUriToPath( repository.getLocation( ) );
1603 private String convertUriToPath( URI uri )
1605 if ( uri.getScheme( ) == null )
1607 return Paths.get( uri.getPath( ) ).toString( );
1609 else if ( "file".equals( uri.getScheme( ) ) )
1611 return Paths.get( uri ).toString( );
1615 return uri.toString( );
1620 public ManagedRepository getRepository( )
1626 public void setRepository( final ManagedRepository repo )
1628 this.repository = repo;
1631 if ( repository instanceof EditableManagedRepository )
1633 ( (EditableManagedRepository) repository ).setContent( this );
1638 private Path getRepoDir( )
1640 return repository.getAsset( "" ).getFilePath( );
1643 private RepositoryStorage getStorage( )
1645 return repository.getAsset( "" ).getStorage( );
1649 * Convert a path to an artifact reference.
1651 * @param path the path to convert. (relative or full location path)
1652 * @throws LayoutException if the path cannot be converted to an artifact reference.
1655 public ArtifactReference toArtifactReference( String path )
1656 throws LayoutException
1658 String repoPath = convertUriToPath( repository.getLocation( ) );
1659 if ( ( path != null ) && path.startsWith( repoPath ) && repoPath.length( ) > 0 )
1661 return super.toArtifactReference( path.substring( repoPath.length( ) + 1 ) );
1666 if ( repoPath != null )
1668 while ( repoPath.startsWith( "/" ) )
1670 repoPath = repoPath.substring( 1 );
1673 return super.toArtifactReference( repoPath );
1678 // The variant with runtime exception for stream usage
1679 private ArtifactReference toArtifactRef( String path )
1683 return toArtifactReference( path );
1685 catch ( LayoutException e )
1687 throw new RuntimeException( e );
1693 public StorageAsset toFile( ArtifactReference reference )
1695 return repository.getAsset( toPath( reference ) );
1699 public StorageAsset toFile( VersionedReference reference )
1701 return repository.getAsset( toPath( reference ) );
1705 * Get the first Artifact found in the provided VersionedReference location.
1707 * @param reference the reference to the versioned reference to search within
1708 * @return the ArtifactReference to the first artifact located within the versioned reference. or null if
1709 * no artifact was found within the versioned reference.
1710 * @throws java.io.IOException if the versioned reference is invalid (example: doesn't exist, or isn't a directory)
1711 * @throws LayoutException
1713 private ArtifactReference getFirstArtifact( VersionedReference reference )
1714 throws ContentNotFoundException, LayoutException, IOException
1716 try ( Stream<ArtifactReference> stream = newArtifactStream( reference ) )
1718 return stream.findFirst( ).orElse( null );
1720 catch ( RuntimeException e )
1722 throw new ContentNotFoundException( e.getMessage( ), e.getCause( ) );
1726 private Stream<ArtifactReference> newArtifactStream( VersionedReference reference ) throws ContentNotFoundException, LayoutException, IOException
1728 final Path repoBase = getRepoDir( );
1729 String path = toMetadataPath( reference );
1730 Path versionDir = repoBase.resolve( path ).getParent( );
1731 if ( !Files.exists( versionDir ) )
1733 throw new ContentNotFoundException( "Unable to gather the list of artifacts on a non-existant directory: "
1734 + versionDir.toAbsolutePath( ) );
1737 if ( !Files.isDirectory( versionDir ) )
1739 throw new ContentNotFoundException(
1740 "Unable to gather the list of snapshot versions on a non-directory: " + versionDir.toAbsolutePath( ) );
1742 return Files.list( versionDir ).filter( Files::isRegularFile )
1743 .map( p -> repoBase.relativize( p ).toString( ) )
1744 .filter( p -> !filetypes.matchesDefaultExclusions( p ) )
1745 .filter( filetypes::matchesArtifactPattern )
1746 .map( this::toArtifactRef );
1749 public List<ArtifactReference> getArtifacts( VersionedReference reference ) throws ContentNotFoundException, LayoutException, ContentAccessException
1751 try ( Stream<ArtifactReference> stream = newArtifactStream( reference ) )
1753 return stream.collect( Collectors.toList( ) );
1755 catch ( IOException e )
1757 String path = toPath( reference );
1758 log.error( "Could not read directory from repository {} - {}: ", getId( ), path, e.getMessage( ), e );
1759 throw new ContentAccessException( "Could not read path from repository " + getId( ) + ": " + path, e );
1764 private boolean hasArtifact( VersionedReference reference )
1767 try ( Stream<ArtifactReference> stream = newArtifactStream( reference ) )
1769 return stream.anyMatch( e -> true );
1771 catch ( ContentNotFoundException e )
1775 catch ( LayoutException | IOException e )
1777 // We throw the runtime exception for better stream handling
1778 throw new RuntimeException( e );
1782 public void setFiletypes( FileTypes filetypes )
1784 this.filetypes = filetypes;
1787 public void setMavenContentHelper( MavenContentHelper contentHelper )
1789 this.mavenContentHelper = contentHelper;
1793 public MavenMetadataReader getMetadataReader( )
1795 return metadataReader;
1798 public void setMetadataReader( MavenMetadataReader metadataReader )
1800 this.metadataReader = metadataReader;