KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > maven > project > artifact > MavenMetadataSource


1 package org.apache.maven.project.artifact;
2
3 /*
4  * Copyright 2001-2005 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import org.apache.maven.artifact.Artifact;
20 import org.apache.maven.artifact.factory.ArtifactFactory;
21 import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
22 import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
23 import org.apache.maven.artifact.metadata.ResolutionGroup;
24 import org.apache.maven.artifact.repository.ArtifactRepository;
25 import org.apache.maven.artifact.repository.metadata.ArtifactRepositoryMetadata;
26 import org.apache.maven.artifact.repository.metadata.Metadata;
27 import org.apache.maven.artifact.repository.metadata.RepositoryMetadata;
28 import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager;
29 import org.apache.maven.artifact.repository.metadata.RepositoryMetadataResolutionException;
30 import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
31 import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
32 import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
33 import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
34 import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
35 import org.apache.maven.artifact.versioning.VersionRange;
36 import org.apache.maven.model.Dependency;
37 import org.apache.maven.model.DistributionManagement;
38 import org.apache.maven.model.Exclusion;
39 import org.apache.maven.model.Relocation;
40 import org.apache.maven.project.InvalidProjectModelException;
41 import org.apache.maven.project.MavenProject;
42 import org.apache.maven.project.MavenProjectBuilder;
43 import org.apache.maven.project.ProjectBuildingException;
44 import org.apache.maven.project.validation.ModelValidationResult;
45 import org.codehaus.plexus.logging.AbstractLogEnabled;
46 import org.codehaus.plexus.util.StringUtils;
47
48 import java.io.File JavaDoc;
49 import java.util.ArrayList JavaDoc;
50 import java.util.Collections JavaDoc;
51 import java.util.HashSet JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.List JavaDoc;
54 import java.util.Set JavaDoc;
55
56 /**
57  * @author <a HREF="mailto:jason@maven.org">Jason van Zyl</a>
58  * @author <a HREF="mailto:brett@apache.org">Brett Porter</a>
59  * @version $Id: MavenMetadataSource.java 379524 2006-02-21 16:39:11Z jdcasey $
60  */

61 public class MavenMetadataSource
62     extends AbstractLogEnabled
63     implements ArtifactMetadataSource
64 {
65     public static final String JavaDoc ROLE_HINT = "maven";
66
67     private MavenProjectBuilder mavenProjectBuilder;
68
69     private ArtifactFactory artifactFactory;
70
71     private RepositoryMetadataManager repositoryMetadataManager;
72
73     // lazily instantiated and cached.
74
private MavenProject superProject;
75
76     /**
77      * Retrieve the metadata for the project from the repository.
78      * Uses the ProjectBuilder, to enable post-processing and inheritance calculation before retrieving the
79      * associated artifacts.
80      */

81     public ResolutionGroup retrieve( Artifact artifact, ArtifactRepository localRepository, List JavaDoc remoteRepositories )
82         throws ArtifactMetadataRetrievalException
83     {
84         MavenProject project = null;
85
86         Artifact pomArtifact;
87         boolean done = false;
88         do
89         {
90             // TODO: can we just modify the original?
91
pomArtifact = artifactFactory.createProjectArtifact( artifact.getGroupId(), artifact.getArtifactId(),
92                                                                  artifact.getVersion(), artifact.getScope() );
93
94             if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) )
95             {
96                 done = true;
97             }
98             else
99             {
100                 try
101                 {
102                     project = mavenProjectBuilder.buildFromRepository( pomArtifact, remoteRepositories, localRepository,
103                                                                        true );
104                 }
105                 catch ( InvalidProjectModelException e )
106                 {
107                     getLogger().warn( "POM for \'" + pomArtifact +
108                         "\' is invalid. It will be ignored for artifact resolution. Reason: " + e.getMessage() );
109
110                     if ( getLogger().isDebugEnabled() )
111                     {
112                         getLogger().debug( "Reason: " + e.getMessage() );
113                         
114                         ModelValidationResult validationResult = e.getValidationResult();
115
116                         if ( validationResult != null )
117                         {
118                             getLogger().debug( "\nValidation Errors:" );
119                             for ( Iterator JavaDoc i = validationResult.getMessages().iterator(); i.hasNext(); )
120                             {
121                                 getLogger().debug( i.next().toString() );
122                             }
123                             getLogger().debug( "\n" );
124                         }
125                     }
126
127                     project = null;
128                 }
129                 catch ( ProjectBuildingException e )
130                 {
131                     throw new ArtifactMetadataRetrievalException( "Unable to read the metadata file for artifact '" +
132                         artifact.getDependencyConflictId() + "': " + e.getMessage(), e );
133                 }
134
135                 if ( project != null )
136                 {
137                     Relocation relocation = null;
138
139                     DistributionManagement distMgmt = project.getDistributionManagement();
140                     if ( distMgmt != null )
141                     {
142                         relocation = distMgmt.getRelocation();
143                         
144                         artifact.setDownloadUrl( distMgmt.getDownloadUrl() );
145                         pomArtifact.setDownloadUrl( distMgmt.getDownloadUrl() );
146                     }
147
148                     if ( relocation != null )
149                     {
150                         if ( relocation.getGroupId() != null )
151                         {
152                             artifact.setGroupId( relocation.getGroupId() );
153                         }
154                         if ( relocation.getArtifactId() != null )
155                         {
156                             artifact.setArtifactId( relocation.getArtifactId() );
157                         }
158                         if ( relocation.getVersion() != null )
159                         {
160                             artifact.setVersionRange( VersionRange.createFromVersion( relocation.getVersion() ) );
161                         }
162
163                         if ( artifact.getDependencyFilter() != null &&
164                             !artifact.getDependencyFilter().include( artifact ) )
165                         {
166                             return null;
167                         }
168
169                         String JavaDoc message = "\n This artifact has been relocated to " + artifact.getGroupId() + ":" +
170                             artifact.getArtifactId() + ":" + artifact.getVersion() + ".\n";
171
172                         if ( relocation.getMessage() != null )
173                         {
174                             message += " " + relocation.getMessage() + "\n";
175                         }
176
177                         if ( artifact.getDependencyTrail() != null && artifact.getDependencyTrail().size() == 1 )
178                         {
179                             getLogger().warn( "While downloading " + pomArtifact.getGroupId() + ":" +
180                                 pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion() + message + "\n" );
181                         }
182                         else
183                         {
184                             getLogger().debug( "While downloading " + pomArtifact.getGroupId() + ":" +
185                                 pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion() + message + "\n" );
186                         }
187                     }
188                     else
189                     {
190                         done = true;
191                     }
192                 }
193                 else
194                 {
195                     done = true;
196                 }
197             }
198         }
199         while ( !done );
200
201         // last ditch effort to try to get this set...
202
if ( artifact.getDownloadUrl() == null )
203         {
204             // TODO: this could come straight from the project, negating the need to set it in the project itself?
205
artifact.setDownloadUrl( pomArtifact.getDownloadUrl() );
206         }
207         
208         ResolutionGroup result;
209
210         if ( project == null )
211         {
212             // if the project is null, we encountered an invalid model (read: m1 POM)
213
// we'll just return an empty resolution group.
214
// or used the inherited scope (should that be passed to the buildFromRepository method above?)
215
result = new ResolutionGroup( pomArtifact, Collections.EMPTY_SET, Collections.EMPTY_LIST );
216         }
217         else
218         {
219             Set JavaDoc artifacts = Collections.EMPTY_SET;
220             if ( !artifact.getArtifactHandler().isIncludesDependencies() )
221             {
222                 // TODO: we could possibly use p.getDependencyArtifacts instead of this call, but they haven't been filtered
223
// or used the inherited scope (should that be passed to the buildFromRepository method above?)
224
try
225                 {
226                     artifacts = project.createArtifacts( artifactFactory, artifact.getScope(),
227                                                          artifact.getDependencyFilter() );
228                 }
229                 catch ( InvalidDependencyVersionException e )
230                 {
231                     throw new ArtifactMetadataRetrievalException( "Error in metadata for artifact '" +
232                         artifact.getDependencyConflictId() + "': " + e.getMessage(), e );
233                 }
234             }
235
236             List JavaDoc repositories = aggregateRepositoryLists( remoteRepositories, project.getRemoteArtifactRepositories() );
237
238             result = new ResolutionGroup( pomArtifact, artifacts, repositories );
239         }
240
241         return result;
242     }
243
244     private List JavaDoc aggregateRepositoryLists( List JavaDoc remoteRepositories, List JavaDoc remoteArtifactRepositories )
245         throws ArtifactMetadataRetrievalException
246     {
247         if ( superProject == null )
248         {
249             try
250             {
251                 superProject = mavenProjectBuilder.buildStandaloneSuperProject( null );
252             }
253             catch ( ProjectBuildingException e )
254             {
255                 throw new ArtifactMetadataRetrievalException(
256                     "Unable to parse the Maven built-in model: " + e.getMessage(), e );
257             }
258         }
259
260         List JavaDoc repositories = new ArrayList JavaDoc();
261
262         repositories.addAll( remoteRepositories );
263
264         // ensure that these are defined
265
for ( Iterator JavaDoc it = superProject.getRemoteArtifactRepositories().iterator(); it.hasNext(); )
266         {
267             ArtifactRepository superRepo = (ArtifactRepository) it.next();
268
269             for ( Iterator JavaDoc aggregatedIterator = repositories.iterator(); aggregatedIterator.hasNext(); )
270             {
271                 ArtifactRepository repo = (ArtifactRepository) aggregatedIterator.next();
272
273                 // if the repository exists in the list and was introduced by another POM's super-pom,
274
// remove it...the repository definitions from the super-POM should only be at the end of
275
// the list.
276
// if the repository has been redefined, leave it.
277
if ( repo.getId().equals( superRepo.getId() ) && repo.getUrl().equals( superRepo.getUrl() ) )
278                 {
279                     aggregatedIterator.remove();
280                 }
281             }
282         }
283
284         // this list should contain the super-POM repositories, so we don't have to explicitly add them back.
285
for ( Iterator JavaDoc it = remoteArtifactRepositories.iterator(); it.hasNext(); )
286         {
287             ArtifactRepository repository = (ArtifactRepository) it.next();
288
289             if ( !repositories.contains( repository ) )
290             {
291                 repositories.add( repository );
292             }
293         }
294
295         return repositories;
296     }
297
298     /**
299      * @todo desperately needs refactoring. It's just here because it's implementation is maven-project specific
300      */

301     public static Set JavaDoc createArtifacts( ArtifactFactory artifactFactory, List JavaDoc dependencies, String JavaDoc inheritedScope,
302                                        ArtifactFilter dependencyFilter, MavenProject project )
303         throws InvalidDependencyVersionException
304     {
305         Set JavaDoc projectArtifacts = new HashSet JavaDoc( dependencies.size() );
306
307         for ( Iterator JavaDoc i = dependencies.iterator(); i.hasNext(); )
308         {
309             Dependency d = (Dependency) i.next();
310
311             String JavaDoc scope = d.getScope();
312
313             if ( StringUtils.isEmpty( scope ) )
314             {
315                 scope = Artifact.SCOPE_COMPILE;
316
317                 d.setScope( scope );
318             }
319
320             VersionRange versionRange;
321             try
322             {
323                 versionRange = VersionRange.createFromVersionSpec( d.getVersion() );
324             }
325             catch ( InvalidVersionSpecificationException e )
326             {
327                 throw new InvalidDependencyVersionException( "Unable to parse version '" + d.getVersion() +
328                     "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e );
329             }
330             Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(),
331                                                                           versionRange, d.getType(), d.getClassifier(),
332                                                                           scope, inheritedScope, d.isOptional() );
333
334             if ( Artifact.SCOPE_SYSTEM.equals( scope ) )
335             {
336                 artifact.setFile( new File JavaDoc( d.getSystemPath() ) );
337             }
338
339             if ( artifact != null && ( dependencyFilter == null || dependencyFilter.include( artifact ) ) )
340             {
341                 if ( d.getExclusions() != null && !d.getExclusions().isEmpty() )
342                 {
343                     List JavaDoc exclusions = new ArrayList JavaDoc();
344                     for ( Iterator JavaDoc j = d.getExclusions().iterator(); j.hasNext(); )
345                     {
346                         Exclusion e = (Exclusion) j.next();
347                         exclusions.add( e.getGroupId() + ":" + e.getArtifactId() );
348                     }
349
350                     ArtifactFilter newFilter = new ExcludesArtifactFilter( exclusions );
351
352                     if ( dependencyFilter != null )
353                     {
354                         AndArtifactFilter filter = new AndArtifactFilter();
355                         filter.add( dependencyFilter );
356                         filter.add( newFilter );
357                         dependencyFilter = filter;
358                     }
359                     else
360                     {
361                         dependencyFilter = newFilter;
362                     }
363                 }
364
365                 artifact.setDependencyFilter( dependencyFilter );
366
367                 if ( project != null )
368                 {
369                     artifact = project.replaceWithActiveArtifact( artifact );
370                 }
371
372                 projectArtifacts.add( artifact );
373             }
374         }
375
376         return projectArtifacts;
377     }
378
379     public List JavaDoc retrieveAvailableVersions( Artifact artifact, ArtifactRepository localRepository,
380                                            List JavaDoc remoteRepositories )
381         throws ArtifactMetadataRetrievalException
382     {
383         RepositoryMetadata metadata = new ArtifactRepositoryMetadata( artifact );
384         try
385         {
386             repositoryMetadataManager.resolve( metadata, remoteRepositories, localRepository );
387         }
388         catch ( RepositoryMetadataResolutionException e )
389         {
390             throw new ArtifactMetadataRetrievalException( e.getMessage(), e );
391         }
392
393         List JavaDoc versions;
394         Metadata repoMetadata = metadata.getMetadata();
395         if ( repoMetadata != null && repoMetadata.getVersioning() != null )
396         {
397             List JavaDoc metadataVersions = repoMetadata.getVersioning().getVersions();
398             versions = new ArrayList JavaDoc( metadataVersions.size() );
399             for ( Iterator JavaDoc i = metadataVersions.iterator(); i.hasNext(); )
400             {
401                 String JavaDoc version = (String JavaDoc) i.next();
402                 versions.add( new DefaultArtifactVersion( version ) );
403             }
404         }
405         else
406         {
407             versions = Collections.EMPTY_LIST;
408         }
409
410         return versions;
411     }
412 }
413
Popular Tags