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.HashMap;
33 import java.util.HashSet;
34 import java.util.LinkedHashMap;
35 import java.util.LinkedHashSet;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.function.Function;
40 import java.util.stream.Stream;
41
42 import org.apache.maven.api.Session;
43 import org.apache.maven.api.model.Model;
44 import org.apache.maven.api.model.Prerequisites;
45 import org.apache.maven.api.model.Profile;
46 import org.apache.maven.artifact.ArtifactUtils;
47 import org.apache.maven.execution.BuildResumptionAnalyzer;
48 import org.apache.maven.execution.BuildResumptionDataRepository;
49 import org.apache.maven.execution.BuildResumptionPersistenceException;
50 import org.apache.maven.execution.DefaultMavenExecutionResult;
51 import org.apache.maven.execution.ExecutionEvent;
52 import org.apache.maven.execution.MavenExecutionRequest;
53 import org.apache.maven.execution.MavenExecutionResult;
54 import org.apache.maven.execution.MavenSession;
55 import org.apache.maven.execution.ProfileActivation;
56 import org.apache.maven.execution.ProjectActivation;
57 import org.apache.maven.execution.ProjectDependencyGraph;
58 import org.apache.maven.graph.GraphBuilder;
59 import org.apache.maven.graph.ProjectSelector;
60 import org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory;
61 import org.apache.maven.internal.aether.MavenChainedWorkspaceReader;
62 import org.apache.maven.internal.impl.DefaultSession;
63 import org.apache.maven.internal.impl.DefaultSessionFactory;
64 import org.apache.maven.lifecycle.LifecycleExecutionException;
65 import org.apache.maven.lifecycle.internal.ExecutionEventCatapult;
66 import org.apache.maven.lifecycle.internal.LifecycleStarter;
67 import org.apache.maven.model.building.ModelProblem;
68 import org.apache.maven.model.building.Result;
69 import org.apache.maven.model.superpom.SuperPomProvider;
70 import org.apache.maven.plugin.LegacySupport;
71 import org.apache.maven.project.MavenProject;
72 import org.apache.maven.project.ProjectBuilder;
73 import org.apache.maven.session.scope.internal.SessionScope;
74 import org.codehaus.plexus.PlexusContainer;
75 import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
76 import org.eclipse.aether.DefaultRepositorySystemSession;
77 import org.eclipse.aether.RepositorySystemSession;
78 import org.eclipse.aether.repository.WorkspaceReader;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import org.slf4j.helpers.MessageFormatter;
82
83 import static java.util.stream.Collectors.toSet;
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(
484 "The project {} uses prerequisites"
485 + " which is only intended for maven-plugin projects "
486 + "but not for non maven-plugin projects. "
487 + "For such purposes you should use the maven-enforcer-plugin. "
488 + "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html",
489 mavenProject.getId());
490 }
491 }
492 }
493 }
494
495
496
497
498
499
500 private Set<String> getAllProfiles(MavenSession session) {
501 final Map<String, Model> superPomModels = new HashMap<>();
502 final Set<MavenProject> projectsIncludingParents = new HashSet<>();
503 for (MavenProject project : session.getProjects()) {
504 superPomModels.computeIfAbsent(
505 project.getModelVersion(),
506 v -> superPomProvider.getSuperModel(v).getDelegate());
507 boolean isAdded = projectsIncludingParents.add(project);
508 MavenProject parent = project.getParent();
509 while (isAdded && parent != null) {
510 isAdded = projectsIncludingParents.add(parent);
511 parent = parent.getParent();
512 }
513 }
514
515 final Stream<String> projectProfiles = projectsIncludingParents.stream()
516 .flatMap(p -> p.getModel().getDelegate().getProfiles().stream())
517 .map(Profile::getId);
518 final Stream<String> settingsProfiles =
519 session.getSettings().getProfiles().stream().map(org.apache.maven.settings.Profile::getId);
520 final Stream<String> superPomProfiles = superPomModels.values().stream()
521 .flatMap(p -> p.getProfiles().stream())
522 .map(Profile::getId);
523
524 return Stream.of(projectProfiles, settingsProfiles, superPomProfiles)
525 .flatMap(Function.identity())
526 .collect(toSet());
527 }
528
529
530
531
532
533
534 private void validateRequiredProfiles(MavenSession session, ProfileActivation profileActivation) {
535 final Set<String> allAvailableProfiles = getAllProfiles(session);
536
537 final Set<String> requiredProfiles = new HashSet<>();
538 requiredProfiles.addAll(profileActivation.getRequiredActiveProfileIds());
539 requiredProfiles.addAll(profileActivation.getRequiredInactiveProfileIds());
540
541
542 final Set<String> notFoundRequiredProfiles = requiredProfiles.stream()
543 .filter(rap -> !allAvailableProfiles.contains(rap))
544 .collect(toSet());
545
546 if (!notFoundRequiredProfiles.isEmpty()) {
547
548 final String message = MessageFormatter.format(
549 "The requested profiles {} could not be activated or deactivated because they do not"
550 + " exist.",
551 notFoundRequiredProfiles)
552 .getMessage();
553 addExceptionToResult(session.getResult(), new MissingProfilesException(message));
554 }
555 }
556
557
558
559
560
561
562 private void validateOptionalProjects(MavenExecutionRequest request, MavenSession session) {
563 final ProjectActivation projectActivation = request.getProjectActivation();
564 final Set<String> allOptionalSelectors = new HashSet<>();
565 allOptionalSelectors.addAll(projectActivation.getOptionalActiveProjectSelectors());
566 allOptionalSelectors.addAll(projectActivation.getRequiredActiveProjectSelectors());
567
568
569 projectSelector.getOptionalProjectsBySelectors(request, session.getAllProjects(), allOptionalSelectors);
570 }
571
572
573
574
575
576
577 private void validateOptionalProfiles(MavenSession session, ProfileActivation profileActivation) {
578 final Set<String> allAvailableProfiles = getAllProfiles(session);
579
580 final Set<String> optionalProfiles = new HashSet<>();
581 optionalProfiles.addAll(profileActivation.getOptionalActiveProfileIds());
582 optionalProfiles.addAll(profileActivation.getOptionalInactiveProfileIds());
583
584 final Set<String> notFoundOptionalProfiles = optionalProfiles.stream()
585 .filter(rap -> !allAvailableProfiles.contains(rap))
586 .collect(toSet());
587
588 if (!notFoundOptionalProfiles.isEmpty()) {
589 logger.info(
590 "The requested optional profiles {} could not be activated or deactivated because they do not"
591 + " exist.",
592 notFoundOptionalProfiles);
593 }
594 }
595
596 private Map<String, MavenProject> getProjectMap(Collection<MavenProject> projects)
597 throws DuplicateProjectException {
598 Map<String, MavenProject> index = new LinkedHashMap<>();
599 Map<String, List<File>> collisions = new LinkedHashMap<>();
600
601 for (MavenProject project : projects) {
602 String projectId = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion());
603
604 MavenProject collision = index.get(projectId);
605
606 if (collision == null) {
607 index.put(projectId, project);
608 } else {
609 List<File> pomFiles = collisions.get(projectId);
610
611 if (pomFiles == null) {
612 pomFiles = new ArrayList<>(Arrays.asList(collision.getFile(), project.getFile()));
613 collisions.put(projectId, pomFiles);
614 } else {
615 pomFiles.add(project.getFile());
616 }
617 }
618 }
619
620 if (!collisions.isEmpty()) {
621 throw new DuplicateProjectException(
622 "Two or more projects in the reactor"
623 + " have the same identifier, please make sure that <groupId>:<artifactId>:<version>"
624 + " is unique for each project: " + collisions,
625 collisions);
626 }
627
628 return index;
629 }
630
631 private Result<? extends ProjectDependencyGraph> buildGraph(MavenSession session) {
632 Result<? extends ProjectDependencyGraph> graphResult = graphBuilder.build(session);
633 for (ModelProblem problem : graphResult.getProblems()) {
634 if (problem.getSeverity() == ModelProblem.Severity.WARNING) {
635 logger.warn(problem.getMessage());
636 } else {
637 logger.error(problem.getMessage());
638 }
639 }
640
641 if (!graphResult.hasErrors()) {
642 ProjectDependencyGraph projectDependencyGraph = graphResult.get();
643 session.setProjects(projectDependencyGraph.getSortedProjects());
644 session.setAllProjects(projectDependencyGraph.getAllProjects());
645 session.setProjectDependencyGraph(projectDependencyGraph);
646 }
647
648 return graphResult;
649 }
650
651 @Deprecated
652
653 protected Logger getLogger() {
654 return logger;
655 }
656 }