1 package org.apache.archiva.repository.scanner.mock;
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.common.filelock.DefaultFileLockManager;
23 import org.apache.archiva.common.utils.VersionUtil;
24 import org.apache.archiva.metadata.model.ArtifactMetadata;
25 import org.apache.archiva.metadata.maven.model.MavenArtifactFacet;
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.*;
30 import org.apache.archiva.repository.content.Artifact;
31 import org.apache.archiva.repository.content.BaseDataItemTypes;
32 import org.apache.archiva.repository.content.ContentItem;
33 import org.apache.archiva.repository.content.DataItem;
34 import org.apache.archiva.repository.content.ItemNotFoundException;
35 import org.apache.archiva.repository.content.ItemSelector;
36 import org.apache.archiva.repository.content.Namespace;
37 import org.apache.archiva.repository.content.Project;
38 import org.apache.archiva.repository.content.Version;
39 import org.apache.archiva.repository.content.base.ArchivaDataItem;
40 import org.apache.archiva.repository.content.base.ArchivaNamespace;
41 import org.apache.archiva.repository.content.base.ArchivaProject;
42 import org.apache.archiva.repository.content.base.ArchivaVersion;
43 import org.apache.archiva.repository.storage.fs.FilesystemStorage;
44 import org.apache.archiva.repository.storage.StorageAsset;
45 import org.apache.commons.lang3.StringUtils;
47 import java.io.IOException;
48 import java.nio.file.Path;
49 import java.nio.file.Paths;
50 import java.util.HashMap;
51 import java.util.List;
53 import java.util.function.Consumer;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
56 import java.util.stream.Stream;
59 * @author Martin Stockhammer <martin_s@apache.org>
61 public class ManagedRepositoryContentMock implements BaseRepositoryContentLayout, ManagedRepositoryContent
63 private static final String PATH_SEPARATOR = "/";
64 private static final String GROUP_SEPARATOR = ".";
65 public static final String MAVEN_METADATA = "maven-metadata.xml";
68 private ManagedRepository repository;
69 private FilesystemStorage fsStorage;
71 public ManagedRepositoryContentMock(ManagedRepository repo) {
72 this.repository = repo;
76 public VersionedReference toVersion( String groupId, String artifactId, String version )
82 public VersionedReference toVersion( ArtifactReference artifactReference )
88 public <T extends ContentItem> T adaptItem( Class<T> clazz, ContentItem item ) throws LayoutException
90 if (clazz.isAssignableFrom( Version.class ))
92 if ( !item.hasCharacteristic( Version.class ) )
94 item.setCharacteristic( Version.class, createVersionFromPath( item.getAsset() ) );
96 return (T) item.adapt( Version.class );
97 } else if ( clazz.isAssignableFrom( Project.class )) {
98 if ( !item.hasCharacteristic( Project.class ) )
100 item.setCharacteristic( Project.class, createProjectFromPath( item.getAsset() ) );
102 return (T) item.adapt( Project.class );
103 } else if ( clazz.isAssignableFrom( Namespace.class )) {
104 if ( !item.hasCharacteristic( Namespace.class ) )
106 item.setCharacteristic( Namespace.class, createNamespaceFromPath( item.getAsset() ) );
108 return (T) item.adapt( Namespace.class );
110 throw new LayoutException( "Could not convert item to class " + clazz);
113 private Version createVersionFromPath( StorageAsset asset )
115 Project proj = createProjectFromPath( asset.getParent( ) );
116 return ArchivaVersion.withRepository( this ).withAsset( asset )
117 .withProject( proj ).withVersion( asset.getName( ) ).build();
120 private Project createProjectFromPath( StorageAsset asset) {
121 Namespace ns = createNamespaceFromPath( asset );
122 return ArchivaProject.withRepository( this ).withAsset( asset )
123 .withNamespace( ns ).withId( asset.getName( ) ).build( );
126 private Namespace createNamespaceFromPath( StorageAsset asset) {
127 String namespace = asset.getPath( ).replace( "/", "." );
128 return ArchivaNamespace.withRepository( this )
129 .withAsset( asset ).withNamespace( namespace ).build();
134 public void deleteAllItems( ItemSelector selector, Consumer<ItemDeleteStatus> consumer ) throws ContentAccessException, IllegalArgumentException
140 public void deleteItem( ContentItem item ) throws ItemNotFoundException, ContentAccessException
146 public ContentItem getItem( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
152 public Namespace getNamespace( ItemSelector namespaceSelector ) throws ContentAccessException, IllegalArgumentException
158 public Project getProject( ItemSelector projectSelector ) throws ContentAccessException, IllegalArgumentException
164 public Version getVersion( ItemSelector versionCoordinates ) throws ContentAccessException, IllegalArgumentException
170 public Artifact getArtifact( ItemSelector selector ) throws ContentAccessException
176 public List<? extends Artifact> getArtifacts( ItemSelector selector ) throws ContentAccessException
182 public Stream<? extends Artifact> newArtifactStream( ItemSelector selector ) throws ContentAccessException
188 public Stream<? extends ContentItem> newItemStream( ItemSelector selector, boolean parallel ) throws ContentAccessException, IllegalArgumentException
194 public List<? extends Project> getProjects( Namespace namespace ) throws ContentAccessException
200 public List<? extends Project> getProjects( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
206 public List<? extends Version> getVersions( Project project ) throws ContentAccessException
212 public List<? extends Version> getVersions( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
218 public List<String> getArtifactVersions( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
224 public List<? extends Artifact> getArtifacts( ContentItem item ) throws ContentAccessException
230 public Stream<? extends Artifact> newArtifactStream( ContentItem item ) throws ContentAccessException
236 public boolean hasContent( ItemSelector selector )
242 public ContentItem getParent( ContentItem item )
246 return toItem( item.getAsset( ).getParent( ) );
248 catch ( LayoutException e )
250 throw new RuntimeException( "Bad layout conversion " + e.getMessage( ) );
255 public List<? extends ContentItem> getChildren( ContentItem item )
261 public <T extends ContentItem> T applyCharacteristic( Class<T> clazz, ContentItem item ) throws LayoutException
267 public <T extends ManagedRepositoryContentLayout> T getLayout( Class<T> clazz ) throws LayoutException
273 public <T extends ManagedRepositoryContentLayout> boolean supportsLayout( Class<T> clazz )
279 public void addArtifact( Path sourceFile, Artifact destination ) throws IllegalArgumentException
285 public DataItem getMetadataItem( Version version )
291 public DataItem getMetadataItem( Project project )
293 return ArchivaDataItem.withAsset( project.getAsset( ).resolve( "maven-metadata.xml" ) ).withId( "maven-metadata.xml" )
294 .withDataType( BaseDataItemTypes.METADATA ).build( );
299 public ContentItem toItem( String path ) throws LayoutException
305 public ContentItem toItem( StorageAsset assetPath ) throws LayoutException
311 public void deleteVersion( VersionedReference reference ) throws ContentNotFoundException, ContentAccessException
317 public void deleteArtifact( ArtifactReference artifactReference ) throws ContentNotFoundException, ContentAccessException
323 public void deleteGroupId( String groupId ) throws ContentNotFoundException, ContentAccessException
329 public void deleteProject( String namespace, String projectId ) throws ContentNotFoundException, ContentAccessException
335 public void deleteProject( ProjectReference reference ) throws ContentNotFoundException, ContentAccessException
341 public String toPath( ContentItem item )
347 public String getId( )
349 return repository.getId();
353 public List<ArtifactReference> getRelatedArtifacts( VersionedReference reference ) throws ContentNotFoundException, LayoutException, ContentAccessException
359 public List<ArtifactReference> getArtifacts( VersionedReference reference ) throws ContentNotFoundException, LayoutException, ContentAccessException
365 public String getRepoRoot( )
367 return getRepoRootAsset().getFilePath().toString();
370 private StorageAsset getRepoRootAsset() {
371 if (fsStorage==null) {
373 fsStorage = new FilesystemStorage(Paths.get("", "target", "test-repository", "managed"), new DefaultFileLockManager());
374 } catch (IOException e) {
378 return fsStorage.getAsset("");
382 public ManagedRepository getRepository( )
388 public void setRepository( ManagedRepository repo )
390 this.repository = repo;
394 public StorageAsset toFile( VersionedReference reference )
399 private Map<ArtifactReference, String> refs = new HashMap<>();
402 public ArtifactReference toArtifactReference( String path ) throws LayoutException
404 if ( StringUtils.isBlank( path ) )
406 throw new LayoutException( "Unable to convert blank path." );
409 ArtifactMetadata metadata = getArtifactForPath("test-repository", path);
411 ArtifactReference artifact = new ArtifactReference();
412 artifact.setGroupId( metadata.getNamespace() );
413 artifact.setArtifactId( metadata.getProject() );
414 artifact.setVersion( metadata.getVersion() );
415 MavenArtifactFacet facet = (MavenArtifactFacet) metadata.getFacet( MavenArtifactFacet.FACET_ID );
418 artifact.setClassifier( facet.getClassifier() );
419 artifact.setType( facet.getType() );
421 refs.put(artifact, path);
425 public ArtifactMetadata getArtifactForPath( String repoId, String relativePath )
427 String[] parts = relativePath.replace( '\\', '/' ).split( "/" );
429 int len = parts.length;
432 throw new IllegalArgumentException(
433 "Not a valid artifact path in a Maven 2 repository, not enough directories: " + relativePath );
436 String id = parts[--len];
437 String baseVersion = parts[--len];
438 String artifactId = parts[--len];
439 StringBuilder groupIdBuilder = new StringBuilder();
440 for ( int i = 0; i < len - 1; i++ )
442 groupIdBuilder.append( parts[i] );
443 groupIdBuilder.append( '.' );
445 groupIdBuilder.append( parts[len - 1] );
447 return getArtifactFromId( repoId, groupIdBuilder.toString(), artifactId, baseVersion, id );
450 private static final Pattern TIMESTAMP_PATTERN = Pattern.compile( "([0-9]{8}.[0-9]{6})-([0-9]+).*" );
454 public ArtifactMetadata getArtifactFromId( String repoId, String namespace, String projectId, String projectVersion,
457 if ( !id.startsWith( projectId + "-" ) )
459 throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
460 + "' doesn't start with artifact ID '" + projectId + "'" );
463 MavenArtifactFacet facet = new MavenArtifactFacet();
465 int index = projectId.length() + 1;
467 String idSubStrFromVersion = id.substring( index );
468 if ( idSubStrFromVersion.startsWith( projectVersion ) && !VersionUtil.isUniqueSnapshot( projectVersion ) )
470 // non-snapshot versions, or non-timestamped snapshot versions
471 version = projectVersion;
473 else if ( VersionUtil.isGenericSnapshot( projectVersion ) )
475 // timestamped snapshots
478 int mainVersionLength = projectVersion.length() - 8; // 8 is length of "SNAPSHOT"
479 if ( mainVersionLength == 0 )
481 throw new IllegalArgumentException(
482 "Timestamped snapshots must contain the main version, filename was '" + id + "'" );
485 Matcher m = TIMESTAMP_PATTERN.matcher( idSubStrFromVersion.substring( mainVersionLength ) );
487 String timestamp = m.group( 1 );
488 String buildNumber = m.group( 2 );
489 facet.setTimestamp( timestamp );
490 facet.setBuildNumber( Integer.parseInt( buildNumber ) );
491 version = idSubStrFromVersion.substring( 0, mainVersionLength ) + timestamp + "-" + buildNumber;
493 catch ( IllegalStateException e )
495 throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
496 + "' doesn't contain a timestamped version matching snapshot '"
497 + projectVersion + "'", e);
503 throw new IllegalArgumentException(
504 "Not a valid artifact path in a Maven 2 repository, filename '" + id + "' doesn't contain version '"
505 + projectVersion + "'" );
510 index += version.length();
511 if ( index == id.length() )
513 // no classifier or extension
519 char c = id.charAt( index );
522 // classifier up until '.'
523 int extIndex = id.indexOf( '.', index );
526 classifier = id.substring( index + 1, extIndex );
527 ext = id.substring( extIndex + 1 );
531 classifier = id.substring( index + 1 );
537 // rest is the extension
539 ext = id.substring( index + 1 );
543 throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
544 + "' expected classifier or extension but got '"
545 + id.substring( index ) + "'" );
549 ArtifactMetadata metadata = new ArtifactMetadata();
550 metadata.setId( id );
551 metadata.setNamespace( namespace );
552 metadata.setProject( projectId );
553 metadata.setRepositoryId( repoId );
554 metadata.setProjectVersion( projectVersion );
555 metadata.setVersion( version );
557 facet.setClassifier( classifier );
559 // we use our own provider here instead of directly accessing Maven's artifact handlers as it has no way
560 // to select the correct order to apply multiple extensions mappings to a preferred type
561 // TODO: this won't allow the user to decide order to apply them if there are conflicts or desired changes -
562 // perhaps the plugins could register missing entries in configuration, then we just use configuration
568 // use extension as default
574 // TODO: should we allow this instead?
577 throw new IllegalArgumentException(
578 "Not a valid artifact path in a Maven 2 repository, filename '" + id + "' does not have a type" );
581 facet.setType( type );
582 metadata.addFacet( facet );
589 public StorageAsset toFile( ArtifactReference reference )
591 return getRepoRootAsset().resolve(refs.get(reference));
594 private String formatAsDirectory( String directory )
596 return directory.replace( GROUP_SEPARATOR, PATH_SEPARATOR );
600 public String toPath( ArtifactReference reference )
606 public String toPath( ItemSelector selector )
612 public ItemSelector toItemSelector( String path ) throws LayoutException
618 public ManagedRepositoryContent getGenericContent( )