1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven;
20
21 import javax.inject.Inject;
22 import javax.inject.Named;
23 import javax.inject.Singleton;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashSet;
33 import java.util.LinkedHashMap;
34 import java.util.LinkedHashSet;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.function.Function;
39 import java.util.stream.Stream;
40
41 import org.apache.maven.api.Session;
42 import org.apache.maven.api.model.Model;
43 import org.apache.maven.api.model.Prerequisites;
44 import org.apache.maven.api.model.Profile;
45 import org.apache.maven.artifact.ArtifactUtils;
46 import org.apache.maven.execution.BuildResumptionAnalyzer;
47 import org.apache.maven.execution.BuildResumptionDataRepository;
48 import org.apache.maven.execution.BuildResumptionPersistenceException;
49 import org.apache.maven.execution.DefaultMavenExecutionResult;
50 import org.apache.maven.execution.ExecutionEvent;
51 import org.apache.maven.execution.MavenExecutionRequest;
52 import org.apache.maven.execution.MavenExecutionResult;
53 import org.apache.maven.execution.MavenSession;
54 import org.apache.maven.execution.ProfileActivation;
55 import org.apache.maven.execution.ProjectActivation;
56 import org.apache.maven.execution.ProjectDependencyGraph;
57 import org.apache.maven.graph.GraphBuilder;
58 import org.apache.maven.graph.ProjectSelector;
59 import org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory;
60 import org.apache.maven.internal.aether.MavenChainedWorkspaceReader;
61 import org.apache.maven.internal.impl.DefaultSession;
62 import org.apache.maven.internal.impl.DefaultSessionFactory;
63 import org.apache.maven.lifecycle.LifecycleExecutionException;
64 import org.apache.maven.lifecycle.internal.ExecutionEventCatapult;
65 import org.apache.maven.lifecycle.internal.LifecycleStarter;
66 import org.apache.maven.model.building.ModelProblem;
67 import org.apache.maven.model.building.Result;
68 import org.apache.maven.model.superpom.SuperPomProvider;
69 import org.apache.maven.plugin.LegacySupport;
70 import org.apache.maven.project.MavenProject;
71 import org.apache.maven.project.ProjectBuilder;
72 import org.apache.maven.session.scope.internal.SessionScope;
73 import org.codehaus.plexus.PlexusContainer;
74 import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
75 import org.eclipse.aether.DefaultRepositorySystemSession;
76 import org.eclipse.aether.RepositorySystemSession;
77 import org.eclipse.aether.repository.WorkspaceReader;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import org.slf4j.helpers.MessageFormatter;
81
82 import static java.util.stream.Collectors.toSet;
83
84
85
86
87 @Named
88 @Singleton
89 public class DefaultMaven implements Maven {
90 private final Logger logger = LoggerFactory.getLogger(getClass());
91
92 protected ProjectBuilder projectBuilder;
93
94 private LifecycleStarter lifecycleStarter;
95
96 protected PlexusContainer container;
97
98 private ExecutionEventCatapult eventCatapult;
99
100 private LegacySupport legacySupport;
101
102 private SessionScope sessionScope;
103
104 private DefaultRepositorySystemSessionFactory repositorySessionFactory;
105
106 private final GraphBuilder graphBuilder;
107
108 private final BuildResumptionAnalyzer buildResumptionAnalyzer;
109
110 private final BuildResumptionDataRepository buildResumptionDataRepository;
111
112 private final SuperPomProvider superPomProvider;
113
114 private final DefaultSessionFactory defaultSessionFactory;
115
116 private final ProjectSelector projectSelector;
117
118 @Inject
119 @SuppressWarnings("checkstyle:ParameterNumber")
120 public DefaultMaven(
121 ProjectBuilder projectBuilder,
122 LifecycleStarter lifecycleStarter,
123 PlexusContainer container,
124 ExecutionEventCatapult eventCatapult,
125 LegacySupport legacySupport,
126 SessionScope sessionScope,
127 DefaultRepositorySystemSessionFactory repositorySessionFactory,
128 @Named(GraphBuilder.HINT) GraphBuilder graphBuilder,
129 BuildResumptionAnalyzer buildResumptionAnalyzer,
130 BuildResumptionDataRepository buildResumptionDataRepository,
131 SuperPomProvider superPomProvider,
132 DefaultSessionFactory defaultSessionFactory) {
133 this.projectBuilder = projectBuilder;
134 this.lifecycleStarter = lifecycleStarter;
135 this.container = container;
136 this.eventCatapult = eventCatapult;
137 this.legacySupport = legacySupport;
138 this.sessionScope = sessionScope;
139 this.repositorySessionFactory = repositorySessionFactory;
140 this.graphBuilder = graphBuilder;
141 this.buildResumptionAnalyzer = buildResumptionAnalyzer;
142 this.buildResumptionDataRepository = buildResumptionDataRepository;
143 this.superPomProvider = superPomProvider;
144 this.defaultSessionFactory = defaultSessionFactory;
145 this.projectSelector = new ProjectSelector();
146 }
147
148 @Override
149 public MavenExecutionResult execute(MavenExecutionRequest request) {
150 MavenExecutionResult result;
151
152 try {
153 result = doExecute(request);
154 } catch (OutOfMemoryError e) {
155 result = addExceptionToResult(new DefaultMavenExecutionResult(), e);
156 } catch (RuntimeException e) {
157
158 if (e.getCause() instanceof ProjectCycleException) {
159 result = addExceptionToResult(new DefaultMavenExecutionResult(), e.getCause());
160 } else {
161 result = addExceptionToResult(
162 new DefaultMavenExecutionResult(), new InternalErrorException("Internal error: " + e, e));
163 }
164 } finally {
165 legacySupport.setSession(null);
166 }
167
168 return result;
169 }
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199 @SuppressWarnings("checkstyle:methodlength")
200 private MavenExecutionResult doExecute(MavenExecutionRequest request) {
201 request.setStartTime(new Date());
202
203 MavenExecutionResult result = new DefaultMavenExecutionResult();
204
205 try {
206 validateLocalRepository(request);
207 } catch (IOException e) {
208 return addExceptionToResult(result, e);
209 }
210
211
212
213
214
215
216 sessionScope.enter();
217 try {
218 DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) newRepositorySession(request);
219 MavenSession session = new MavenSession(container, repoSession, request, result);
220 session.setSession(defaultSessionFactory.getSession(session));
221
222 sessionScope.seed(MavenSession.class, session);
223 sessionScope.seed(Session.class, session.getSession());
224 sessionScope.seed(DefaultSession.class, (DefaultSession) session.getSession());
225
226 legacySupport.setSession(session);
227
228 return doExecute(request, session, result, repoSession);
229 } finally {
230 sessionScope.exit();
231 }
232 }
233
234 private MavenExecutionResult doExecute(
235 MavenExecutionRequest request,
236 MavenSession session,
237 MavenExecutionResult result,
238 DefaultRepositorySystemSession repoSession) {
239 try {
240 afterSessionStart(session);
241 } catch (MavenExecutionException e) {
242 return addExceptionToResult(result, e);
243 }
244
245 try {
246 WorkspaceReader reactorReader = container.lookup(WorkspaceReader.class, ReactorReader.HINT);
247 repoSession.setWorkspaceReader(reactorReader);
248 } catch (ComponentLookupException e) {
249 return addExceptionToResult(result, e);
250 }
251
252 eventCatapult.fire(ExecutionEvent.Type.ProjectDiscoveryStarted, session, null);
253
254 Result<? extends ProjectDependencyGraph> graphResult = buildGraph(session);
255
256 if (graphResult.hasErrors()) {
257 return addExceptionToResult(
258 result, graphResult.getProblems().iterator().next().getException());
259 }
260
261 try {
262 session.setProjectMap(getProjectMap(session.getProjects()));
263 } catch (DuplicateProjectException e) {
264 return addExceptionToResult(result, e);
265 }
266
267 try {
268 setupWorkspaceReader(session, repoSession);
269 } catch (ComponentLookupException e) {
270 return addExceptionToResult(result, e);
271 }
272 repoSession.setReadOnly();
273 try {
274 afterProjectsRead(session);
275 } catch (MavenExecutionException e) {
276 return addExceptionToResult(result, e);
277 }
278
279
280
281
282
283
284
285
286
287
288 graphResult = buildGraph(session);
289
290 if (graphResult.hasErrors()) {
291 return addExceptionToResult(
292 result, graphResult.getProblems().iterator().next().getException());
293 }
294
295 try {
296 if (result.hasExceptions()) {
297 return result;
298 }
299
300 result.setTopologicallySortedProjects(session.getProjects());
301
302 result.setProject(session.getTopLevelProject());
303
304 validatePrerequisitesForNonMavenPluginProjects(session.getProjects());
305
306 validateRequiredProfiles(session, request.getProfileActivation());
307 if (session.getResult().hasExceptions()) {
308 return result;
309 }
310
311 validateOptionalProfiles(session, request.getProfileActivation());
312
313 lifecycleStarter.execute(session);
314
315 validateOptionalProjects(request, session);
316 validateOptionalProfiles(session, request.getProfileActivation());
317
318 if (session.getResult().hasExceptions()) {
319 addExceptionToResult(result, session.getResult().getExceptions().get(0));
320 persistResumptionData(result, session);
321 return result;
322 } else {
323 session.getAllProjects().stream()
324 .filter(MavenProject::isExecutionRoot)
325 .findFirst()
326 .ifPresent(buildResumptionDataRepository::removeResumptionData);
327 }
328 } finally {
329 try {
330 afterSessionEnd(session);
331 } catch (MavenExecutionException e) {
332 return addExceptionToResult(result, e);
333 }
334 }
335
336 return result;
337 }
338
339 private void setupWorkspaceReader(MavenSession session, DefaultRepositorySystemSession repoSession)
340 throws ComponentLookupException {
341
342 Set<WorkspaceReader> workspaceReaders = new LinkedHashSet<>();
343
344 WorkspaceReader reactorReader = container.lookup(WorkspaceReader.class, ReactorReader.HINT);
345 workspaceReaders.add(reactorReader);
346
347 WorkspaceReader repoWorkspaceReader = repoSession.getWorkspaceReader();
348 if (repoWorkspaceReader != null && repoWorkspaceReader != reactorReader) {
349 workspaceReaders.add(repoWorkspaceReader);
350 }
351
352 workspaceReaders.addAll(getProjectScopedExtensionComponents(session.getProjects(), WorkspaceReader.class));
353 repoSession.setWorkspaceReader(MavenChainedWorkspaceReader.of(workspaceReaders));
354 }
355
356 private void afterSessionStart(MavenSession session) throws MavenExecutionException {
357 callListeners(session, AbstractMavenLifecycleParticipant::afterSessionStart);
358 }
359
360 private void afterProjectsRead(MavenSession session) throws MavenExecutionException {
361 callListeners(session, AbstractMavenLifecycleParticipant::afterProjectsRead);
362 }
363
364 private void afterSessionEnd(MavenSession session) throws MavenExecutionException {
365 callListeners(session, AbstractMavenLifecycleParticipant::afterSessionEnd);
366 }
367
368 @FunctionalInterface
369 interface ListenerMethod {
370 void run(AbstractMavenLifecycleParticipant listener, MavenSession session) throws MavenExecutionException;
371 }
372
373 private void callListeners(MavenSession session, ListenerMethod method) throws MavenExecutionException {
374 ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
375 try {
376 for (AbstractMavenLifecycleParticipant listener :
377 getExtensionComponents(session.getProjects(), AbstractMavenLifecycleParticipant.class)) {
378 Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
379 method.run(listener, session);
380 }
381 } finally {
382 Thread.currentThread().setContextClassLoader(originalClassLoader);
383 }
384 }
385
386 private void persistResumptionData(MavenExecutionResult result, MavenSession session) {
387 boolean hasLifecycleExecutionExceptions =
388 result.getExceptions().stream().anyMatch(LifecycleExecutionException.class::isInstance);
389
390 if (hasLifecycleExecutionExceptions) {
391 MavenProject rootProject = session.getAllProjects().stream()
392 .filter(MavenProject::isExecutionRoot)
393 .findFirst()
394 .orElseThrow(() -> new IllegalStateException("No project in the session is execution root"));
395
396 buildResumptionAnalyzer.determineBuildResumptionData(result).ifPresent(resumption -> {
397 try {
398 buildResumptionDataRepository.persistResumptionData(rootProject, resumption);
399 result.setCanResume(true);
400 } catch (BuildResumptionPersistenceException e) {
401 logger.warn("Could not persist build resumption data", e);
402 }
403 });
404 }
405 }
406
407 public RepositorySystemSession newRepositorySession(MavenExecutionRequest request) {
408 return repositorySessionFactory.newRepositorySession(request);
409 }
410
411 private void validateLocalRepository(MavenExecutionRequest request) throws IOException {
412 File localRepoDir = request.getLocalRepositoryPath();
413
414 logger.debug("Using local repository at " + localRepoDir);
415
416 localRepoDir.mkdirs();
417
418 if (!localRepoDir.isDirectory()) {
419 throw new IOException("Could not create local repository at " + localRepoDir);
420 }
421 }
422
423 private <T> Collection<T> getExtensionComponents(Collection<MavenProject> projects, Class<T> role) {
424 Collection<T> foundComponents = new LinkedHashSet<>();
425
426 try {
427 foundComponents.addAll(container.lookupList(role));
428 } catch (ComponentLookupException e) {
429
430 logger.warn("Failed to lookup " + role + ": " + e.getMessage());
431 }
432
433 foundComponents.addAll(getProjectScopedExtensionComponents(projects, role));
434
435 return foundComponents;
436 }
437
438 protected <T> Collection<T> getProjectScopedExtensionComponents(Collection<MavenProject> projects, Class<T> role) {
439 if (projects == null) {
440 return Collections.emptyList();
441 }
442
443 Collection<T> foundComponents = new LinkedHashSet<>();
444 Collection<ClassLoader> scannedRealms = new HashSet<>();
445
446 Thread currentThread = Thread.currentThread();
447 ClassLoader originalContextClassLoader = currentThread.getContextClassLoader();
448 try {
449 for (MavenProject project : projects) {
450 ClassLoader projectRealm = project.getClassRealm();
451
452 if (projectRealm != null && scannedRealms.add(projectRealm)) {
453 currentThread.setContextClassLoader(projectRealm);
454
455 try {
456 foundComponents.addAll(container.lookupList(role));
457 } catch (ComponentLookupException e) {
458
459 logger.warn("Failed to lookup " + role + ": " + e.getMessage());
460 }
461 }
462 }
463 return foundComponents;
464 } finally {
465 currentThread.setContextClassLoader(originalContextClassLoader);
466 }
467 }
468
469 private MavenExecutionResult addExceptionToResult(MavenExecutionResult result, Throwable e) {
470 if (!result.getExceptions().contains(e)) {
471 result.addException(e);
472 }
473
474 return result;
475 }
476
477 private void validatePrerequisitesForNonMavenPluginProjects(List<MavenProject> projects) {
478 for (MavenProject mavenProject : projects) {
479 if (!"maven-plugin".equals(mavenProject.getPackaging())) {
480 Prerequisites prerequisites =
481 mavenProject.getModel().getDelegate().getPrerequisites();
482 if (prerequisites != null && prerequisites.getMaven() != null) {
483 logger.warn("The project " + mavenProject.getId() + " uses prerequisites"
484 + " which is only intended for maven-plugin projects "
485 + "but not for non maven-plugin projects. "
486 + "For such purposes you should use the maven-enforcer-plugin. "
487 + "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html");
488 }
489 }
490 }
491 }
492
493
494
495
496
497
498 private Set<String> getAllProfiles(MavenSession session) {
499 final Model superPomModel = superPomProvider.getSuperModel("4.0.0").getDelegate();
500 final Set<MavenProject> projectsIncludingParents = new HashSet<>();
501 for (MavenProject project : session.getProjects()) {
502 boolean isAdded = projectsIncludingParents.add(project);
503 MavenProject parent = project.getParent();
504 while (isAdded && parent != null) {
505 isAdded = projectsIncludingParents.add(parent);
506 parent = parent.getParent();
507 }
508 }
509
510 final Stream<String> projectProfiles = projectsIncludingParents.stream()
511 .flatMap(p -> p.getModel().getDelegate().getProfiles().stream())
512 .map(Profile::getId);
513 final Stream<String> settingsProfiles =
514 session.getSettings().getProfiles().stream().map(org.apache.maven.settings.Profile::getId);
515 final Stream<String> superPomProfiles =
516 superPomModel.getProfiles().stream().map(Profile::getId);
517
518 return Stream.of(projectProfiles, settingsProfiles, superPomProfiles)
519 .flatMap(Function.identity())
520 .collect(toSet());
521 }
522
523
524
525
526
527
528 private void validateRequiredProfiles(MavenSession session, ProfileActivation profileActivation) {
529 final Set<String> allAvailableProfiles = getAllProfiles(session);
530
531 final Set<String> requiredProfiles = new HashSet<>();
532 requiredProfiles.addAll(profileActivation.getRequiredActiveProfileIds());
533 requiredProfiles.addAll(profileActivation.getRequiredInactiveProfileIds());
534
535
536 final Set<String> notFoundRequiredProfiles = requiredProfiles.stream()
537 .filter(rap -> !allAvailableProfiles.contains(rap))
538 .collect(toSet());
539
540 if (!notFoundRequiredProfiles.isEmpty()) {
541
542 final String message = MessageFormatter.format(
543 "The requested profiles {} could not be activated or deactivated because they do not"
544 + " exist.",
545 notFoundRequiredProfiles)
546 .getMessage();
547 addExceptionToResult(session.getResult(), new MissingProfilesException(message));
548 }
549 }
550
551
552
553
554
555
556 private void validateOptionalProjects(MavenExecutionRequest request, MavenSession session) {
557 final ProjectActivation projectActivation = request.getProjectActivation();
558 final Set<String> allOptionalSelectors = new HashSet<>();
559 allOptionalSelectors.addAll(projectActivation.getOptionalActiveProjectSelectors());
560 allOptionalSelectors.addAll(projectActivation.getRequiredActiveProjectSelectors());
561
562
563 projectSelector.getOptionalProjectsBySelectors(request, session.getAllProjects(), allOptionalSelectors);
564 }
565
566
567
568
569
570
571 private void validateOptionalProfiles(MavenSession session, ProfileActivation profileActivation) {
572 final Set<String> allAvailableProfiles = getAllProfiles(session);
573
574 final Set<String> optionalProfiles = new HashSet<>();
575 optionalProfiles.addAll(profileActivation.getOptionalActiveProfileIds());
576 optionalProfiles.addAll(profileActivation.getOptionalInactiveProfileIds());
577
578 final Set<String> notFoundOptionalProfiles = optionalProfiles.stream()
579 .filter(rap -> !allAvailableProfiles.contains(rap))
580 .collect(toSet());
581
582 if (!notFoundOptionalProfiles.isEmpty()) {
583 logger.info(
584 "The requested optional profiles {} could not be activated or deactivated because they do not"
585 + " exist.",
586 notFoundOptionalProfiles);
587 }
588 }
589
590 private Map<String, MavenProject> getProjectMap(Collection<MavenProject> projects)
591 throws DuplicateProjectException {
592 Map<String, MavenProject> index = new LinkedHashMap<>();
593 Map<String, List<File>> collisions = new LinkedHashMap<>();
594
595 for (MavenProject project : projects) {
596 String projectId = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion());
597
598 MavenProject collision = index.get(projectId);
599
600 if (collision == null) {
601 index.put(projectId, project);
602 } else {
603 List<File> pomFiles = collisions.get(projectId);
604
605 if (pomFiles == null) {
606 pomFiles = new ArrayList<>(Arrays.asList(collision.getFile(), project.getFile()));
607 collisions.put(projectId, pomFiles);
608 } else {
609 pomFiles.add(project.getFile());
610 }
611 }
612 }
613
614 if (!collisions.isEmpty()) {
615 throw new DuplicateProjectException(
616 "Two or more projects in the reactor"
617 + " have the same identifier, please make sure that <groupId>:<artifactId>:<version>"
618 + " is unique for each project: " + collisions,
619 collisions);
620 }
621
622 return index;
623 }
624
625 private Result<? extends ProjectDependencyGraph> buildGraph(MavenSession session) {
626 Result<? extends ProjectDependencyGraph> graphResult = graphBuilder.build(session);
627 for (ModelProblem problem : graphResult.getProblems()) {
628 if (problem.getSeverity() == ModelProblem.Severity.WARNING) {
629 logger.warn(problem.getMessage());
630 } else {
631 logger.error(problem.getMessage());
632 }
633 }
634
635 if (!graphResult.hasErrors()) {
636 ProjectDependencyGraph projectDependencyGraph = graphResult.get();
637 session.setProjects(projectDependencyGraph.getSortedProjects());
638 session.setAllProjects(projectDependencyGraph.getAllProjects());
639 session.setProjectDependencyGraph(projectDependencyGraph);
640 }
641
642 return graphResult;
643 }
644
645 @Deprecated
646
647 protected Logger getLogger() {
648 return logger;
649 }
650 }