1 package org.apache.archiva.metadata.repository.storage.maven2;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.admin.model.beans.NetworkProxy;
25 import org.apache.archiva.admin.model.beans.ProxyConnector;
26 import org.apache.archiva.admin.model.beans.RemoteRepository;
27 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
28 import org.apache.archiva.admin.model.networkproxy.NetworkProxyAdmin;
29 import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin;
30 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
31 import org.apache.archiva.checksum.ChecksumAlgorithm;
32 import org.apache.archiva.checksum.ChecksummedFile;
33 import org.apache.archiva.common.utils.VersionUtil;
34 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
35 import org.apache.archiva.metadata.model.ArtifactMetadata;
36 import org.apache.archiva.metadata.model.ProjectMetadata;
37 import org.apache.archiva.metadata.model.ProjectVersionMetadata;
38 import org.apache.archiva.metadata.repository.filter.Filter;
39 import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
40 import org.apache.archiva.metadata.repository.storage.RelocationException;
41 import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
42 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
43 import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException;
44 import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException;
45 import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException;
46 import org.apache.archiva.model.ArchivaRepositoryMetadata;
47 import org.apache.archiva.model.ArtifactReference;
48 import org.apache.archiva.model.SnapshotVersion;
49 import org.apache.archiva.policies.ProxyDownloadException;
50 import org.apache.archiva.proxy.common.WagonFactory;
51 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
52 import org.apache.archiva.reports.RepositoryProblemFacet;
53 import org.apache.archiva.repository.ManagedRepositoryContent;
54 import org.apache.archiva.repository.content.PathParser;
55 import org.apache.archiva.repository.layout.LayoutException;
56 import org.apache.archiva.xml.XMLException;
57 import org.apache.commons.lang.ArrayUtils;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.maven.model.CiManagement;
60 import org.apache.maven.model.Dependency;
61 import org.apache.maven.model.DistributionManagement;
62 import org.apache.maven.model.IssueManagement;
63 import org.apache.maven.model.License;
64 import org.apache.maven.model.MailingList;
65 import org.apache.maven.model.Model;
66 import org.apache.maven.model.Organization;
67 import org.apache.maven.model.Relocation;
68 import org.apache.maven.model.Scm;
69 import org.apache.maven.model.building.DefaultModelBuilderFactory;
70 import org.apache.maven.model.building.DefaultModelBuildingRequest;
71 import org.apache.maven.model.building.ModelBuilder;
72 import org.apache.maven.model.building.ModelBuildingException;
73 import org.apache.maven.model.building.ModelBuildingRequest;
74 import org.apache.maven.model.building.ModelProblem;
75 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
76 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import org.springframework.context.ApplicationContext;
80 import org.springframework.stereotype.Service;
82 import javax.annotation.PostConstruct;
83 import javax.inject.Inject;
84 import javax.inject.Named;
86 import java.io.FileNotFoundException;
87 import java.io.FilenameFilter;
88 import java.io.IOException;
89 import java.io.Reader;
90 import java.nio.charset.Charset;
91 import java.nio.file.Files;
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.Collection;
95 import java.util.Collections;
96 import java.util.Date;
97 import java.util.HashMap;
98 import java.util.List;
102 * Maven 2 repository format storage implementation. This class currently takes parameters to indicate the repository to
103 * deal with rather than being instantiated per-repository.
104 * FIXME: instantiate one per repository and allocate permanently from a factory (which can be obtained within the session).
106 * The session is passed in as an argument to obtain any necessary resources, rather than the class being instantiated
107 * within the session in the context of a single managed repository's resolution needs.
110 @Service( "repositoryStorage#maven2" )
111 public class Maven2RepositoryStorage
112 implements RepositoryStorage
115 private static final Logger LOGGER = LoggerFactory.getLogger( Maven2RepositoryStorage.class );
117 private ModelBuilder builder;
120 private RemoteRepositoryAdmin remoteRepositoryAdmin;
123 private ManagedRepositoryAdmin managedRepositoryAdmin;
126 private ProxyConnectorAdmin proxyConnectorAdmin;
129 private NetworkProxyAdmin networkProxyAdmin;
132 @Named( "repositoryPathTranslator#maven2" )
133 private RepositoryPathTranslator pathTranslator;
136 private WagonFactory wagonFactory;
139 private ApplicationContext applicationContext;
142 @Named( "pathParser#default" )
143 private PathParser pathParser;
145 private static final String METADATA_FILENAME_START = "maven-metadata";
147 private static final String METADATA_FILENAME = METADATA_FILENAME_START + ".xml";
149 private static final MavenXpp3Reader MAVEN_XPP_3_READER = new MavenXpp3Reader();
153 public void initialize()
155 builder = new DefaultModelBuilderFactory().newInstance();
160 public ProjectMetadata readProjectMetadata( String repoId, String namespace, String projectId )
162 // TODO: could natively implement the "shared model" concept from the browse action to avoid needing it there?
167 public ProjectVersionMetadata readProjectVersionMetadata( ReadMetadataRequest readMetadataRequest )
168 throws RepositoryStorageMetadataNotFoundException, RepositoryStorageMetadataInvalidException,
169 RepositoryStorageRuntimeException
173 ManagedRepository managedRepository =
174 managedRepositoryAdmin.getManagedRepository( readMetadataRequest.getRepositoryId() );
175 String artifactVersion = readMetadataRequest.getProjectVersion();
176 // olamy: in case of browsing via the ui we can mix repos (parent of a SNAPSHOT can come from release repo)
177 if ( !readMetadataRequest.isBrowsingRequest() )
179 if ( VersionUtil.isSnapshot( artifactVersion ) )
181 // skygo trying to improve speed by honoring managed configuration MRM-1658
182 if ( managedRepository.isReleases() && !managedRepository.isSnapshots() )
184 throw new RepositoryStorageRuntimeException( "lookforsnaponreleaseonly",
185 "managed repo is configured for release only" );
190 if ( !managedRepository.isReleases() && managedRepository.isSnapshots() )
192 throw new RepositoryStorageRuntimeException( "lookforsreleaseonsneponly",
193 "managed repo is configured for snapshot only" );
197 File basedir = new File( managedRepository.getLocation() );
198 if ( VersionUtil.isSnapshot( artifactVersion ) )
200 File metadataFile = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(),
201 readMetadataRequest.getProjectId(), artifactVersion,
205 ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile );
207 // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename
208 SnapshotVersion snapshotVersion = metadata.getSnapshotVersion();
209 if ( snapshotVersion != null )
212 artifactVersion.substring( 0, artifactVersion.length() - 8 ); // remove SNAPSHOT from end
214 artifactVersion + snapshotVersion.getTimestamp() + "-" + snapshotVersion.getBuildNumber();
217 catch ( XMLException e )
219 // unable to parse metadata - LOGGER it, and continue with the version as the original SNAPSHOT version
220 LOGGER.warn( "Invalid metadata: {} - {}", metadataFile, e.getMessage() );
224 // TODO: won't work well with some other layouts, might need to convert artifact parts to ID by path translator
225 String id = readMetadataRequest.getProjectId() + "-" + artifactVersion + ".pom";
227 pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(),
228 readMetadataRequest.getProjectVersion(), id );
230 if ( !file.exists() )
232 // metadata could not be resolved
233 throw new RepositoryStorageMetadataNotFoundException(
234 "The artifact's POM file '" + file.getAbsolutePath() + "' was missing" );
237 // TODO: this is a workaround until we can properly resolve using proxies as well - this doesn't cache
239 List<RemoteRepository> remoteRepositories = new ArrayList<>();
240 Map<String, NetworkProxy> networkProxies = new HashMap<>();
242 Map<String, List<ProxyConnector>> proxyConnectorsMap = proxyConnectorAdmin.getProxyConnectorAsMap();
243 List<ProxyConnector> proxyConnectors = proxyConnectorsMap.get( readMetadataRequest.getRepositoryId() );
244 if ( proxyConnectors != null )
246 for ( ProxyConnector proxyConnector : proxyConnectors )
248 RemoteRepository remoteRepoConfig =
249 remoteRepositoryAdmin.getRemoteRepository( proxyConnector.getTargetRepoId() );
251 if ( remoteRepoConfig != null )
253 remoteRepositories.add( remoteRepoConfig );
255 NetworkProxy networkProxyConfig =
256 networkProxyAdmin.getNetworkProxy( proxyConnector.getProxyId() );
258 if ( networkProxyConfig != null )
260 // key/value: remote repo ID/proxy info
261 networkProxies.put( proxyConnector.getTargetRepoId(), networkProxyConfig );
267 // That's a browsing request so we can a mix of SNAPSHOT and release artifacts (especially with snapshots which
268 // can have released parent pom
269 if ( readMetadataRequest.isBrowsingRequest() )
271 remoteRepositories.addAll( remoteRepositoryAdmin.getRemoteRepositories() );
274 ModelBuildingRequest req =
275 new DefaultModelBuildingRequest().setProcessPlugins( false ).setPomFile( file ).setTwoPhaseBuilding(
276 false ).setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
278 //MRM-1607. olamy this will resolve jdk profiles on the current running archiva jvm
279 req.setSystemProperties( System.getProperties() );
282 req.setModelResolver(
283 new RepositoryModelResolver( managedRepository, pathTranslator, wagonFactory, remoteRepositories,
284 networkProxies, managedRepository ) );
289 model = builder.build( req ).getEffectiveModel();
291 catch ( ModelBuildingException e )
293 String msg = "The artifact's POM file '" + file + "' was invalid: " + e.getMessage();
295 List<ModelProblem> modelProblems = e.getProblems();
296 for ( ModelProblem problem : modelProblems )
298 // MRM-1411, related to MRM-1335
299 // this means that the problem was that the parent wasn't resolved!
300 // olamy really hackhish but fail with java profile so use error message
301 // || ( StringUtils.startsWith( problem.getMessage(), "Failed to determine Java version for profile" ) )
302 // but setTwoPhaseBuilding(true) fix that
303 if ( ( problem.getException() instanceof FileNotFoundException && e.getModelId() != null &&
304 !e.getModelId().equals( problem.getModelId() ) ) )
306 LOGGER.warn( "The artifact's parent POM file '{}' cannot be resolved. "
307 + "Using defaults for project version metadata..", file );
309 ProjectVersionMetadata metadata = new ProjectVersionMetadata();
310 metadata.setId( readMetadataRequest.getProjectVersion() );
312 MavenProjectFacet facet = new MavenProjectFacet();
313 facet.setGroupId( readMetadataRequest.getNamespace() );
314 facet.setArtifactId( readMetadataRequest.getProjectId() );
315 facet.setPackaging( "jar" );
316 metadata.addFacet( facet );
319 "Error in resolving artifact's parent POM file. " + ( problem.getException() == null
320 ? problem.getMessage()
321 : problem.getException().getMessage() );
322 RepositoryProblemFacet repoProblemFacet = new RepositoryProblemFacet();
323 repoProblemFacet.setRepositoryId( readMetadataRequest.getRepositoryId() );
324 repoProblemFacet.setId( readMetadataRequest.getRepositoryId() );
325 repoProblemFacet.setMessage( errMsg );
326 repoProblemFacet.setProblem( errMsg );
327 repoProblemFacet.setProject( readMetadataRequest.getProjectId() );
328 repoProblemFacet.setVersion( readMetadataRequest.getProjectVersion() );
329 repoProblemFacet.setNamespace( readMetadataRequest.getNamespace() );
331 metadata.addFacet( repoProblemFacet );
337 throw new RepositoryStorageMetadataInvalidException( "invalid-pom", msg, e );
340 // Check if the POM is in the correct location
341 boolean correctGroupId = readMetadataRequest.getNamespace().equals( model.getGroupId() );
342 boolean correctArtifactId = readMetadataRequest.getProjectId().equals( model.getArtifactId() );
343 boolean correctVersion = readMetadataRequest.getProjectVersion().equals( model.getVersion() );
344 if ( !correctGroupId || !correctArtifactId || !correctVersion )
346 StringBuilder message = new StringBuilder( "Incorrect POM coordinates in '" + file + "':" );
347 if ( !correctGroupId )
349 message.append( "\nIncorrect group ID: " ).append( model.getGroupId() );
351 if ( !correctArtifactId )
353 message.append( "\nIncorrect artifact ID: " ).append( model.getArtifactId() );
355 if ( !correctVersion )
357 message.append( "\nIncorrect version: " ).append( model.getVersion() );
360 throw new RepositoryStorageMetadataInvalidException( "mislocated-pom", message.toString() );
363 ProjectVersionMetadata metadata = new ProjectVersionMetadata();
364 metadata.setCiManagement( convertCiManagement( model.getCiManagement() ) );
365 metadata.setDescription( model.getDescription() );
366 metadata.setId( readMetadataRequest.getProjectVersion() );
367 metadata.setIssueManagement( convertIssueManagement( model.getIssueManagement() ) );
368 metadata.setLicenses( convertLicenses( model.getLicenses() ) );
369 metadata.setMailingLists( convertMailingLists( model.getMailingLists() ) );
370 metadata.setDependencies( convertDependencies( model.getDependencies() ) );
371 metadata.setName( model.getName() );
372 metadata.setOrganization( convertOrganization( model.getOrganization() ) );
373 metadata.setScm( convertScm( model.getScm() ) );
374 metadata.setUrl( model.getUrl() );
376 MavenProjectFacet facet = new MavenProjectFacet();
377 facet.setGroupId( model.getGroupId() != null ? model.getGroupId() : model.getParent().getGroupId() );
378 facet.setArtifactId( model.getArtifactId() );
379 facet.setPackaging( model.getPackaging() );
380 if ( model.getParent() != null )
382 MavenProjectParent parent = new MavenProjectParent();
383 parent.setGroupId( model.getParent().getGroupId() );
384 parent.setArtifactId( model.getParent().getArtifactId() );
385 parent.setVersion( model.getParent().getVersion() );
386 facet.setParent( parent );
388 metadata.addFacet( facet );
392 catch ( RepositoryAdminException e )
394 throw new RepositoryStorageRuntimeException( "repo-admin", e.getMessage(), e );
398 public void setWagonFactory( WagonFactory wagonFactory )
400 this.wagonFactory = wagonFactory;
403 private List<org.apache.archiva.metadata.model.Dependency> convertDependencies( List<Dependency> dependencies )
405 List<org.apache.archiva.metadata.model.Dependency> l =
407 for ( Dependency dependency : dependencies )
409 org.apache.archiva.metadata.model.Dependency newDependency =
410 new org.apache.archiva.metadata.model.Dependency();
411 newDependency.setArtifactId( dependency.getArtifactId() );
412 newDependency.setClassifier( dependency.getClassifier() );
413 newDependency.setGroupId( dependency.getGroupId() );
414 newDependency.setOptional( dependency.isOptional() );
415 newDependency.setScope( dependency.getScope() );
416 newDependency.setSystemPath( dependency.getSystemPath() );
417 newDependency.setType( dependency.getType() );
418 newDependency.setVersion( dependency.getVersion() );
419 l.add( newDependency );
424 private org.apache.archiva.metadata.model.Scm convertScm( Scm scm )
426 org.apache.archiva.metadata.model.Scm newScm = null;
429 newScm = new org.apache.archiva.metadata.model.Scm();
430 newScm.setConnection( scm.getConnection() );
431 newScm.setDeveloperConnection( scm.getDeveloperConnection() );
432 newScm.setUrl( scm.getUrl() );
437 private org.apache.archiva.metadata.model.Organization convertOrganization( Organization organization )
439 org.apache.archiva.metadata.model.Organization org = null;
440 if ( organization != null )
442 org = new org.apache.archiva.metadata.model.Organization();
443 org.setName( organization.getName() );
444 org.setUrl( organization.getUrl() );
449 private List<org.apache.archiva.metadata.model.License> convertLicenses( List<License> licenses )
451 List<org.apache.archiva.metadata.model.License> l = new ArrayList<>();
452 for ( License license : licenses )
454 org.apache.archiva.metadata.model.License newLicense = new org.apache.archiva.metadata.model.License();
455 newLicense.setName( license.getName() );
456 newLicense.setUrl( license.getUrl() );
462 private List<org.apache.archiva.metadata.model.MailingList> convertMailingLists( List<MailingList> mailingLists )
464 List<org.apache.archiva.metadata.model.MailingList> l =
466 for ( MailingList mailingList : mailingLists )
468 org.apache.archiva.metadata.model.MailingList newMailingList =
469 new org.apache.archiva.metadata.model.MailingList();
470 newMailingList.setName( mailingList.getName() );
471 newMailingList.setMainArchiveUrl( mailingList.getArchive() );
472 newMailingList.setPostAddress( mailingList.getPost() );
473 newMailingList.setSubscribeAddress( mailingList.getSubscribe() );
474 newMailingList.setUnsubscribeAddress( mailingList.getUnsubscribe() );
475 newMailingList.setOtherArchives( mailingList.getOtherArchives() );
476 l.add( newMailingList );
481 private org.apache.archiva.metadata.model.IssueManagement convertIssueManagement( IssueManagement issueManagement )
483 org.apache.archiva.metadata.model.IssueManagement im = null;
484 if ( issueManagement != null )
486 im = new org.apache.archiva.metadata.model.IssueManagement();
487 im.setSystem( issueManagement.getSystem() );
488 im.setUrl( issueManagement.getUrl() );
493 private org.apache.archiva.metadata.model.CiManagement convertCiManagement( CiManagement ciManagement )
495 org.apache.archiva.metadata.model.CiManagement ci = null;
496 if ( ciManagement != null )
498 ci = new org.apache.archiva.metadata.model.CiManagement();
499 ci.setSystem( ciManagement.getSystem() );
500 ci.setUrl( ciManagement.getUrl() );
506 public Collection<String> listRootNamespaces( String repoId, Filter<String> filter )
507 throws RepositoryStorageRuntimeException
509 File dir = getRepositoryBasedir( repoId );
511 return getSortedFiles( dir, filter );
514 private static Collection<String> getSortedFiles( File dir, Filter<String> filter )
516 List<String> fileNames;
517 String[] files = dir.list( new DirectoryFilter( filter ) );
520 fileNames = new ArrayList<>( Arrays.asList( files ) );
521 Collections.sort( fileNames );
525 fileNames = Collections.emptyList();
530 private File getRepositoryBasedir( String repoId )
531 throws RepositoryStorageRuntimeException
535 ManagedRepository repositoryConfiguration = managedRepositoryAdmin.getManagedRepository( repoId );
537 return new File( repositoryConfiguration.getLocation() );
539 catch ( RepositoryAdminException e )
541 throw new RepositoryStorageRuntimeException( "repo-admin", e.getMessage(), e );
546 public Collection<String> listNamespaces( String repoId, String namespace, Filter<String> filter )
547 throws RepositoryStorageRuntimeException
549 File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace );
551 // scan all the directories which are potential namespaces. Any directories known to be projects are excluded
552 List<String> namespaces = new ArrayList<>();
553 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
556 for ( File file : files )
558 if ( !isProject( file, filter ) )
560 namespaces.add( file.getName() );
564 Collections.sort( namespaces );
569 public Collection<String> listProjects( String repoId, String namespace, Filter<String> filter )
570 throws RepositoryStorageRuntimeException
572 File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace );
574 // scan all directories in the namespace, and only include those that are known to be projects
575 List<String> projects = new ArrayList<>();
577 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
580 for ( File file : files )
582 if ( isProject( file, filter ) )
584 projects.add( file.getName() );
588 Collections.sort( projects );
593 public Collection<String> listProjectVersions( String repoId, String namespace, String projectId,
594 Filter<String> filter )
595 throws RepositoryStorageRuntimeException
597 File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace, projectId );
599 // all directories in a project directory can be considered a version
600 return getSortedFiles( dir, filter );
604 public Collection<ArtifactMetadata> readArtifactsMetadata( ReadMetadataRequest readMetadataRequest )
605 throws RepositoryStorageRuntimeException
607 File dir = pathTranslator.toFile( getRepositoryBasedir( readMetadataRequest.getRepositoryId() ),
608 readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(),
609 readMetadataRequest.getProjectVersion() );
611 // all files that are not metadata and not a checksum / signature are considered artifacts
612 File[] files = dir.listFiles( new ArtifactDirectoryFilter( readMetadataRequest.getFilter() ) );
614 List<ArtifactMetadata> artifacts = new ArrayList<>();
617 for ( File file : files )
619 ArtifactMetadata metadata =
620 getArtifactFromFile( readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(),
621 readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(),
623 artifacts.add( metadata );
630 public ArtifactMetadata readArtifactMetadataFromPath( String repoId, String path )
631 throws RepositoryStorageRuntimeException
633 ArtifactMetadata metadata = pathTranslator.getArtifactForPath( repoId, path );
635 populateArtifactMetadataFromFile( metadata, new File( getRepositoryBasedir( repoId ), path ) );
640 private ArtifactMetadata getArtifactFromFile( String repoId, String namespace, String projectId,
641 String projectVersion, File file )
643 ArtifactMetadata metadata =
644 pathTranslator.getArtifactFromId( repoId, namespace, projectId, projectVersion, file.getName() );
646 populateArtifactMetadataFromFile( metadata, file );
652 public void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
653 throws ProxyDownloadException
655 if ( "pom".equals( artifact.getType() ) )
660 // Build the artifact POM reference
661 ArtifactReference pomReference = new ArtifactReference();
662 pomReference.setGroupId( artifact.getGroupId() );
663 pomReference.setArtifactId( artifact.getArtifactId() );
664 pomReference.setVersion( artifact.getVersion() );
665 pomReference.setType( "pom" );
667 RepositoryProxyConnectors connectors =
668 applicationContext.getBean( "repositoryProxyConnectors#default", RepositoryProxyConnectors.class );
670 // Get the artifact POM from proxied repositories if needed
671 connectors.fetchFromProxies( managedRepository, pomReference );
673 // Open and read the POM from the managed repo
674 File pom = managedRepository.toFile( pomReference );
683 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
686 try (Reader reader = Files.newBufferedReader( pom.toPath(), Charset.defaultCharset() ))
688 model = MAVEN_XPP_3_READER.read( reader );
691 DistributionManagement dist = model.getDistributionManagement();
694 Relocation relocation = dist.getRelocation();
695 if ( relocation != null )
697 // artifact is relocated : update the repositoryPath
698 if ( relocation.getGroupId() != null )
700 artifact.setGroupId( relocation.getGroupId() );
702 if ( relocation.getArtifactId() != null )
704 artifact.setArtifactId( relocation.getArtifactId() );
706 if ( relocation.getVersion() != null )
708 artifact.setVersion( relocation.getVersion() );
713 catch ( IOException e )
715 // Unable to read POM : ignore.
717 catch ( XmlPullParserException e )
719 // Invalid POM : ignore
725 public String getFilePath( String requestPath, ManagedRepository managedRepository )
727 // managedRepository can be null
728 // extract artifact reference from url
729 // groupId:artifactId:version:packaging:classifier
730 //org/apache/archiva/archiva-checksum/1.4-M4-SNAPSHOT/archiva-checksum-1.4-M4-SNAPSHOT.jar
731 String logicalResource = null;
732 String requestPathInfo = StringUtils.defaultString( requestPath );
734 //remove prefix ie /repository/blah becomes /blah
735 requestPathInfo = removePrefix( requestPathInfo );
737 // Remove prefixing slash as the repository id doesn't contain it;
738 if ( requestPathInfo.startsWith( "/" ) )
740 requestPathInfo = requestPathInfo.substring( 1 );
743 int slash = requestPathInfo.indexOf( '/' );
746 logicalResource = requestPathInfo.substring( slash );
748 if ( logicalResource.endsWith( "/.." ) )
750 logicalResource += "/";
753 if ( logicalResource != null && logicalResource.startsWith( "//" ) )
755 logicalResource = logicalResource.substring( 1 );
758 if ( logicalResource == null )
760 logicalResource = "/";
765 logicalResource = "/";
767 return logicalResource;
772 public String getFilePathWithVersion( final String requestPath, ManagedRepositoryContent managedRepositoryContent )
773 throws XMLException, RelocationException
776 if ( StringUtils.endsWith( requestPath, METADATA_FILENAME ) )
778 return getFilePath( requestPath, managedRepositoryContent.getRepository() );
781 String filePath = getFilePath( requestPath, managedRepositoryContent.getRepository() );
783 ArtifactReference artifactReference = null;
786 artifactReference = pathParser.toArtifactReference( filePath );
788 catch ( LayoutException e )
793 if ( StringUtils.endsWith( artifactReference.getVersion(), VersionUtil.SNAPSHOT ) )
795 // read maven metadata to get last timestamp
796 File metadataDir = new File( managedRepositoryContent.getRepoRoot(), filePath ).getParentFile();
797 if ( !metadataDir.exists() )
801 File metadataFile = new File( metadataDir, METADATA_FILENAME );
802 if ( !metadataFile.exists() )
806 ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile );
807 int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
808 String timestamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
810 // org/apache/archiva/archiva-checksum/1.4-M4-SNAPSHOT/archiva-checksum-1.4-M4-SNAPSHOT.jar
811 // -> archiva-checksum-1.4-M4-20130425.081822-1.jar
814 StringUtils.replace( filePath, artifactReference.getArtifactId() + "-" + artifactReference.getVersion(),
815 artifactReference.getArtifactId() + "-" + StringUtils.remove(
816 artifactReference.getVersion(), "-" + VersionUtil.SNAPSHOT ) + "-" + timestamp
817 + "-" + buildNumber );
819 throw new RelocationException( "/repository/" + managedRepositoryContent.getRepository().getId() +
820 ( StringUtils.startsWith( filePath, "/" ) ? "" : "/" ) + filePath,
821 RelocationException.RelocationType.TEMPORARY );
828 //-----------------------------
830 //-----------------------------
838 private static String removePrefix( final String href )
840 String[] parts = StringUtils.split( href, '/' );
841 parts = (String[]) ArrayUtils.subarray( parts, 1, parts.length );
842 if ( parts == null || parts.length == 0 )
847 String joinedString = StringUtils.join( parts, '/' );
848 if ( href.endsWith( "/" ) )
850 joinedString = joinedString + "/";
856 private static void populateArtifactMetadataFromFile( ArtifactMetadata metadata, File file )
858 metadata.setWhenGathered( new Date() );
859 metadata.setFileLastModified( file.lastModified() );
860 ChecksummedFile checksummedFile = new ChecksummedFile( file );
863 metadata.setMd5( checksummedFile.calculateChecksum( ChecksumAlgorithm.MD5 ) );
865 catch ( IOException e )
867 LOGGER.error( "Unable to checksum file {}: {},MD5", file, e.getMessage() );
871 metadata.setSha1( checksummedFile.calculateChecksum( ChecksumAlgorithm.SHA1 ) );
873 catch ( IOException e )
875 LOGGER.error( "Unable to checksum file {}: {},SHA1", file, e.getMessage() );
877 metadata.setSize( file.length() );
880 private boolean isProject( File dir, Filter<String> filter )
882 // scan directories for a valid project version subdirectory, meaning this must be a project directory
883 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
886 for ( File file : files )
888 if ( isProjectVersion( file ) )
895 // if a metadata file is present, check if this is the "artifactId" directory, marking it as a project
896 ArchivaRepositoryMetadata metadata = readMetadata( dir );
897 if ( metadata != null && dir.getName().equals( metadata.getArtifactId() ) )
905 private boolean isProjectVersion( File dir )
907 final String artifactId = dir.getParentFile().getName();
908 final String projectVersion = dir.getName();
910 // check if there is a POM artifact file to ensure it is a version directory
912 if ( VersionUtil.isSnapshot( projectVersion ) )
914 files = dir.listFiles( new PomFilenameFilter( artifactId, projectVersion ) );
918 final String pomFile = artifactId + "-" + projectVersion + ".pom";
919 files = dir.listFiles( new PomFileFilter( pomFile ) );
921 if ( files != null && files.length > 0 )
926 // if a metadata file is present, check if this is the "version" directory, marking it as a project version
927 ArchivaRepositoryMetadata metadata = readMetadata( dir );
928 if ( metadata != null && projectVersion.equals( metadata.getVersion() ) )
936 private ArchivaRepositoryMetadata readMetadata( File directory )
938 ArchivaRepositoryMetadata metadata = null;
939 File metadataFile = new File( directory, METADATA_FILENAME );
940 if ( metadataFile.exists() )
944 metadata = MavenMetadataReader.read( metadataFile );
946 catch ( XMLException e )
948 // ignore missing or invalid metadata
954 private static class DirectoryFilter
955 implements FilenameFilter
957 private final Filter<String> filter;
959 public DirectoryFilter( Filter<String> filter )
961 this.filter = filter;
965 public boolean accept( File dir, String name )
967 if ( !filter.accept( name ) )
971 else if ( name.startsWith( "." ) )
975 else if ( !new File( dir, name ).isDirectory() )
983 private static class ArtifactDirectoryFilter
984 implements FilenameFilter
986 private final Filter<String> filter;
988 private ArtifactDirectoryFilter( Filter<String> filter )
990 this.filter = filter;
994 public boolean accept( File dir, String name )
996 // TODO compare to logic in maven-repository-layer
997 if ( !filter.accept( name ) )
1001 else if ( name.startsWith( "." ) )
1005 else if ( name.endsWith( ".md5" ) || name.endsWith( ".sha1" ) || name.endsWith( ".asc" ) )
1009 else if ( name.equals( METADATA_FILENAME ) )
1013 else if ( new File( dir, name ).isDirectory() )
1017 // some files from remote repositories can have name like maven-metadata-archiva-vm-all-public.xml
1018 else if ( StringUtils.startsWith( name, METADATA_FILENAME_START ) && StringUtils.endsWith( name, ".xml" ) )
1029 private static final class PomFilenameFilter
1030 implements FilenameFilter
1033 private final String artifactId, projectVersion;
1035 private PomFilenameFilter( String artifactId, String projectVersion )
1037 this.artifactId = artifactId;
1038 this.projectVersion = projectVersion;
1042 public boolean accept( File dir, String name )
1044 if ( name.startsWith( artifactId + "-" ) && name.endsWith( ".pom" ) )
1046 String v = name.substring( artifactId.length() + 1, name.length() - 4 );
1047 v = VersionUtil.getBaseVersion( v );
1048 if ( v.equals( projectVersion ) )
1057 private static class PomFileFilter
1058 implements FilenameFilter
1060 private final String pomFile;
1062 private PomFileFilter( String pomFile )
1064 this.pomFile = pomFile;
1068 public boolean accept( File dir, String name )
1070 return pomFile.equals( name );
1075 public PathParser getPathParser()
1080 public void setPathParser( PathParser pathParser )
1082 this.pathParser = pathParser;