View Javadoc

1   package org.apache.maven.repository.internal;
2   
3   /*
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
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
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
19   * under the License.
20   */
21  
22  import java.util.ArrayList;
23  import java.util.Collections;
24  import java.util.LinkedHashMap;
25  import java.util.LinkedHashSet;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.Properties;
29  import java.util.Set;
30  
31  import org.apache.maven.model.DependencyManagement;
32  import org.apache.maven.model.DistributionManagement;
33  import org.apache.maven.model.License;
34  import org.apache.maven.model.Model;
35  import org.apache.maven.model.Relocation;
36  import org.apache.maven.model.Repository;
37  import org.apache.maven.model.building.DefaultModelBuilderFactory;
38  import org.apache.maven.model.building.DefaultModelBuildingRequest;
39  import org.apache.maven.model.building.FileModelSource;
40  import org.apache.maven.model.building.ModelBuilder;
41  import org.apache.maven.model.building.ModelBuildingException;
42  import org.apache.maven.model.building.ModelBuildingRequest;
43  import org.apache.maven.model.building.ModelProblem;
44  import org.apache.maven.model.resolution.UnresolvableModelException;
45  import org.codehaus.plexus.component.annotations.Component;
46  import org.codehaus.plexus.component.annotations.Requirement;
47  import org.sonatype.aether.RepositoryException;
48  import org.sonatype.aether.RepositoryListener;
49  import org.sonatype.aether.RepositorySystemSession;
50  import org.sonatype.aether.artifact.Artifact;
51  import org.sonatype.aether.artifact.ArtifactType;
52  import org.sonatype.aether.artifact.ArtifactTypeRegistry;
53  import org.sonatype.aether.graph.Dependency;
54  import org.sonatype.aether.graph.Exclusion;
55  import org.sonatype.aether.impl.ArtifactDescriptorReader;
56  import org.sonatype.aether.impl.ArtifactResolver;
57  import org.sonatype.aether.impl.RemoteRepositoryManager;
58  import org.sonatype.aether.impl.VersionResolver;
59  import org.sonatype.aether.transfer.ArtifactNotFoundException;
60  import org.sonatype.aether.util.artifact.ArtifactProperties;
61  import org.sonatype.aether.util.artifact.DefaultArtifact;
62  import org.sonatype.aether.util.artifact.DefaultArtifactType;
63  import org.sonatype.aether.util.artifact.SubArtifact;
64  import org.sonatype.aether.util.listener.DefaultRepositoryEvent;
65  import org.sonatype.aether.repository.RemoteRepository;
66  import org.sonatype.aether.repository.RepositoryPolicy;
67  import org.sonatype.aether.repository.WorkspaceRepository;
68  import org.sonatype.aether.resolution.ArtifactDescriptorException;
69  import org.sonatype.aether.resolution.ArtifactDescriptorRequest;
70  import org.sonatype.aether.resolution.ArtifactDescriptorResult;
71  import org.sonatype.aether.resolution.ArtifactRequest;
72  import org.sonatype.aether.resolution.ArtifactResolutionException;
73  import org.sonatype.aether.resolution.ArtifactResult;
74  import org.sonatype.aether.resolution.VersionRequest;
75  import org.sonatype.aether.resolution.VersionResolutionException;
76  import org.sonatype.aether.resolution.VersionResult;
77  import org.sonatype.aether.spi.locator.Service;
78  import org.sonatype.aether.spi.locator.ServiceLocator;
79  import org.sonatype.aether.spi.log.Logger;
80  import org.sonatype.aether.spi.log.NullLogger;
81  
82  /**
83   * @author Benjamin Bentmann
84   */
85  @Component( role = ArtifactDescriptorReader.class )
86  public class DefaultArtifactDescriptorReader
87      implements ArtifactDescriptorReader, Service
88  {
89  
90      @Requirement
91      private Logger logger = NullLogger.INSTANCE;
92  
93      @Requirement
94      private RemoteRepositoryManager remoteRepositoryManager;
95  
96      @Requirement
97      private VersionResolver versionResolver;
98  
99      @Requirement
100     private ArtifactResolver artifactResolver;
101 
102     @Requirement
103     private ModelBuilder modelBuilder;
104 
105     public void initService( ServiceLocator locator )
106     {
107         setLogger( locator.getService( Logger.class ) );
108         setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) );
109         setVersionResolver( locator.getService( VersionResolver.class ) );
110         setArtifactResolver( locator.getService( ArtifactResolver.class ) );
111         modelBuilder = locator.getService( ModelBuilder.class );
112         if ( modelBuilder == null )
113         {
114             setModelBuilder( new DefaultModelBuilderFactory().newInstance() );
115         }
116     }
117 
118     public DefaultArtifactDescriptorReader setLogger( Logger logger )
119     {
120         this.logger = ( logger != null ) ? logger : NullLogger.INSTANCE;
121         return this;
122     }
123 
124     public DefaultArtifactDescriptorReader setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager )
125     {
126         if ( remoteRepositoryManager == null )
127         {
128             throw new IllegalArgumentException( "remote repository manager has not been specified" );
129         }
130         this.remoteRepositoryManager = remoteRepositoryManager;
131         return this;
132     }
133 
134     public DefaultArtifactDescriptorReader setVersionResolver( VersionResolver versionResolver )
135     {
136         if ( versionResolver == null )
137         {
138             throw new IllegalArgumentException( "version resolver has not been specified" );
139         }
140         this.versionResolver = versionResolver;
141         return this;
142     }
143 
144     public DefaultArtifactDescriptorReader setArtifactResolver( ArtifactResolver artifactResolver )
145     {
146         if ( artifactResolver == null )
147         {
148             throw new IllegalArgumentException( "artifact resolver has not been specified" );
149         }
150         this.artifactResolver = artifactResolver;
151         return this;
152     }
153 
154     public DefaultArtifactDescriptorReader setModelBuilder( ModelBuilder modelBuilder )
155     {
156         if ( modelBuilder == null )
157         {
158             throw new IllegalArgumentException( "model builder has not been specified" );
159         }
160         this.modelBuilder = modelBuilder;
161         return this;
162     }
163 
164     public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session,
165                                                             ArtifactDescriptorRequest request )
166         throws ArtifactDescriptorException
167     {
168         ArtifactDescriptorResult result = new ArtifactDescriptorResult( request );
169 
170         Model model = loadPom( session, request, result );
171 
172         if ( model != null )
173         {
174             ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();
175 
176             for ( Repository r : model.getRepositories() )
177             {
178                 result.addRepository( convert( r ) );
179             }
180 
181             for ( org.apache.maven.model.Dependency dependency : model.getDependencies() )
182             {
183                 result.addDependency( convert( dependency, stereotypes ) );
184             }
185 
186             DependencyManagement mngt = model.getDependencyManagement();
187             if ( mngt != null )
188             {
189                 for ( org.apache.maven.model.Dependency dependency : mngt.getDependencies() )
190                 {
191                     result.addManagedDependency( convert( dependency, stereotypes ) );
192                 }
193             }
194 
195             Map<String, Object> properties = new LinkedHashMap<String, Object>();
196 
197             List<License> licenses = model.getLicenses();
198             properties.put( "license.count", Integer.valueOf( licenses.size() ) );
199             for ( int i = 0; i < licenses.size(); i++ )
200             {
201                 License license = licenses.get( i );
202                 properties.put( "license." + i + ".name", license.getName() );
203                 properties.put( "license." + i + ".url", license.getUrl() );
204                 properties.put( "license." + i + ".comments", license.getComments() );
205                 properties.put( "license." + i + ".distribution", license.getDistribution() );
206             }
207 
208             result.setProperties( properties );
209         }
210 
211         return result;
212     }
213 
214     private Model loadPom( RepositorySystemSession session, ArtifactDescriptorRequest request,
215                            ArtifactDescriptorResult result )
216         throws ArtifactDescriptorException
217     {
218         Set<String> visited = new LinkedHashSet<String>();
219         for ( Artifact artifact = request.getArtifact();; )
220         {
221             try
222             {
223                 VersionRequest versionRequest =
224                     new VersionRequest( artifact, request.getRepositories(), request.getRequestContext() );
225                 VersionResult versionResult = versionResolver.resolveVersion( session, versionRequest );
226 
227                 artifact = artifact.setVersion( versionResult.getVersion() );
228             }
229             catch ( VersionResolutionException e )
230             {
231                 result.addException( e );
232                 throw new ArtifactDescriptorException( result );
233             }
234 
235             if ( !visited.add( artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getBaseVersion() ) )
236             {
237                 RepositoryException exception =
238                     new RepositoryException( "Artifact relocations form a cycle: " + visited );
239                 invalidDescriptor( session, artifact, exception );
240                 if ( session.isIgnoreInvalidArtifactDescriptor() )
241                 {
242                     return null;
243                 }
244                 result.addException( exception );
245                 throw new ArtifactDescriptorException( result );
246             }
247 
248             Artifact pomArtifact = artifact;
249             if ( pomArtifact.getClassifier().length() > 0 || !"pom".equals( pomArtifact.getExtension() ) )
250             {
251                 pomArtifact = new SubArtifact( artifact, "", "pom" );
252             }
253 
254             ArtifactResult resolveResult;
255             try
256             {
257                 ArtifactRequest resolveRequest =
258                     new ArtifactRequest( pomArtifact, request.getRepositories(), request.getRequestContext() );
259                 resolveResult = artifactResolver.resolveArtifact( session, resolveRequest );
260                 pomArtifact = resolveResult.getArtifact();
261                 result.setRepository( resolveResult.getRepository() );
262             }
263             catch ( ArtifactResolutionException e )
264             {
265                 if ( e.getCause() instanceof ArtifactNotFoundException )
266                 {
267                     missingDescriptor( session, artifact );
268                     if ( session.isIgnoreMissingArtifactDescriptor() )
269                     {
270                         return null;
271                     }
272                 }
273                 result.addException( e );
274                 throw new ArtifactDescriptorException( result );
275             }
276 
277             Model model;
278             try
279             {
280                 ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
281                 modelRequest.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
282                 modelRequest.setProcessPlugins( false );
283                 modelRequest.setTwoPhaseBuilding( false );
284                 modelRequest.setSystemProperties( toProperties( session.getSystemProperties() ) );
285                 modelRequest.setUserProperties( toProperties( session.getUserProperties() ) );
286                 modelRequest.setModelCache( DefaultModelCache.newInstance( session ) );
287                 modelRequest.setModelResolver( new DefaultModelResolver( session, request.getRequestContext(),
288                                                                          artifactResolver, remoteRepositoryManager,
289                                                                          request.getRepositories() ) );
290                 if ( resolveResult.getRepository() instanceof WorkspaceRepository )
291                 {
292                     modelRequest.setPomFile( pomArtifact.getFile() );
293                 }
294                 else
295                 {
296                     modelRequest.setModelSource( new FileModelSource( pomArtifact.getFile() ) );
297                 }
298 
299                 model = modelBuilder.build( modelRequest ).getEffectiveModel();
300             }
301             catch ( ModelBuildingException e )
302             {
303                 for ( ModelProblem problem : e.getProblems() )
304                 {
305                     if ( problem.getException() instanceof UnresolvableModelException )
306                     {
307                         result.addException( problem.getException() );
308                         throw new ArtifactDescriptorException( result );
309                     }
310                 }
311                 invalidDescriptor( session, artifact, e );
312                 if ( session.isIgnoreInvalidArtifactDescriptor() )
313                 {
314                     return null;
315                 }
316                 result.addException( e );
317                 throw new ArtifactDescriptorException( result );
318             }
319 
320             Relocation relocation = getRelocation( model );
321 
322             if ( relocation != null )
323             {
324                 result.addRelocation( artifact );
325                 artifact =
326                     new RelocatedArtifact( artifact, relocation.getGroupId(), relocation.getArtifactId(),
327                                            relocation.getVersion() );
328                 result.setArtifact( artifact );
329             }
330             else
331             {
332                 return model;
333             }
334         }
335     }
336 
337     private Properties toProperties( Map<String, String> map )
338     {
339         Properties props = new Properties();
340         if ( map != null )
341         {
342             props.putAll( map );
343         }
344         return props;
345     }
346 
347     private Relocation getRelocation( Model model )
348     {
349         Relocation relocation = null;
350         DistributionManagement distMngt = model.getDistributionManagement();
351         if ( distMngt != null )
352         {
353             relocation = distMngt.getRelocation();
354         }
355         return relocation;
356     }
357 
358     private Dependency convert( org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry stereotypes )
359     {
360         ArtifactType stereotype = stereotypes.get( dependency.getType() );
361         if ( stereotype == null )
362         {
363             stereotype = new DefaultArtifactType( dependency.getType() );
364         }
365 
366         boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0;
367 
368         Map<String, String> props = null;
369         if ( system )
370         {
371             props = Collections.singletonMap( ArtifactProperties.LOCAL_PATH, dependency.getSystemPath() );
372         }
373 
374         Artifact artifact =
375             new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null,
376                                  dependency.getVersion(), props, stereotype );
377 
378         List<Exclusion> exclusions = new ArrayList<Exclusion>( dependency.getExclusions().size() );
379         for ( org.apache.maven.model.Exclusion exclusion : dependency.getExclusions() )
380         {
381             exclusions.add( convert( exclusion ) );
382         }
383 
384         Dependency result = new Dependency( artifact, dependency.getScope(), dependency.isOptional(), exclusions );
385 
386         return result;
387     }
388 
389     private Exclusion convert( org.apache.maven.model.Exclusion exclusion )
390     {
391         return new Exclusion( exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*" );
392     }
393 
394     static RemoteRepository convert( Repository repository )
395     {
396         RemoteRepository result =
397             new RemoteRepository( repository.getId(), repository.getLayout(), repository.getUrl() );
398         result.setPolicy( true, convert( repository.getSnapshots() ) );
399         result.setPolicy( false, convert( repository.getReleases() ) );
400         return result;
401     }
402 
403     private static RepositoryPolicy convert( org.apache.maven.model.RepositoryPolicy policy )
404     {
405         boolean enabled = true;
406         String checksums = RepositoryPolicy.CHECKSUM_POLICY_WARN;
407         String updates = RepositoryPolicy.UPDATE_POLICY_DAILY;
408 
409         if ( policy != null )
410         {
411             enabled = policy.isEnabled();
412             if ( policy.getUpdatePolicy() != null )
413             {
414                 updates = policy.getUpdatePolicy();
415             }
416             if ( policy.getChecksumPolicy() != null )
417             {
418                 checksums = policy.getChecksumPolicy();
419             }
420         }
421 
422         return new RepositoryPolicy( enabled, updates, checksums );
423     }
424 
425     private void missingDescriptor( RepositorySystemSession session, Artifact artifact )
426     {
427         RepositoryListener listener = session.getRepositoryListener();
428         if ( listener != null )
429         {
430             DefaultRepositoryEvent event = new DefaultRepositoryEvent( session, artifact );
431             listener.artifactDescriptorMissing( event );
432         }
433     }
434 
435     private void invalidDescriptor( RepositorySystemSession session, Artifact artifact, Exception exception )
436     {
437         RepositoryListener listener = session.getRepositoryListener();
438         if ( listener != null )
439         {
440             DefaultRepositoryEvent event = new DefaultRepositoryEvent( session, artifact );
441             event.setException( exception );
442             listener.artifactDescriptorInvalid( event );
443         }
444     }
445 
446 }