1 package org.apache.archiva.repository.metadata;
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.checksum.ChecksumAlgorithm;
23 import org.apache.archiva.checksum.ChecksummedFile;
24 import org.apache.archiva.common.utils.FileUtils;
25 import org.apache.archiva.common.utils.PathUtil;
26 import org.apache.archiva.common.utils.VersionComparator;
27 import org.apache.archiva.common.utils.VersionUtil;
28 import org.apache.archiva.configuration.ArchivaConfiguration;
29 import org.apache.archiva.configuration.ConfigurationNames;
30 import org.apache.archiva.configuration.FileTypes;
31 import org.apache.archiva.configuration.ProxyConnectorConfiguration;
32 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
33 import org.apache.archiva.model.ArchivaRepositoryMetadata;
34 import org.apache.archiva.model.ArtifactReference;
35 import org.apache.archiva.model.Plugin;
36 import org.apache.archiva.model.ProjectReference;
37 import org.apache.archiva.model.SnapshotVersion;
38 import org.apache.archiva.model.VersionedReference;
39 import org.apache.archiva.redback.components.registry.Registry;
40 import org.apache.archiva.redback.components.registry.RegistryListener;
41 import org.apache.archiva.repository.ContentNotFoundException;
42 import org.apache.archiva.repository.LayoutException;
43 import org.apache.archiva.repository.ManagedRepositoryContent;
44 import org.apache.archiva.repository.RemoteRepositoryContent;
45 import org.apache.archiva.xml.XMLException;
46 import org.apache.commons.collections.CollectionUtils;
47 import org.apache.commons.lang.StringUtils;
48 import org.apache.commons.lang.math.NumberUtils;
49 import org.apache.commons.lang.time.DateUtils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.stereotype.Service;
54 import javax.annotation.PostConstruct;
55 import javax.inject.Inject;
56 import javax.inject.Named;
57 import java.io.IOException;
58 import java.nio.file.Files;
59 import java.nio.file.Path;
60 import java.nio.file.Paths;
61 import java.text.ParseException;
62 import java.text.SimpleDateFormat;
63 import java.util.ArrayList;
64 import java.util.Arrays;
65 import java.util.Calendar;
66 import java.util.Collection;
67 import java.util.Collections;
68 import java.util.Date;
69 import java.util.HashMap;
70 import java.util.HashSet;
71 import java.util.Iterator;
72 import java.util.LinkedHashSet;
73 import java.util.List;
76 import java.util.regex.Matcher;
77 import java.util.stream.Stream;
84 @Service( "metadataTools#default" )
85 public class MetadataTools
86 implements RegistryListener
88 private Logger log = LoggerFactory.getLogger( getClass() );
90 public static final String MAVEN_METADATA = "maven-metadata.xml";
92 public static final String MAVEN_ARCHETYPE_CATALOG ="archetype-catalog.xml";
94 private static final char PATH_SEPARATOR = '/';
96 private static final char GROUP_SEPARATOR = '.';
102 @Named( value = "archivaConfiguration#default" )
103 private ArchivaConfiguration configuration;
109 @Named( value = "fileTypes" )
110 private FileTypes filetypes;
112 private List<ChecksumAlgorithm> algorithms = Arrays.asList(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 );
114 private List<String> artifactPatterns;
116 private Map<String, Set<String>> proxies;
118 private static final char NUMS[] = new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
120 private SimpleDateFormat lastUpdatedFormat;
122 public MetadataTools()
124 lastUpdatedFormat = new SimpleDateFormat( "yyyyMMddHHmmss" );
125 lastUpdatedFormat.setTimeZone( DateUtils.UTC_TIME_ZONE );
129 public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue )
131 if ( ConfigurationNames.isProxyConnector( propertyName ) )
133 initConfigVariables();
138 public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue )
144 * Gather the set of snapshot versions found in a particular versioned reference.
146 * @return the Set of snapshot artifact versions found.
147 * @throws LayoutException
148 * @throws ContentNotFoundException
150 public Set<String> gatherSnapshotVersions( ManagedRepositoryContent managedRepository,
151 VersionedReference reference )
152 throws LayoutException, IOException, ContentNotFoundException
154 Set<String> foundVersions = managedRepository.getVersions( reference );
156 // Next gather up the referenced 'latest' versions found in any proxied repositories
157 // maven-metadata-${proxyId}.xml files that may be present.
159 // Does this repository have a set of remote proxied repositories?
160 Set<String> proxiedRepoIds = this.proxies.get( managedRepository.getId() );
162 if ( CollectionUtils.isNotEmpty( proxiedRepoIds ) )
164 String baseVersion = VersionUtil.getBaseVersion( reference.getVersion() );
165 baseVersion = baseVersion.substring( 0, baseVersion.indexOf( VersionUtil.SNAPSHOT ) - 1 );
167 // Add in the proxied repo version ids too.
168 Iterator<String> it = proxiedRepoIds.iterator();
169 while ( it.hasNext() )
171 String proxyId = it.next();
173 ArchivaRepositoryMetadata proxyMetadata = readProxyMetadata( managedRepository, reference, proxyId );
174 if ( proxyMetadata == null )
176 // There is no proxy metadata, skip it.
180 // Is there some snapshot info?
181 SnapshotVersion snapshot = proxyMetadata.getSnapshotVersion();
182 if ( snapshot != null )
184 String timestamp = snapshot.getTimestamp();
185 int buildNumber = snapshot.getBuildNumber();
187 // Only interested in the timestamp + buildnumber.
188 if ( StringUtils.isNotBlank( timestamp ) && ( buildNumber > 0 ) )
190 foundVersions.add( baseVersion + "-" + timestamp + "-" + buildNumber );
196 return foundVersions;
200 * Take a path to a maven-metadata.xml, and attempt to translate it to a VersionedReference.
205 public VersionedReference toVersionedReference( String path )
206 throws RepositoryMetadataException
208 if ( !path.endsWith( "/" + MAVEN_METADATA ) )
210 throw new RepositoryMetadataException( "Cannot convert to versioned reference, not a metadata file. " );
213 VersionedReference reference = new VersionedReference();
215 String normalizedPath = StringUtils.replace( path, "\\", "/" );
216 String pathParts[] = StringUtils.split( normalizedPath, '/' );
218 int versionOffset = pathParts.length - 2;
219 int artifactIdOffset = versionOffset - 1;
220 int groupIdEnd = artifactIdOffset - 1;
222 reference.setVersion( pathParts[versionOffset] );
224 if ( !hasNumberAnywhere( reference.getVersion() ) )
226 // Scary check, but without it, all paths are version references;
227 throw new RepositoryMetadataException(
228 "Not a versioned reference, as version id on path has no number in it." );
231 reference.setArtifactId( pathParts[artifactIdOffset] );
233 StringBuilder gid = new StringBuilder();
234 for ( int i = 0; i <= groupIdEnd; i++ )
240 gid.append( pathParts[i] );
243 reference.setGroupId( gid.toString() );
248 private boolean hasNumberAnywhere( String version )
250 return StringUtils.indexOfAny( version, NUMS ) != ( -1 );
253 public ProjectReference toProjectReference( String path )
254 throws RepositoryMetadataException
256 if ( !path.endsWith( "/" + MAVEN_METADATA ) )
258 throw new RepositoryMetadataException( "Cannot convert to versioned reference, not a metadata file. " );
261 ProjectReference reference = new ProjectReference();
263 String normalizedPath = StringUtils.replace( path, "\\", "/" );
264 String pathParts[] = StringUtils.split( normalizedPath, '/' );
266 // Assume last part of the path is the version.
268 int artifactIdOffset = pathParts.length - 2;
269 int groupIdEnd = artifactIdOffset - 1;
271 reference.setArtifactId( pathParts[artifactIdOffset] );
273 StringBuilder gid = new StringBuilder();
274 for ( int i = 0; i <= groupIdEnd; i++ )
280 gid.append( pathParts[i] );
283 reference.setGroupId( gid.toString() );
288 public String toPath( ProjectReference reference )
290 StringBuilder path = new StringBuilder();
292 path.append( formatAsDirectory( reference.getGroupId() ) ).append( PATH_SEPARATOR );
293 path.append( reference.getArtifactId() ).append( PATH_SEPARATOR );
294 path.append( MAVEN_METADATA );
296 return path.toString();
299 public String toPath( VersionedReference reference )
301 StringBuilder path = new StringBuilder();
303 path.append( formatAsDirectory( reference.getGroupId() ) ).append( PATH_SEPARATOR );
304 path.append( reference.getArtifactId() ).append( PATH_SEPARATOR );
305 if ( reference.getVersion() != null )
307 // add the version only if it is present
308 path.append( VersionUtil.getBaseVersion( reference.getVersion() ) ).append( PATH_SEPARATOR );
310 path.append( MAVEN_METADATA );
312 return path.toString();
315 private String formatAsDirectory( String directory )
317 return directory.replace( GROUP_SEPARATOR, PATH_SEPARATOR );
321 * Adjusts a path for a metadata.xml file to its repository specific path.
323 * @param repository the repository to base new path off of.
324 * @param path the path to the metadata.xml file to adjust the name of.
325 * @return the newly adjusted path reference to the repository specific metadata path.
327 public String getRepositorySpecificName( RemoteRepositoryContent repository, String path )
329 return getRepositorySpecificName( repository.getId(), path );
333 * Adjusts a path for a metadata.xml file to its repository specific path.
335 * @param proxyId the repository id to base new path off of.
336 * @param path the path to the metadata.xml file to adjust the name of.
337 * @return the newly adjusted path reference to the repository specific metadata path.
339 public String getRepositorySpecificName( String proxyId, String path )
341 StringBuilder ret = new StringBuilder();
343 int idx = path.lastIndexOf( '/' );
346 ret.append( path.substring( 0, idx + 1 ) );
349 // TODO: need to filter out 'bad' characters from the proxy id.
350 ret.append( "maven-metadata-" ).append( proxyId ).append( ".xml" );
352 return ret.toString();
356 public void initialize()
358 this.artifactPatterns = new ArrayList<>();
359 this.proxies = new HashMap<>();
360 initConfigVariables();
362 configuration.addChangeListener( this );
365 public ArchivaRepositoryMetadata readProxyMetadata( ManagedRepositoryContent managedRepository,
366 ProjectReference reference, String proxyId )
368 String metadataPath = getRepositorySpecificName( proxyId, toPath( reference ) );
369 Path metadataFile = Paths.get( managedRepository.getRepoRoot(), metadataPath );
371 if ( !Files.exists(metadataFile) || !Files.isRegularFile( metadataFile ))
373 // Nothing to do. return null.
379 return MavenMetadataReader.read( metadataFile );
381 catch ( XMLException e )
383 // TODO: [monitor] consider a monitor for this event.
384 // TODO: consider a read-redo on monitor return code?
385 log.warn( "Unable to read metadata: {}", metadataFile.toAbsolutePath(), e );
390 public ArchivaRepositoryMetadata readProxyMetadata( ManagedRepositoryContent managedRepository,
391 String logicalResource, String proxyId )
393 String metadataPath = getRepositorySpecificName( proxyId, logicalResource );
394 Path metadataFile = Paths.get( managedRepository.getRepoRoot(), metadataPath );
396 if ( !Files.exists(metadataFile) || !Files.isRegularFile( metadataFile))
398 // Nothing to do. return null.
404 return MavenMetadataReader.read( metadataFile );
406 catch ( XMLException e )
408 // TODO: [monitor] consider a monitor for this event.
409 // TODO: consider a read-redo on monitor return code?
410 log.warn( "Unable to read metadata: {}", metadataFile.toAbsolutePath(), e );
415 public ArchivaRepositoryMetadata readProxyMetadata( ManagedRepositoryContent managedRepository,
416 VersionedReference reference, String proxyId )
418 String metadataPath = getRepositorySpecificName( proxyId, toPath( reference ) );
419 Path metadataFile = Paths.get( managedRepository.getRepoRoot(), metadataPath );
421 if ( !Files.exists(metadataFile) || !Files.isRegularFile(metadataFile))
423 // Nothing to do. return null.
429 return MavenMetadataReader.read( metadataFile );
431 catch ( XMLException e )
433 // TODO: [monitor] consider a monitor for this event.
434 // TODO: consider a read-redo on monitor return code?
435 log.warn( "Unable to read metadata: {}", metadataFile.toAbsolutePath(), e );
440 public void updateMetadata( ManagedRepositoryContent managedRepository, String logicalResource )
441 throws RepositoryMetadataException
443 final Path metadataFile = Paths.get( managedRepository.getRepoRoot(), logicalResource );
444 ArchivaRepositoryMetadata metadata = null;
446 //Gather and merge all metadata available
447 List<ArchivaRepositoryMetadata> metadatas =
448 getMetadatasForManagedRepository( managedRepository, logicalResource );
449 for ( ArchivaRepositoryMetadata proxiedMetadata : metadatas )
451 if ( metadata == null )
453 metadata = proxiedMetadata;
456 metadata = RepositoryMetadataMerge.merge( metadata, proxiedMetadata );
459 if ( metadata == null )
461 log.debug( "No metadata to update for {}", logicalResource );
465 Set<String> availableVersions = new HashSet<String>();
466 List<String> metadataAvailableVersions = metadata.getAvailableVersions();
467 if ( metadataAvailableVersions != null )
469 availableVersions.addAll( metadataAvailableVersions );
471 availableVersions = findPossibleVersions( availableVersions, metadataFile.getParent() );
473 if ( availableVersions.size() > 0 )
475 updateMetadataVersions( availableVersions, metadata );
478 RepositoryMetadataWriter.write( metadata, metadataFile );
480 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
481 checksum.fixChecksums( algorithms );
485 * Skims the parent directory of a metadata in vain hope of finding
486 * subdirectories that contain poms.
488 * @param metadataParentDirectory
489 * @return origional set plus newly found versions
491 private Set<String> findPossibleVersions( Set<String> versions, Path metadataParentDirectory )
494 Set<String> result = new HashSet<String>( versions );
496 try (Stream<Path> stream = Files.list( metadataParentDirectory )) {
497 stream.filter( Files::isDirectory ).filter(
500 try(Stream<Path> substream = Files.list(p))
502 return substream.anyMatch( f -> Files.isRegularFile( f ) && f.toString().endsWith( ".pom" ));
504 catch ( IOException e )
510 p -> result.add(p.getFileName().toString())
512 } catch (IOException e) {
518 private List<ArchivaRepositoryMetadata> getMetadatasForManagedRepository(
519 ManagedRepositoryContent managedRepository, String logicalResource )
521 List<ArchivaRepositoryMetadata> metadatas = new ArrayList<>();
522 Path file = Paths.get( managedRepository.getRepoRoot(), logicalResource );
523 if ( Files.exists(file) )
527 ArchivaRepositoryMetadata existingMetadata = MavenMetadataReader.read( file );
528 if ( existingMetadata != null )
530 metadatas.add( existingMetadata );
533 catch ( XMLException e )
535 log.debug( "Could not read metadata at {}. Metadata will be removed.", file.toAbsolutePath() );
536 FileUtils.deleteQuietly( file );
540 Set<String> proxyIds = proxies.get( managedRepository.getId() );
541 if ( proxyIds != null )
543 for ( String proxyId : proxyIds )
545 ArchivaRepositoryMetadata proxyMetadata =
546 readProxyMetadata( managedRepository, logicalResource, proxyId );
547 if ( proxyMetadata != null )
549 metadatas.add( proxyMetadata );
559 * Update the metadata to represent the all versions/plugins of
560 * the provided groupId:artifactId project or group reference,
561 * based off of information present in the repository,
562 * the maven-metadata.xml files, and the proxy/repository specific
563 * metadata file contents.
565 * We must treat this as a group or a project metadata file as there is no way to know in advance
567 * @param managedRepository the managed repository where the metadata is kept.
568 * @param reference the reference to update.
569 * @throws LayoutException
570 * @throws RepositoryMetadataException
571 * @throws IOException
572 * @throws ContentNotFoundException
575 public void updateMetadata( ManagedRepositoryContent managedRepository, ProjectReference reference )
576 throws LayoutException, RepositoryMetadataException, IOException, ContentNotFoundException
578 Path metadataFile = Paths.get( managedRepository.getRepoRoot(), toPath( reference ) );
580 long lastUpdated = getExistingLastUpdated( metadataFile );
582 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
583 metadata.setGroupId( reference.getGroupId() );
584 metadata.setArtifactId( reference.getArtifactId() );
586 // Gather up all versions found in the managed repository.
587 Set<String> allVersions = managedRepository.getVersions( reference );
589 // Gather up all plugins found in the managed repository.
590 // TODO: do we know this information instead?
591 // Set<Plugin> allPlugins = managedRepository.getPlugins( reference );
592 Set<Plugin> allPlugins;
593 if ( Files.exists(metadataFile))
597 allPlugins = new LinkedHashSet<Plugin>( MavenMetadataReader.read( metadataFile ).getPlugins() );
599 catch ( XMLException e )
601 throw new RepositoryMetadataException( e.getMessage(), e );
606 allPlugins = new LinkedHashSet<Plugin>();
609 // Does this repository have a set of remote proxied repositories?
610 Set<String> proxiedRepoIds = this.proxies.get( managedRepository.getId() );
612 if ( CollectionUtils.isNotEmpty( proxiedRepoIds ) )
614 // Add in the proxied repo version ids too.
615 Iterator<String> it = proxiedRepoIds.iterator();
616 while ( it.hasNext() )
618 String proxyId = it.next();
620 ArchivaRepositoryMetadata proxyMetadata = readProxyMetadata( managedRepository, reference, proxyId );
621 if ( proxyMetadata != null )
623 allVersions.addAll( proxyMetadata.getAvailableVersions() );
624 allPlugins.addAll( proxyMetadata.getPlugins() );
625 long proxyLastUpdated = getLastUpdated( proxyMetadata );
627 lastUpdated = Math.max( lastUpdated, proxyLastUpdated );
632 if ( !allVersions.isEmpty() )
634 updateMetadataVersions( allVersions, metadata );
638 // Add the plugins to the metadata model.
639 metadata.setPlugins( new ArrayList<>( allPlugins ) );
641 // artifact ID was actually the last part of the group
642 metadata.setGroupId( metadata.getGroupId() + "." + metadata.getArtifactId() );
643 metadata.setArtifactId( null );
646 if ( lastUpdated > 0 )
648 metadata.setLastUpdatedTimestamp( toLastUpdatedDate( lastUpdated ) );
651 // Save the metadata model to disk.
652 RepositoryMetadataWriter.write( metadata, metadataFile );
653 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
654 checksum.fixChecksums( algorithms );
657 private void updateMetadataVersions( Collection<String> allVersions, ArchivaRepositoryMetadata metadata )
660 List<String> sortedVersions = new ArrayList<>( allVersions );
661 Collections.sort( sortedVersions, VersionComparator.getInstance() );
663 // Split the versions into released and snapshots.
664 List<String> releasedVersions = new ArrayList<>();
665 List<String> snapshotVersions = new ArrayList<>();
667 for ( String version : sortedVersions )
669 if ( VersionUtil.isSnapshot( version ) )
671 snapshotVersions.add( version );
675 releasedVersions.add( version );
679 Collections.sort( releasedVersions, VersionComparator.getInstance() );
680 Collections.sort( snapshotVersions, VersionComparator.getInstance() );
682 String latestVersion = sortedVersions.get( sortedVersions.size() - 1 );
683 String releaseVersion = null;
685 if ( CollectionUtils.isNotEmpty( releasedVersions ) )
687 releaseVersion = releasedVersions.get( releasedVersions.size() - 1 );
690 // Add the versions to the metadata model.
691 metadata.setAvailableVersions( sortedVersions );
693 metadata.setLatestVersion( latestVersion );
694 metadata.setReleasedVersion( releaseVersion );
697 private Date toLastUpdatedDate( long lastUpdated )
699 Calendar cal = Calendar.getInstance( DateUtils.UTC_TIME_ZONE );
700 cal.setTimeInMillis( lastUpdated );
702 return cal.getTime();
705 private long toLastUpdatedLong( String timestampString )
709 Date date = lastUpdatedFormat.parse( timestampString );
710 Calendar cal = Calendar.getInstance( DateUtils.UTC_TIME_ZONE );
713 return cal.getTimeInMillis();
715 catch ( ParseException e )
721 private long getLastUpdated( ArchivaRepositoryMetadata metadata )
723 if ( metadata == null )
731 String lastUpdated = metadata.getLastUpdated();
732 if ( StringUtils.isBlank( lastUpdated ) )
738 Date lastUpdatedDate = lastUpdatedFormat.parse( lastUpdated );
739 return lastUpdatedDate.getTime();
741 catch ( ParseException e )
743 // Bad format on the last updated string.
748 private long getExistingLastUpdated( Path metadataFile )
750 if ( !Files.exists(metadataFile) )
758 ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile );
760 return getLastUpdated( metadata );
762 catch ( XMLException e )
770 * Update the metadata based on the following rules.
772 * 1) If this is a SNAPSHOT reference, then utilize the proxy/repository specific
773 * metadata files to represent the current / latest SNAPSHOT available.
774 * 2) If this is a RELEASE reference, and the metadata file does not exist, then
775 * create the metadata file with contents required of the VersionedReference
777 * @param managedRepository the managed repository where the metadata is kept.
778 * @param reference the versioned reference to update
779 * @throws LayoutException
780 * @throws RepositoryMetadataException
781 * @throws IOException
782 * @throws ContentNotFoundException
785 public void updateMetadata( ManagedRepositoryContent managedRepository, VersionedReference reference )
786 throws LayoutException, RepositoryMetadataException, IOException, ContentNotFoundException
788 Path metadataFile = Paths.get( managedRepository.getRepoRoot(), toPath( reference ) );
790 long lastUpdated = getExistingLastUpdated( metadataFile );
792 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
793 metadata.setGroupId( reference.getGroupId() );
794 metadata.setArtifactId( reference.getArtifactId() );
796 if ( VersionUtil.isSnapshot( reference.getVersion() ) )
798 // Do SNAPSHOT handling.
799 metadata.setVersion( VersionUtil.getBaseVersion( reference.getVersion() ) );
801 // Gather up all of the versions found in the reference dir, and any
802 // proxied maven-metadata.xml files.
803 Set<String> snapshotVersions = gatherSnapshotVersions( managedRepository, reference );
805 if ( snapshotVersions.isEmpty() )
807 throw new ContentNotFoundException(
808 "No snapshot versions found on reference [" + VersionedReference.toKey( reference ) + "]." );
811 // sort the list to determine to aide in determining the Latest version.
812 List<String> sortedVersions = new ArrayList<>();
813 sortedVersions.addAll( snapshotVersions );
814 Collections.sort( sortedVersions, new VersionComparator() );
816 String latestVersion = sortedVersions.get( sortedVersions.size() - 1 );
818 if ( VersionUtil.isUniqueSnapshot( latestVersion ) )
820 // The latestVersion will contain the full version string "1.0-alpha-5-20070821.213044-8"
821 // This needs to be broken down into ${base}-${timestamp}-${build_number}
823 Matcher m = VersionUtil.UNIQUE_SNAPSHOT_PATTERN.matcher( latestVersion );
826 metadata.setSnapshotVersion( new SnapshotVersion() );
827 int buildNumber = NumberUtils.toInt( m.group( 3 ), -1 );
828 metadata.getSnapshotVersion().setBuildNumber( buildNumber );
830 Matcher mtimestamp = VersionUtil.TIMESTAMP_PATTERN.matcher( m.group( 2 ) );
831 if ( mtimestamp.matches() )
833 String tsDate = mtimestamp.group( 1 );
834 String tsTime = mtimestamp.group( 2 );
836 long snapshotLastUpdated = toLastUpdatedLong( tsDate + tsTime );
838 lastUpdated = Math.max( lastUpdated, snapshotLastUpdated );
840 metadata.getSnapshotVersion().setTimestamp( m.group( 2 ) );
844 else if ( VersionUtil.isGenericSnapshot( latestVersion ) )
846 // The latestVersion ends with the generic version string.
847 // Example: 1.0-alpha-5-SNAPSHOT
849 metadata.setSnapshotVersion( new SnapshotVersion() );
851 /* Disabled due to decision in [MRM-535].
852 * Do not set metadata.lastUpdated to file.lastModified.
854 * Should this be the last updated timestamp of the file, or in the case of an
855 * archive, the most recent timestamp in the archive?
857 ArtifactReference artifact = getFirstArtifact( managedRepository, reference );
859 if ( artifact == null )
861 throw new IOException( "Not snapshot artifact found to reference in " + reference );
864 File artifactFile = managedRepository.toFile( artifact );
866 if ( artifactFile.exists() )
868 Date lastModified = new Date( artifactFile.lastModified() );
869 metadata.setLastUpdatedTimestamp( lastModified );
875 throw new RepositoryMetadataException(
876 "Unable to process snapshot version <" + latestVersion + "> reference <" + reference + ">" );
881 // Do RELEASE handling.
882 metadata.setVersion( reference.getVersion() );
886 if ( lastUpdated > 0 )
888 metadata.setLastUpdatedTimestamp( toLastUpdatedDate( lastUpdated ) );
891 // Save the metadata model to disk.
892 RepositoryMetadataWriter.write( metadata, metadataFile );
893 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
894 checksum.fixChecksums( algorithms );
897 private void initConfigVariables()
899 synchronized ( this.artifactPatterns )
901 this.artifactPatterns.clear();
903 this.artifactPatterns.addAll( filetypes.getFileTypePatterns( FileTypes.ARTIFACTS ) );
906 synchronized ( proxies )
908 this.proxies.clear();
910 List<ProxyConnectorConfiguration> proxyConfigs = configuration.getConfiguration().getProxyConnectors();
911 for ( ProxyConnectorConfiguration proxyConfig : proxyConfigs )
913 String key = proxyConfig.getSourceRepoId();
915 Set<String> remoteRepoIds = this.proxies.get( key );
917 if ( remoteRepoIds == null )
919 remoteRepoIds = new HashSet<String>();
922 remoteRepoIds.add( proxyConfig.getTargetRepoId() );
924 this.proxies.put( key, remoteRepoIds );
930 * Get the first Artifact found in the provided VersionedReference location.
932 * @param managedRepository the repository to search within.
933 * @param reference the reference to the versioned reference to search within
934 * @return the ArtifactReference to the first artifact located within the versioned reference. or null if
935 * no artifact was found within the versioned reference.
936 * @throws IOException if the versioned reference is invalid (example: doesn't exist, or isn't a directory)
937 * @throws LayoutException
939 public ArtifactReference getFirstArtifact( ManagedRepositoryContent managedRepository,
940 VersionedReference reference )
941 throws LayoutException, IOException
943 String path = toPath( reference );
945 int idx = path.lastIndexOf( '/' );
948 path = path.substring( 0, idx );
951 Path repoDir = Paths.get( managedRepository.getRepoRoot(), path );
953 if ( !Files.exists(repoDir))
955 throw new IOException( "Unable to gather the list of snapshot versions on a non-existant directory: "
956 + repoDir.toAbsolutePath() );
959 if ( !Files.isDirectory( repoDir ))
961 throw new IOException(
962 "Unable to gather the list of snapshot versions on a non-directory: " + repoDir.toAbsolutePath() );
965 try(Stream<Path> stream = Files.list(repoDir)) {
966 String result = stream.filter( Files::isRegularFile ).map( path1 ->
967 PathUtil.getRelative( managedRepository.getRepoRoot(), path1 )
968 ).filter( filetypes::matchesArtifactPattern ).findFirst().orElse( null );
970 return managedRepository.toArtifactReference( result );
973 // No artifact was found.
977 public ArchivaConfiguration getConfiguration()
979 return configuration;
982 public void setConfiguration( ArchivaConfiguration configuration )
984 this.configuration = configuration;
987 public FileTypes getFiletypes()
992 public void setFiletypes( FileTypes filetypes )
994 this.filetypes = filetypes;