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 // extract artifact reference from url
717 // groupId:artifactId:version:packaging:classifier
718 //org/apache/archiva/archiva-checksum/1.4-M4-SNAPSHOT/archiva-checksum-1.4-M4-SNAPSHOT.jar
719 String logicalResource = null;
720 String requestPathInfo = StringUtils.defaultString( requestPath );
722 //remove prefix ie /repository/blah becomes /blah
723 requestPathInfo = removePrefix( requestPathInfo );
725 // Remove prefixing slash as the repository id doesn't contain it;
726 if ( requestPathInfo.startsWith( "/" ) )
728 requestPathInfo = requestPathInfo.substring( 1 );
731 int slash = requestPathInfo.indexOf( '/' );
734 logicalResource = requestPathInfo.substring( slash );
736 if ( logicalResource.endsWith( "/.." ) )
738 logicalResource += "/";
741 if ( logicalResource != null && logicalResource.startsWith( "//" ) )
743 logicalResource = logicalResource.substring( 1 );
746 if ( logicalResource == null )
748 logicalResource = "/";
753 logicalResource = "/";
755 return logicalResource;
761 //-----------------------------
763 //-----------------------------
770 private static String removePrefix( final String href )
772 String[] parts = StringUtils.split( href, '/' );
773 parts = (String[]) ArrayUtils.subarray( parts, 1, parts.length );
774 if ( parts == null || parts.length == 0 )
779 String joinedString = StringUtils.join( parts, '/' );
780 if ( href.endsWith( "/" ) )
782 joinedString = joinedString + "/";
788 private static void populateArtifactMetadataFromFile( ArtifactMetadata metadata, File file )
790 metadata.setWhenGathered( new Date() );
791 metadata.setFileLastModified( file.lastModified() );
792 ChecksummedFile checksummedFile = new ChecksummedFile( file );
795 metadata.setMd5( checksummedFile.calculateChecksum( ChecksumAlgorithm.MD5 ) );
797 catch ( IOException e )
799 log.error( "Unable to checksum file {}: {},MD5", file, e.getMessage() );
803 metadata.setSha1( checksummedFile.calculateChecksum( ChecksumAlgorithm.SHA1 ) );
805 catch ( IOException e )
807 log.error( "Unable to checksum file {}: {},SHA1", file, e.getMessage() );
809 metadata.setSize( file.length() );
812 private boolean isProject( File dir, Filter<String> filter )
814 // scan directories for a valid project version subdirectory, meaning this must be a project directory
815 File[] files = dir.listFiles( new DirectoryFilter( filter ) );
818 for ( File file : files )
820 if ( isProjectVersion( file ) )
827 // if a metadata file is present, check if this is the "artifactId" directory, marking it as a project
828 ArchivaRepositoryMetadata metadata = readMetadata( dir );
829 if ( metadata != null && dir.getName().equals( metadata.getArtifactId() ) )
837 private boolean isProjectVersion( File dir )
839 final String artifactId = dir.getParentFile().getName();
840 final String projectVersion = dir.getName();
842 // check if there is a POM artifact file to ensure it is a version directory
844 if ( VersionUtil.isSnapshot( projectVersion ) )
846 files = dir.listFiles( new PomFilenameFilter( artifactId, projectVersion ) );
850 final String pomFile = artifactId + "-" + projectVersion + ".pom";
851 files = dir.listFiles( new PomFileFilter( pomFile ) );
853 if ( files != null && files.length > 0 )
858 // if a metadata file is present, check if this is the "version" directory, marking it as a project version
859 ArchivaRepositoryMetadata metadata = readMetadata( dir );
860 if ( metadata != null && projectVersion.equals( metadata.getVersion() ) )
868 private ArchivaRepositoryMetadata readMetadata( File directory )
870 ArchivaRepositoryMetadata metadata = null;
871 File metadataFile = new File( directory, METADATA_FILENAME );
872 if ( metadataFile.exists() )
876 metadata = MavenMetadataReader.read( metadataFile );
878 catch ( XMLException e )
880 // ignore missing or invalid metadata
886 private static class DirectoryFilter
887 implements FilenameFilter
889 private final Filter<String> filter;
891 public DirectoryFilter( Filter<String> filter )
893 this.filter = filter;
896 public boolean accept( File dir, String name )
898 if ( !filter.accept( name ) )
902 else if ( name.startsWith( "." ) )
906 else if ( !new File( dir, name ).isDirectory() )
914 private static class ArtifactDirectoryFilter
915 implements FilenameFilter
917 private final Filter<String> filter;
919 private ArtifactDirectoryFilter( Filter<String> filter )
921 this.filter = filter;
924 public boolean accept( File dir, String name )
926 // TODO compare to logic in maven-repository-layer
927 if ( !filter.accept( name ) )
931 else if ( name.startsWith( "." ) )
935 else if ( name.endsWith( ".md5" ) || name.endsWith( ".sha1" ) || name.endsWith( ".asc" ) )
939 else if ( name.equals( METADATA_FILENAME ) )
943 else if ( new File( dir, name ).isDirectory() )
947 // some files from remote repositories can have name like maven-metadata-archiva-vm-all-public.xml
948 else if ( StringUtils.startsWith( name, METADATA_FILENAME_START ) && StringUtils.endsWith( name, ".xml" ) )
960 private static final class PomFilenameFilter
961 implements FilenameFilter
964 private final String artifactId, projectVersion;
966 private PomFilenameFilter( String artifactId, String projectVersion )
968 this.artifactId = artifactId;
969 this.projectVersion = projectVersion;
972 public boolean accept( File dir, String name )
974 if ( name.startsWith( artifactId + "-" ) && name.endsWith( ".pom" ) )
976 String v = name.substring( artifactId.length() + 1, name.length() - 4 );
977 v = VersionUtil.getBaseVersion( v );
978 if ( v.equals( projectVersion ) )
987 private static class PomFileFilter
988 implements FilenameFilter
990 private final String pomFile;
992 private PomFileFilter( String pomFile )
994 this.pomFile = pomFile;
997 public boolean accept( File dir, String name )
999 return pomFile.equals( name );