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;
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.util.ArrayList;
27  import java.util.Arrays;
28  import java.util.Collection;
29  import java.util.Collections;
30  import java.util.Date;
31  import java.util.HashSet;
32  import java.util.LinkedHashMap;
33  import java.util.LinkedHashSet;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.Set;
37  import java.util.function.Function;
38  import java.util.stream.Stream;
39  
40  import org.apache.maven.api.Session;
41  import org.apache.maven.api.model.Model;
42  import org.apache.maven.api.model.Prerequisites;
43  import org.apache.maven.api.model.Profile;
44  import org.apache.maven.artifact.ArtifactUtils;
45  import org.apache.maven.execution.BuildResumptionAnalyzer;
46  import org.apache.maven.execution.BuildResumptionDataRepository;
47  import org.apache.maven.execution.BuildResumptionPersistenceException;
48  import org.apache.maven.execution.DefaultMavenExecutionResult;
49  import org.apache.maven.execution.ExecutionEvent;
50  import org.apache.maven.execution.MavenExecutionRequest;
51  import org.apache.maven.execution.MavenExecutionResult;
52  import org.apache.maven.execution.MavenSession;
53  import org.apache.maven.execution.ProfileActivation;
54  import org.apache.maven.execution.ProjectActivation;
55  import org.apache.maven.execution.ProjectDependencyGraph;
56  import org.apache.maven.graph.GraphBuilder;
57  import org.apache.maven.graph.ProjectSelector;
58  import org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory;
59  import org.apache.maven.internal.aether.MavenChainedWorkspaceReader;
60  import org.apache.maven.internal.impl.DefaultSession;
61  import org.apache.maven.internal.impl.DefaultSessionFactory;
62  import org.apache.maven.lifecycle.LifecycleExecutionException;
63  import org.apache.maven.lifecycle.internal.ExecutionEventCatapult;
64  import org.apache.maven.lifecycle.internal.LifecycleStarter;
65  import org.apache.maven.model.building.ModelProblem;
66  import org.apache.maven.model.building.Result;
67  import org.apache.maven.model.superpom.SuperPomProvider;
68  import org.apache.maven.plugin.LegacySupport;
69  import org.apache.maven.project.MavenProject;
70  import org.apache.maven.project.ProjectBuilder;
71  import org.apache.maven.repository.LocalRepositoryNotAccessibleException;
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   * @author Jason van Zyl
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(); // if necessary switch to DI
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             // TODO Hack to make the cycle detection the same for the new graph builder
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     // 1) Setup initial properties.
173     //
174     // 2) Validate local repository directory is accessible.
175     //
176     // 3) Create RepositorySystemSession.
177     //
178     // 4) Create MavenSession.
179     //
180     // 5) Execute AbstractLifecycleParticipant.afterSessionStart(session)
181     //
182     // 6) Get reactor projects looking for general POM errors
183     //
184     // 7) Create ProjectDependencyGraph using trimming which takes into account --projects and reactor mode.
185     // This ensures that the projects passed into the ReactorReader are only those specified.
186     //
187     // 8) Create ReactorReader with the getProjectMap( projects ). NOTE that getProjectMap(projects) is the code that
188     // checks for duplicate projects definitions in the build. Ideally this type of duplicate checking should be
189     // part of getting the reactor projects in 6). The duplicate checking is conflated with getProjectMap(projects).
190     //
191     // 9) Execute AbstractLifecycleParticipant.afterProjectsRead(session)
192     //
193     // 10) Create ProjectDependencyGraph without trimming (as trimming was done in 7). A new topological sort is
194     // required after the execution of 9) as the AbstractLifecycleParticipants are free to mutate the MavenProject
195     // instances, which may change dependencies which can, in turn, affect the build order.
196     //
197     // 11) Execute LifecycleStarter.start()
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 (LocalRepositoryNotAccessibleException e) {
208             return addExceptionToResult(result, e);
209         }
210 
211         //
212         // We enter the session scope right after the MavenSession creation and before any of the
213         // AbstractLifecycleParticipant lookups
214         // so that @SessionScoped components can be @Injected into AbstractLifecycleParticipants.
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         // The projects need to be topologically after the participants have run their afterProjectsRead(session)
281         // because the participant is free to change the dependencies of a project which can potentially change the
282         // topological order of the projects, and therefore can potentially change the build order.
283         //
284         // Note that participants may affect the topological order of the projects but it is
285         // not expected that a participant will add or remove projects from the session.
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.getProjects(), 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         // Desired order of precedence for workspace readers before querying the local artifact repositories
342         List<WorkspaceReader> workspaceReaders = new ArrayList<>();
343         // 1) Reactor workspace reader
344         WorkspaceReader reactorReader = container.lookup(WorkspaceReader.class, ReactorReader.HINT);
345         workspaceReaders.add(reactorReader);
346         // 2) Repository system session-scoped workspace reader
347         WorkspaceReader repoWorkspaceReader = repoSession.getWorkspaceReader();
348         if (repoWorkspaceReader != null && repoWorkspaceReader != reactorReader) {
349             workspaceReaders.add(repoWorkspaceReader);
350         }
351         // 3) .. n) Project-scoped workspace readers
352         for (WorkspaceReader workspaceReader :
353                 getProjectScopedExtensionComponents(session.getProjects(), WorkspaceReader.class)) {
354             if (workspaceReaders.contains(workspaceReader)) {
355                 continue;
356             }
357             workspaceReaders.add(workspaceReader);
358         }
359         repoSession.setWorkspaceReader(MavenChainedWorkspaceReader.of(workspaceReaders));
360     }
361 
362     private void afterSessionStart(MavenSession session) throws MavenExecutionException {
363         // CHECKSTYLE_OFF: LineLength
364         for (AbstractMavenLifecycleParticipant listener :
365                 getExtensionComponents(Collections.emptyList(), AbstractMavenLifecycleParticipant.class))
366         // CHECKSTYLE_ON: LineLength
367         {
368             listener.afterSessionStart(session);
369         }
370     }
371 
372     private void afterProjectsRead(MavenSession session) throws MavenExecutionException {
373         ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
374         try {
375             // CHECKSTYLE_OFF: LineLength
376             for (AbstractMavenLifecycleParticipant listener :
377                     getExtensionComponents(session.getProjects(), AbstractMavenLifecycleParticipant.class))
378             // CHECKSTYLE_ON: LineLength
379             {
380                 Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
381 
382                 listener.afterProjectsRead(session);
383             }
384         } finally {
385             Thread.currentThread().setContextClassLoader(originalClassLoader);
386         }
387     }
388 
389     private void afterSessionEnd(Collection<MavenProject> projects, MavenSession session)
390             throws MavenExecutionException {
391         ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
392         try {
393             // CHECKSTYLE_OFF: LineLength
394             for (AbstractMavenLifecycleParticipant listener :
395                     getExtensionComponents(projects, AbstractMavenLifecycleParticipant.class))
396             // CHECKSTYLE_ON: LineLength
397             {
398                 Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
399 
400                 listener.afterSessionEnd(session);
401             }
402         } finally {
403             Thread.currentThread().setContextClassLoader(originalClassLoader);
404         }
405     }
406 
407     private void persistResumptionData(MavenExecutionResult result, MavenSession session) {
408         boolean hasLifecycleExecutionExceptions =
409                 result.getExceptions().stream().anyMatch(LifecycleExecutionException.class::isInstance);
410 
411         if (hasLifecycleExecutionExceptions) {
412             MavenProject rootProject = session.getAllProjects().stream()
413                     .filter(MavenProject::isExecutionRoot)
414                     .findFirst()
415                     .orElseThrow(() -> new IllegalStateException("No project in the session is execution root"));
416 
417             buildResumptionAnalyzer.determineBuildResumptionData(result).ifPresent(resumption -> {
418                 try {
419                     buildResumptionDataRepository.persistResumptionData(rootProject, resumption);
420                     result.setCanResume(true);
421                 } catch (BuildResumptionPersistenceException e) {
422                     logger.warn("Could not persist build resumption data", e);
423                 }
424             });
425         }
426     }
427 
428     public RepositorySystemSession newRepositorySession(MavenExecutionRequest request) {
429         return repositorySessionFactory.newRepositorySession(request);
430     }
431 
432     private void validateLocalRepository(MavenExecutionRequest request) throws LocalRepositoryNotAccessibleException {
433         File localRepoDir = request.getLocalRepositoryPath();
434 
435         logger.debug("Using local repository at " + localRepoDir);
436 
437         localRepoDir.mkdirs();
438 
439         if (!localRepoDir.isDirectory()) {
440             throw new LocalRepositoryNotAccessibleException("Could not create local repository at " + localRepoDir);
441         }
442     }
443 
444     private <T> Collection<T> getExtensionComponents(Collection<MavenProject> projects, Class<T> role) {
445         Collection<T> foundComponents = new LinkedHashSet<>();
446 
447         try {
448             foundComponents.addAll(container.lookupList(role));
449         } catch (ComponentLookupException e) {
450             // this is just silly, lookupList should return an empty list!
451             logger.warn("Failed to lookup " + role + ": " + e.getMessage());
452         }
453 
454         foundComponents.addAll(getProjectScopedExtensionComponents(projects, role));
455 
456         return foundComponents;
457     }
458 
459     protected <T> Collection<T> getProjectScopedExtensionComponents(Collection<MavenProject> projects, Class<T> role) {
460 
461         Collection<T> foundComponents = new LinkedHashSet<>();
462         Collection<ClassLoader> scannedRealms = new HashSet<>();
463 
464         Thread currentThread = Thread.currentThread();
465         ClassLoader originalContextClassLoader = currentThread.getContextClassLoader();
466         try {
467             for (MavenProject project : projects) {
468                 ClassLoader projectRealm = project.getClassRealm();
469 
470                 if (projectRealm != null && scannedRealms.add(projectRealm)) {
471                     currentThread.setContextClassLoader(projectRealm);
472 
473                     try {
474                         foundComponents.addAll(container.lookupList(role));
475                     } catch (ComponentLookupException e) {
476                         // this is just silly, lookupList should return an empty list!
477                         logger.warn("Failed to lookup " + role + ": " + e.getMessage());
478                     }
479                 }
480             }
481             return foundComponents;
482         } finally {
483             currentThread.setContextClassLoader(originalContextClassLoader);
484         }
485     }
486 
487     private MavenExecutionResult addExceptionToResult(MavenExecutionResult result, Throwable e) {
488         if (!result.getExceptions().contains(e)) {
489             result.addException(e);
490         }
491 
492         return result;
493     }
494 
495     private void validatePrerequisitesForNonMavenPluginProjects(List<MavenProject> projects) {
496         for (MavenProject mavenProject : projects) {
497             if (!"maven-plugin".equals(mavenProject.getPackaging())) {
498                 Prerequisites prerequisites =
499                         mavenProject.getModel().getDelegate().getPrerequisites();
500                 if (prerequisites != null && prerequisites.getMaven() != null) {
501                     logger.warn("The project " + mavenProject.getId() + " uses prerequisites"
502                             + " which is only intended for maven-plugin projects "
503                             + "but not for non maven-plugin projects. "
504                             + "For such purposes you should use the maven-enforcer-plugin. "
505                             + "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html");
506                 }
507             }
508         }
509     }
510 
511     /**
512      * Get all profiles that are detected in the projects, any parent of the projects, or the settings.
513      * @param session The Maven session
514      * @return A {@link Set} of profile identifiers, never {@code null}.
515      */
516     private Set<String> getAllProfiles(MavenSession session) {
517         final Model superPomModel = superPomProvider.getSuperModel("4.0.0");
518         final Set<MavenProject> projectsIncludingParents = new HashSet<>();
519         for (MavenProject project : session.getProjects()) {
520             boolean isAdded = projectsIncludingParents.add(project);
521             MavenProject parent = project.getParent();
522             while (isAdded && parent != null) {
523                 isAdded = projectsIncludingParents.add(parent);
524                 parent = parent.getParent();
525             }
526         }
527 
528         final Stream<String> projectProfiles = projectsIncludingParents.stream()
529                 .flatMap(p -> p.getModel().getDelegate().getProfiles().stream())
530                 .map(Profile::getId);
531         final Stream<String> settingsProfiles =
532                 session.getSettings().getProfiles().stream().map(org.apache.maven.settings.Profile::getId);
533         final Stream<String> superPomProfiles =
534                 superPomModel.getProfiles().stream().map(Profile::getId);
535 
536         return Stream.of(projectProfiles, settingsProfiles, superPomProfiles)
537                 .flatMap(Function.identity())
538                 .collect(toSet());
539     }
540 
541     /**
542      * Check whether the required profiles were found in any of the projects we're building or the settings.
543      * @param session the Maven session.
544      * @param profileActivation the requested optional and required profiles.
545      */
546     private void validateRequiredProfiles(MavenSession session, ProfileActivation profileActivation) {
547         final Set<String> allAvailableProfiles = getAllProfiles(session);
548 
549         final Set<String> requiredProfiles = new HashSet<>();
550         requiredProfiles.addAll(profileActivation.getRequiredActiveProfileIds());
551         requiredProfiles.addAll(profileActivation.getRequiredInactiveProfileIds());
552 
553         // Check whether the required profiles were found in any of the projects we're building.
554         final Set<String> notFoundRequiredProfiles = requiredProfiles.stream()
555                 .filter(rap -> !allAvailableProfiles.contains(rap))
556                 .collect(toSet());
557 
558         if (!notFoundRequiredProfiles.isEmpty()) {
559             // Use SLF4J formatter for consistency with warnings reported by logger
560             final String message = MessageFormatter.format(
561                             "The requested profiles {} could not be activated or deactivated because they do not"
562                                     + " exist.",
563                             notFoundRequiredProfiles)
564                     .getMessage();
565             addExceptionToResult(session.getResult(), new MissingProfilesException(message));
566         }
567     }
568 
569     /**
570      * Check whether any of the requested optional projects were not activated or deactivated.
571      * @param request the {@link MavenExecutionRequest}.
572      * @param session the {@link MavenSession}.
573      */
574     private void validateOptionalProjects(MavenExecutionRequest request, MavenSession session) {
575         final ProjectActivation projectActivation = request.getProjectActivation();
576         final Set<String> allOptionalSelectors = new HashSet<>();
577         allOptionalSelectors.addAll(projectActivation.getOptionalActiveProjectSelectors());
578         allOptionalSelectors.addAll(projectActivation.getRequiredActiveProjectSelectors());
579         // We intentionally ignore the results of this method.
580         // As a side effect it will log the optional projects that could not be resolved.
581         projectSelector.getOptionalProjectsBySelectors(request, session.getAllProjects(), allOptionalSelectors);
582     }
583 
584     /**
585      * Check whether any of the requested optional profiles were not activated or deactivated.
586      * @param session the Maven session.
587      * @param profileActivation the requested optional and required profiles.
588      */
589     private void validateOptionalProfiles(MavenSession session, ProfileActivation profileActivation) {
590         final Set<String> allAvailableProfiles = getAllProfiles(session);
591 
592         final Set<String> optionalProfiles = new HashSet<>();
593         optionalProfiles.addAll(profileActivation.getOptionalActiveProfileIds());
594         optionalProfiles.addAll(profileActivation.getOptionalInactiveProfileIds());
595 
596         final Set<String> notFoundOptionalProfiles = optionalProfiles.stream()
597                 .filter(rap -> !allAvailableProfiles.contains(rap))
598                 .collect(toSet());
599 
600         if (!notFoundOptionalProfiles.isEmpty()) {
601             logger.info(
602                     "The requested optional profiles {} could not be activated or deactivated because they do not"
603                             + " exist.",
604                     notFoundOptionalProfiles);
605         }
606     }
607 
608     private Map<String, MavenProject> getProjectMap(Collection<MavenProject> projects)
609             throws DuplicateProjectException {
610         Map<String, MavenProject> index = new LinkedHashMap<>();
611         Map<String, List<File>> collisions = new LinkedHashMap<>();
612 
613         for (MavenProject project : projects) {
614             String projectId = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion());
615 
616             MavenProject collision = index.get(projectId);
617 
618             if (collision == null) {
619                 index.put(projectId, project);
620             } else {
621                 List<File> pomFiles = collisions.get(projectId);
622 
623                 if (pomFiles == null) {
624                     pomFiles = new ArrayList<>(Arrays.asList(collision.getFile(), project.getFile()));
625                     collisions.put(projectId, pomFiles);
626                 } else {
627                     pomFiles.add(project.getFile());
628                 }
629             }
630         }
631 
632         if (!collisions.isEmpty()) {
633             throw new DuplicateProjectException(
634                     "Two or more projects in the reactor"
635                             + " have the same identifier, please make sure that <groupId>:<artifactId>:<version>"
636                             + " is unique for each project: " + collisions,
637                     collisions);
638         }
639 
640         return index;
641     }
642 
643     private Result<? extends ProjectDependencyGraph> buildGraph(MavenSession session) {
644         Result<? extends ProjectDependencyGraph> graphResult = graphBuilder.build(session);
645         for (ModelProblem problem : graphResult.getProblems()) {
646             if (problem.getSeverity() == ModelProblem.Severity.WARNING) {
647                 logger.warn(problem.getMessage());
648             } else {
649                 logger.error(problem.getMessage());
650             }
651         }
652 
653         if (!graphResult.hasErrors()) {
654             ProjectDependencyGraph projectDependencyGraph = graphResult.get();
655             session.setProjects(projectDependencyGraph.getSortedProjects());
656             session.setAllProjects(projectDependencyGraph.getAllProjects());
657             session.setProjectDependencyGraph(projectDependencyGraph);
658         }
659 
660         return graphResult;
661     }
662 
663     @Deprecated
664     // 5 January 2014
665     protected Logger getLogger() {
666         return logger;
667     }
668 }