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                 if (pomFile != null) {
712                     problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.V20)
713                             .setMessage("Malformed POM " + modelSource.getLocation() + ": " + e.getMessage())
714                             .setException(e));
715                 } else {
716                     problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20)
717                             .setMessage("Malformed POM " + modelSource.getLocation() + ": " + e.getMessage())
718                             .setException(e));
719                 }
720             }
721 
722             if (source != null) {
723                 source.setModelId(ModelProblemUtils.toId(model));
724                 source.setLocation(modelSource.getLocation());
725             }
726         } catch (ModelParseException e) {
727             problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
728                     .setMessage("Non-parseable POM " + modelSource.getLocation() + ": " + e.getMessage())
729                     .setException(e));
730             throw problems.newModelBuildingException();
731         } catch (IOException e) {
732             String msg = e.getMessage();
733             if (msg == null || msg.length() <= 0) {
734                 // NOTE: There's java.nio.charset.MalformedInputException and sun.io.MalformedInputException
735                 if (e.getClass().getName().endsWith("MalformedInputException")) {
736                     msg = "Some input bytes do not match the file encoding.";
737                 } else {
738                     msg = e.getClass().getSimpleName();
739                 }
740             }
741             problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
742                     .setMessage("Non-readable POM " + modelSource.getLocation() + ": " + msg)
743                     .setException(e));
744             throw problems.newModelBuildingException();
745         }
746 
747         model.setPomFile(pomFile);
748 
749         problems.setSource(model);
750         modelValidator.validateRawModel(model, request, problems);
751 
752         if (hasFatalErrors(problems)) {
753             throw problems.newModelBuildingException();
754         }
755 
756         return model;
757     }
758 
759     private DefaultProfileActivationContext getProfileActivationContext(ModelBuildingRequest request, Model rawModel) {
760         DefaultProfileActivationContext context = new DefaultProfileActivationContext();
761 
762         context.setActiveProfileIds(request.getActiveProfileIds());
763         context.setInactiveProfileIds(request.getInactiveProfileIds());
764         context.setSystemProperties(request.getSystemProperties());
765         // enrich user properties with project packaging
766         Properties userProperties = request.getUserProperties();
767         userProperties.computeIfAbsent(
768                 (Object) ProfileActivationContext.PROPERTY_NAME_PACKAGING, (p) -> (Object) rawModel.getPackaging());
769         context.setUserProperties(userProperties);
770         context.setProjectDirectory(
771                 (request.getPomFile() != null) ? request.getPomFile().getParentFile() : null);
772 
773         return context;
774     }
775 
776     private void configureResolver(ModelResolver modelResolver, Model model, DefaultModelProblemCollector problems) {
777         configureResolver(modelResolver, model, problems, false);
778     }
779 
780     private void configureResolver(
781             ModelResolver modelResolver,
782             Model model,
783             DefaultModelProblemCollector problems,
784             boolean replaceRepositories) {
785         if (modelResolver == null) {
786             return;
787         }
788 
789         problems.setSource(model);
790 
791         List<Repository> repositories = model.getRepositories();
792 
793         for (Repository repository : repositories) {
794             try {
795                 modelResolver.addRepository(repository, replaceRepositories);
796             } catch (InvalidRepositoryException e) {
797                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
798                         .setMessage("Invalid repository " + repository.getId() + ": " + e.getMessage())
799                         .setLocation(repository.getLocation(""))
800                         .setException(e));
801             }
802         }
803     }
804 
805     private void checkPluginVersions(
806             List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems) {
807         if (request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
808             return;
809         }
810 
811         Map<String, Plugin> plugins = new HashMap<>();
812         Map<String, String> versions = new HashMap<>();
813         Map<String, String> managedVersions = new HashMap<>();
814 
815         for (int i = lineage.size() - 1; i >= 0; i--) {
816             Model model = lineage.get(i).getModel();
817             Build build = model.getBuild();
818             if (build != null) {
819                 for (Plugin plugin : build.getPlugins()) {
820                     String key = plugin.getKey();
821                     if (versions.get(key) == null) {
822                         versions.put(key, plugin.getVersion());
823                         plugins.put(key, plugin);
824                     }
825                 }
826                 PluginManagement mgmt = build.getPluginManagement();
827                 if (mgmt != null) {
828                     for (Plugin plugin : mgmt.getPlugins()) {
829                         String key = plugin.getKey();
830                         if (managedVersions.get(key) == null) {
831                             managedVersions.put(key, plugin.getVersion());
832                         }
833                     }
834                 }
835             }
836         }
837 
838         for (String key : versions.keySet()) {
839             if (versions.get(key) == null && managedVersions.get(key) == null) {
840                 InputLocation location = plugins.get(key).getLocation("");
841                 problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20)
842                         .setMessage("'build.plugins.plugin.version' for " + key + " is missing.")
843                         .setLocation(location));
844             }
845         }
846     }
847 
848     private void assembleInheritance(
849             List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems) {
850         for (int i = lineage.size() - 2; i >= 0; i--) {
851             Model parent = lineage.get(i + 1).getModel();
852             Model child = lineage.get(i).getModel();
853             inheritanceAssembler.assembleModelInheritance(child, parent, request, problems);
854         }
855     }
856 
857     private List<Profile> getProfiles(Model model, boolean clone) {
858         ArrayList<Profile> profiles = new ArrayList<>();
859         for (Profile profile : model.getProfiles()) {
860             if (clone) {
861                 profile = profile.clone();
862             }
863             profiles.add(profile);
864         }
865         return profiles;
866     }
867 
868     private Model interpolateModel(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {
869         // save profile activations before interpolation, since they are evaluated with limited scope
870         List<Profile> originalProfiles = getProfiles(model, true);
871 
872         Model interpolatedModel =
873                 modelInterpolator.interpolateModel(model, model.getProjectDirectory(), request, problems);
874         if (interpolatedModel.getParent() != null) {
875             StringSearchInterpolator ssi = new StringSearchInterpolator();
876             ssi.addValueSource(new MapBasedValueSource(request.getUserProperties()));
877 
878             ssi.addValueSource(new MapBasedValueSource(model.getProperties()));
879 
880             ssi.addValueSource(new MapBasedValueSource(request.getSystemProperties()));
881 
882             try {
883                 String interpolated =
884                         ssi.interpolate(interpolatedModel.getParent().getVersion());
885                 interpolatedModel.getParent().setVersion(interpolated);
886             } catch (Exception e) {
887                 ModelProblemCollectorRequest mpcr = new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
888                         .setMessage("Failed to interpolate field: "
889                                 + interpolatedModel.getParent().getVersion()
890                                 + " on class: ")
891                         .setException(e);
892                 problems.add(mpcr);
893             }
894         }
895         interpolatedModel.setPomFile(model.getPomFile());
896 
897         // restore profiles with any activation to their value before full interpolation
898         List<Profile> interpolatedProfiles = model.getProfiles();
899         IntStream.range(0, interpolatedProfiles.size())
900                 .forEach(i -> interpolatedProfiles
901                         .get(i)
902                         .setActivation(originalProfiles.get(i).getActivation()));
903 
904         return interpolatedModel;
905     }
906 
907     private ModelData readParent(
908             Model childModel,
909             ModelSource childSource,
910             ModelBuildingRequest request,
911             DefaultModelProblemCollector problems)
912             throws ModelBuildingException {
913         ModelData parentData;
914 
915         Parent parent = childModel.getParent();
916 
917         if (parent != null) {
918             String groupId = parent.getGroupId();
919             String artifactId = parent.getArtifactId();
920             String version = parent.getVersion();
921 
922             parentData = getCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.RAW);
923 
924             if (parentData == null) {
925                 parentData = readParentLocally(childModel, childSource, request, problems);
926 
927                 if (parentData == null) {
928                     parentData = readParentExternally(childModel, request, problems);
929                 }
930 
931                 putCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.RAW, parentData);
932             } else {
933                 /*
934                  * NOTE: This is a sanity check of the cache hit. If the cached parent POM was locally resolved, the
935                  * child's <relativePath> should point at that parent, too. If it doesn't, we ignore the cache and
936                  * resolve externally, to mimic the behavior if the cache didn't exist in the first place. Otherwise,
937                  * the cache would obscure a bad POM.
938                  */
939 
940                 File pomFile = parentData.getModel().getPomFile();
941                 if (pomFile != null) {
942                     FileModelSource pomSource = new FileModelSource(pomFile);
943                     ModelSource expectedParentSource = getParentPomFile(childModel, childSource);
944 
945                     if (expectedParentSource == null
946                             || (expectedParentSource instanceof ModelSource2
947                                     && !pomSource.equals(expectedParentSource))) {
948                         parentData = readParentExternally(childModel, request, problems);
949                     }
950                 }
951             }
952 
953             Model parentModel = parentData.getModel();
954 
955             if (!"pom".equals(parentModel.getPackaging())) {
956                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
957                         .setMessage("Invalid packaging for parent POM " + ModelProblemUtils.toSourceHint(parentModel)
958                                 + ", must be \"pom\" but is \"" + parentModel.getPackaging() + "\"")
959                         .setLocation(parentModel.getLocation("packaging")));
960             }
961         } else {
962             parentData = null;
963         }
964 
965         return parentData;
966     }
967 
968     private ModelData readParentLocally(
969             Model childModel,
970             ModelSource childSource,
971             ModelBuildingRequest request,
972             DefaultModelProblemCollector problems)
973             throws ModelBuildingException {
974         final Parent parent = childModel.getParent();
975         final ModelSource candidateSource;
976         final Model candidateModel;
977         final WorkspaceModelResolver resolver = request.getWorkspaceModelResolver();
978         if (resolver == null) {
979             candidateSource = getParentPomFile(childModel, childSource);
980 
981             if (candidateSource == null) {
982                 return null;
983             }
984 
985             File pomFile = null;
986             if (candidateSource instanceof FileModelSource) {
987                 pomFile = ((FileModelSource) candidateSource).getPomFile();
988             }
989 
990             candidateModel = readModel(candidateSource, pomFile, request, problems);
991         } else {
992             try {
993                 candidateModel =
994                         resolver.resolveRawModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
995             } catch (UnresolvableModelException e) {
996                 problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE) //
997                         .setMessage(e.getMessage().toString())
998                         .setLocation(parent.getLocation(""))
999                         .setException(e));
1000                 throw problems.newModelBuildingException();
1001             }
1002             if (candidateModel == null) {
1003                 return null;
1004             }
1005             candidateSource = new FileModelSource(candidateModel.getPomFile());
1006         }
1007 
1008         //
1009         // TODO jvz Why isn't all this checking the job of the duty of the workspace resolver, we know that we
1010         // have a model that is suitable, yet more checks are done here and the one for the version is problematic
1011         // before because with parents as ranges it will never work in this scenario.
1012         //
1013 
1014         String groupId = candidateModel.getGroupId();
1015         if (groupId == null && candidateModel.getParent() != null) {
1016             groupId = candidateModel.getParent().getGroupId();
1017         }
1018         String artifactId = candidateModel.getArtifactId();
1019         String version = candidateModel.getVersion();
1020         if (version == null && candidateModel.getParent() != null) {
1021             version = candidateModel.getParent().getVersion();
1022         }
1023 
1024         if (groupId == null
1025                 || !groupId.equals(parent.getGroupId())
1026                 || artifactId == null
1027                 || !artifactId.equals(parent.getArtifactId())) {
1028             StringBuilder buffer = new StringBuilder(256);
1029             buffer.append("'parent.relativePath'");
1030             if (childModel != problems.getRootModel()) {
1031                 buffer.append(" of POM ").append(ModelProblemUtils.toSourceHint(childModel));
1032             }
1033             buffer.append(" points at ").append(groupId).append(':').append(artifactId);
1034             buffer.append(" instead of ").append(parent.getGroupId()).append(':');
1035             buffer.append(parent.getArtifactId()).append(", please verify your project structure");
1036 
1037             problems.setSource(childModel);
1038             problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.BASE)
1039                     .setMessage(buffer.toString())
1040                     .setLocation(parent.getLocation("")));
1041             return null;
1042         }
1043         if (version != null && parent.getVersion() != null && !version.equals(parent.getVersion())) {
1044             try {
1045                 VersionRange parentRange = VersionRange.createFromVersionSpec(parent.getVersion());
1046                 if (!parentRange.hasRestrictions()) {
1047                     // the parent version is not a range, we have version skew, drop back to resolution from repo
1048                     return null;
1049                 }
1050                 if (!parentRange.containsVersion(new DefaultArtifactVersion(version))) {
1051                     // version skew drop back to resolution from the repository
1052                     return null;
1053                 }
1054 
1055                 // Validate versions aren't inherited when using parent ranges the same way as when read externally.
1056                 String rawChildModelVersion = childModel.getVersion();
1057 
1058                 if (rawChildModelVersion == null) {
1059                     // Message below is checked for in the MNG-2199 core IT.
1060                     problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1061                             .setMessage("Version must be a constant")
1062                             .setLocation(childModel.getLocation("")));
1063 
1064                 } else {
1065                     if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1066                         // Message below is checked for in the MNG-2199 core IT.
1067                         problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1068                                 .setMessage("Version must be a constant")
1069                                 .setLocation(childModel.getLocation("version")));
1070                     }
1071                 }
1072 
1073                 // MNG-2199: What else to check here ?
1074             } catch (InvalidVersionSpecificationException e) {
1075                 // invalid version range, so drop back to resolution from the repository
1076                 return null;
1077             }
1078         }
1079 
1080         //
1081         // Here we just need to know that a version is fine to use but this validation we can do in our workspace
1082         // resolver.
1083         //
1084 
1085         /*
1086          * if ( version == null || !version.equals( parent.getVersion() ) ) { return null; }
1087          */
1088 
1089         ModelData parentData = new ModelData(candidateSource, candidateModel, groupId, artifactId, version);
1090 
1091         return parentData;
1092     }
1093 
1094     private boolean rawChildVersionReferencesParent(String rawChildModelVersion) {
1095         return rawChildModelVersion.equals("${pom.version}")
1096                 || rawChildModelVersion.equals("${project.version}")
1097                 || rawChildModelVersion.equals("${pom.parent.version}")
1098                 || rawChildModelVersion.equals("${project.parent.version}");
1099     }
1100 
1101     private ModelSource getParentPomFile(Model childModel, ModelSource source) {
1102         if (!(source instanceof ModelSource2)) {
1103             return null;
1104         }
1105 
1106         String parentPath = childModel.getParent().getRelativePath();
1107 
1108         if (parentPath == null || parentPath.length() <= 0) {
1109             return null;
1110         }
1111 
1112         return ((ModelSource2) source).getRelatedSource(parentPath);
1113     }
1114 
1115     private ModelData readParentExternally(
1116             Model childModel, ModelBuildingRequest request, DefaultModelProblemCollector problems)
1117             throws ModelBuildingException {
1118         problems.setSource(childModel);
1119 
1120         Parent parent = childModel.getParent().clone();
1121 
1122         String groupId = parent.getGroupId();
1123         String artifactId = parent.getArtifactId();
1124         String version = parent.getVersion();
1125 
1126         ModelResolver modelResolver = request.getModelResolver();
1127         Objects.requireNonNull(
1128                 modelResolver,
1129                 String.format(
1130                         "request.modelResolver cannot be null (parent POM %s and POM %s)",
1131                         ModelProblemUtils.toId(groupId, artifactId, version),
1132                         ModelProblemUtils.toSourceHint(childModel)));
1133 
1134         ModelSource modelSource;
1135         try {
1136             modelSource = modelResolver.resolveModel(parent);
1137         } catch (UnresolvableModelException e) {
1138             // Message below is checked for in the MNG-2199 core IT.
1139             StringBuilder buffer = new StringBuilder(256);
1140             buffer.append("Non-resolvable parent POM");
1141             if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
1142                 buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
1143             }
1144             if (childModel != problems.getRootModel()) {
1145                 buffer.append(" for ").append(ModelProblemUtils.toId(childModel));
1146             }
1147             buffer.append(": ").append(e.getMessage());
1148             if (childModel.getProjectDirectory() != null) {
1149                 if (parent.getRelativePath() == null || parent.getRelativePath().length() <= 0) {
1150                     buffer.append(" and 'parent.relativePath' points at no local POM");
1151                 } else {
1152                     buffer.append(" and 'parent.relativePath' points at wrong local POM");
1153                 }
1154             }
1155 
1156             problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
1157                     .setMessage(buffer.toString())
1158                     .setLocation(parent.getLocation(""))
1159                     .setException(e));
1160             throw problems.newModelBuildingException();
1161         }
1162 
1163         ModelBuildingRequest lenientRequest = request;
1164         if (request.getValidationLevel() > ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
1165             lenientRequest = new FilterModelBuildingRequest(request) {
1166                 @Override
1167                 public int getValidationLevel() {
1168                     return ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0;
1169                 }
1170             };
1171         }
1172 
1173         Model parentModel = readModel(modelSource, null, lenientRequest, problems);
1174 
1175         if (!parent.getVersion().equals(version)) {
1176             String rawChildModelVersion = childModel.getVersion();
1177 
1178             if (rawChildModelVersion == null) {
1179                 // Message below is checked for in the MNG-2199 core IT.
1180                 problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1181                         .setMessage("Version must be a constant")
1182                         .setLocation(childModel.getLocation("")));
1183 
1184             } else {
1185                 if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1186                     // Message below is checked for in the MNG-2199 core IT.
1187                     problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
1188                             .setMessage("Version must be a constant")
1189                             .setLocation(childModel.getLocation("version")));
1190                 }
1191             }
1192 
1193             // MNG-2199: What else to check here ?
1194         }
1195 
1196         ModelData parentData = new ModelData(
1197                 modelSource, parentModel, parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1198 
1199         return parentData;
1200     }
1201 
1202     private Model getSuperModel() {
1203         return superPomProvider.getSuperModel("4.0.0").clone();
1204     }
1205 
1206     @SuppressWarnings("checkstyle:methodlength")
1207     private void importDependencyManagement(
1208             Model model,
1209             ModelBuildingRequest request,
1210             DefaultModelProblemCollector problems,
1211             Collection<String> importIds) {
1212         DependencyManagement depMgmt = model.getDependencyManagement();
1213 
1214         if (depMgmt == null) {
1215             return;
1216         }
1217 
1218         String importing = model.getGroupId() + ':' + model.getArtifactId() + ':' + model.getVersion();
1219 
1220         importIds.add(importing);
1221 
1222         final WorkspaceModelResolver workspaceResolver = request.getWorkspaceModelResolver();
1223         final ModelResolver modelResolver = request.getModelResolver();
1224 
1225         ModelBuildingRequest importRequest = null;
1226 
1227         List<DependencyManagement> importMgmts = null;
1228 
1229         for (Iterator<Dependency> it = depMgmt.getDependencies().iterator(); it.hasNext(); ) {
1230             Dependency dependency = it.next();
1231 
1232             if (!"pom".equals(dependency.getType()) || !"import".equals(dependency.getScope())) {
1233                 continue;
1234             }
1235 
1236             it.remove();
1237 
1238             String groupId = dependency.getGroupId();
1239             String artifactId = dependency.getArtifactId();
1240             String version = dependency.getVersion();
1241 
1242             if (groupId == null || groupId.length() <= 0) {
1243                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1244                         .setMessage("'dependencyManagement.dependencies.dependency.groupId' for "
1245                                 + dependency.getManagementKey() + " is missing.")
1246                         .setLocation(dependency.getLocation("")));
1247                 continue;
1248             }
1249             if (artifactId == null || artifactId.length() <= 0) {
1250                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1251                         .setMessage("'dependencyManagement.dependencies.dependency.artifactId' for "
1252                                 + dependency.getManagementKey() + " is missing.")
1253                         .setLocation(dependency.getLocation("")));
1254                 continue;
1255             }
1256             if (version == null || version.length() <= 0) {
1257                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1258                         .setMessage("'dependencyManagement.dependencies.dependency.version' for "
1259                                 + dependency.getManagementKey() + " is missing.")
1260                         .setLocation(dependency.getLocation("")));
1261                 continue;
1262             }
1263 
1264             String imported = groupId + ':' + artifactId + ':' + version;
1265 
1266             if (importIds.contains(imported)) {
1267                 String message = "The dependencies of type=pom and with scope=import form a cycle: ";
1268                 for (String modelId : importIds) {
1269                     message += modelId + " -> ";
1270                 }
1271                 message += imported;
1272                 problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE).setMessage(message));
1273 
1274                 continue;
1275             }
1276 
1277             DependencyManagement importMgmt =
1278                     getCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.IMPORT);
1279 
1280             if (importMgmt == null) {
1281                 if (workspaceResolver == null && modelResolver == null) {
1282                     throw new NullPointerException(String.format(
1283                             "request.workspaceModelResolver and request.modelResolver cannot be null"
1284                                     + " (parent POM %s and POM %s)",
1285                             ModelProblemUtils.toId(groupId, artifactId, version),
1286                             ModelProblemUtils.toSourceHint(model)));
1287                 }
1288 
1289                 Model importModel = null;
1290                 if (workspaceResolver != null) {
1291                     try {
1292                         importModel = workspaceResolver.resolveEffectiveModel(groupId, artifactId, version);
1293                     } catch (UnresolvableModelException e) {
1294                         problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
1295                                 .setMessage(e.getMessage().toString())
1296                                 .setException(e));
1297                         continue;
1298                     }
1299                 }
1300 
1301                 // no workspace resolver or workspace resolver returned null (i.e. model not in workspace)
1302                 if (importModel == null) {
1303                     final ModelSource importSource;
1304                     try {
1305                         importSource = modelResolver.resolveModel(groupId, artifactId, version);
1306                     } catch (UnresolvableModelException e) {
1307                         StringBuilder buffer = new StringBuilder(256);
1308                         buffer.append("Non-resolvable import POM");
1309                         if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
1310                             buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
1311                         }
1312                         buffer.append(": ").append(e.getMessage());
1313 
1314                         problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
1315                                 .setMessage(buffer.toString())
1316                                 .setLocation(dependency.getLocation(""))
1317                                 .setException(e));
1318                         continue;
1319                     }
1320 
1321                     if (importRequest == null) {
1322                         importRequest = new DefaultModelBuildingRequest();
1323                         importRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
1324                         importRequest.setModelCache(request.getModelCache());
1325                         importRequest.setSystemProperties(request.getSystemProperties());
1326                         importRequest.setUserProperties(request.getUserProperties());
1327                         importRequest.setLocationTracking(request.isLocationTracking());
1328                     }
1329 
1330                     importRequest.setModelSource(importSource);
1331                     importRequest.setModelResolver(modelResolver.newCopy());
1332 
1333                     final ModelBuildingResult importResult;
1334                     try {
1335                         importResult = build(importRequest, importIds);
1336                     } catch (ModelBuildingException e) {
1337                         problems.addAll(e.getProblems());
1338                         continue;
1339                     }
1340 
1341                     problems.addAll(importResult.getProblems());
1342 
1343                     importModel = importResult.getEffectiveModel();
1344                 }
1345 
1346                 importMgmt = importModel.getDependencyManagement();
1347 
1348                 if (importMgmt == null) {
1349                     importMgmt = new DependencyManagement();
1350                 }
1351 
1352                 putCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.IMPORT, importMgmt);
1353             }
1354 
1355             if (importMgmts == null) {
1356                 importMgmts = new ArrayList<>();
1357             }
1358 
1359             importMgmts.add(importMgmt);
1360         }
1361 
1362         importIds.remove(importing);
1363 
1364         dependencyManagementImporter.importManagement(model, importMgmts, request, problems);
1365     }
1366 
1367     private <T> void putCache(
1368             ModelCache modelCache, String groupId, String artifactId, String version, ModelCacheTag<T> tag, T data) {
1369         if (modelCache != null) {
1370             modelCache.put(groupId, artifactId, version, tag.getName(), tag.intoCache(data));
1371         }
1372     }
1373 
1374     private <T> T getCache(
1375             ModelCache modelCache, String groupId, String artifactId, String version, ModelCacheTag<T> tag) {
1376         if (modelCache != null) {
1377             Object data = modelCache.get(groupId, artifactId, version, tag.getName());
1378             if (data != null) {
1379                 return tag.fromCache(tag.getType().cast(data));
1380             }
1381         }
1382         return null;
1383     }
1384 
1385     private void fireEvent(
1386             Model model,
1387             ModelBuildingRequest request,
1388             ModelProblemCollector problems,
1389             ModelBuildingEventCatapult catapult)
1390             throws ModelBuildingException {
1391         ModelBuildingListener listener = request.getModelBuildingListener();
1392 
1393         if (listener != null) {
1394             ModelBuildingEvent event = new DefaultModelBuildingEvent(model, request, problems);
1395 
1396             catapult.fire(listener, event);
1397         }
1398     }
1399 
1400     private boolean containsCoordinates(String message, String groupId, String artifactId, String version) {
1401         return message != null
1402                 && (groupId == null || message.contains(groupId))
1403                 && (artifactId == null || message.contains(artifactId))
1404                 && (version == null || message.contains(version));
1405     }
1406 
1407     protected boolean hasModelErrors(ModelProblemCollectorExt problems) {
1408         if (problems instanceof DefaultModelProblemCollector) {
1409             return ((DefaultModelProblemCollector) problems).hasErrors();
1410         } else {
1411             // the default execution path only knows the DefaultModelProblemCollector,
1412             // only reason it's not in signature is because it's package private
1413             throw new IllegalStateException();
1414         }
1415     }
1416 
1417     protected boolean hasFatalErrors(ModelProblemCollectorExt problems) {
1418         if (problems instanceof DefaultModelProblemCollector) {
1419             return ((DefaultModelProblemCollector) problems).hasFatalErrors();
1420         } else {
1421             // the default execution path only knows the DefaultModelProblemCollector,
1422             // only reason it's not in signature is because it's package private
1423             throw new IllegalStateException();
1424         }
1425     }
1426 }