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.RepositoryPathTranslator;
41 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
42 import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException;
43 import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException;
44 import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException;
45 import org.apache.archiva.model.ArchivaRepositoryMetadata;
46 import org.apache.archiva.model.ArtifactReference;
47 import org.apache.archiva.model.SnapshotVersion;
48 import org.apache.archiva.policies.ProxyDownloadException;
49 import org.apache.archiva.proxy.common.WagonFactory;
50 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
51 import org.apache.archiva.reports.RepositoryProblemFacet;
52 import org.apache.archiva.repository.ManagedRepositoryContent;
53 import org.apache.archiva.xml.XMLException;
54 import org.apache.commons.lang.ArrayUtils;
55 import org.apache.commons.lang.StringUtils;
56 import org.apache.maven.model.CiManagement;
57 import org.apache.maven.model.Dependency;
58 import org.apache.maven.model.DistributionManagement;
59 import org.apache.maven.model.IssueManagement;
60 import org.apache.maven.model.License;
61 import org.apache.maven.model.MailingList;
62 import org.apache.maven.model.Model;
63 import org.apache.maven.model.Organization;
64 import org.apache.maven.model.Relocation;
65 import org.apache.maven.model.Scm;
66 import org.apache.maven.model.building.DefaultModelBuilderFactory;
67 import org.apache.maven.model.building.DefaultModelBuildingRequest;
68 import org.apache.maven.model.building.ModelBuilder;
69 import org.apache.maven.model.building.ModelBuildingException;
70 import org.apache.maven.model.building.ModelBuildingRequest;
71 import org.apache.maven.model.building.ModelProblem;
72 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
73 import org.apache.maven.wagon.PathUtils;
74 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.springframework.context.ApplicationContext;
78 import org.springframework.stereotype.Service;
80 import javax.annotation.PostConstruct;
81 import javax.inject.Inject;
82 import javax.inject.Named;
84 import java.io.FileNotFoundException;
85 import java.io.FileReader;
86 import java.io.FilenameFilter;
87 import java.io.IOException;
88 import java.util.ArrayList;
89 import java.util.Arrays;
90 import java.util.Collection;
91 import java.util.Collections;
92 import java.util.Date;
93 import java.util.HashMap;
94 import java.util.List;
98 * Maven 2 repository format storage implementation. This class currently takes parameters to indicate the repository to
99 * deal with rather than being instantiated per-repository.
100 * FIXME: instantiate one per repository and allocate permanently from a factory (which can be obtained within the session).
102 * The session is passed in as an argument to obtain any necessary resources, rather than the class being instantiated
103 * within the session in the context of a single managed repository's resolution needs.
106 @Service ( "repositoryStorage#maven2" )
107 public class Maven2RepositoryStorage
108 implements RepositoryStorage
110 private ModelBuilder builder;
113 private RemoteRepositoryAdmin remoteRepositoryAdmin;
116 private ManagedRepositoryAdmin managedRepositoryAdmin;
119 private ProxyConnectorAdmin proxyConnectorAdmin;
122 private NetworkProxyAdmin networkProxyAdmin;
125 @Named ( value = "repositoryPathTranslator#maven2" )
126 private RepositoryPathTranslator pathTranslator;
129 private WagonFactory wagonFactory;
132 private ApplicationContext applicationContext;
134 private static final Logger log = LoggerFactory.getLogger( Maven2RepositoryStorage.class );
136 private static final String METADATA_FILENAME_START = "maven-metadata";
138 private static final String METADATA_FILENAME = METADATA_FILENAME_START + ".xml";
140 private static final MavenXpp3Reader MAVEN_XPP_3_READER = new MavenXpp3Reader();
144 public void initialize()
146 builder = new DefaultModelBuilderFactory().newInstance();
150 public ProjectMetadata readProjectMetadata( String repoId, String namespace, String projectId )
152 // TODO: could natively implement the "shared model" concept from the browse action to avoid needing it there?
156 public ProjectVersionMetadata readProjectVersionMetadata( ReadMetadataRequest readMetadataRequest )
157 throws RepositoryStorageMetadataNotFoundException, RepositoryStorageMetadataInvalidException,
158 RepositoryStorageRuntimeException
162 ManagedRepository managedRepository =
163 managedRepositoryAdmin.getManagedRepository( readMetadataRequest.getRepositoryId() );
165 String artifactVersion = readMetadataRequest.getProjectVersion();
166 if ( VersionUtil.isSnapshot(
167 readMetadataRequest.getProjectVersion() ) ) // skygo trying to improve speed by honoring managed configuration MRM-1658
169 if ( managedRepository.isReleases() && !managedRepository.isSnapshots() )
171 throw new RepositoryStorageRuntimeException( "lookforsnaponreleaseonly",
172 "managed repo is configured for release only" );
177 if ( !managedRepository.isReleases() && managedRepository.isSnapshots() )
179 throw new RepositoryStorageRuntimeException( "lookforsreleaseonsneponly",
180 "managed repo is configured for snapshot only" );
183 File basedir = new File( managedRepository.getLocation() );
184 if ( VersionUtil.isSnapshot( readMetadataRequest.getProjectVersion() ) )
186 File metadataFile = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(),
187 readMetadataRequest.getProjectId(),
188 readMetadataRequest.getProjectVersion(), METADATA_FILENAME );
191 ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile );
193 // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename
194 SnapshotVersion snapshotVersion = metadata.getSnapshotVersion();
195 if ( snapshotVersion != null )
198 artifactVersion.substring( 0, artifactVersion.length() - 8 ); // remove SNAPSHOT from end
200 artifactVersion + snapshotVersion.getTimestamp() + "-" + snapshotVersion.getBuildNumber();
203 catch ( XMLException e )
205 // unable to parse metadata - log it, and continue with the version as the original SNAPSHOT version
206 log.warn( "Invalid metadata: {} - {}", metadataFile, e.getMessage() );
210 // TODO: won't work well with some other layouts, might need to convert artifact parts to ID by path translator
211 String id = readMetadataRequest.getProjectId() + "-" + artifactVersion + ".pom";
213 pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(),
214 readMetadataRequest.getProjectVersion(), id );
216 if ( !file.exists() )
218 // metadata could not be resolved
219 throw new RepositoryStorageMetadataNotFoundException(
220 "The artifact's POM file '" + file.getAbsolutePath() + "' was missing" );
223 // TODO: this is a workaround until we can properly resolve using proxies as well - this doesn't cache
225 List<RemoteRepository> remoteRepositories = new ArrayList<RemoteRepository>();
226 Map<String, NetworkProxy> networkProxies = new HashMap<String, NetworkProxy>();
228 Map<String, List<ProxyConnector>> proxyConnectorsMap = proxyConnectorAdmin.getProxyConnectorAsMap();
229 List<ProxyConnector> proxyConnectors = proxyConnectorsMap.get( readMetadataRequest.getRepositoryId() );
230 if ( proxyConnectors != null )
232 for ( ProxyConnector proxyConnector : proxyConnectors )
234 RemoteRepository remoteRepoConfig =
235 remoteRepositoryAdmin.getRemoteRepository( proxyConnector.getTargetRepoId() );
237 if ( remoteRepoConfig != null )
239 remoteRepositories.add( remoteRepoConfig );
241 NetworkProxy networkProxyConfig =
242 networkProxyAdmin.getNetworkProxy( proxyConnector.getProxyId() );
244 if ( networkProxyConfig != null )
246 // key/value: remote repo ID/proxy info
247 networkProxies.put( proxyConnector.getTargetRepoId(), networkProxyConfig );
253 ModelBuildingRequest req =
254 new DefaultModelBuildingRequest().setProcessPlugins( false ).setPomFile( file ).setTwoPhaseBuilding(
255 false ).setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
257 //MRM-1607. olamy this will resolve jdk profiles on the current running archiva jvm
258 req.setSystemProperties( System.getProperties() );
261 req.setModelResolver(
262 new RepositoryModelResolver( managedRepository, pathTranslator, wagonFactory, remoteRepositories,
263 networkProxies, managedRepository ) );
268 model = builder.build( req ).getEffectiveModel();
270 catch ( ModelBuildingException e )
272 String msg = "The artifact's POM file '" + file + "' was invalid: " + e.getMessage();
274 List<ModelProblem> modelProblems = e.getProblems();
275 for ( ModelProblem problem : modelProblems )
277 // MRM-1411, related to MRM-1335
278 // this means that the problem was that the parent wasn't resolved!
279 // olamy really hackhish but fail with java profile so use error message
280 // || ( StringUtils.startsWith( problem.getMessage(), "Failed to determine Java version for profile" ) )
281 // but setTwoPhaseBuilding(true) fix that
282 if ( ( problem.getException() instanceof FileNotFoundException && e.getModelId() != null &&
283 !e.getModelId().equals( problem.getModelId() ) ) )
285 log.warn( "The artifact's parent POM file '{}' cannot be resolved. " +
286 "Using defaults for project version metadata..", file );
288 ProjectVersionMetadata metadata = new ProjectVersionMetadata();
289 metadata.setId( readMetadataRequest.getProjectVersion() );
291 MavenProjectFacet facet = new MavenProjectFacet();
292 facet.setGroupId( readMetadataRequest.getNamespace() );
293 facet.setArtifactId( readMetadataRequest.getProjectId() );
294 facet.setPackaging( "jar" );
295 metadata.addFacet( facet );
298 "Error in resolving artifact's parent POM file. " + ( problem.getException() == null
299 ? problem.getMessage()
300 : problem.getException().getMessage() );
301 RepositoryProblemFacet repoProblemFacet = new RepositoryProblemFacet();
302 repoProblemFacet.setRepositoryId( readMetadataRequest.getRepositoryId() );
303 repoProblemFacet.setId( readMetadataRequest.getRepositoryId() );
304 repoProblemFacet.setMessage( errMsg );
305 repoProblemFacet.setProblem( errMsg );
306 repoProblemFacet.setProject( readMetadataRequest.getProjectId() );
307 repoProblemFacet.setVersion( readMetadataRequest.getProjectVersion() );
308 repoProblemFacet.setNamespace( readMetadataRequest.getNamespace() );
310 metadata.addFacet( repoProblemFacet );
316 throw new RepositoryStorageMetadataInvalidException( "invalid-pom", msg, e );
319 // Check if the POM is in the correct location
320 boolean correctGroupId = readMetadataRequest.getNamespace().equals( model.getGroupId() );
321 boolean correctArtifactId = readMetadataRequest.getProjectId().equals( model.getArtifactId() );
322 boolean correctVersion = readMetadataRequest.getProjectVersion().equals( model.getVersion() );
323 if ( !correctGroupId || !correctArtifactId || !correctVersion )
325 StringBuilder message = new StringBuilder( "Incorrect POM coordinates in '" + file + "':" );
326 if ( !correctGroupId )
328 message.append( "\nIncorrect group ID: " ).append( model.getGroupId() );
330 if ( !correctArtifactId )
332 message.append( "\nIncorrect artifact ID: " ).append( model.getArtifactId() );
334 if ( !correctVersion )
336 message.append( "\nIncorrect version: " ).append( model.getVersion() );
339 throw new RepositoryStorageMetadataInvalidException( "mislocated-pom", message.toString() );
342 ProjectVersionMetadata metadata = new ProjectVersionMetadata();
343 metadata.setCiManagement( convertCiManagement( model.getCiManagement() ) );
344 metadata.setDescription( model.getDescription() );
345 metadata.setId( readMetadataRequest.getProjectVersion() );
346 metadata.setIssueManagement( convertIssueManagement( model.getIssueManagement() ) );
347 metadata.setLicenses( convertLicenses( model.getLicenses() ) );
348 metadata.setMailingLists( convertMailingLists( model.getMailingLists() ) );
349 metadata.setDependencies( convertDependencies( model.getDependencies() ) );
350 metadata.setName( model.getName() );
351 metadata.setOrganization( convertOrganization( model.getOrganization() ) );
352 metadata.setScm( convertScm( model.getScm() ) );
353 metadata.setUrl( model.getUrl() );
355 MavenProjectFacet facet = new MavenProjectFacet();
356 facet.setGroupId( model.getGroupId() != null ? model.getGroupId() : model.getParent().getGroupId() );
357 facet.setArtifactId( model.getArtifactId() );
358 facet.setPackaging( model.getPackaging() );
359 if ( model.getParent() != null )
361 MavenProjectParent parent = new MavenProjectParent();
362 parent.setGroupId( model.getParent().getGroupId() );
363 parent.setArtifactId( model.getParent().getArtifactId() );
364 parent.setVersion( model.getParent().getVersion() );
365 facet.setParent( parent );
367 metadata.addFacet( facet );
371 catch ( RepositoryAdminException e )
373 throw new RepositoryStorageRuntimeException( "repo-admin", e.getMessage(), e);
377 public void setWagonFactory( WagonFactory wagonFactory )
379 this.wagonFactory = wagonFactory;
382 private List<org.apache.archiva.metadata.model.Dependency> convertDependencies( List<Dependency> dependencies )
384 List<org.apache.archiva.metadata.model.Dependency> l =
385 new ArrayList<org.apache.archiva.metadata.model.Dependency>();
386 for ( Dependency dependency : dependencies )
388 org.apache.archiva.metadata.model.Dependency newDependency =
389 new org.apache.archiva.metadata.model.Dependency();
390 newDependency.setArtifactId( dependency.getArtifactId() );
391 newDependency.setClassifier( dependency.getClassifier() );
392 newDependency.setGroupId( dependency.getGroupId() );
393 newDependency.setOptional( dependency.isOptional() );
394 newDependency.setScope( dependency.getScope() );
395 newDependency.setSystemPath( dependency.getSystemPath() );
396 newDependency.setType( dependency.getType() );
397 newDependency.setVersion( dependency.getVersion() );
398 l.add( newDependency );
403 private org.apache.archiva.metadata.model.Scm convertScm( Scm scm )
405 org.apache.archiva.metadata.model.Scm newScm = null;
408 newScm = new org.apache.archiva.metadata.model.Scm();
409 newScm.setConnection( scm.getConnection() );
410 newScm.setDeveloperConnection( scm.getDeveloperConnection() );
411 newScm.setUrl( scm.getUrl() );
416 private org.apache.archiva.metadata.model.Organization convertOrganization( Organization organization )
418 org.apache.archiva.metadata.model.Organization org = null;
419 if ( organization != null )
421 org = new org.apache.archiva.metadata.model.Organization();
422 org.setName( organization.getName() );
423 org.setUrl( organization.getUrl() );
428 private List<org.apache.archiva.metadata.model.License> convertLicenses( List<License> licenses )
430 List<org.apache.archiva.metadata.model.License> l = new ArrayList<org.apache.archiva.metadata.model.License>();
431 for ( License license : licenses )
433 org.apache.archiva.metadata.model.License newLicense = new org.apache.archiva.metadata.model.License();
434 newLicense.setName( license.getName() );
435 newLicense.setUrl( license.getUrl() );
441 private List<org.apache.archiva.metadata.model.MailingList> convertMailingLists( List<MailingList> mailingLists )
443 List<org.apache.archiva.metadata.model.MailingList> l =
444 new ArrayList<org.apache.archiva.metadata.model.MailingList>();
445 for ( MailingList mailingList : mailingLists )
447 org.apache.archiva.metadata.model.MailingList newMailingList =
448 new org.apache.archiva.metadata.model.MailingList();
449 newMailingList.setName( mailingList.getName() );
450 newMailingList.setMainArchiveUrl( mailingList.getArchive() );
451 newMailingList.setPostAddress( mailingList.getPost() );
452 newMailingList.setSubscribeAddress( mailingList.getSubscribe() );
453 newMailingList.setUnsubscribeAddress( mailingList.getUnsubscribe() );
454 newMailingList.setOtherArchives( mailingList.getOtherArchives() );
455 l.add( newMailingList );
460 private org.apache.archiva.metadata.model.IssueManagement convertIssueManagement( IssueManagement issueManagement )
462 org.apache.archiva.metadata.model.IssueManagement im = null;
463 if ( issueManagement != null )
465 im = new org.apache.archiva.metadata.model.IssueManagement();
466 im.setSystem( issueManagement.getSystem() );
467 im.setUrl( issueManagement.getUrl() );
472 private org.apache.archiva.metadata.model.CiManagement convertCiManagement( CiManagement ciManagement )
474 org.apache.archiva.metadata.model.CiManagement ci = null;
475 if ( ciManagement != null )
477 ci = new org.apache.archiva.metadata.model.CiManagement();
478 ci.setSystem( ciManagement.getSystem() );
479 ci.setUrl( ciManagement.getUrl() );
484 public Collection<String> listRootNamespaces( String repoId, Filter<String> filter )
485 throws RepositoryStorageRuntimeException
487 File dir = getRepositoryBasedir( repoId );
489 return getSortedFiles( dir, filter );
492 private static Collection<String> getSortedFiles( File dir, Filter<String> filter )
494 List<String> fileNames;
495 String[] files = dir.list( new DirectoryFilter( filter ) );
498 fileNames = new ArrayList<String>( Arrays.asList( files ) );
499 Collections.sort( fileNames );
503 fileNames = Collections.emptyList();
508 private File getRepositoryBasedir( String repoId )
509 throws RepositoryStorageRuntimeException
513 ManagedRepository repositoryConfiguration = managedRepositoryAdmin.getManagedRepository( repoId );
515 return new File( repositoryConfiguration.getLocation() );
517 catch ( RepositoryAdminException e )
519 throw new RepositoryStorageRuntimeException( "repo-admin", e.getMessage(), e);
523 public Collection<String> listNamespaces( String repoId, String namespace, Filter<String> filter )
524 throws RepositoryStorageRuntimeException
526 File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace );
528 // scan all the directories which are potential namespaces. Any directories known to be projects are excluded
529 List<String> namespaces = new ArrayList<String>();
530 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
533 for ( File file : files )
535 if ( !isProject( file, filter ) )
537 namespaces.add( file.getName() );
541 Collections.sort( namespaces );
545 public Collection<String> listProjects( String repoId, String namespace, Filter<String> filter )
546 throws RepositoryStorageRuntimeException
548 File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace );
550 // scan all directories in the namespace, and only include those that are known to be projects
551 List<String> projects = new ArrayList<String>();
552 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
555 for ( File file : files )
557 if ( isProject( file, filter ) )
559 projects.add( file.getName() );
563 Collections.sort( projects );
567 public Collection<String> listProjectVersions( String repoId, String namespace, String projectId,
568 Filter<String> filter )
569 throws RepositoryStorageRuntimeException
571 File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace, projectId );
573 // all directories in a project directory can be considered a version
574 return getSortedFiles( dir, filter );
577 public Collection<ArtifactMetadata> readArtifactsMetadata( ReadMetadataRequest readMetadataRequest )
578 throws RepositoryStorageRuntimeException
580 File dir = pathTranslator.toFile( getRepositoryBasedir( readMetadataRequest.getRepositoryId() ),
581 readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(),
582 readMetadataRequest.getProjectVersion() );
584 // all files that are not metadata and not a checksum / signature are considered artifacts
585 File[] files = dir.listFiles( new ArtifactDirectoryFilter( readMetadataRequest.getFilter() ) );
587 List<ArtifactMetadata> artifacts = new ArrayList<ArtifactMetadata>();
590 for ( File file : files )
592 ArtifactMetadata metadata =
593 getArtifactFromFile( readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(),
594 readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(),
596 artifacts.add( metadata );
602 public ArtifactMetadata readArtifactMetadataFromPath( String repoId, String path )
603 throws RepositoryStorageRuntimeException
605 ArtifactMetadata metadata = pathTranslator.getArtifactForPath( repoId, path );
607 populateArtifactMetadataFromFile( metadata, new File( getRepositoryBasedir( repoId ), path ) );
612 private ArtifactMetadata getArtifactFromFile( String repoId, String namespace, String projectId,
613 String projectVersion, File file )
615 ArtifactMetadata metadata =
616 pathTranslator.getArtifactFromId( repoId, namespace, projectId, projectVersion, file.getName() );
618 populateArtifactMetadataFromFile( metadata, file );
624 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
625 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
628 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
629 * metadatas and serving the expected artifact.
631 public void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
632 throws ProxyDownloadException
634 if ( "pom".equals( artifact.getType() ) )
639 // Build the artifact POM reference
640 ArtifactReference pomReference = new ArtifactReference();
641 pomReference.setGroupId( artifact.getGroupId() );
642 pomReference.setArtifactId( artifact.getArtifactId() );
643 pomReference.setVersion( artifact.getVersion() );
644 pomReference.setType( "pom" );
646 RepositoryProxyConnectors connectors =
647 applicationContext.getBean( "repositoryProxyConnectors#default", RepositoryProxyConnectors.class );
649 // Get the artifact POM from proxied repositories if needed
650 connectors.fetchFromProxies( managedRepository, pomReference );
652 // Open and read the POM from the managed repo
653 File pom = managedRepository.toFile( pomReference );
662 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
663 FileReader reader = new FileReader( pom );
667 model = MAVEN_XPP_3_READER.read( reader );
671 if ( reader != null )
677 DistributionManagement dist = model.getDistributionManagement();
680 Relocation relocation = dist.getRelocation();
681 if ( relocation != null )
683 // artifact is relocated : update the repositoryPath
684 if ( relocation.getGroupId() != null )
686 artifact.setGroupId( relocation.getGroupId() );
688 if ( relocation.getArtifactId() != null )
690 artifact.setArtifactId( relocation.getArtifactId() );
692 if ( relocation.getVersion() != null )
694 artifact.setVersion( relocation.getVersion() );
699 catch ( FileNotFoundException e )
701 // Artifact has no POM in repo : ignore
703 catch ( IOException e )
705 // Unable to read POM : ignore.
707 catch ( XmlPullParserException e )
709 // Invalid POM : ignore
714 public String getFilePath( String requestPath, ManagedRepository managedRepository )
716 // managedRepository can be null
717 // extract artifact reference from url
718 // groupId:artifactId:version:packaging:classifier
719 //org/apache/archiva/archiva-checksum/1.4-M4-SNAPSHOT/archiva-checksum-1.4-M4-SNAPSHOT.jar
720 String logicalResource = null;
721 String requestPathInfo = StringUtils.defaultString( requestPath );
723 //remove prefix ie /repository/blah becomes /blah
724 requestPathInfo = removePrefix( requestPathInfo );
726 // Remove prefixing slash as the repository id doesn't contain it;
727 if ( requestPathInfo.startsWith( "/" ) )
729 requestPathInfo = requestPathInfo.substring( 1 );
732 int slash = requestPathInfo.indexOf( '/' );
735 logicalResource = requestPathInfo.substring( slash );
737 if ( logicalResource.endsWith( "/.." ) )
739 logicalResource += "/";
742 if ( logicalResource != null && logicalResource.startsWith( "//" ) )
744 logicalResource = logicalResource.substring( 1 );
747 if ( logicalResource == null )
749 logicalResource = "/";
754 logicalResource = "/";
756 return logicalResource;
762 //-----------------------------
764 //-----------------------------
771 private static String removePrefix( final String href )
773 String[] parts = StringUtils.split( href, '/' );
774 parts = (String[]) ArrayUtils.subarray( parts, 1, parts.length );
775 if ( parts == null || parts.length == 0 )
780 String joinedString = StringUtils.join( parts, '/' );
781 if ( href.endsWith( "/" ) )
783 joinedString = joinedString + "/";
789 private static void populateArtifactMetadataFromFile( ArtifactMetadata metadata, File file )
791 metadata.setWhenGathered( new Date() );
792 metadata.setFileLastModified( file.lastModified() );
793 ChecksummedFile checksummedFile = new ChecksummedFile( file );
796 metadata.setMd5( checksummedFile.calculateChecksum( ChecksumAlgorithm.MD5 ) );
798 catch ( IOException e )
800 log.error( "Unable to checksum file {}: {},MD5", file, e.getMessage() );
804 metadata.setSha1( checksummedFile.calculateChecksum( ChecksumAlgorithm.SHA1 ) );
806 catch ( IOException e )
808 log.error( "Unable to checksum file {}: {},SHA1", file, e.getMessage() );
810 metadata.setSize( file.length() );
813 private boolean isProject( File dir, Filter<String> filter )
815 // scan directories for a valid project version subdirectory, meaning this must be a project directory
816 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
819 for ( File file : files )
821 if ( isProjectVersion( file ) )
828 // if a metadata file is present, check if this is the "artifactId" directory, marking it as a project
829 ArchivaRepositoryMetadata metadata = readMetadata( dir );
830 if ( metadata != null && dir.getName().equals( metadata.getArtifactId() ) )
838 private boolean isProjectVersion( File dir )
840 final String artifactId = dir.getParentFile().getName();
841 final String projectVersion = dir.getName();
843 // check if there is a POM artifact file to ensure it is a version directory
845 if ( VersionUtil.isSnapshot( projectVersion ) )
847 files = dir.listFiles( new PomFilenameFilter( artifactId, projectVersion ) );
851 final String pomFile = artifactId + "-" + projectVersion + ".pom";
852 files = dir.listFiles( new PomFileFilter( pomFile ) );
854 if ( files != null && files.length > 0 )
859 // if a metadata file is present, check if this is the "version" directory, marking it as a project version
860 ArchivaRepositoryMetadata metadata = readMetadata( dir );
861 if ( metadata != null && projectVersion.equals( metadata.getVersion() ) )
869 private ArchivaRepositoryMetadata readMetadata( File directory )
871 ArchivaRepositoryMetadata metadata = null;
872 File metadataFile = new File( directory, METADATA_FILENAME );
873 if ( metadataFile.exists() )
877 metadata = MavenMetadataReader.read( metadataFile );
879 catch ( XMLException e )
881 // ignore missing or invalid metadata
887 private static class DirectoryFilter
888 implements FilenameFilter
890 private final Filter<String> filter;
892 public DirectoryFilter( Filter<String> filter )
894 this.filter = filter;
897 public boolean accept( File dir, String name )
899 if ( !filter.accept( name ) )
903 else if ( name.startsWith( "." ) )
907 else if ( !new File( dir, name ).isDirectory() )
915 private static class ArtifactDirectoryFilter
916 implements FilenameFilter
918 private final Filter<String> filter;
920 private ArtifactDirectoryFilter( Filter<String> filter )
922 this.filter = filter;
925 public boolean accept( File dir, String name )
927 // TODO compare to logic in maven-repository-layer
928 if ( !filter.accept( name ) )
932 else if ( name.startsWith( "." ) )
936 else if ( name.endsWith( ".md5" ) || name.endsWith( ".sha1" ) || name.endsWith( ".asc" ) )
940 else if ( name.equals( METADATA_FILENAME ) )
944 else if ( new File( dir, name ).isDirectory() )
948 // some files from remote repositories can have name like maven-metadata-archiva-vm-all-public.xml
949 else if ( StringUtils.startsWith( name, METADATA_FILENAME_START ) && StringUtils.endsWith( name, ".xml" ) )
961 private static final class PomFilenameFilter
962 implements FilenameFilter
965 private final String artifactId, projectVersion;
967 private PomFilenameFilter( String artifactId, String projectVersion )
969 this.artifactId = artifactId;
970 this.projectVersion = projectVersion;
973 public boolean accept( File dir, String name )
975 if ( name.startsWith( artifactId + "-" ) && name.endsWith( ".pom" ) )
977 String v = name.substring( artifactId.length() + 1, name.length() - 4 );
978 v = VersionUtil.getBaseVersion( v );
979 if ( v.equals( projectVersion ) )
988 private static class PomFileFilter
989 implements FilenameFilter
991 private final String pomFile;
993 private PomFileFilter( String pomFile )
995 this.pomFile = pomFile;
998 public boolean accept( File dir, String name )
1000 return pomFile.equals( name );