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.model.building;
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.Collection;
29  import java.util.Collections;
30  import java.util.HashMap;
31  import java.util.Iterator;
32  import java.util.LinkedHashSet;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.Objects;
36  import java.util.Optional;
37  import java.util.Properties;
38  import java.util.function.Consumer;
39  import java.util.stream.IntStream;
40  
41  import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
42  import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
43  import org.apache.maven.artifact.versioning.VersionRange;
44  import org.apache.maven.model.Activation;
45  import org.apache.maven.model.Build;
46  import org.apache.maven.model.Dependency;
47  import org.apache.maven.model.DependencyManagement;
48  import org.apache.maven.model.InputLocation;
49  import org.apache.maven.model.InputLocationTracker;
50  import org.apache.maven.model.InputSource;
51  import org.apache.maven.model.Model;
52  import org.apache.maven.model.Parent;
53  import org.apache.maven.model.Plugin;
54  import org.apache.maven.model.PluginManagement;
55  import org.apache.maven.model.Profile;
56  import org.apache.maven.model.Repository;
57  import org.apache.maven.model.building.ModelProblem.Severity;
58  import org.apache.maven.model.building.ModelProblem.Version;
59  import org.apache.maven.model.composition.DependencyManagementImporter;
60  import org.apache.maven.model.inheritance.InheritanceAssembler;
61  import org.apache.maven.model.interpolation.AbstractStringBasedModelInterpolator;
62  import org.apache.maven.model.interpolation.ModelInterpolator;
63  import org.apache.maven.model.io.ModelParseException;
64  import org.apache.maven.model.management.DependencyManagementInjector;
65  import org.apache.maven.model.management.PluginManagementInjector;
66  import org.apache.maven.model.normalization.ModelNormalizer;
67  import org.apache.maven.model.path.ModelPathTranslator;
68  import org.apache.maven.model.path.ModelUrlNormalizer;
69  import org.apache.maven.model.path.ProfileActivationFilePathInterpolator;
70  import org.apache.maven.model.plugin.LifecycleBindingsInjector;
71  import org.apache.maven.model.plugin.PluginConfigurationExpander;
72  import org.apache.maven.model.plugin.ReportConfigurationExpander;
73  import org.apache.maven.model.plugin.ReportingConverter;
74  import org.apache.maven.model.profile.DefaultProfileActivationContext;
75  import org.apache.maven.model.profile.ProfileActivationContext;
76  import org.apache.maven.model.profile.ProfileInjector;
77  import org.apache.maven.model.profile.ProfileSelector;
78  import org.apache.maven.model.resolution.InvalidRepositoryException;
79  import org.apache.maven.model.resolution.ModelResolver;
80  import org.apache.maven.model.resolution.UnresolvableModelException;
81  import org.apache.maven.model.resolution.WorkspaceModelResolver;
82  import org.apache.maven.model.superpom.SuperPomProvider;
83  import org.apache.maven.model.validation.ModelValidator;
84  import org.codehaus.plexus.interpolation.InterpolationException;
85  import org.codehaus.plexus.interpolation.MapBasedValueSource;
86  import org.codehaus.plexus.interpolation.RegexBasedInterpolator;
87  import org.codehaus.plexus.interpolation.StringSearchInterpolator;
88  import org.codehaus.plexus.util.StringUtils;
89  import org.eclipse.sisu.Nullable;
90  
91  import static org.apache.maven.model.building.Result.error;
92  import static org.apache.maven.model.building.Result.newResult;
93  
94  /**
95   * @author Benjamin Bentmann
96   */
97  @Named
98  @Singleton
99  public class DefaultModelBuilder implements ModelBuilder {
100     @Inject
101     private ModelProcessor modelProcessor;
102 
103     @Inject
104     private ModelValidator modelValidator;
105 
106     @Inject
107     private ModelNormalizer modelNormalizer;
108 
109     @Inject
110     private ModelInterpolator modelInterpolator;
111 
112     @Inject
113     private ModelPathTranslator modelPathTranslator;
114 
115     @Inject
116     private ModelUrlNormalizer modelUrlNormalizer;
117 
118     @Inject
119     private SuperPomProvider superPomProvider;
120 
121     @Inject
122     private InheritanceAssembler inheritanceAssembler;
123 
124     @Inject
125     private ProfileSelector profileSelector;
126 
127     @Inject
128     private ProfileInjector profileInjector;
129 
130     @Inject
131     private PluginManagementInjector pluginManagementInjector;
132 
133     @Inject
134     private DependencyManagementInjector dependencyManagementInjector;
135 
136     @Inject
137     private DependencyManagementImporter dependencyManagementImporter;
138 
139     @Inject
140     @Nullable
141     private LifecycleBindingsInjector lifecycleBindingsInjector;
142 
143     @Inject
144     private PluginConfigurationExpander pluginConfigurationExpander;
145 
146     @Inject
147     private ReportConfigurationExpander reportConfigurationExpander;
148 
149     @Inject
150     private ReportingConverter reportingConverter;
151 
152     @Inject
153     private ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator;
154 
155     public DefaultModelBuilder setModelProcessor(ModelProcessor modelProcessor) {
156         this.modelProcessor = modelProcessor;
157         return this;
158     }
159 
160     public DefaultModelBuilder setModelValidator(ModelValidator modelValidator) {
161         this.modelValidator = modelValidator;
162         return this;
163     }
164 
165     public DefaultModelBuilder setModelNormalizer(ModelNormalizer modelNormalizer) {
166         this.modelNormalizer = modelNormalizer;
167         return this;
168     }
169 
170     public DefaultModelBuilder setModelInterpolator(ModelInterpolator modelInterpolator) {
171         this.modelInterpolator = modelInterpolator;
172         return this;
173     }
174 
175     public DefaultModelBuilder setModelPathTranslator(ModelPathTranslator modelPathTranslator) {
176         this.modelPathTranslator = modelPathTranslator;
177         return this;
178     }
179 
180     public DefaultModelBuilder setModelUrlNormalizer(ModelUrlNormalizer modelUrlNormalizer) {
181         this.modelUrlNormalizer = modelUrlNormalizer;
182         return this;
183     }
184 
185     public DefaultModelBuilder setSuperPomProvider(SuperPomProvider superPomProvider) {
186         this.superPomProvider = superPomProvider;
187         return this;
188     }
189 
190     public DefaultModelBuilder setProfileSelector(ProfileSelector profileSelector) {
191         this.profileSelector = profileSelector;
192         return this;
193     }
194 
195     public DefaultModelBuilder setProfileInjector(ProfileInjector profileInjector) {
196         this.profileInjector = profileInjector;
197         return this;
198     }
199 
200     public DefaultModelBuilder setInheritanceAssembler(InheritanceAssembler inheritanceAssembler) {
201         this.inheritanceAssembler = inheritanceAssembler;
202         return this;
203     }
204 
205     public DefaultModelBuilder setDependencyManagementImporter(DependencyManagementImporter depMgmtImporter) {
206         this.dependencyManagementImporter = depMgmtImporter;
207         return this;
208     }
209 
210     public DefaultModelBuilder setDependencyManagementInjector(DependencyManagementInjector depMgmtInjector) {
211         this.dependencyManagementInjector = depMgmtInjector;
212         return this;
213     }
214 
215     public DefaultModelBuilder setLifecycleBindingsInjector(LifecycleBindingsInjector lifecycleBindingsInjector) {
216         this.lifecycleBindingsInjector = lifecycleBindingsInjector;
217         return this;
218     }
219 
220     public DefaultModelBuilder setPluginConfigurationExpander(PluginConfigurationExpander pluginConfigurationExpander) {
221         this.pluginConfigurationExpander = pluginConfigurationExpander;
222         return this;
223     }
224 
225     public DefaultModelBuilder setPluginManagementInjector(PluginManagementInjector pluginManagementInjector) {
226         this.pluginManagementInjector = pluginManagementInjector;
227         return this;
228     }
229 
230     public DefaultModelBuilder setReportConfigurationExpander(ReportConfigurationExpander reportConfigurationExpander) {
231         this.reportConfigurationExpander = reportConfigurationExpander;
232         return this;
233     }
234 
235     public DefaultModelBuilder setReportingConverter(ReportingConverter reportingConverter) {
236         this.reportingConverter = reportingConverter;
237         return this;
238     }
239 
240     public DefaultModelBuilder setProfileActivationFilePathInterpolator(
241             ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator) {
242         this.profileActivationFilePathInterpolator = profileActivationFilePathInterpolator;
243         return this;
244     }
245 
246     @SuppressWarnings("checkstyle:methodlength")
247     @Override
248     public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
249         return build(request, new LinkedHashSet<String>());
250     }
251 
252     @SuppressWarnings("checkstyle:methodlength")
253     protected ModelBuildingResult build(ModelBuildingRequest request, Collection<String> importIds)
254             throws ModelBuildingException {
255         // phase 1
256         DefaultModelBuildingResult result = new DefaultModelBuildingResult();
257 
258         DefaultModelProblemCollector problems = new DefaultModelProblemCollector(result);
259 
260         // read and validate raw model
261         Model inputModel = request.getRawModel();
262         if (inputModel == null) {
263             inputModel = readModel(request.getModelSource(), request.getPomFile(), request, problems);
264         }
265 
266         // profile activation
267         DefaultProfileActivationContext profileActivationContext = getProfileActivationContext(request, inputModel);
268 
269         problems.setSource("(external profiles)");
270         List<Profile> activeExternalProfiles =
271                 profileSelector.getActiveProfiles(request.getProfiles(), profileActivationContext, problems);
272 
273         result.setActiveExternalProfiles(activeExternalProfiles);
274 
275         if (!activeExternalProfiles.isEmpty()) {
276             Properties profileProps = new Properties();
277             for (Profile profile : activeExternalProfiles) {
278                 profileProps.putAll(profile.getProperties());
279             }
280             profileProps.putAll(profileActivationContext.getUserProperties());
281             profileActivationContext.setUserProperties(profileProps);
282         }
283 
284         problems.setRootModel(inputModel);
285 
286         ModelData resultData = new ModelData(request.getModelSource(), inputModel);
287         ModelData superData = new ModelData(null, getSuperModel());
288 
289         Collection<String> parentIds = new LinkedHashSet<>();
290         List<ModelData> lineage = new ArrayList<>();
291 
292         // Models resolved for dependency, parent or BOM POMs evaluate only platform-derived
293         // activation (JDK, OS, activeByDefault).
294         boolean externalModel = isExternalModelBuildingRequest(request);
295 
296         for (ModelData currentData = resultData; currentData != null; ) {
297             lineage.add(currentData);
298 
299             Model rawModel = currentData.getModel();
300             currentData.setRawModel(rawModel);
301 
302             Model tmpModel = rawModel.clone();
303             currentData.setModel(tmpModel);
304 
305             problems.setSource(tmpModel);
306 
307             // model normalization
308             modelNormalizer.mergeDuplicates(tmpModel, request, problems);
309 
310             profileActivationContext.setProjectProperties(tmpModel.getProperties());
311 
312             List<Profile> interpolatedProfiles = getInterpolatedProfiles(rawModel, profileActivationContext, problems);
313             tmpModel.setProfiles(interpolatedProfiles);
314 
315             List<Profile> profilesToEvaluate =
316                     externalModel ? withoutFileActivation(tmpModel.getProfiles()) : tmpModel.getProfiles();
317             List<Profile> activePomProfiles = profileSelector.getActiveProfiles(
318                     profilesToEvaluate,
319                     externalModel ? externalActivationContext(profileActivationContext) : profileActivationContext,
320                     problems);
321 
322             List<Profile> rawProfiles = new ArrayList<>();
323             for (Profile activePomProfile : activePomProfiles) {
324                 rawProfiles.add(rawModel.getProfiles().get(interpolatedProfiles.indexOf(activePomProfile)));
325             }
326             currentData.setActiveProfiles(rawProfiles);
327 
328             // profile injection
329             // TODO(#13146): repositories contributed by external-model profiles can shadow
330             // central; a WARN/FAIL policy for URL mismatches should be added separately.
331             for (Profile activeProfile : activePomProfiles) {
332                 profileInjector.injectProfile(tmpModel, activeProfile, request, problems);
333             }
334 
335             if (currentData == resultData) {
336                 for (Profile activeProfile : activeExternalProfiles) {
337                     profileInjector.injectProfile(tmpModel, activeProfile, request, problems);
338                 }
339             }
340 
341             if (currentData == superData) {
342                 break;
343             }
344 
345             configureResolver(request.getModelResolver(), tmpModel, problems);
346 
347             ModelData parentData = readParent(tmpModel, currentData.getSource(), request, problems);
348 
349             if (parentData == null) {
350                 currentData = superData;
351             } else if (currentData == resultData) { // First iteration - add initial id after version resolution.
352                 currentData.setGroupId(
353                         currentData.getRawModel().getGroupId() == null
354                                 ? parentData.getGroupId()
355                                 : currentData.getRawModel().getGroupId());
356 
357                 currentData.setVersion(
358                         currentData.getRawModel().getVersion() == null
359                                 ? parentData.getVersion()
360                                 : currentData.getRawModel().getVersion());
361 
362                 currentData.setArtifactId(currentData.getRawModel().getArtifactId());
363                 parentIds.add(currentData.getId());
364                 // Reset - only needed for 'getId'.
365                 currentData.setGroupId(null);
366                 currentData.setArtifactId(null);
367                 currentData.setVersion(null);
368                 currentData = parentData;
369             } else if (!parentIds.add(parentData.getId())) {
370                 String message = "The parents form a cycle: ";
371                 for (String modelId : parentIds) {
372                     message += modelId + " -> ";
373                 }
374                 message += parentData.getId();
375 
376                 problems.add(new ModelProblemCollectorRequest(ModelProblem.Severity.FATAL, ModelProblem.Version.BASE)
377                         .setMessage(message));
378 
379                 throw problems.newModelBuildingException();
380             } else {
381                 currentData = parentData;
382             }
383         }
384 
385         problems.setSource(inputModel);
386         checkPluginVersions(lineage, request, problems);
387 
388         // inheritance assembly
389         assembleInheritance(lineage, request, problems);
390 
391         Model resultModel = resultData.getModel();
392 
393         problems.setSource(resultModel);
394         problems.setRootModel(resultModel);
395 
396         // model interpolation
397         resultModel = interpolateModel(resultModel, request, problems);
398         resultData.setModel(resultModel);
399 
400         if (resultModel.getParent() != null) {
401             final ModelData parentData = lineage.get(1);
402             if (parentData.getVersion() == null || parentData.getVersion().contains("${")) {
403                 final Model interpolatedParent = interpolateModel(parentData.getModel(), request, problems);
404                 // parentData.setModel( interpolatedParent );
405                 parentData.setVersion(interpolatedParent.getVersion());
406             }
407         }
408 
409         // url normalization
410         modelUrlNormalizer.normalize(resultModel, request);
411 
412         // Now the fully interpolated model is available: reconfigure the resolver
413         configureResolver(request.getModelResolver(), resultModel, problems, true);
414 
415         resultData.setGroupId(resultModel.getGroupId());
416         resultData.setArtifactId(resultModel.getArtifactId());
417         resultData.setVersion(resultModel.getVersion());
418 
419         result.setEffectiveModel(resultModel);
420 
421         for (ModelData currentData : lineage) {
422             String modelId = (currentData != superData) ? currentData.getId() : "";
423 
424             result.addModelId(modelId);
425             result.setActivePomProfiles(modelId, currentData.getActiveProfiles());
426             result.setRawModel(modelId, currentData.getRawModel());
427         }
428 
429         if (!request.isTwoPhaseBuilding()) {
430             build(request, result, importIds);
431         }
432 
433         return result;
434     }
435 
436     @FunctionalInterface
437     private interface InterpolateString {
438         String apply(String s) throws InterpolationException;
439     }
440 
441     private List<Profile> getInterpolatedProfiles(
442             Model rawModel, DefaultProfileActivationContext context, DefaultModelProblemCollector problems) {
443         List<Profile> interpolatedActivations = getProfiles(rawModel, true);
444 
445         if (interpolatedActivations.isEmpty()) {
446             return Collections.emptyList();
447         }
448         RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
449 
450         interpolator.addValueSource(new MapBasedValueSource(context.getProjectProperties()));
451         interpolator.addValueSource(new MapBasedValueSource(context.getUserProperties()));
452         interpolator.addValueSource(new MapBasedValueSource(context.getSystemProperties()));
453 
454         class Interpolation {
455             final InputLocationTracker target;
456 
457             final InterpolateString impl;
458 
459             Interpolation(InputLocationTracker target, InterpolateString impl) {
460                 this.target = target;
461                 this.impl = impl;
462             }
463 
464             void performFor(String value, String locationKey, Consumer<String> mutator) {
465                 if (StringUtils.isEmpty(value)) {
466                     return;
467                 }
468                 try {
469                     mutator.accept(impl.apply(value));
470                 } catch (InterpolationException e) {
471                     problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
472                             .setMessage("Failed to interpolate value " + value + ": " + e.getMessage())
473                             .setLocation(target.getLocation(locationKey))
474                             .setException(e));
475                 }
476             }
477         }
478         for (Profile profile : interpolatedActivations) {
479             Activation activation = profile.getActivation();
480             Optional<Activation> a = Optional.ofNullable(activation);
481             a.map(Activation::getFile).ifPresent(fa -> {
482                 Interpolation nt =
483                         new Interpolation(fa, s -> profileActivationFilePathInterpolator.interpolate(s, context));
484                 nt.performFor(fa.getExists(), "exists", fa::setExists);
485                 nt.performFor(fa.getMissing(), "missing", fa::setMissing);
486             });
487             a.map(Activation::getOs).ifPresent(oa -> {
488                 Interpolation nt = new Interpolation(oa, interpolator::interpolate);
489                 nt.performFor(oa.getArch(), "arch", oa::setArch);
490                 nt.performFor(oa.getFamily(), "family", oa::setFamily);
491                 nt.performFor(oa.getName(), "name", oa::setName);
492                 nt.performFor(oa.getVersion(), "version", oa::setVersion);
493             });
494             a.map(Activation::getProperty).ifPresent(pa -> {
495                 Interpolation nt = new Interpolation(pa, interpolator::interpolate);
496                 nt.performFor(pa.getName(), "name", pa::setName);
497                 nt.performFor(pa.getValue(), "value", pa::setValue);
498             });
499             a.map(Activation::getJdk)
500                     .ifPresent(ja -> new Interpolation(activation, interpolator::interpolate)
501                             .performFor(ja, "jdk", activation::setJdk));
502         }
503         return interpolatedActivations;
504     }
505 
506     /**
507      * Determines whether the given request builds a model to resolve a dependency, i.e. a POM
508      * read from a remote repository (a dependency POM, one of its parents, or an imported BOM)
509      * rather than a POM belonging to the project being built. Such requests have no POM file
510      * (see {@link ModelBuildingRequest#setPomFile(File)}) and use
511      * {@link ModelBuildingRequest#VALIDATION_LEVEL_MINIMAL}, see for instance
512      * {@code DefaultArtifactDescriptorReader#loadPom}; a project build uses
513      * {@link ModelBuildingRequest#VALIDATION_LEVEL_MAVEN_2_0} or higher. A request with a POM file is in project
514      * mode whatever its validation level, so an embedder that builds its own project at
515      * {@code VALIDATION_LEVEL_MINIMAL} keeps full profile activation. A request that sets
516      * {@value AbstractStringBasedModelInterpolator#FULL_EXTERNAL_INTERPOLATION_PROPERTY} is never external, so
517      * that tools building their own projects at a low validation level can opt out.
518      */
519     private static boolean isExternalModelBuildingRequest(ModelBuildingRequest request) {
520         return request.getPomFile() == null
521                 && request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0
522                 && !AbstractStringBasedModelInterpolator.isFullExternalModelBuild(request);
523     }
524 
525     /**
526      * Returns a sandboxed {@link ProfileActivationContext} for evaluating profiles in
527      * repository-resolved (external) models — dependency POMs, parent POMs, and imported BOMs.
528      * <p>
529      * The sandboxed context preserves system properties (so JDK/OS activation works).
530      * User properties (consumer {@code -D} flags) are suppressed because they were not
531      * set for the dependency and must not accidentally activate its profiles.
532      * Model properties are <b>not</b> exposed through the system-property lookup — a
533      * dependency POM's own {@code <properties>} must not activate its own property-based
534      * profiles (see #13390).
535      * File-based profiles are pre-filtered via {@link #withoutFileActivation(List)} before
536      * reaching this context, so {@code getProjectDirectory()} is not relied on for file checks.
537      *
538      * @param delegate the original full context for this model build
539      * @return a sandboxed context suitable for external model profile activation
540      */
541     private static ProfileActivationContext externalActivationContext(ProfileActivationContext delegate) {
542         return new ProfileActivationContext() {
543             @Override
544             public List<String> getActiveProfileIds() {
545                 return delegate.getActiveProfileIds();
546             }
547 
548             @Override
549             public List<String> getInactiveProfileIds() {
550                 return delegate.getInactiveProfileIds();
551             }
552 
553             @Override
554             public Map<String, String> getSystemProperties() {
555                 return delegate.getSystemProperties();
556             }
557 
558             /** User properties are suppressed: consumer -D flags do not activate dependency profiles. */
559             @Override
560             public Map<String, String> getUserProperties() {
561                 return Collections.emptyMap();
562             }
563 
564             @Override
565             public Map<String, String> getProjectProperties() {
566                 return delegate.getProjectProperties();
567             }
568 
569             @Override
570             public File getProjectDirectory() {
571                 return delegate.getProjectDirectory();
572             }
573         };
574     }
575 
576     /**
577      * Returns the profiles from the given list whose activation does not depend on a file.
578      * File-activated profiles are suppressed in external model builds because publisher-local
579      * paths do not exist in the consumer's environment and resolving them against the consumer's
580      * filesystem would produce non-deterministic or incorrect results.
581      *
582      * @param profiles the full profile list
583      * @return profiles with file-activated ones removed
584      */
585     private static List<Profile> withoutFileActivation(List<Profile> profiles) {
586         List<Profile> eligible = new ArrayList<>(profiles.size());
587         for (Profile profile : profiles) {
588             Activation activation = profile.getActivation();
589             if (activation == null || activation.getFile() == null) {
590                 eligible.add(profile);
591             }
592         }
593         return eligible;
594     }
595 
596     @Override
597     public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result)
598             throws ModelBuildingException {
599         return build(request, result, new LinkedHashSet<String>());
600     }
601 
602     private ModelBuildingResult build(
603             ModelBuildingRequest request, ModelBuildingResult result, Collection<String> imports)
604             throws ModelBuildingException {
605         // phase 2
606         Model resultModel = result.getEffectiveModel();
607 
608         DefaultModelProblemCollector problems = new DefaultModelProblemCollector(result);
609         problems.setSource(resultModel);
610         problems.setRootModel(resultModel);
611 
612         // model path translation
613         modelPathTranslator.alignToBaseDirectory(resultModel, resultModel.getProjectDirectory(), request);
614 
615         // plugin management injection
616         pluginManagementInjector.injectManagement(resultModel, request, problems);
617 
618         fireEvent(resultModel, request, problems, ModelBuildingEventCatapult.BUILD_EXTENSIONS_ASSEMBLED);
619 
620         if (request.isProcessPlugins()) {
621             if (lifecycleBindingsInjector == null) {
622                 throw new IllegalStateException("lifecycle bindings injector is missing");
623             }
624 
625             // lifecycle bindings injection
626             lifecycleBindingsInjector.injectLifecycleBindings(resultModel, request, problems);
627         }
628 
629         // dependency management import
630         importDependencyManagement(resultModel, request, problems, imports);
631 
632         // dependency management injection
633         dependencyManagementInjector.injectManagement(resultModel, request, problems);
634 
635         modelNormalizer.injectDefaultValues(resultModel, request, problems);
636 
637         if (request.isProcessPlugins()) {
638             // reports configuration
639             reportConfigurationExpander.expandPluginConfiguration(resultModel, request, problems);
640 
641             // reports conversion to decoupled site plugin
642             reportingConverter.convertReporting(resultModel, request, problems);
643 
644             // plugins configuration
645             pluginConfigurationExpander.expandPluginConfiguration(resultModel, request, problems);
646         }
647 
648         // effective model validation
649         modelValidator.validateEffectiveModel(resultModel, request, problems);
650 
651         if (hasModelErrors(problems)) {
652             throw problems.newModelBuildingException();
653         }
654 
655         return result;
656     }
657 
658     @Override
659     public Result<? extends Model> buildRawModel(File pomFile, int validationLevel, boolean locationTracking) {
660         final ModelBuildingRequest request = new DefaultModelBuildingRequest()
661                 .setValidationLevel(validationLevel)
662                 .setLocationTracking(locationTracking);
663         final DefaultModelProblemCollector collector =
664                 new DefaultModelProblemCollector(new DefaultModelBuildingResult());
665         try {
666             return newResult(readModel(null, pomFile, request, collector), collector.getProblems());
667         } catch (ModelBuildingException e) {
668             return error(collector.getProblems());
669         }
670     }
671 
672     private Model readModel(
673             ModelSource modelSource, File pomFile, ModelBuildingRequest request, DefaultModelProblemCollector problems)
674             throws ModelBuildingException {
675         Model model;
676 
677         if (modelSource == null) {
678             if (pomFile != null) {
679                 modelSource = new FileModelSource(pomFile);
680             } else {
681                 throw new NullPointerException("neither pomFile nor modelSource can be null");
682             }
683         }
684 
685         problems.setSource(modelSource.getLocation());
686         try {
687             boolean strict = request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0;
688             InputSource source = request.isLocationTracking() ? new InputSource() : null;
689 
690             Map<String, Object> options = new HashMap<>();
691             options.put(ModelProcessor.IS_STRICT, strict);
692             options.put(ModelProcessor.INPUT_SOURCE, source);
693             options.put(ModelProcessor.SOURCE, modelSource);
694 
695             try {
696                 model = modelProcessor.read(modelSource.getInputStream(), options);
697             } catch (ModelParseException e) {
698                 if (!strict) {
699                     throw e;
700                 }
701 
702                 options.put(ModelProcessor.IS_STRICT, Boolean.FALSE);
703 
704                 try {
705                     model = modelProcessor.read(modelSource.getInputStream(), options);
706                 } catch (ModelParseException ne) {
707                     // still unreadable even in non-strict mode, rethrow original error
708                     throw e;
709                 }
710 
711                 // the document parsed successfully once unknown/misplaced elements were tolerated,
712                 // so it is well-formed XML that merely violates the POM schema - invalid, not malformed
713                 if (pomFile != null) {
714                     problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.V20)
715                             .setMessage("Invalid POM " + modelSource.getLocation() + ": " + e.getMessage())
716                             .setException(e));
717                 } else {
718                     problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20)
719                             .setMessage("Invalid POM " + modelSource.getLocation() + ": " + e.getMessage())
720                             .setException(e));
721                 }
722             }
723 
724             if (source != null) {
725                 source.setModelId(ModelProblemUtils.toId(model));
726                 source.setLocation(modelSource.getLocation());
727             }
728         } catch (ModelParseException e) {
729             problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
730                     .setMessage("Non-parseable POM " + modelSource.getLocation() + ": " + e.getMessage())
731                     .setException(e));
732             throw problems.newModelBuildingException();
733         } catch (IOException e) {
734             String msg = e.getMessage();
735             if (msg == null || msg.length() <= 0) {
736                 // NOTE: There's java.nio.charset.MalformedInputException and sun.io.MalformedInputException
737                 if (e.getClass().getName().endsWith("MalformedInputException")) {
738                     msg = "Some input bytes do not match the file encoding.";
739                 } else {
740                     msg = e.getClass().getSimpleName();
741                 }
742             }
743             problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
744                     .setMessage("Non-readable POM " + modelSource.getLocation() + ": " + msg)
745                     .setException(e));
746             throw problems.newModelBuildingException();
747         }
748 
749         model.setPomFile(pomFile);
750 
751         problems.setSource(model);
752         modelValidator.validateRawModel(model, request, problems);
753 
754         if (hasFatalErrors(problems)) {
755             throw problems.newModelBuildingException();
756         }
757 
758         return model;
759     }
760 
761     private DefaultProfileActivationContext getProfileActivationContext(ModelBuildingRequest request, Model rawModel) {
762         DefaultProfileActivationContext context = new DefaultProfileActivationContext();
763 
764         context.setActiveProfileIds(request.getActiveProfileIds());
765         context.setInactiveProfileIds(request.getInactiveProfileIds());
766         context.setSystemProperties(request.getSystemProperties());
767         // enrich user properties with project packaging
768         Properties userProperties = request.getUserProperties();
769         userProperties.computeIfAbsent(
770                 (Object) ProfileActivationContext.PROPERTY_NAME_PACKAGING, (p) -> (Object) rawModel.getPackaging());
771         context.setUserProperties(userProperties);
772         context.setProjectDirectory(
773                 (request.getPomFile() != null) ? request.getPomFile().getParentFile() : null);
774 
775         return context;
776     }
777 
778     private void configureResolver(ModelResolver modelResolver, Model model, DefaultModelProblemCollector problems) {
779         configureResolver(modelResolver, model, problems, false);
780     }
781 
782     private void configureResolver(
783             ModelResolver modelResolver,
784             Model model,
785             DefaultModelProblemCollector problems,
786             boolean replaceRepositories) {
787         if (modelResolver == null) {
788             return;
789         }
790 
791         problems.setSource(model);
792 
793         List<Repository> repositories = model.getRepositories();
794 
795         for (Repository repository : repositories) {
796             try {
797                 modelResolver.addRepository(repository, replaceRepositories);
798             } catch (InvalidRepositoryException e) {
799                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
800                         .setMessage("Invalid repository " + repository.getId() + ": " + e.getMessage())
801                         .setLocation(repository.getLocation(""))
802                         .setException(e));
803             }
804         }
805     }
806 
807     private void checkPluginVersions(
808             List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems) {
809         if (request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
810             return;
811         }
812 
813         Map<String, Plugin> plugins = new HashMap<>();
814         Map<String, String> versions = new HashMap<>();
815         Map<String, String> managedVersions = new HashMap<>();
816 
817         for (int i = lineage.size() - 1; i >= 0; i--) {
818             Model model = lineage.get(i).getModel();
819             Build build = model.getBuild();
820             if (build != null) {
821                 for (Plugin plugin : build.getPlugins()) {
822                     String key = plugin.getKey();
823                     if (versions.get(key) == null) {
824                         versions.put(key, plugin.getVersion());
825                         plugins.put(key, plugin);
826                     }
827                 }
828                 PluginManagement mgmt = build.getPluginManagement();
829                 if (mgmt != null) {
830                     for (Plugin plugin : mgmt.getPlugins()) {
831                         String key = plugin.getKey();
832                         if (managedVersions.get(key) == null) {
833                             managedVersions.put(key, plugin.getVersion());
834                         }
835                     }
836                 }
837             }
838         }
839 
840         for (String key : versions.keySet()) {
841             if (versions.get(key) == null && managedVersions.get(key) == null) {
842                 InputLocation location = plugins.get(key).getLocation("");
843                 problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20)
844                         .setMessage("'build.plugins.plugin.version' for " + key + " is missing.")
845                         .setLocation(location));
846             }
847         }
848     }
849 
850     private void assembleInheritance(
851             List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems) {
852         for (int i = lineage.size() - 2; i >= 0; i--) {
853             Model parent = lineage.get(i + 1).getModel();
854             Model child = lineage.get(i).getModel();
855             inheritanceAssembler.assembleModelInheritance(child, parent, request, problems);
856         }
857     }
858 
859     private List<Profile> getProfiles(Model model, boolean clone) {
860         ArrayList<Profile> profiles = new ArrayList<>();
861         for (Profile profile : model.getProfiles()) {
862             if (clone) {
863                 profile = profile.clone();
864             }
865             profiles.add(profile);
866         }
867         return profiles;
868     }
869 
870     private Model interpolateModel(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {
871         // save profile activations before interpolation, since they are evaluated with limited scope
872         List<Profile> originalProfiles = getProfiles(model, true);
873 
874         Model interpolatedModel =
875                 modelInterpolator.interpolateModel(model, model.getProjectDirectory(), request, problems);
876         if (interpolatedModel.getParent() != null) {
877             StringSearchInterpolator ssi = new StringSearchInterpolator();
878             ssi.addValueSource(new MapBasedValueSource(request.getUserProperties()));
879 
880             ssi.addValueSource(new MapBasedValueSource(model.getProperties()));
881 
882             ssi.addValueSource(new MapBasedValueSource(request.getSystemProperties()));
883 
884             try {
885                 String interpolated =
886                         ssi.interpolate(interpolatedModel.getParent().getVersion());
887                 interpolatedModel.getParent().setVersion(interpolated);
888             } catch (Exception e) {
889                 ModelProblemCollectorRequest mpcr = new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
890                         .setMessage("Failed to interpolate field: "
891                                 + interpolatedModel.getParent().getVersion()
892                                 + " on class: ")
893                         .setException(e);
894                 problems.add(mpcr);
895             }
896         }
897         interpolatedModel.setPomFile(model.getPomFile());
898 
899         // restore profiles with any activation to their value before full interpolation
900         List<Profile> interpolatedProfiles = model.getProfiles();
901         IntStream.range(0, interpolatedProfiles.size())
902                 .forEach(i -> interpolatedProfiles
903                         .get(i)
904                         .setActivation(originalProfiles.get(i).getActivation()));
905 
906         return interpolatedModel;
907     }
908 
909     private ModelData readParent(
910             Model childModel,
911             ModelSource childSource,
912             ModelBuildingRequest request,
913             DefaultModelProblemCollector problems)
914             throws ModelBuildingException {
915         ModelData parentData;
916 
917         Parent parent = childModel.getParent();
918 
919         if (parent != null) {
920             String groupId = parent.getGroupId();
921             String artifactId = parent.getArtifactId();
922             String version = parent.getVersion();
923 
924             parentData = getCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.RAW);
925 
926             if (parentData == null) {
927                 parentData = readParentLocally(childModel, childSource, request, problems);
928 
929                 if (parentData == null) {
930                     parentData = readParentExternally(childModel, request, problems);
931                 }
932 
933                 putCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.RAW, parentData);
934             } else {
935                 /*
936                  * NOTE: This is a sanity check of the cache hit. If the cached parent POM was locally resolved, the
937                  * child's <relativePath> should point at that parent, too. If it doesn't, we ignore the cache and
938                  * resolve externally, to mimic the behavior if the cache didn't exist in the first place. Otherwise,
939                  * the cache would obscure a bad POM.
940                  */
941 
942                 File pomFile = parentData.getModel().getPomFile();
943                 if (pomFile != null) {
944                     FileModelSource pomSource = new FileModelSource(pomFile);
945                     ModelSource expectedParentSource = getParentPomFile(childModel, childSource);
946 
947                     if (expectedParentSource == null
948                             || (expectedParentSource instanceof ModelSource2
949                                     && !pomSource.equals(expectedParentSource))) {
950                         parentData = readParentExternally(childModel, request, problems);
951                     }
952                 }
953             }
954 
955             Model parentModel = parentData.getModel();
956 
957             if (!"pom".equals(parentModel.getPackaging())) {
958                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
959                         .setMessage("Invalid packaging for parent POM " + ModelProblemUtils.toSourceHint(parentModel)
960                                 + ", must be \"pom\" but is \"" + parentModel.getPackaging() + "\"")
961                         .setLocation(parentModel.getLocation("packaging")));
962             }
963         } else {
964             parentData = null;
965         }
966 
967         return parentData;
968     }
969 
970     private ModelData readParentLocally(
971             Model childModel,
972             ModelSource childSource,
973             ModelBuildingRequest request,
974             DefaultModelProblemCollector problems)
975             throws ModelBuildingException {
976         final Parent parent = childModel.getParent();
977         final ModelSource candidateSource;
978         final Model candidateModel;
979         final WorkspaceModelResolver resolver = request.getWorkspaceModelResolver();
980         if (resolver == null) {
981             candidateSource = getParentPomFile(childModel, childSource);
982 
983             if (candidateSource == null) {
984                 return null;
985             }
986 
987             File pomFile = null;
988             if (candidateSource instanceof FileModelSource) {
989                 pomFile = ((FileModelSource) candidateSource).getPomFile();
990             }
991 
992             candidateModel = readModel(candidateSource, pomFile, request, problems);
993         } else {
994             try {
995                 candidateModel =
996                         resolver.resolveRawModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
997             } catch (UnresolvableModelException e) {
998                 problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE) //
999                         .setMessage(e.getMessage().toString())
1000                         .setLocation(parent.getLocation(""))
1001                         .setException(e));
1002                 throw problems.newModelBuildingException();
1003             }
1004             if (candidateModel == null) {
1005                 return null;
1006             }
1007             candidateSource = new FileModelSource(candidateModel.getPomFile());
1008         }
1009 
1010         //
1011         // TODO jvz Why isn't all this checking the job of the duty of the workspace resolver, we know that we
1012         // have a model that is suitable, yet more checks are done here and the one for the version is problematic
1013         // before because with parents as ranges it will never work in this scenario.
1014         //
1015 
1016         String groupId = candidateModel.getGroupId();
1017         if (groupId == null && candidateModel.getParent() != null) {
1018             groupId = candidateModel.getParent().getGroupId();
1019         }
1020         String artifactId = candidateModel.getArtifactId();
1021         String version = candidateModel.getVersion();
1022         if (version == null && candidateModel.getParent() != null) {
1023             version = candidateModel.getParent().getVersion();
1024         }
1025 
1026         if (groupId == null
1027                 || !groupId.equals(parent.getGroupId())
1028                 || artifactId == null
1029                 || !artifactId.equals(parent.getArtifactId())) {
1030             StringBuilder buffer = new StringBuilder(256);
1031             buffer.append("'parent.relativePath'");
1032             if (childModel != problems.getRootModel()) {
1033                 buffer.append(" of POM ").append(ModelProblemUtils.toSourceHint(childModel));
1034             }
1035             buffer.append(" points at ").append(groupId).append(':').append(artifactId);
1036             buffer.append(" instead of ").append(parent.getGroupId()).append(':');
1037             buffer.append(parent.getArtifactId()).append(", please verify your project structure");
1038 
1039             problems.setSource(childModel);
1040             problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.BASE)
1041                     .setMessage(buffer.toString())
1042                     .setLocation(parent.getLocation("")));
1043             return null;
1044         }
1045         if (version != null && parent.getVersion() != null && !version.equals(parent.getVersion())) {
1046             try {
1047                 VersionRange parentRange = VersionRange.createFromVersionSpec(parent.getVersion());
1048                 if (!parentRange.hasRestrictions()) {
1049                     // the parent version is not a range, we have version skew, drop back to resolution from repo
1050                     return null;
1051                 }
1052                 if (!parentRange.containsVersion(new DefaultArtifactVersion(version))) {
1053                     // version skew drop back to resolution from the repository
1054                     return null;
1055                 }
1056 
1057                 // Validate versions aren't inherited when using parent ranges the same way as when read externally.
1058                 String rawChildModelVersion = childModel.getVersion();
1059 
1060                 if (rawChildModelVersion == null) {
1061                     // Message below is checked for in the MNG-2199 core IT.
1062                     problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1063                             .setMessage("Version must be a constant")
1064                             .setLocation(childModel.getLocation("")));
1065 
1066                 } else {
1067                     if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1068                         // Message below is checked for in the MNG-2199 core IT.
1069                         problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1070                                 .setMessage("Version must be a constant")
1071                                 .setLocation(childModel.getLocation("version")));
1072                     }
1073                 }
1074 
1075                 // MNG-2199: What else to check here ?
1076             } catch (InvalidVersionSpecificationException e) {
1077                 // invalid version range, so drop back to resolution from the repository
1078                 return null;
1079             }
1080         }
1081 
1082         //
1083         // Here we just need to know that a version is fine to use but this validation we can do in our workspace
1084         // resolver.
1085         //
1086 
1087         /*
1088          * if ( version == null || !version.equals( parent.getVersion() ) ) { return null; }
1089          */
1090 
1091         ModelData parentData = new ModelData(candidateSource, candidateModel, groupId, artifactId, version);
1092 
1093         return parentData;
1094     }
1095 
1096     private boolean rawChildVersionReferencesParent(String rawChildModelVersion) {
1097         return rawChildModelVersion.equals("${pom.version}")
1098                 || rawChildModelVersion.equals("${project.version}")
1099                 || rawChildModelVersion.equals("${pom.parent.version}")
1100                 || rawChildModelVersion.equals("${project.parent.version}");
1101     }
1102 
1103     private ModelSource getParentPomFile(Model childModel, ModelSource source) {
1104         if (!(source instanceof ModelSource2)) {
1105             return null;
1106         }
1107 
1108         String parentPath = childModel.getParent().getRelativePath();
1109 
1110         if (parentPath == null || parentPath.length() <= 0) {
1111             return null;
1112         }
1113 
1114         return ((ModelSource2) source).getRelatedSource(parentPath);
1115     }
1116 
1117     private ModelData readParentExternally(
1118             Model childModel, ModelBuildingRequest request, DefaultModelProblemCollector problems)
1119             throws ModelBuildingException {
1120         problems.setSource(childModel);
1121 
1122         Parent parent = childModel.getParent().clone();
1123 
1124         String groupId = parent.getGroupId();
1125         String artifactId = parent.getArtifactId();
1126         String version = parent.getVersion();
1127 
1128         ModelResolver modelResolver = request.getModelResolver();
1129         Objects.requireNonNull(
1130                 modelResolver,
1131                 String.format(
1132                         "request.modelResolver cannot be null (parent POM %s and POM %s)",
1133                         ModelProblemUtils.toId(groupId, artifactId, version),
1134                         ModelProblemUtils.toSourceHint(childModel)));
1135 
1136         ModelSource modelSource;
1137         try {
1138             modelSource = modelResolver.resolveModel(parent);
1139         } catch (UnresolvableModelException e) {
1140             // Message below is checked for in the MNG-2199 core IT.
1141             StringBuilder buffer = new StringBuilder(256);
1142             buffer.append("Non-resolvable parent POM");
1143             if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
1144                 buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
1145             }
1146             if (childModel != problems.getRootModel()) {
1147                 buffer.append(" for ").append(ModelProblemUtils.toId(childModel));
1148             }
1149             buffer.append(": ").append(e.getMessage());
1150             if (childModel.getProjectDirectory() != null) {
1151                 if (parent.getRelativePath() == null || parent.getRelativePath().length() <= 0) {
1152                     buffer.append(" and 'parent.relativePath' points at no local POM");
1153                 } else {
1154                     buffer.append(" and 'parent.relativePath' points at wrong local POM");
1155                 }
1156             }
1157 
1158             problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
1159                     .setMessage(buffer.toString())
1160                     .setLocation(parent.getLocation(""))
1161                     .setException(e));
1162             throw problems.newModelBuildingException();
1163         }
1164 
1165         ModelBuildingRequest lenientRequest = request;
1166         if (request.getValidationLevel() > ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
1167             lenientRequest = new FilterModelBuildingRequest(request) {
1168                 @Override
1169                 public int getValidationLevel() {
1170                     return ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0;
1171                 }
1172             };
1173         }
1174 
1175         Model parentModel = readModel(modelSource, null, lenientRequest, problems);
1176 
1177         if (!parent.getVersion().equals(version)) {
1178             String rawChildModelVersion = childModel.getVersion();
1179 
1180             if (rawChildModelVersion == null) {
1181                 // Message below is checked for in the MNG-2199 core IT.
1182                 problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1183                         .setMessage("Version must be a constant")
1184                         .setLocation(childModel.getLocation("")));
1185 
1186             } else {
1187                 if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1188                     // Message below is checked for in the MNG-2199 core IT.
1189                     problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1190                             .setMessage("Version must be a constant")
1191                             .setLocation(childModel.getLocation("version")));
1192                 }
1193             }
1194 
1195             // MNG-2199: What else to check here ?
1196         }
1197 
1198         ModelData parentData = new ModelData(
1199                 modelSource, parentModel, parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1200 
1201         return parentData;
1202     }
1203 
1204     private Model getSuperModel() {
1205         return superPomProvider.getSuperModel("4.0.0").clone();
1206     }
1207 
1208     @SuppressWarnings("checkstyle:methodlength")
1209     private void importDependencyManagement(
1210             Model model,
1211             ModelBuildingRequest request,
1212             DefaultModelProblemCollector problems,
1213             Collection<String> importIds) {
1214         DependencyManagement depMgmt = model.getDependencyManagement();
1215 
1216         if (depMgmt == null) {
1217             return;
1218         }
1219 
1220         String importing = model.getGroupId() + ':' + model.getArtifactId() + ':' + model.getVersion();
1221 
1222         importIds.add(importing);
1223 
1224         final WorkspaceModelResolver workspaceResolver = request.getWorkspaceModelResolver();
1225         final ModelResolver modelResolver = request.getModelResolver();
1226 
1227         ModelBuildingRequest importRequest = null;
1228 
1229         ModelCacheTag<DependencyManagement> importTag =
1230                 request.isLocationTracking() ? ModelCacheTag.IMPORT_WITH_LOCATIONS : ModelCacheTag.IMPORT;
1231 
1232         List<DependencyManagement> importMgmts = null;
1233 
1234         for (Iterator<Dependency> it = depMgmt.getDependencies().iterator(); it.hasNext(); ) {
1235             Dependency dependency = it.next();
1236 
1237             if (!"pom".equals(dependency.getType()) || !"import".equals(dependency.getScope())) {
1238                 continue;
1239             }
1240 
1241             it.remove();
1242 
1243             String groupId = dependency.getGroupId();
1244             String artifactId = dependency.getArtifactId();
1245             String version = dependency.getVersion();
1246 
1247             if (groupId == null || groupId.length() <= 0) {
1248                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1249                         .setMessage("'dependencyManagement.dependencies.dependency.groupId' for "
1250                                 + dependency.getManagementKey() + " is missing.")
1251                         .setLocation(dependency.getLocation("")));
1252                 continue;
1253             }
1254             if (artifactId == null || artifactId.length() <= 0) {
1255                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1256                         .setMessage("'dependencyManagement.dependencies.dependency.artifactId' for "
1257                                 + dependency.getManagementKey() + " is missing.")
1258                         .setLocation(dependency.getLocation("")));
1259                 continue;
1260             }
1261             if (version == null || version.length() <= 0) {
1262                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1263                         .setMessage("'dependencyManagement.dependencies.dependency.version' for "
1264                                 + dependency.getManagementKey() + " is missing.")
1265                         .setLocation(dependency.getLocation("")));
1266                 continue;
1267             }
1268 
1269             String imported = groupId + ':' + artifactId + ':' + version;
1270 
1271             if (importIds.contains(imported)) {
1272                 String message = "The dependencies of type=pom and with scope=import form a cycle: ";
1273                 for (String modelId : importIds) {
1274                     message += modelId + " -> ";
1275                 }
1276                 message += imported;
1277                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE).setMessage(message));
1278 
1279                 continue;
1280             }
1281 
1282             DependencyManagement importMgmt =
1283                     getCache(request.getModelCache(), groupId, artifactId, version, importTag);
1284 
1285             if (importMgmt == null) {
1286                 if (workspaceResolver == null && modelResolver == null) {
1287                     throw new NullPointerException(String.format(
1288                             "request.workspaceModelResolver and request.modelResolver cannot be null"
1289                                     + " (parent POM %s and POM %s)",
1290                             ModelProblemUtils.toId(groupId, artifactId, version),
1291                             ModelProblemUtils.toSourceHint(model)));
1292                 }
1293 
1294                 Model importModel = null;
1295                 if (workspaceResolver != null) {
1296                     try {
1297                         importModel = workspaceResolver.resolveEffectiveModel(groupId, artifactId, version);
1298                     } catch (UnresolvableModelException e) {
1299                         problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
1300                                 .setMessage(e.getMessage().toString())
1301                                 .setException(e));
1302                         continue;
1303                     }
1304                 }
1305 
1306                 // no workspace resolver or workspace resolver returned null (i.e. model not in workspace)
1307                 if (importModel == null) {
1308                     final ModelSource importSource;
1309                     try {
1310                         importSource = modelResolver.resolveModel(groupId, artifactId, version);
1311                     } catch (UnresolvableModelException e) {
1312                         StringBuilder buffer = new StringBuilder(256);
1313                         buffer.append("Non-resolvable import POM");
1314                         if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
1315                             buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
1316                         }
1317                         buffer.append(": ").append(e.getMessage());
1318 
1319                         problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1320                                 .setMessage(buffer.toString())
1321                                 .setLocation(dependency.getLocation(""))
1322                                 .setException(e));
1323                         continue;
1324                     }
1325 
1326                     if (importRequest == null) {
1327                         importRequest = new DefaultModelBuildingRequest();
1328                         importRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
1329                         importRequest.setModelCache(request.getModelCache());
1330                         importRequest.setSystemProperties(request.getSystemProperties());
1331                         importRequest.setUserProperties(request.getUserProperties());
1332                         importRequest.setLocationTracking(request.isLocationTracking());
1333                     }
1334 
1335                     importRequest.setModelSource(importSource);
1336                     importRequest.setModelResolver(modelResolver.newCopy());
1337 
1338                     final ModelBuildingResult importResult;
1339                     try {
1340                         importResult = build(importRequest, importIds);
1341                     } catch (ModelBuildingException e) {
1342                         problems.addAll(e.getProblems());
1343                         continue;
1344                     }
1345 
1346                     problems.addAll(importResult.getProblems());
1347 
1348                     importModel = importResult.getEffectiveModel();
1349                 }
1350 
1351                 importMgmt = importModel.getDependencyManagement();
1352 
1353                 if (importMgmt == null) {
1354                     importMgmt = new DependencyManagement();
1355                 }
1356 
1357                 putCache(request.getModelCache(), groupId, artifactId, version, importTag, importMgmt);
1358             }
1359 
1360             if (importMgmts == null) {
1361                 importMgmts = new ArrayList<>();
1362             }
1363 
1364             importMgmts.add(importMgmt);
1365         }
1366 
1367         importIds.remove(importing);
1368 
1369         dependencyManagementImporter.importManagement(model, importMgmts, request, problems);
1370     }
1371 
1372     private <T> void putCache(
1373             ModelCache modelCache, String groupId, String artifactId, String version, ModelCacheTag<T> tag, T data) {
1374         if (modelCache != null) {
1375             modelCache.put(groupId, artifactId, version, tag.getName(), tag.intoCache(data));
1376         }
1377     }
1378 
1379     private <T> T getCache(
1380             ModelCache modelCache, String groupId, String artifactId, String version, ModelCacheTag<T> tag) {
1381         if (modelCache != null) {
1382             Object data = modelCache.get(groupId, artifactId, version, tag.getName());
1383             if (data != null) {
1384                 return tag.fromCache(tag.getType().cast(data));
1385             }
1386         }
1387         return null;
1388     }
1389 
1390     private void fireEvent(
1391             Model model,
1392             ModelBuildingRequest request,
1393             ModelProblemCollector problems,
1394             ModelBuildingEventCatapult catapult)
1395             throws ModelBuildingException {
1396         ModelBuildingListener listener = request.getModelBuildingListener();
1397 
1398         if (listener != null) {
1399             ModelBuildingEvent event = new DefaultModelBuildingEvent(model, request, problems);
1400 
1401             catapult.fire(listener, event);
1402         }
1403     }
1404 
1405     private boolean containsCoordinates(String message, String groupId, String artifactId, String version) {
1406         return message != null
1407                 && (groupId == null || message.contains(groupId))
1408                 && (artifactId == null || message.contains(artifactId))
1409                 && (version == null || message.contains(version));
1410     }
1411 
1412     protected boolean hasModelErrors(ModelProblemCollectorExt problems) {
1413         if (problems instanceof DefaultModelProblemCollector) {
1414             return ((DefaultModelProblemCollector) problems).hasErrors();
1415         } else {
1416             // the default execution path only knows the DefaultModelProblemCollector,
1417             // only reason it's not in signature is because it's package private
1418             throw new IllegalStateException();
1419         }
1420     }
1421 
1422     protected boolean hasFatalErrors(ModelProblemCollectorExt problems) {
1423         if (problems instanceof DefaultModelProblemCollector) {
1424             return ((DefaultModelProblemCollector) problems).hasFatalErrors();
1425         } else {
1426             // the default execution path only knows the DefaultModelProblemCollector,
1427             // only reason it's not in signature is because it's package private
1428             throw new IllegalStateException();
1429         }
1430     }
1431 }