View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  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,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.lifecycle.internal;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  
24  import java.io.File;
25  import java.util.Collection;
26  import java.util.Collections;
27  import java.util.HashMap;
28  import java.util.HashSet;
29  import java.util.LinkedHashSet;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.stream.Collectors;
34  
35  import org.apache.maven.RepositoryUtils;
36  import org.apache.maven.api.services.MessageBuilderFactory;
37  import org.apache.maven.artifact.Artifact;
38  import org.apache.maven.artifact.ArtifactUtils;
39  import org.apache.maven.eventspy.internal.EventSpyDispatcher;
40  import org.apache.maven.execution.MavenSession;
41  import org.apache.maven.lifecycle.LifecycleExecutionException;
42  import org.apache.maven.project.DefaultDependencyResolutionRequest;
43  import org.apache.maven.project.DependencyResolutionException;
44  import org.apache.maven.project.DependencyResolutionResult;
45  import org.apache.maven.project.MavenProject;
46  import org.apache.maven.project.ProjectDependenciesResolver;
47  import org.apache.maven.project.artifact.InvalidDependencyVersionException;
48  import org.apache.maven.project.artifact.ProjectArtifactsCache;
49  import org.eclipse.aether.graph.Dependency;
50  import org.eclipse.aether.graph.DependencyFilter;
51  import org.eclipse.aether.graph.DependencyNode;
52  import org.eclipse.aether.util.filter.AndDependencyFilter;
53  import org.eclipse.aether.util.filter.ScopeDependencyFilter;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  /**
58   * <p>
59   * Resolves dependencies for the artifacts in context of the lifecycle build
60   * </p>
61   * <strong>NOTE:</strong> This class is not part of any public api and can be changed or deleted without prior notice.
62   * @since 3.0
63   */
64  @Named
65  public class LifecycleDependencyResolver {
66      private final Logger logger = LoggerFactory.getLogger(getClass());
67  
68      private final ProjectDependenciesResolver dependenciesResolver;
69  
70      private final ProjectArtifactFactory artifactFactory;
71  
72      private final EventSpyDispatcher eventSpyDispatcher;
73  
74      private final ProjectArtifactsCache projectArtifactsCache;
75  
76      private final MessageBuilderFactory messageBuilderFactory;
77  
78      @Inject
79      public LifecycleDependencyResolver(
80              ProjectDependenciesResolver dependenciesResolver,
81              ProjectArtifactFactory artifactFactory,
82              EventSpyDispatcher eventSpyDispatcher,
83              ProjectArtifactsCache projectArtifactsCache,
84              MessageBuilderFactory messageBuilderFactory) {
85          this.dependenciesResolver = dependenciesResolver;
86          this.artifactFactory = artifactFactory;
87          this.eventSpyDispatcher = eventSpyDispatcher;
88          this.projectArtifactsCache = projectArtifactsCache;
89          this.messageBuilderFactory = messageBuilderFactory;
90      }
91  
92      public static List<MavenProject> getProjects(MavenProject project, MavenSession session, boolean aggregator) {
93          if (aggregator && project.getCollectedProjects() != null) {
94              // get the unsorted list of wanted projects
95              Set<MavenProject> projectAndSubmodules = new HashSet<>(project.getCollectedProjects());
96              projectAndSubmodules.add(project);
97              return session.getProjects().stream() // sorted all
98                      .filter(projectAndSubmodules::contains)
99                      .collect(Collectors.toList()); // sorted and filtered to what we need
100         } else {
101             return Collections.singletonList(project);
102         }
103     }
104 
105     public void resolveProjectDependencies(
106             MavenProject project,
107             Collection<String> scopesToCollect,
108             Collection<String> scopesToResolve,
109             MavenSession session,
110             boolean aggregating,
111             Set<Artifact> projectArtifacts)
112             throws LifecycleExecutionException {
113         ClassLoader tccl = Thread.currentThread().getContextClassLoader();
114         try {
115             ClassLoader projectRealm = project.getClassRealm();
116             if (projectRealm != null && projectRealm != tccl) {
117                 Thread.currentThread().setContextClassLoader(projectRealm);
118             }
119 
120             if (project.getDependencyArtifacts() == null) {
121                 try {
122                     project.setDependencyArtifacts(artifactFactory.createArtifacts(project));
123                 } catch (InvalidDependencyVersionException e) {
124                     throw new LifecycleExecutionException(e);
125                 }
126             }
127 
128             Set<Artifact> resolvedArtifacts = resolveProjectArtifacts(
129                     project, scopesToCollect, scopesToResolve, session, aggregating, projectArtifacts);
130 
131             Map<Artifact, File> reactorProjects =
132                     new HashMap<>(session.getProjects().size());
133             for (MavenProject reactorProject : session.getProjects()) {
134                 reactorProjects.put(
135                         reactorProject.getArtifact(),
136                         reactorProject.getArtifact().getFile());
137             }
138 
139             Map<String, Artifact> map = new HashMap<>();
140             for (Artifact artifact : resolvedArtifacts) {
141                 /**
142                  * MNG-6300: resolvedArtifacts can be cache result; this ensures reactor files are always up-to-date
143                  * During lifecycle the Artifact.getFile() can change from target/classes to the actual jar.
144                  * This clearly shows that target/classes should not be abused as artifactFile just for the classpath
145                  */
146                 File reactorProjectFile = reactorProjects.get(artifact);
147                 if (reactorProjectFile != null) {
148                     artifact.setFile(reactorProjectFile);
149                 }
150 
151                 map.put(artifact.getDependencyConflictId(), artifact);
152             }
153 
154             project.setResolvedArtifacts(resolvedArtifacts);
155 
156             for (Artifact artifact : project.getDependencyArtifacts()) {
157                 if (artifact.getFile() == null) {
158                     Artifact resolved = map.get(artifact.getDependencyConflictId());
159                     if (resolved != null) {
160                         artifact.setFile(resolved.getFile());
161                         artifact.setDependencyTrail(resolved.getDependencyTrail());
162                         artifact.setResolvedVersion(resolved.getVersion());
163                         artifact.setResolved(true);
164                     }
165                 }
166             }
167         } finally {
168             Thread.currentThread().setContextClassLoader(tccl);
169         }
170     }
171 
172     public Set<Artifact> resolveProjectArtifacts(
173             MavenProject project,
174             Collection<String> scopesToCollect,
175             Collection<String> scopesToResolve,
176             MavenSession session,
177             boolean aggregating,
178             Set<Artifact> projectArtifacts)
179             throws LifecycleExecutionException {
180         Set<Artifact> resolvedArtifacts;
181         ProjectArtifactsCache.Key cacheKey = projectArtifactsCache.createKey(
182                 project, scopesToCollect, scopesToResolve, aggregating, session.getRepositorySession());
183         ProjectArtifactsCache.CacheRecord recordArtifacts;
184         recordArtifacts = projectArtifactsCache.get(cacheKey);
185 
186         if (recordArtifacts != null) {
187             resolvedArtifacts = recordArtifacts.getArtifacts();
188         } else {
189             try {
190                 resolvedArtifacts = getDependencies(
191                         project, scopesToCollect, scopesToResolve, session, aggregating, projectArtifacts);
192                 recordArtifacts = projectArtifactsCache.put(cacheKey, resolvedArtifacts);
193             } catch (LifecycleExecutionException e) {
194                 projectArtifactsCache.put(cacheKey, e);
195                 projectArtifactsCache.register(project, cacheKey, recordArtifacts);
196                 throw e;
197             }
198         }
199         projectArtifactsCache.register(project, cacheKey, recordArtifacts);
200         return resolvedArtifacts;
201     }
202 
203     private Set<Artifact> getDependencies(
204             MavenProject project,
205             Collection<String> scopesToCollect,
206             Collection<String> scopesToResolve,
207             MavenSession session,
208             boolean aggregating,
209             Set<Artifact> projectArtifacts)
210             throws LifecycleExecutionException {
211         if (scopesToCollect == null) {
212             scopesToCollect = Collections.emptySet();
213         }
214         if (scopesToResolve == null) {
215             scopesToResolve = Collections.emptySet();
216         }
217 
218         if (scopesToCollect.isEmpty() && scopesToResolve.isEmpty()) {
219             return new LinkedHashSet<>();
220         }
221 
222         scopesToCollect = new HashSet<>(scopesToCollect);
223         scopesToCollect.addAll(scopesToResolve);
224 
225         DependencyFilter collectionFilter = new ScopeDependencyFilter(null, negate(scopesToCollect));
226         DependencyFilter resolutionFilter = new ScopeDependencyFilter(null, negate(scopesToResolve));
227         resolutionFilter = AndDependencyFilter.newInstance(collectionFilter, resolutionFilter);
228         resolutionFilter =
229                 AndDependencyFilter.newInstance(resolutionFilter, new ReactorDependencyFilter(projectArtifacts));
230 
231         DependencyResolutionResult result;
232         try {
233             DefaultDependencyResolutionRequest request =
234                     new DefaultDependencyResolutionRequest(project, session.getRepositorySession());
235             request.setResolutionFilter(resolutionFilter);
236 
237             eventSpyDispatcher.onEvent(request);
238 
239             result = dependenciesResolver.resolve(request);
240         } catch (DependencyResolutionException e) {
241             result = e.getResult();
242 
243             /*
244              * MNG-2277, the check below compensates for our bad plugin support where we ended up with aggregator
245              * plugins that require dependency resolution although they usually run in phases of the build where project
246              * artifacts haven't been assembled yet. The prime example of this is "mvn release:prepare".
247              */
248             if (aggregating && areAllDependenciesInReactor(session.getProjects(), result.getUnresolvedDependencies())) {
249                 logger.warn("The following dependencies could not be resolved at this point of the build"
250                         + " but seem to be part of the reactor:");
251 
252                 for (Dependency dependency : result.getUnresolvedDependencies()) {
253                     logger.warn("o {}", dependency);
254                 }
255 
256                 logger.warn("Try running the build up to the lifecycle phase \"package\"");
257             } else {
258                 throw new LifecycleExecutionException(messageBuilderFactory, null, project, e);
259             }
260         }
261 
262         eventSpyDispatcher.onEvent(result);
263 
264         Set<Artifact> artifacts = new LinkedHashSet<>();
265         if (result.getDependencyGraph() != null
266                 && !result.getDependencyGraph().getChildren().isEmpty()) {
267             RepositoryUtils.toArtifacts(
268                     artifacts,
269                     result.getDependencyGraph().getChildren(),
270                     Collections.singletonList(project.getArtifact().getId()),
271                     collectionFilter);
272         }
273         return artifacts;
274     }
275 
276     private boolean areAllDependenciesInReactor(
277             Collection<MavenProject> projects, Collection<Dependency> dependencies) {
278         Set<String> projectKeys = getReactorProjectKeys(projects);
279 
280         for (Dependency dependency : dependencies) {
281             org.eclipse.aether.artifact.Artifact a = dependency.getArtifact();
282             String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getVersion());
283             if (!projectKeys.contains(key)) {
284                 return false;
285             }
286         }
287 
288         return true;
289     }
290 
291     private Set<String> getReactorProjectKeys(Collection<MavenProject> projects) {
292         Set<String> projectKeys = new HashSet<>(projects.size() * 2);
293         for (MavenProject project : projects) {
294             String key = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion());
295             projectKeys.add(key);
296         }
297         return projectKeys;
298     }
299 
300     private Collection<String> negate(Collection<String> scopes) {
301         Collection<String> result = new HashSet<>();
302         Collections.addAll(result, "system", "compile", "provided", "runtime", "test");
303 
304         for (String scope : scopes) {
305             if ("compile".equals(scope)) {
306                 result.remove("compile");
307                 result.remove("system");
308                 result.remove("provided");
309             } else if ("runtime".equals(scope)) {
310                 result.remove("compile");
311                 result.remove("runtime");
312             } else if ("compile+runtime".equals(scope)) {
313                 result.remove("compile");
314                 result.remove("system");
315                 result.remove("provided");
316                 result.remove("runtime");
317             } else if ("runtime+system".equals(scope)) {
318                 result.remove("compile");
319                 result.remove("system");
320                 result.remove("runtime");
321             } else if ("test".equals(scope)) {
322                 result.clear();
323             }
324         }
325 
326         return result;
327     }
328 
329     private static class ReactorDependencyFilter implements DependencyFilter {
330 
331         private Set<String> keys = new HashSet<>();
332 
333         ReactorDependencyFilter(Collection<Artifact> artifacts) {
334             for (Artifact artifact : artifacts) {
335                 String key = ArtifactUtils.key(artifact);
336                 keys.add(key);
337             }
338         }
339 
340         public boolean accept(DependencyNode node, List<DependencyNode> parents) {
341             Dependency dependency = node.getDependency();
342             if (dependency != null) {
343                 org.eclipse.aether.artifact.Artifact a = dependency.getArtifact();
344                 String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getVersion());
345                 return !keys.contains(key);
346             }
347             return false;
348         }
349     }
350 }