1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.impl.model;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.LinkedHashSet;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Objects;
38 import java.util.Set;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.CopyOnWriteArrayList;
41 import java.util.concurrent.Executor;
42 import java.util.concurrent.Executors;
43 import java.util.concurrent.atomic.AtomicReference;
44 import java.util.function.BiFunction;
45 import java.util.function.Supplier;
46 import java.util.function.UnaryOperator;
47 import java.util.stream.Collectors;
48 import java.util.stream.Stream;
49
50 import org.apache.maven.api.Constants;
51 import org.apache.maven.api.RemoteRepository;
52 import org.apache.maven.api.Session;
53 import org.apache.maven.api.Type;
54 import org.apache.maven.api.VersionRange;
55 import org.apache.maven.api.annotations.Nonnull;
56 import org.apache.maven.api.annotations.Nullable;
57 import org.apache.maven.api.cache.CacheMetadata;
58 import org.apache.maven.api.cache.CacheRetention;
59 import org.apache.maven.api.di.Inject;
60 import org.apache.maven.api.di.Named;
61 import org.apache.maven.api.di.Singleton;
62 import org.apache.maven.api.feature.Features;
63 import org.apache.maven.api.model.Activation;
64 import org.apache.maven.api.model.Dependency;
65 import org.apache.maven.api.model.DependencyManagement;
66 import org.apache.maven.api.model.DeploymentRepository;
67 import org.apache.maven.api.model.DistributionManagement;
68 import org.apache.maven.api.model.Exclusion;
69 import org.apache.maven.api.model.InputLocation;
70 import org.apache.maven.api.model.Model;
71 import org.apache.maven.api.model.Parent;
72 import org.apache.maven.api.model.Profile;
73 import org.apache.maven.api.model.Repository;
74 import org.apache.maven.api.services.BuilderProblem;
75 import org.apache.maven.api.services.BuilderProblem.Severity;
76 import org.apache.maven.api.services.Interpolator;
77 import org.apache.maven.api.services.MavenException;
78 import org.apache.maven.api.services.ModelBuilder;
79 import org.apache.maven.api.services.ModelBuilderException;
80 import org.apache.maven.api.services.ModelBuilderRequest;
81 import org.apache.maven.api.services.ModelBuilderResult;
82 import org.apache.maven.api.services.ModelProblem;
83 import org.apache.maven.api.services.ModelProblem.Version;
84 import org.apache.maven.api.services.ModelProblemCollector;
85 import org.apache.maven.api.services.ModelSource;
86 import org.apache.maven.api.services.ProblemCollector;
87 import org.apache.maven.api.services.RepositoryFactory;
88 import org.apache.maven.api.services.Request;
89 import org.apache.maven.api.services.RequestTrace;
90 import org.apache.maven.api.services.Result;
91 import org.apache.maven.api.services.Source;
92 import org.apache.maven.api.services.Sources;
93 import org.apache.maven.api.services.SuperPomProvider;
94 import org.apache.maven.api.services.VersionParserException;
95 import org.apache.maven.api.services.model.DependencyManagementImporter;
96 import org.apache.maven.api.services.model.DependencyManagementInjector;
97 import org.apache.maven.api.services.model.InheritanceAssembler;
98 import org.apache.maven.api.services.model.ModelInterpolator;
99 import org.apache.maven.api.services.model.ModelNormalizer;
100 import org.apache.maven.api.services.model.ModelPathTranslator;
101 import org.apache.maven.api.services.model.ModelProcessor;
102 import org.apache.maven.api.services.model.ModelResolver;
103 import org.apache.maven.api.services.model.ModelResolverException;
104 import org.apache.maven.api.services.model.ModelUrlNormalizer;
105 import org.apache.maven.api.services.model.ModelValidator;
106 import org.apache.maven.api.services.model.ModelVersionParser;
107 import org.apache.maven.api.services.model.PathTranslator;
108 import org.apache.maven.api.services.model.PluginConfigurationExpander;
109 import org.apache.maven.api.services.model.PluginManagementInjector;
110 import org.apache.maven.api.services.model.ProfileActivationContext;
111 import org.apache.maven.api.services.model.ProfileInjector;
112 import org.apache.maven.api.services.model.ProfileSelector;
113 import org.apache.maven.api.services.model.RootLocator;
114 import org.apache.maven.api.services.xml.XmlReaderException;
115 import org.apache.maven.api.services.xml.XmlReaderRequest;
116 import org.apache.maven.api.spi.ModelParserException;
117 import org.apache.maven.api.spi.ModelTransformer;
118 import org.apache.maven.impl.DefaultRemoteRepository;
119 import org.apache.maven.impl.InternalSession;
120 import org.apache.maven.impl.RequestTraceHelper;
121 import org.apache.maven.impl.util.PhasingExecutor;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
124
125
126
127
128
129
130
131 @Named
132 @Singleton
133 public class DefaultModelBuilder implements ModelBuilder {
134
135 public static final String NAMESPACE_PREFIX = "http://maven.apache.org/POM/";
136 private static final String RAW = "raw";
137 private static final String FILE = "file";
138 private static final String IMPORT = "import";
139 private static final String PARENT = "parent";
140 private static final String PARENT_EXTERNAL = "parent-external";
141 private static final String MODEL = "model";
142
143 private final Logger logger = LoggerFactory.getLogger(getClass());
144
145 private final ModelProcessor modelProcessor;
146 private final ModelValidator modelValidator;
147 private final ModelNormalizer modelNormalizer;
148 private final ModelInterpolator modelInterpolator;
149 private final ModelPathTranslator modelPathTranslator;
150 private final ModelUrlNormalizer modelUrlNormalizer;
151 private final SuperPomProvider superPomProvider;
152 private final InheritanceAssembler inheritanceAssembler;
153 private final ProfileSelector profileSelector;
154 private final ProfileInjector profileInjector;
155 private final PluginManagementInjector pluginManagementInjector;
156 private final DependencyManagementInjector dependencyManagementInjector;
157 private final DependencyManagementImporter dependencyManagementImporter;
158 private final PluginConfigurationExpander pluginConfigurationExpander;
159 private final ModelVersionParser versionParser;
160 private final List<ModelTransformer> transformers;
161 private final ModelResolver modelResolver;
162 private final Interpolator interpolator;
163 private final PathTranslator pathTranslator;
164 private final RootLocator rootLocator;
165
166 @SuppressWarnings("checkstyle:ParameterNumber")
167 @Inject
168 public DefaultModelBuilder(
169 ModelProcessor modelProcessor,
170 ModelValidator modelValidator,
171 ModelNormalizer modelNormalizer,
172 ModelInterpolator modelInterpolator,
173 ModelPathTranslator modelPathTranslator,
174 ModelUrlNormalizer modelUrlNormalizer,
175 SuperPomProvider superPomProvider,
176 InheritanceAssembler inheritanceAssembler,
177 ProfileSelector profileSelector,
178 ProfileInjector profileInjector,
179 PluginManagementInjector pluginManagementInjector,
180 DependencyManagementInjector dependencyManagementInjector,
181 DependencyManagementImporter dependencyManagementImporter,
182 PluginConfigurationExpander pluginConfigurationExpander,
183 ModelVersionParser versionParser,
184 @Nullable List<ModelTransformer> transformers,
185 ModelResolver modelResolver,
186 Interpolator interpolator,
187 PathTranslator pathTranslator,
188 RootLocator rootLocator) {
189 this.modelProcessor = modelProcessor;
190 this.modelValidator = modelValidator;
191 this.modelNormalizer = modelNormalizer;
192 this.modelInterpolator = modelInterpolator;
193 this.modelPathTranslator = modelPathTranslator;
194 this.modelUrlNormalizer = modelUrlNormalizer;
195 this.superPomProvider = superPomProvider;
196 this.inheritanceAssembler = inheritanceAssembler;
197 this.profileSelector = profileSelector;
198 this.profileInjector = profileInjector;
199 this.pluginManagementInjector = pluginManagementInjector;
200 this.dependencyManagementInjector = dependencyManagementInjector;
201 this.dependencyManagementImporter = dependencyManagementImporter;
202 this.pluginConfigurationExpander = pluginConfigurationExpander;
203 this.versionParser = versionParser;
204 this.transformers = transformers;
205 this.modelResolver = modelResolver;
206 this.interpolator = interpolator;
207 this.pathTranslator = pathTranslator;
208 this.rootLocator = rootLocator;
209 }
210
211 @Override
212 public ModelBuilderSession newSession() {
213 return new ModelBuilderSessionImpl();
214 }
215
216 protected class ModelBuilderSessionImpl implements ModelBuilderSession {
217 ModelBuilderSessionState mainSession;
218
219
220
221
222
223
224
225
226 @Override
227 public ModelBuilderResult build(ModelBuilderRequest request) throws ModelBuilderException {
228 RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(request.getSession(), request);
229 try {
230
231 ModelBuilderSessionState session;
232 if (mainSession == null) {
233 mainSession = new ModelBuilderSessionState(request);
234 session = mainSession;
235 } else {
236 session = mainSession.deriveTopLevel(
237 request,
238 new DefaultModelBuilderResult(request, ProblemCollector.create(mainSession.session)));
239 }
240
241 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
242
243 session.buildBuildPom();
244 } else {
245
246 session.buildEffectiveModel(new LinkedHashSet<>());
247 }
248 return session.result;
249 } finally {
250 RequestTraceHelper.exit(trace);
251 }
252 }
253 }
254
255 protected class ModelBuilderSessionState implements ModelProblemCollector {
256 final Session session;
257 final ModelBuilderRequest request;
258 final DefaultModelBuilderResult result;
259 final Graph dag;
260 final Map<GAKey, Set<ModelSource>> mappedSources;
261 final Set<ImportWarningKey> reportedImportWarnings;
262 final Map<String, ProblemCollector<ModelProblem>> reactorProblemCollectors;
263
264 String source;
265 Model sourceModel;
266 Model rootModel;
267
268 List<RemoteRepository> pomRepositories;
269 List<RemoteRepository> externalRepositories;
270 List<RemoteRepository> repositories;
271
272 List<RemoteRepository> getRepositories() {
273 return repositories;
274 }
275
276 List<RemoteRepository> getExternalRepositories() {
277 return externalRepositories;
278 }
279
280
281
282 final Set<String> parentChain;
283
284
285
286
287
288
289
290 final boolean externalOrigin;
291
292 ModelBuilderSessionState(ModelBuilderRequest request) {
293 this(
294 request.getSession(),
295 request,
296 new DefaultModelBuilderResult(request, ProblemCollector.create(request.getSession())),
297 new Graph(),
298 new ConcurrentHashMap<>(64),
299 ConcurrentHashMap.newKeySet(),
300 new ConcurrentHashMap<>(),
301 List.of(),
302 repos(request),
303 repos(request),
304 new LinkedHashSet<>(),
305 isExternalOrigin(request));
306 }
307
308 static List<RemoteRepository> repos(ModelBuilderRequest request) {
309 List<RemoteRepository> repos = request.getRepositories() != null
310 ? request.getRepositories()
311 : request.getSession().getRemoteRepositories();
312 return mergeRepositoriesById(repos);
313 }
314
315
316
317
318
319
320
321
322
323
324 private static List<RemoteRepository> mergeRepositoriesById(List<RemoteRepository> repos) {
325 if (repos.size() <= 1) {
326 return List.copyOf(repos);
327 }
328 LinkedHashMap<String, RemoteRepository> byId = new LinkedHashMap<>();
329 boolean hasDuplicates = false;
330 for (RemoteRepository repo : repos) {
331 RemoteRepository existing = byId.putIfAbsent(repo.getId(), repo);
332 if (existing != null) {
333 hasDuplicates = true;
334 byId.put(repo.getId(), mergeRepositoryPolicies(existing, repo));
335 }
336 }
337 return hasDuplicates ? List.copyOf(byId.values()) : List.copyOf(repos);
338 }
339
340
341
342
343
344
345
346 private static RemoteRepository mergeRepositoryPolicies(RemoteRepository dominant, RemoteRepository recessive) {
347 if (dominant instanceof DefaultRemoteRepository d && recessive instanceof DefaultRemoteRepository r) {
348 org.eclipse.aether.repository.RemoteRepository dr = d.getRepository();
349 org.eclipse.aether.repository.RemoteRepository rr = r.getRepository();
350
351 boolean mergeSnapshots =
352 rr.getPolicy(true).isEnabled() && !dr.getPolicy(true).isEnabled();
353 boolean mergeReleases =
354 rr.getPolicy(false).isEnabled() && !dr.getPolicy(false).isEnabled();
355
356 if (mergeSnapshots || mergeReleases) {
357 org.eclipse.aether.repository.RemoteRepository.Builder builder =
358 new org.eclipse.aether.repository.RemoteRepository.Builder(dr);
359 if (mergeSnapshots) {
360 builder.setSnapshotPolicy(rr.getPolicy(true));
361 }
362 if (mergeReleases) {
363 builder.setReleasePolicy(rr.getPolicy(false));
364 }
365 return new DefaultRemoteRepository(builder.build());
366 }
367 }
368 return dominant;
369 }
370
371 @SuppressWarnings("checkstyle:ParameterNumber")
372 private ModelBuilderSessionState(
373 Session session,
374 ModelBuilderRequest request,
375 DefaultModelBuilderResult result,
376 Graph dag,
377 Map<GAKey, Set<ModelSource>> mappedSources,
378 Set<ImportWarningKey> reportedImportWarnings,
379 Map<String, ProblemCollector<ModelProblem>> reactorProblemCollectors,
380 List<RemoteRepository> pomRepositories,
381 List<RemoteRepository> externalRepositories,
382 List<RemoteRepository> repositories,
383 Set<String> parentChain,
384 boolean externalOrigin) {
385 this.session = session;
386 this.request = request;
387 this.result = result;
388 this.dag = dag;
389 this.mappedSources = mappedSources;
390 this.reportedImportWarnings = reportedImportWarnings;
391 this.reactorProblemCollectors = reactorProblemCollectors;
392 this.pomRepositories = pomRepositories;
393 this.externalRepositories = externalRepositories;
394 this.repositories = repositories;
395 this.parentChain = parentChain;
396 this.externalOrigin = externalOrigin;
397 this.result.setSource(this.request.getSource());
398 }
399
400 ModelBuilderSessionState derive(ModelSource source) {
401 return derive(source, new DefaultModelBuilderResult(request, ProblemCollector.create(session)));
402 }
403
404 ModelBuilderSessionState derive(ModelSource source, DefaultModelBuilderResult result) {
405 return derive(ModelBuilderRequest.build(request, source), result);
406 }
407
408
409
410
411 ModelBuilderSessionState derive(ModelBuilderRequest request) {
412 return derive(request, new DefaultModelBuilderResult(request, ProblemCollector.create(session)));
413 }
414
415 ModelBuilderSessionState derive(ModelBuilderRequest request, DefaultModelBuilderResult result) {
416 return derive(request, result, reportedImportWarnings, reactorProblemCollectors);
417 }
418
419 ModelBuilderSessionState deriveTopLevel(ModelBuilderRequest request, DefaultModelBuilderResult result) {
420 return derive(request, result, ConcurrentHashMap.newKeySet(), new ConcurrentHashMap<>());
421 }
422
423 private ModelBuilderSessionState derive(
424 ModelBuilderRequest request,
425 DefaultModelBuilderResult result,
426 Set<ImportWarningKey> reportedImportWarnings,
427 Map<String, ProblemCollector<ModelProblem>> reactorProblemCollectors) {
428 if (session != request.getSession()) {
429 throw new IllegalArgumentException("Session mismatch");
430 }
431
432
433
434
435
436
437 List<RemoteRepository> derivedExtRepos = externalRepositories;
438 List<RemoteRepository> derivedRepos = repositories;
439 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER
440 && request.getRepositories() != null
441 && !request.getRepositories().isEmpty()) {
442 derivedExtRepos = List.copyOf(request.getRepositories());
443 if (pomRepositories.isEmpty()) {
444 derivedRepos = derivedExtRepos;
445 } else {
446 RepositoryFactory repositoryFactory = session.getService(RepositoryFactory.class);
447 derivedRepos = repositoryFactory.aggregate(session, pomRepositories, derivedExtRepos, false);
448 }
449 }
450 boolean derivedExternalOrigin = externalOrigin || isExternalOrigin(request);
451 return new ModelBuilderSessionState(
452 session,
453 request,
454 result,
455 dag,
456 mappedSources,
457 reportedImportWarnings,
458 reactorProblemCollectors,
459 pomRepositories,
460 derivedExtRepos,
461 derivedRepos,
462 new LinkedHashSet<>(),
463 derivedExternalOrigin);
464 }
465
466 @Override
467 public String toString() {
468 return "ModelBuilderSession[" + "session="
469 + session + ", " + "request="
470 + request + ", " + "result="
471 + result + ']';
472 }
473
474 PhasingExecutor createExecutor() {
475 return new PhasingExecutor(Executors.newFixedThreadPool(getParallelism()));
476 }
477
478 private int getParallelism() {
479 int parallelism = Runtime.getRuntime().availableProcessors() / 2 + 1;
480 try {
481 String str = request.getUserProperties().get(Constants.MAVEN_MODEL_BUILDER_PARALLELISM);
482 if (str != null) {
483 parallelism = Integer.parseInt(str);
484 }
485 } catch (Exception e) {
486
487 }
488 return Math.max(1, Math.min(parallelism, Runtime.getRuntime().availableProcessors()));
489 }
490
491 public Model getRawModel(Path from, String groupId, String artifactId) {
492 ModelSource source = getSource(groupId, artifactId);
493 if (source != null) {
494 if (addEdge(from, source.getPath())) {
495 return null;
496 }
497 try {
498 return derive(source).readRawModel();
499 } catch (ModelBuilderException e) {
500
501 }
502 }
503 return null;
504 }
505
506 public Model getRawModel(Path from, Path path) {
507 if (!Files.isRegularFile(path)) {
508 throw new IllegalArgumentException("Not a regular file: " + path);
509 }
510 if (addEdge(from, path)) {
511 return null;
512 }
513 try {
514 return derive(Sources.buildSource(path)).readRawModel();
515 } catch (ModelBuilderException e) {
516
517 }
518 return null;
519 }
520
521
522
523
524 private boolean addEdge(Path from, Path p) {
525 try {
526 dag.addEdge(from.toString(), p.toString());
527 return false;
528 } catch (Graph.CycleDetectedException e) {
529 add(Severity.FATAL, Version.BASE, "Cycle detected between models at " + from + " and " + p, null, e);
530 return true;
531 }
532 }
533
534 public ModelSource getSource(String groupId, String artifactId) {
535 Set<ModelSource> sources = mappedSources.get(new GAKey(groupId, artifactId));
536 if (sources != null) {
537 return sources.stream()
538 .reduce((a, b) -> {
539 throw new IllegalStateException(String.format(
540 "No unique Source for %s:%s: %s and %s",
541 groupId, artifactId, a.getLocation(), b.getLocation()));
542 })
543 .orElse(null);
544 }
545 return null;
546 }
547
548 public void putSource(String groupId, String artifactId, ModelSource source) {
549 mappedSources
550 .computeIfAbsent(new GAKey(groupId, artifactId), k -> new HashSet<>())
551 .add(source);
552
553 if (groupId != null) {
554 putSource(null, artifactId, source);
555 }
556 }
557
558 @Override
559 public ProblemCollector<ModelProblem> getProblemCollector() {
560 return result.getProblemCollector();
561 }
562
563 @Override
564 public void setSource(String source) {
565 this.source = source;
566 this.sourceModel = null;
567 }
568
569 @Override
570 public void setSource(Model source) {
571 this.sourceModel = source;
572 this.source = null;
573
574 if (rootModel == null) {
575 rootModel = source;
576 }
577 }
578
579 @Override
580 public String getSource() {
581 if (source == null && sourceModel != null) {
582 source = ModelProblemUtils.toPath(sourceModel);
583 }
584 return source;
585 }
586
587 private String getModelId() {
588 return ModelProblemUtils.toId(sourceModel);
589 }
590
591 @Override
592 public void setRootModel(Model rootModel) {
593 this.rootModel = rootModel;
594 }
595
596 @Override
597 public Model getRootModel() {
598 return rootModel;
599 }
600
601 @Override
602 public void add(
603 BuilderProblem.Severity severity,
604 ModelProblem.Version version,
605 String message,
606 InputLocation location,
607 Exception exception) {
608 int line = -1;
609 int column = -1;
610 String source = null;
611 String modelId = null;
612
613 if (location != null) {
614 line = location.getLineNumber();
615 column = location.getColumnNumber();
616 if (location.getSource() != null) {
617 modelId = location.getSource().getModelId();
618 source = location.getSource().getLocation();
619 }
620 }
621
622 if (modelId == null) {
623 modelId = getModelId();
624 source = getSource();
625 }
626
627 if (line <= 0 && column <= 0 && exception instanceof ModelParserException e) {
628 line = e.getLineNumber();
629 column = e.getColumnNumber();
630 }
631
632 ModelProblem problem =
633 new DefaultModelProblem(message, severity, version, source, line, column, modelId, exception);
634
635 add(problem);
636 }
637
638 @Override
639 public ModelBuilderException newModelBuilderException() {
640 return new ModelBuilderException(result);
641 }
642
643 public void mergeRepositories(Model model, boolean replace) {
644 if (model.getRepositories().isEmpty()
645 || InternalSession.from(session).getSession().isIgnoreArtifactDescriptorRepositories()) {
646 return;
647 }
648
649 Model interpolatedModel = interpolateModel(
650 Model.newBuilder()
651 .pomFile(model.getPomFile())
652 .properties(model.getProperties())
653 .repositories(model.getRepositories())
654 .build(),
655 request,
656 this);
657 List<RemoteRepository> repos = interpolatedModel.getRepositories().stream()
658
659
660
661 .filter(repo -> repo.getUrl() != null
662 && !repo.getUrl().contains("${")
663 && (repo.getId() == null || !repo.getId().contains("${")))
664 .map(session::createRemoteRepository)
665 .toList();
666
667
668
669
670
671
672 if (replace && isBuildRequest()) {
673 Set<String> ids = repos.stream().map(RemoteRepository::getId).collect(Collectors.toSet());
674 repositories = repositories.stream()
675 .filter(r -> !ids.contains(r.getId()))
676 .toList();
677 pomRepositories = pomRepositories.stream()
678 .filter(r -> !ids.contains(r.getId()))
679 .toList();
680 } else {
681 Set<String> ids =
682 pomRepositories.stream().map(RemoteRepository::getId).collect(Collectors.toSet());
683 repos = repos.stream().filter(r -> !ids.contains(r.getId())).toList();
684 }
685
686 RepositoryFactory repositoryFactory = session.getService(RepositoryFactory.class);
687 if (request.getRepositoryMerging() == ModelBuilderRequest.RepositoryMerging.REQUEST_DOMINANT) {
688 repositories = repositoryFactory.aggregate(session, repositories, repos, true);
689 pomRepositories = repositories;
690 } else {
691 pomRepositories = repositoryFactory.aggregate(session, pomRepositories, repos, true);
692 repositories = repositoryFactory.aggregate(session, pomRepositories, externalRepositories, false);
693 }
694 }
695
696
697
698
699
700 Model transformFileToRaw(Model model) {
701 Parent newParent = inferParentVersion(model);
702
703 List<Dependency> newDeps = null;
704 boolean depsChanged = false;
705 if (!model.getDependencies().isEmpty()) {
706 newDeps = new ArrayList<>(model.getDependencies().size());
707 depsChanged = inferDependencies(model, model.getDependencies(), newDeps);
708 }
709
710 DependencyManagement depMgmt = model.getDependencyManagement();
711 List<Dependency> newManagedDeps = null;
712 boolean managedDepsChanged = false;
713 if (depMgmt != null && !depMgmt.getDependencies().isEmpty()) {
714 newManagedDeps = new ArrayList<>(depMgmt.getDependencies().size());
715 managedDepsChanged = inferDependencies(model, depMgmt.getDependencies(), newManagedDeps);
716 }
717
718 if (newParent == null && !depsChanged && !managedDepsChanged) {
719 return model;
720 }
721 Model.Builder builder = Model.newBuilder(model);
722 if (newParent != null) {
723 builder.parent(newParent);
724 }
725 if (depsChanged) {
726 builder.dependencies(newDeps);
727 }
728 if (managedDepsChanged) {
729 builder.dependencyManagement(depMgmt.withDependencies(newManagedDeps));
730 }
731 return builder.build();
732 }
733
734 private Parent inferParentVersion(Model model) {
735 Parent parent = model.getParent();
736 if (parent == null
737 || parent.getVersion() != null
738 || parent.getGroupId() == null
739 || parent.getArtifactId() == null) {
740 return null;
741 }
742
743 Model parentModel = getRawModel(model.getPomFile(), parent.getGroupId(), parent.getArtifactId());
744 if (parentModel == null) {
745 return null;
746 }
747
748 String version = parentModel.getVersion();
749 InputLocation versionLocation = parentModel.getLocation("version");
750 if (version == null && parentModel.getParent() != null) {
751
752
753
754 version = parentModel.getParent().getVersion();
755 versionLocation = parentModel.getParent().getLocation("version");
756 }
757 return version != null
758 ? parent.with()
759 .version(version)
760 .location("version", versionLocation)
761 .build()
762 : null;
763 }
764
765
766
767
768
769
770
771
772
773
774 private boolean inferDependencies(Model model, List<Dependency> dependencies, List<Dependency> result) {
775 boolean changed = false;
776 for (Dependency dep : dependencies) {
777 Dependency newDep = null;
778 if (dep.getVersion() == null) {
779 newDep = inferDependencyVersion(model, dep);
780 } else if (dep.getGroupId() == null) {
781
782 newDep = inferDependencyGroupId(model, dep);
783 }
784 if (newDep != null) {
785 changed = true;
786 }
787 result.add(newDep == null ? dep : newDep);
788 }
789 return changed;
790 }
791
792 private Dependency inferDependencyVersion(Model model, Dependency dep) {
793 Model depModel = getRawModel(model.getPomFile(), dep.getGroupId(), dep.getArtifactId());
794 if (depModel == null) {
795 return null;
796 }
797 Dependency.Builder depBuilder = Dependency.newBuilder(dep);
798 String version = depModel.getVersion();
799 InputLocation versionLocation = depModel.getLocation("version");
800 if (version == null && depModel.getParent() != null) {
801 version = depModel.getParent().getVersion();
802 versionLocation = depModel.getParent().getLocation("version");
803 }
804 depBuilder.version(version).location("version", versionLocation);
805 if (dep.getGroupId() == null) {
806 String depGroupId = depModel.getGroupId();
807 InputLocation groupIdLocation = depModel.getLocation("groupId");
808 if (depGroupId == null && depModel.getParent() != null) {
809 depGroupId = depModel.getParent().getGroupId();
810 groupIdLocation = depModel.getParent().getLocation("groupId");
811 }
812 depBuilder.groupId(depGroupId).location("groupId", groupIdLocation);
813 }
814 return depBuilder.build();
815 }
816
817 private Dependency inferDependencyGroupId(Model model, Dependency dep) {
818 Model depModel = getRawModel(model.getPomFile(), dep.getGroupId(), dep.getArtifactId());
819 if (depModel == null) {
820 return null;
821 }
822 Dependency.Builder depBuilder = Dependency.newBuilder(dep);
823 String depGroupId = depModel.getGroupId();
824 InputLocation groupIdLocation = depModel.getLocation("groupId");
825 if (depGroupId == null && depModel.getParent() != null) {
826 depGroupId = depModel.getParent().getGroupId();
827 groupIdLocation = depModel.getParent().getLocation("groupId");
828 }
829 depBuilder.groupId(depGroupId).location("groupId", groupIdLocation);
830 return depBuilder.build();
831 }
832
833 String replaceCiFriendlyVersion(Map<String, String> properties, String version) {
834 return version != null ? interpolator.interpolate(version, properties::get) : null;
835 }
836
837
838
839
840
841
842
843 private Map<String, String> getEnhancedProperties(Model model, Path rootDirectory, Set<Path> activeModelReads) {
844 Map<String, String> properties = new HashMap<>();
845
846
847 if (model.getProjectDirectory() != null) {
848 String basedir = model.getProjectDirectory().toString();
849 String basedirUri = model.getProjectDirectory().toUri().toString();
850 properties.put("basedir", basedir);
851 properties.put("project.basedir", basedir);
852 properties.put("project.basedir.uri", basedirUri);
853 }
854 if (rootDirectory != null) {
855 try {
856 String root = rootDirectory.toString();
857 String rootUri = rootDirectory.toUri().toString();
858 properties.put("project.rootDirectory", root);
859 properties.put("project.rootDirectory.uri", rootUri);
860 } catch (IllegalStateException e) {
861
862 }
863 }
864
865
866
867
868
869
870
871 Path normalizedRootDir =
872 rootDirectory != null ? rootDirectory.toAbsolutePath().normalize() : null;
873 Path normalizedProjectDir = model.getProjectDirectory() != null
874 ? model.getProjectDirectory().toAbsolutePath().normalize()
875 : null;
876 if (!Objects.equals(normalizedRootDir, normalizedProjectDir)) {
877 Path rootModelPath = modelProcessor.locateExistingPom(rootDirectory);
878 if (rootModelPath != null) {
879
880
881
882
883
884
885
886
887 if (isParentWithinRootDirectory(rootModelPath, rootDirectory)
888 && !activeModelReads.contains(
889 rootModelPath.toAbsolutePath().normalize())) {
890 Model rootModel =
891 derive(Sources.buildSource(rootModelPath)).readFileModel(activeModelReads);
892 properties.putAll(getPropertiesWithProfiles(rootModel, properties));
893 }
894 }
895 } else {
896 properties.putAll(getPropertiesWithProfiles(model, properties));
897 }
898
899 return properties;
900 }
901
902
903
904
905
906
907
908
909 private Map<String, String> getPropertiesWithProfiles(Model model, Map<String, String> baseProperties) {
910 Map<String, String> properties = new HashMap<>();
911
912
913 properties.putAll(baseProperties);
914
915
916 properties.putAll(model.getProperties());
917
918 try {
919
920 DefaultProfileActivationContext profileContext = getProfileActivationContext(request, model);
921
922
923 List<Profile> activeProfiles = getActiveProfiles(model.getProfiles(), profileContext);
924
925 for (Profile profile : activeProfiles) {
926 properties.putAll(profile.getProperties());
927 }
928 } catch (Exception e) {
929
930
931 logger.warn("Failed to activate profiles for CI-friendly version processing: {}", e.getMessage());
932 logger.debug("Profile activation failure details", e);
933 }
934
935
936
937 properties.putAll(request.getSystemProperties());
938 properties.putAll(request.getUserProperties());
939
940 return properties;
941 }
942
943
944
945
946
947 private Map<String, String> getPropertiesWithProfiles(Model model) {
948 return getPropertiesWithProfiles(model, new HashMap<>());
949 }
950
951 private void buildBuildPom() throws ModelBuilderException {
952
953 Path top = request.getSource().getPath();
954 if (top == null) {
955 throw new IllegalStateException("Recursive build requested but source has no path");
956 }
957 top = top.toAbsolutePath().normalize();
958
959
960 Path rootDirectory;
961 try {
962 rootDirectory = session.getRootDirectory();
963 } catch (IllegalStateException e) {
964 rootDirectory = session.getService(RootLocator.class).findMandatoryRoot(top);
965 }
966
967
968 Path root = modelProcessor.locateExistingPom(rootDirectory);
969 if (root != null) {
970 root = root.toAbsolutePath().normalize();
971 } else {
972 root = top;
973 }
974
975
976 loadFromRoot(root, top);
977
978
979 if (hasErrors()) {
980 throw newModelBuilderException();
981 }
982
983
984
985 var allResults = results(result).toList();
986 List<RuntimeException> exceptions = new CopyOnWriteArrayList<>();
987 InternalSession session = InternalSession.from(this.session);
988 RequestTrace trace = session.getCurrentTrace();
989 try (PhasingExecutor executor = createExecutor()) {
990 for (DefaultModelBuilderResult r : allResults) {
991 executor.execute(() -> {
992 ModelBuilderSessionState mbs = derive(r.getSource(), r);
993 session.setCurrentTrace(trace);
994 try {
995 mbs.buildEffectiveModel(new LinkedHashSet<>());
996 } catch (ModelBuilderException e) {
997
998
999 for (var problem : e.getResult()
1000 .getProblemCollector()
1001 .problems()
1002 .toList()) {
1003 getProblemCollector().reportProblem(problem);
1004 }
1005 } catch (RuntimeException t) {
1006 exceptions.add(t);
1007 } finally {
1008 session.setCurrentTrace(null);
1009 }
1010 });
1011 }
1012 }
1013
1014
1015 if (exceptions.size() == 1) {
1016 throw exceptions.get(0);
1017 } else if (exceptions.size() > 1) {
1018 MavenException fatalException = new MavenException("Multiple fatal exceptions occurred");
1019 exceptions.forEach(fatalException::addSuppressed);
1020 throw fatalException;
1021 } else if (hasErrors()) {
1022 throw newModelBuilderException();
1023 }
1024 }
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034 Stream<DefaultModelBuilderResult> results(DefaultModelBuilderResult r) {
1035 return Stream.concat(Stream.of(r), r.getChildren().stream().flatMap(this::results));
1036 }
1037
1038 private void loadFromRoot(Path root, Path top) {
1039 try (PhasingExecutor executor = createExecutor()) {
1040 DefaultModelBuilderResult r = Objects.equals(top, root)
1041 ? result
1042 : new DefaultModelBuilderResult(request, ProblemCollector.create(session));
1043 loadFilePom(executor, top, root, Set.of(), r);
1044 }
1045 if (result.getFileModel() == null && !Objects.equals(top, root)) {
1046 logger.warn(
1047 "The top project ({}) cannot be found in the reactor from root project ({}). "
1048 + "Make sure the root directory is correct (a missing '.mvn' directory in the root "
1049 + "project is the most common cause) and the project is correctly included "
1050 + "in the reactor (missing activated profiles, command line options, etc.). For this "
1051 + "build, the top project will be used as the root project.",
1052 top,
1053 root);
1054 mappedSources.clear();
1055 reportedImportWarnings.clear();
1056 reactorProblemCollectors.clear();
1057 loadFromRoot(top, top);
1058 }
1059 }
1060
1061 private void loadFilePom(
1062 Executor executor, Path top, Path pom, Set<Path> parents, DefaultModelBuilderResult r) {
1063 try {
1064 Path pomDirectory = Files.isDirectory(pom) ? pom : pom.getParent();
1065 ModelSource src = Sources.buildSource(pom);
1066 Model model = derive(src, r).readFileModel();
1067
1068
1069 registerReactorProblemCollector(src, r.getProblemCollector());
1070 putSource(getGroupId(model), model.getArtifactId(), src);
1071 Model activated = activateFileModel(model);
1072 for (String subproject : getSubprojects(activated)) {
1073 if (subproject == null || subproject.isEmpty()) {
1074 continue;
1075 }
1076
1077
1078
1079
1080
1081
1082 subproject = interpolator.interpolate(
1083 subproject,
1084 Interpolator.chain(
1085 request.getUserProperties()::get,
1086 activated.getProperties()::get,
1087 request.getSystemProperties()::get));
1088
1089 subproject = subproject.replace('\\', File.separatorChar).replace('/', File.separatorChar);
1090
1091 Path rawSubprojectFile = modelProcessor.locateExistingPom(pomDirectory.resolve(subproject));
1092
1093 if (rawSubprojectFile == null) {
1094 ModelProblem problem = new DefaultModelProblem(
1095 "Child subproject " + subproject + " of " + pomDirectory + " does not exist",
1096 Severity.ERROR,
1097 Version.BASE,
1098 model,
1099 -1,
1100 -1,
1101 null);
1102 r.getProblemCollector().reportProblem(problem);
1103 continue;
1104 }
1105
1106 Path subprojectFile = rawSubprojectFile.toAbsolutePath().normalize();
1107
1108 if (parents.contains(subprojectFile)) {
1109 StringBuilder buffer = new StringBuilder(256);
1110 for (Path aggregatorFile : parents) {
1111 buffer.append(aggregatorFile).append(" -> ");
1112 }
1113 buffer.append(subprojectFile);
1114
1115 ModelProblem problem = new DefaultModelProblem(
1116 "Child subproject " + subprojectFile + " of " + pom + " forms aggregation cycle "
1117 + buffer,
1118 Severity.ERROR,
1119 Version.BASE,
1120 model,
1121 -1,
1122 -1,
1123 null);
1124 r.getProblemCollector().reportProblem(problem);
1125 continue;
1126 }
1127
1128 DefaultModelBuilderResult cr = Objects.equals(top, subprojectFile)
1129 ? result
1130 : new DefaultModelBuilderResult(request, ProblemCollector.create(session));
1131 if (request.isRecursive()) {
1132 r.getChildren().add(cr);
1133 }
1134
1135 InternalSession session = InternalSession.from(this.session);
1136 RequestTrace trace = session.getCurrentTrace();
1137 executor.execute(() -> {
1138 session.setCurrentTrace(trace);
1139 try {
1140 loadFilePom(executor, top, subprojectFile, concat(parents, pom), cr);
1141 } finally {
1142 session.setCurrentTrace(null);
1143 }
1144 });
1145 }
1146 } catch (ModelBuilderException e) {
1147
1148 add(Severity.ERROR, Version.V40, "Failed to load project " + pom, e);
1149 }
1150 }
1151
1152 static <T> Set<T> concat(Set<T> a, T b) {
1153 Set<T> result = new HashSet<>(a);
1154 result.add(b);
1155 return Set.copyOf(result);
1156 }
1157
1158 void buildEffectiveModel(Collection<String> importIds) throws ModelBuilderException {
1159 Model resultModel = readEffectiveModel();
1160 setSource(resultModel);
1161 setRootModel(resultModel);
1162
1163
1164 resultModel =
1165 modelPathTranslator.alignToBaseDirectory(resultModel, resultModel.getProjectDirectory(), request);
1166
1167
1168 resultModel = pluginManagementInjector.injectManagement(resultModel, request, this);
1169
1170
1171 if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY) {
1172 org.apache.maven.api.services.ModelTransformer lifecycleBindingsInjector =
1173 request.getLifecycleBindingsInjector();
1174 if (lifecycleBindingsInjector != null) {
1175 resultModel = lifecycleBindingsInjector.transform(resultModel, request, this);
1176 }
1177 }
1178
1179
1180 resultModel = importDependencyManagement(resultModel, importIds);
1181
1182
1183 resultModel = dependencyManagementInjector.injectManagement(resultModel, request, this);
1184
1185 resultModel = modelNormalizer.injectDefaultValues(resultModel, request, this);
1186
1187 if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY) {
1188
1189 resultModel = pluginConfigurationExpander.expandPluginConfiguration(resultModel, request, this);
1190 }
1191
1192 for (var transformer : transformers) {
1193 resultModel = transformer.transformEffectiveModel(resultModel);
1194 }
1195
1196 result.setEffectiveModel(resultModel);
1197
1198 if (result.getFileModel().getParent() != null
1199 && result.getFileModel().getParent().getRelativePath() == null) {
1200 result.setFileModel(result.getFileModel()
1201 .withParent(result.getFileModel()
1202 .getParent()
1203 .withRelativePath(resultModel.getParent().getRelativePath())));
1204 }
1205
1206
1207 modelValidator.validateEffectiveModel(
1208 session,
1209 resultModel,
1210 isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
1211 this);
1212
1213 if (hasErrors()) {
1214 throw newModelBuilderException();
1215 }
1216 }
1217
1218 Model readParent(
1219 Model childModel,
1220 Parent parent,
1221 DefaultProfileActivationContext profileActivationContext,
1222 Set<String> parentChain) {
1223 Model parentModel;
1224
1225 if (parent != null) {
1226
1227 String parentId = parent.getGroupId() + ":" + parent.getArtifactId() + ":" + parent.getVersion();
1228 if (!parentChain.add(parentId)) {
1229 StringBuilder message = new StringBuilder("The parents form a cycle: ");
1230 for (String id : parentChain) {
1231 message.append(id).append(" -> ");
1232 }
1233 message.append(parentId);
1234
1235 add(Severity.FATAL, Version.BASE, message.toString());
1236 throw newModelBuilderException();
1237 }
1238
1239 try {
1240 parentModel = resolveParent(childModel, parent, profileActivationContext, parentChain);
1241
1242 if (!"pom".equals(parentModel.getPackaging())) {
1243 add(
1244 Severity.ERROR,
1245 Version.BASE,
1246 "Invalid packaging for parent POM " + ModelProblemUtils.toSourceHint(parentModel)
1247 + ", must be \"pom\" but is \"" + parentModel.getPackaging() + "\"",
1248 parentModel.getLocation("packaging"));
1249 }
1250 result.setParentModel(parentModel);
1251
1252
1253 if (parentModel.getParent() != null) {
1254 readParent(parentModel, parentModel.getParent(), profileActivationContext, parentChain);
1255 }
1256 } finally {
1257
1258 parentChain.remove(parentId);
1259 }
1260 } else {
1261 String superModelVersion = childModel.getModelVersion();
1262 if (superModelVersion == null || !KNOWN_MODEL_VERSIONS.contains(superModelVersion)) {
1263
1264
1265
1266 superModelVersion = MODEL_VERSION_4_0_0;
1267 }
1268 parentModel = getSuperModel(superModelVersion);
1269 }
1270
1271 return parentModel;
1272 }
1273
1274 private Model resolveParent(
1275 Model childModel,
1276 Parent parent,
1277 DefaultProfileActivationContext profileActivationContext,
1278 Set<String> parentChain)
1279 throws ModelBuilderException {
1280 Model parentModel = null;
1281 if (isBuildRequest()) {
1282 parentModel = readParentLocally(childModel, parent, profileActivationContext, parentChain);
1283 }
1284 if (parentModel == null) {
1285 parentModel = resolveAndReadParentExternally(childModel, parent, profileActivationContext, parentChain);
1286 }
1287 return parentModel;
1288 }
1289
1290 private Model readParentLocally(
1291 Model childModel,
1292 Parent parent,
1293 DefaultProfileActivationContext profileActivationContext,
1294 Set<String> parentChain)
1295 throws ModelBuilderException {
1296 ModelSource candidateSource;
1297 String parentPath = parent.getRelativePath();
1298 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
1299 if (parentPath != null && !parentPath.isEmpty()) {
1300 candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath);
1301 if (candidateSource == null) {
1302 wrongParentRelativePath(childModel);
1303 return null;
1304 }
1305 } else {
1306 candidateSource =
1307 resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1308 if (candidateSource == null && parentPath == null) {
1309 candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, "..");
1310 }
1311 }
1312 } else {
1313 candidateSource = resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1314 if (candidateSource == null) {
1315 if (parentPath == null) {
1316 parentPath = "..";
1317 }
1318 if (!parentPath.isEmpty()) {
1319 candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath);
1320 }
1321 }
1322 }
1323
1324 if (candidateSource == null) {
1325 return null;
1326 }
1327
1328
1329
1330 String sourceLocation = candidateSource.getLocation();
1331
1332 if (!parentChain.add(sourceLocation)) {
1333 StringBuilder message = new StringBuilder("The parents form a cycle: ");
1334 for (String location : parentChain) {
1335 message.append(location).append(" -> ");
1336 }
1337 message.append(sourceLocation);
1338
1339 add(Severity.FATAL, Version.BASE, message.toString());
1340 throw newModelBuilderException();
1341 }
1342
1343 try {
1344 ModelBuilderSessionState derived = derive(
1345 request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER
1346 ? ModelBuilderRequest.builder(request)
1347 .requestType(ModelBuilderRequest.RequestType.CONSUMER_PARENT)
1348 .source(candidateSource)
1349 .build()
1350 : ModelBuilderRequest.build(request, candidateSource));
1351
1352
1353
1354 Model fileModel = derived.readFileModel();
1355 String fileGroupId = getGroupId(fileModel);
1356 String fileArtifactId = fileModel.getArtifactId();
1357
1358 if (fileGroupId == null
1359 || !fileGroupId.equals(parent.getGroupId())
1360 || fileArtifactId == null
1361 || !fileArtifactId.equals(parent.getArtifactId())) {
1362 mismatchRelativePathAndGA(childModel, parent, fileGroupId, fileArtifactId);
1363 return null;
1364 }
1365 Model candidateModel = derived.readAsParentModel(profileActivationContext, parentChain);
1366
1367 for (Map.Entry<String, List<Profile>> entry :
1368 derived.result.getActivePomProfilesByModel().entrySet()) {
1369 addActivePomProfiles(entry.getKey(), entry.getValue());
1370 }
1371
1372 String version = getVersion(candidateModel);
1373
1374 if (version != null && parent.getVersion() != null && !version.equals(parent.getVersion())) {
1375 try {
1376 VersionRange parentRange = versionParser.parseVersionRange(parent.getVersion());
1377 if (!parentRange.contains(versionParser.parseVersion(version))) {
1378
1379 return null;
1380 }
1381
1382
1383
1384 String rawChildModelVersion = childModel.getVersion();
1385
1386 if (rawChildModelVersion == null) {
1387
1388 add(Severity.FATAL, Version.V31, "Version must be a constant", childModel.getLocation(""));
1389
1390 } else {
1391 if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1392
1393 add(
1394 Severity.FATAL,
1395 Version.V31,
1396 "Version must be a constant",
1397 childModel.getLocation("version"));
1398 }
1399 }
1400
1401
1402 } catch (VersionParserException e) {
1403
1404 return null;
1405 }
1406 }
1407 return candidateModel;
1408 } finally {
1409
1410 parentChain.remove(sourceLocation);
1411 }
1412 }
1413
1414 private void mismatchRelativePathAndGA(Model childModel, Parent parent, String groupId, String artifactId) {
1415 boolean defaultPath = parent.getRelativePath() == null;
1416 boolean maven3Mode = Features.mavenMaven3Personality(
1417 InternalSession.from(session).getSession().getConfigProperties());
1418
1419 String actual = groupId + ':' + artifactId;
1420 String declared = parent.getGroupId() + ':' + parent.getArtifactId();
1421 String sourceHint = (childModel != getRootModel()) ? ModelProblemUtils.toSourceHint(childModel) : null;
1422
1423 String message;
1424 if (defaultPath) {
1425
1426 message = "Maven probed the default location '../pom.xml'"
1427 + (sourceHint != null ? " for POM " + sourceHint : "")
1428 + " and found " + actual
1429 + " instead of the declared parent " + declared
1430 + ". Maven will fall back to repository resolution."
1431 + " To suppress this warning, add <relativePath/> to your <parent> declaration.";
1432 } else {
1433
1434 message = "'parent.relativePath'"
1435 + (sourceHint != null ? " of POM " + sourceHint : "")
1436 + " points at '" + parent.getRelativePath() + "'"
1437 + " which resolves to " + actual
1438 + " instead of the declared parent " + declared
1439 + (maven3Mode
1440 ? ". Please verify your project structure."
1441 : ". Correct the <relativePath> value or remove it to let Maven resolve the parent"
1442 + " from the repository."
1443 + " If this POM was generated by a build tool (e.g. maven-shade-plugin),"
1444 + " upgrade that tool or use -Dmaven.maven3Personality as a temporary workaround.");
1445 }
1446
1447 setSource(childModel);
1448
1449
1450
1451 boolean warn = defaultPath || maven3Mode;
1452 add(warn ? Severity.WARNING : Severity.FATAL, Version.BASE, message, parent.getLocation(""));
1453 }
1454
1455 private void wrongParentRelativePath(Model childModel) {
1456 Parent parent = childModel.getParent();
1457 String parentPath = parent.getRelativePath();
1458 StringBuilder buffer = new StringBuilder(256);
1459 buffer.append("'parent.relativePath'");
1460 if (childModel != getRootModel()) {
1461 buffer.append(" of POM ").append(ModelProblemUtils.toSourceHint(childModel));
1462 }
1463 buffer.append(" points at '").append(parentPath);
1464 buffer.append("' but no POM could be found, please verify your project structure");
1465
1466 setSource(childModel);
1467 add(Severity.FATAL, Version.BASE, buffer.toString(), parent.getLocation(""));
1468 }
1469
1470 Model resolveAndReadParentExternally(
1471 Model childModel,
1472 Parent parent,
1473 DefaultProfileActivationContext profileActivationContext,
1474 Set<String> parentChain)
1475 throws ModelBuilderException {
1476 ModelBuilderRequest request = this.request;
1477 setSource(childModel);
1478
1479 String groupId = parent.getGroupId();
1480 String artifactId = parent.getArtifactId();
1481 String version = parent.getVersion();
1482
1483
1484 if (!childModel.getRepositories().isEmpty()) {
1485 var previousRepositories = repositories;
1486 mergeRepositories(childModel, false);
1487 if (!Objects.equals(previousRepositories, repositories)) {
1488 if (logger.isDebugEnabled()) {
1489 logger.debug("Merging repositories from " + childModel.getId() + "\n"
1490 + repositories.stream()
1491 .map(Object::toString)
1492 .collect(Collectors.joining("\n", " ", "")));
1493 }
1494 }
1495 }
1496
1497 ModelSource modelSource;
1498 try {
1499 modelSource = resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1500 if (modelSource == null) {
1501 AtomicReference<Parent> modified = new AtomicReference<>();
1502 modelSource = modelResolver.resolveModel(request.getSession(), repositories, parent, modified);
1503 if (modified.get() != null) {
1504 parent = modified.get();
1505 }
1506 }
1507 } catch (ModelResolverException e) {
1508
1509 StringBuilder buffer = new StringBuilder(256);
1510 buffer.append("Non-resolvable parent POM");
1511 if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
1512 buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
1513 }
1514 if (childModel != getRootModel()) {
1515 buffer.append(" for ").append(ModelProblemUtils.toId(childModel));
1516 }
1517 buffer.append(": ").append(e.getMessage());
1518 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
1519 buffer.append(" and parent could not be found in reactor");
1520 }
1521
1522 add(Severity.FATAL, Version.BASE, buffer.toString(), parent.getLocation(""), e);
1523 throw newModelBuilderException();
1524 }
1525
1526 ModelBuilderRequest lenientRequest = ModelBuilderRequest.builder(request)
1527 .requestType(ModelBuilderRequest.RequestType.CONSUMER_PARENT)
1528 .source(modelSource)
1529 .build();
1530
1531 ModelBuilderSessionState derived = derive(lenientRequest);
1532 Model parentModel = derived.readAsParentModel(profileActivationContext, parentChain);
1533
1534 for (Map.Entry<String, List<Profile>> entry :
1535 derived.result.getActivePomProfilesByModel().entrySet()) {
1536 addActivePomProfiles(entry.getKey(), entry.getValue());
1537 }
1538
1539 if (!parent.getVersion().equals(version)) {
1540 String rawChildModelVersion = childModel.getVersion();
1541
1542 if (rawChildModelVersion == null) {
1543
1544 add(Severity.FATAL, Version.V31, "Version must be a constant", childModel.getLocation(""));
1545 } else {
1546 if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1547
1548 add(
1549 Severity.FATAL,
1550 Version.V31,
1551 "Version must be a constant",
1552 childModel.getLocation("version"));
1553 }
1554 }
1555
1556
1557 }
1558
1559 return parentModel;
1560 }
1561
1562 Model activateFileModel(Model inputModel) throws ModelBuilderException {
1563 setRootModel(inputModel);
1564
1565
1566 DefaultProfileActivationContext profileActivationContext = getProfileActivationContext(request, inputModel);
1567
1568 setSource("(external profiles)");
1569 List<Profile> activeExternalProfiles = getActiveProfiles(request.getProfiles(), profileActivationContext);
1570
1571 result.setActiveExternalProfiles(activeExternalProfiles);
1572
1573 if (!activeExternalProfiles.isEmpty()) {
1574 Map<String, String> profileProps = new HashMap<>();
1575 for (Profile profile : activeExternalProfiles) {
1576 profileProps.putAll(profile.getProperties());
1577 }
1578 profileProps.putAll(request.getUserProperties());
1579 profileActivationContext.setUserProperties(profileProps);
1580 }
1581
1582 profileActivationContext.setModel(inputModel);
1583 setSource(inputModel);
1584 List<Profile> activePomProfiles = getActiveProfiles(inputModel.getProfiles(), profileActivationContext);
1585
1586
1587 setSource(inputModel);
1588 inputModel = modelNormalizer.mergeDuplicates(inputModel, request, this);
1589
1590 List<Activation> interpolatedActivations = getProfileActivations(inputModel);
1591 inputModel = injectProfileActivations(inputModel, interpolatedActivations);
1592
1593
1594 inputModel = profileInjector.injectProfiles(inputModel, activePomProfiles, request, this);
1595 inputModel = profileInjector.injectProfiles(inputModel, activeExternalProfiles, request, this);
1596
1597 return inputModel;
1598 }
1599
1600 @SuppressWarnings("checkstyle:methodlength")
1601 private Model readEffectiveModel() throws ModelBuilderException {
1602 Model inputModel = readRawModel();
1603 if (hasFatalErrors()) {
1604 throw newModelBuilderException();
1605 }
1606
1607 setRootModel(inputModel);
1608
1609 Model activatedFileModel = activateFileModel(inputModel);
1610
1611
1612 DefaultProfileActivationContext profileActivationContext =
1613 getProfileActivationContext(request, activatedFileModel);
1614
1615 List<Profile> activeExternalProfiles = result.getActiveExternalProfiles();
1616
1617 if (!activeExternalProfiles.isEmpty()) {
1618 Map<String, String> profileProps = new HashMap<>();
1619 for (Profile profile : activeExternalProfiles) {
1620 profileProps.putAll(profile.getProperties());
1621 }
1622 profileProps.putAll(request.getUserProperties());
1623 profileActivationContext.setUserProperties(profileProps);
1624 }
1625
1626 Model parentModel = readParent(
1627 activatedFileModel, activatedFileModel.getParent(), profileActivationContext, parentChain);
1628
1629
1630
1631 if (inputModel.getParent() != null && inputModel.getParent().getRelativePath() == null) {
1632 String relPath;
1633 if (isBuildRequest() && parentModel.getPomFile() != null && inputModel.getPomFile() != null) {
1634 relPath = inputModel
1635 .getPomFile()
1636 .getParent()
1637 .toAbsolutePath()
1638 .relativize(
1639 parentModel.getPomFile().toAbsolutePath().getParent())
1640 .toString();
1641 } else {
1642 relPath = "..";
1643 }
1644 inputModel = inputModel.withParent(inputModel.getParent().withRelativePath(relPath));
1645 }
1646
1647 Model model = inheritanceAssembler.assembleModelInheritance(inputModel, parentModel, request, this);
1648
1649
1650 profileActivationContext.setModel(model);
1651
1652
1653
1654 List<Profile> localActivePomProfiles =
1655 getActiveProfiles(inputModel.getProfiles(), profileActivationContext);
1656
1657
1658 List<Profile> activePomProfiles = getActiveProfiles(model.getProfiles(), profileActivationContext);
1659 model = profileInjector.injectProfiles(model, activePomProfiles, request, this);
1660 model = profileInjector.injectProfiles(model, activeExternalProfiles, request, this);
1661
1662
1663
1664 addActivePomProfiles(ModelProblemUtils.toId(model), localActivePomProfiles);
1665
1666
1667 Model resultModel = model;
1668 resultModel = interpolateModel(resultModel, request, this);
1669
1670
1671 resultModel = modelNormalizer.mergeDuplicates(resultModel, request, this);
1672
1673
1674 resultModel = modelUrlNormalizer.normalize(resultModel, request);
1675
1676
1677 if (!resultModel.getRepositories().isEmpty()) {
1678 List<String> oldRepos =
1679 repositories.stream().map(Object::toString).toList();
1680 mergeRepositories(resultModel, true);
1681 List<String> newRepos =
1682 repositories.stream().map(Object::toString).toList();
1683 if (!Objects.equals(oldRepos, newRepos)) {
1684 logger.debug("Replacing repositories from " + resultModel.getId() + "\n"
1685 + newRepos.stream().map(s -> " " + s).collect(Collectors.joining("\n")));
1686 }
1687 }
1688
1689 return resultModel;
1690 }
1691
1692 private void addActivePomProfiles(String modelId, List<Profile> activePomProfiles) {
1693 if (activePomProfiles != null && !activePomProfiles.isEmpty()) {
1694
1695 result.setActivePomProfiles(modelId, activePomProfiles);
1696 }
1697 }
1698
1699 private List<Profile> getActiveProfiles(
1700 Collection<Profile> interpolatedProfiles, DefaultProfileActivationContext profileActivationContext) {
1701 if (isBuildRequestWithActivation()) {
1702 if (externalOrigin) {
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726 Collection<Profile> nonFileProfiles = interpolatedProfiles.stream()
1727 .filter(p -> p.getActivation() == null
1728 || (p.getActivation().getFile() == null && !hasFileConditionExpression(p)))
1729 .toList();
1730 ProfileActivationContext externalContext =
1731 profileActivationContext.withoutUserPropertiesAndFilesystem();
1732 return profileSelector.getActiveProfiles(nonFileProfiles, externalContext, this);
1733 }
1734
1735
1736 return profileSelector.getActiveProfiles(interpolatedProfiles, profileActivationContext, this);
1737 } else {
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749 Collection<Profile> deterministicProfiles = interpolatedProfiles.stream()
1750 .filter(profile ->
1751 !hasFileOrPropertyOrConditionActivation(profile) && !hasPackagingActivation(profile))
1752 .map(profile -> profile.withRepositories(List.of()).withPluginRepositories(List.of()))
1753 .toList();
1754 return profileSelector.getActiveProfiles(deterministicProfiles, profileActivationContext, this);
1755 }
1756 }
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767 private static boolean hasFileOrPropertyOrConditionActivation(Profile profile) {
1768 Activation activation = profile.getActivation();
1769 return activation != null
1770 && (activation.getFile() != null
1771 || activation.getProperty() != null
1772 || (activation.getCondition() != null
1773 && !activation.getCondition().isBlank()));
1774 }
1775
1776
1777
1778
1779
1780
1781
1782
1783 private static boolean hasFileConditionExpression(Profile profile) {
1784 Activation a = profile.getActivation();
1785 if (a == null || a.getCondition() == null) {
1786 return false;
1787 }
1788 String c = a.getCondition();
1789 return c.contains("exists(") || c.contains("missing(");
1790 }
1791
1792
1793
1794
1795
1796
1797
1798 private static boolean hasPackagingActivation(Profile profile) {
1799 Activation activation = profile.getActivation();
1800 return activation != null && activation.getPackaging() != null;
1801 }
1802
1803 Model readFileModel() throws ModelBuilderException {
1804 return readFileModel(new HashSet<>());
1805 }
1806
1807 Model readFileModel(Set<Path> activeModelReads) throws ModelBuilderException {
1808 Model model = cache(request.getSource(), FILE, () -> doReadFileModel(activeModelReads));
1809
1810 result.setFileModel(model);
1811 return model;
1812 }
1813
1814 @SuppressWarnings("checkstyle:methodlength")
1815 Model doReadFileModel(Set<Path> activeModelReads) throws ModelBuilderException {
1816 ModelSource modelSource = request.getSource();
1817 Model model;
1818 Path rootDirectory;
1819 boolean rootDirectoryFromSession = false;
1820 setSource(modelSource.getLocation());
1821 logger.debug("Reading file model from " + modelSource.getLocation());
1822 Path sourcePath = modelSource.getPath();
1823
1824
1825
1826 Path normalizedPath =
1827 sourcePath != null ? sourcePath.toAbsolutePath().normalize() : null;
1828 boolean trackRead = normalizedPath != null && activeModelReads.add(normalizedPath);
1829 try {
1830 try {
1831 boolean strict = isBuildRequest();
1832 try {
1833 rootDirectory = request.getSession().getRootDirectory();
1834 rootDirectoryFromSession = true;
1835 } catch (IllegalStateException ignore) {
1836 rootDirectory = modelSource.getPath();
1837 while (rootDirectory != null && !Files.isDirectory(rootDirectory)) {
1838 rootDirectory = rootDirectory.getParent();
1839 }
1840 }
1841 try (InputStream is = modelSource.openStream()) {
1842 model = modelProcessor.read(XmlReaderRequest.builder()
1843 .strict(strict)
1844 .location(modelSource.getLocation())
1845 .path(modelSource.getPath())
1846 .rootDirectory(rootDirectory)
1847 .inputStream(is)
1848 .transformer(new InterningTransformer(session))
1849 .build());
1850 } catch (XmlReaderException e) {
1851 if (!strict) {
1852 throw e;
1853 }
1854 try (InputStream is = modelSource.openStream()) {
1855 model = modelProcessor.read(XmlReaderRequest.builder()
1856 .strict(false)
1857 .location(modelSource.getLocation())
1858 .path(modelSource.getPath())
1859 .rootDirectory(rootDirectory)
1860 .inputStream(is)
1861 .transformer(new InterningTransformer(session))
1862 .build());
1863 } catch (XmlReaderException ne) {
1864
1865 throw e;
1866 }
1867
1868 add(
1869 Severity.ERROR,
1870 Version.V20,
1871 "Malformed POM " + modelSource.getLocation() + ": " + e.getMessage(),
1872 e);
1873 }
1874 } catch (XmlReaderException e) {
1875 add(
1876 Severity.FATAL,
1877 Version.BASE,
1878 "Non-parseable POM " + modelSource.getLocation() + ": " + e.getMessage(),
1879 e);
1880 throw newModelBuilderException();
1881 } catch (IOException e) {
1882 String msg = e.getMessage();
1883 if (msg == null || msg.isEmpty()) {
1884
1885 if (e.getClass().getName().endsWith("MalformedInputException")) {
1886 msg = "Some input bytes do not match the file encoding.";
1887 } else {
1888 msg = e.getClass().getSimpleName();
1889 }
1890 }
1891 add(Severity.FATAL, Version.BASE, "Non-readable POM " + modelSource.getLocation() + ": " + msg, e);
1892 throw newModelBuilderException();
1893 }
1894
1895 if (model.getModelVersion() == null) {
1896 String namespace = model.getNamespaceUri();
1897 if (namespace != null && namespace.startsWith(NAMESPACE_PREFIX)) {
1898 model = model.withModelVersion(namespace.substring(NAMESPACE_PREFIX.length()));
1899 }
1900 }
1901
1902 if (isBuildRequest()) {
1903 model = model.withPomFile(modelSource.getPath());
1904
1905 Parent parent = model.getParent();
1906 if (parent != null) {
1907 String groupId = parent.getGroupId();
1908 String artifactId = parent.getArtifactId();
1909 String version = parent.getVersion();
1910 String path = parent.getRelativePath();
1911 boolean versionContainsExpression = version != null && version.contains("${");
1912 if ((groupId == null || artifactId == null || version == null || versionContainsExpression)
1913 && (path == null || !path.isEmpty())) {
1914 Path pomFile = model.getPomFile();
1915 Path relativePath = Paths.get(path != null ? path : "..");
1916 Path pomPath = pomFile.resolveSibling(relativePath).normalize();
1917 if (Files.isDirectory(pomPath)) {
1918 pomPath = modelProcessor.locateExistingPom(pomPath);
1919 }
1920 if (pomPath != null && Files.isRegularFile(pomPath)) {
1921 if (rootDirectoryFromSession && !isParentWithinRootDirectory(pomPath, rootDirectory)) {
1922 add(
1923 Severity.FATAL,
1924 Version.BASE,
1925 "Parent POM " + pomPath + " is located above the root directory "
1926 + rootDirectory
1927 + ". This setup is invalid when a .mvn directory exists in a subdirectory.",
1928 parent.getLocation("relativePath"));
1929 throw newModelBuilderException();
1930 }
1931
1932 Model parentModel =
1933 derive(Sources.buildSource(pomPath)).readFileModel(activeModelReads);
1934 String parentGroupId = getGroupId(parentModel);
1935 String parentArtifactId = parentModel.getArtifactId();
1936 String parentVersion = getVersion(parentModel);
1937 if ((groupId == null || groupId.equals(parentGroupId))
1938 && (artifactId == null || artifactId.equals(parentArtifactId))
1939 && (version == null
1940 || version.equals(parentVersion)
1941 || versionContainsExpression)) {
1942 model = model.withParent(parent.with()
1943 .groupId(parentGroupId)
1944 .artifactId(parentArtifactId)
1945 .version(parentVersion)
1946 .build());
1947 } else {
1948 mismatchRelativePathAndGA(model, parent, parentGroupId, parentArtifactId);
1949 }
1950 } else {
1951 if (!MODEL_VERSION_4_0_0.equals(model.getModelVersion()) && path != null) {
1952 wrongParentRelativePath(model);
1953 }
1954 }
1955 }
1956 }
1957
1958
1959 if (!hasSubprojectsDefined(model)
1960
1961 && !MODEL_VERSION_4_0_0.equals(model.getModelVersion())
1962
1963
1964 && Type.POM.equals(model.getPackaging())
1965
1966 && Features.discoverSubprojects(request.getUserProperties())) {
1967 List<String> subprojects = new ArrayList<>();
1968 try (Stream<Path> files = Files.list(model.getProjectDirectory())) {
1969 for (Path f : files.toList()) {
1970 if (Files.isDirectory(f)) {
1971 Path subproject = modelProcessor.locateExistingPom(f);
1972 if (subproject != null) {
1973 subprojects.add(f.getFileName().toString());
1974 }
1975 }
1976 }
1977 if (!subprojects.isEmpty()) {
1978 model = model.withSubprojects(subprojects);
1979 }
1980 } catch (IOException e) {
1981 add(Severity.FATAL, Version.V41, "Error discovering subprojects", e);
1982 }
1983 }
1984
1985
1986
1987 Map<String, String> properties = getEnhancedProperties(model, rootDirectory, activeModelReads);
1988
1989
1990 model = model.with()
1991 .version(replaceCiFriendlyVersion(properties, model.getVersion()))
1992 .parent(
1993 model.getParent() != null
1994 ? model.getParent()
1995 .withVersion(replaceCiFriendlyVersion(
1996 properties,
1997 model.getParent().getVersion()))
1998 : null)
1999 .build();
2000
2001
2002 UnaryOperator<String> callback = properties::get;
2003 model = model.with()
2004 .repositories(interpolateRepository(model.getRepositories(), callback))
2005 .pluginRepositories(interpolateRepository(model.getPluginRepositories(), callback))
2006 .profiles(map(model.getProfiles(), this::interpolateRepository, callback))
2007 .distributionManagement(interpolateRepository(model.getDistributionManagement(), callback))
2008 .build();
2009
2010
2011 Map<String, String> userProps = request.getUserProperties();
2012 Map<String, String> newProps = merge(model.getProperties(), userProps);
2013 if (newProps != null) {
2014 model = model.withProperties(newProps);
2015 }
2016 model = model.withProfiles(merge(model.getProfiles(), userProps));
2017 } else {
2018 if (modelSource.getPath() != null) {
2019 model = model.withPomFile(modelSource.getPath());
2020 }
2021 if (rootDirectory != null) {
2022 try {
2023 Map<String, String> properties =
2024 getEnhancedProperties(model, rootDirectory, activeModelReads);
2025 model = model.with()
2026 .version(replaceCiFriendlyVersion(properties, model.getVersion()))
2027 .parent(
2028 model.getParent() != null
2029 ? model.getParent()
2030 .withVersion(replaceCiFriendlyVersion(
2031 properties,
2032 model.getParent()
2033 .getVersion()))
2034 : null)
2035 .build();
2036 } catch (ModelBuilderException e) {
2037 logger.debug(
2038 "Could not read root model properties for CI-friendly" + " version interpolation",
2039 e);
2040 }
2041 }
2042 }
2043
2044 for (var transformer : transformers) {
2045 model = transformer.transformFileModel(model);
2046 }
2047
2048 setSource(model);
2049 modelValidator.validateFileModel(
2050 session,
2051 model,
2052 isBuildRequest()
2053 ? ModelValidator.VALIDATION_LEVEL_STRICT
2054 : ModelValidator.VALIDATION_LEVEL_MINIMAL,
2055 this);
2056 InternalSession internalSession = InternalSession.from(session);
2057 if (Features.mavenMaven3Personality(internalSession.getSession().getConfigProperties())
2058 && Objects.equals(ModelBuilder.MODEL_VERSION_4_1_0, model.getModelVersion())) {
2059 add(Severity.FATAL, Version.BASE, "Maven3 mode: no higher model version than 4.0.0 allowed");
2060 }
2061 if (hasFatalErrors()) {
2062 throw newModelBuilderException();
2063 }
2064
2065 return model;
2066 } finally {
2067 if (trackRead) {
2068 activeModelReads.remove(normalizedPath);
2069 }
2070 }
2071 }
2072
2073 private DistributionManagement interpolateRepository(
2074 DistributionManagement distributionManagement, UnaryOperator<String> callback) {
2075 return distributionManagement == null
2076 ? null
2077 : distributionManagement
2078 .with()
2079 .repository((DeploymentRepository)
2080 interpolateRepository(distributionManagement.getRepository(), callback))
2081 .snapshotRepository((DeploymentRepository)
2082 interpolateRepository(distributionManagement.getSnapshotRepository(), callback))
2083 .build();
2084 }
2085
2086 private Profile interpolateRepository(Profile profile, UnaryOperator<String> callback) {
2087 return profile == null
2088 ? null
2089 : profile.with()
2090 .repositories(interpolateRepository(profile.getRepositories(), callback))
2091 .pluginRepositories(interpolateRepository(profile.getPluginRepositories(), callback))
2092 .build();
2093 }
2094
2095 private List<Repository> interpolateRepository(List<Repository> repositories, UnaryOperator<String> callback) {
2096 return map(repositories, this::interpolateRepository, callback);
2097 }
2098
2099 private Repository interpolateRepository(Repository repository, UnaryOperator<String> callback) {
2100 return repository == null
2101 ? null
2102 : repository
2103 .with()
2104 .id(interpolator.interpolate(repository.getId(), callback))
2105 .url(interpolator.interpolate(repository.getUrl(), callback))
2106 .build();
2107 }
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119 List<Profile> merge(List<Profile> profiles, Map<String, String> userProperties) {
2120 List<Profile> result = null;
2121 for (int i = 0; i < profiles.size(); i++) {
2122 Profile profile = profiles.get(i);
2123 Map<String, String> props = merge(profile.getProperties(), userProperties);
2124 if (props != null) {
2125 Profile merged = profile.withProperties(props);
2126 if (result == null) {
2127 result = new ArrayList<>(profiles);
2128 }
2129 result.set(i, merged);
2130 }
2131 }
2132 return result != null ? result : profiles;
2133 }
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145 Map<String, String> merge(Map<String, String> properties, Map<String, String> userProperties) {
2146 Map<String, String> result = null;
2147 for (Map.Entry<String, String> entry : properties.entrySet()) {
2148 String key = entry.getKey();
2149 String value = userProperties.get(key);
2150 if (value != null && !Objects.equals(value, entry.getValue())) {
2151 if (result == null) {
2152 result = new LinkedHashMap<>(properties);
2153 }
2154 result.put(entry.getKey(), value);
2155 }
2156 }
2157 return result;
2158 }
2159
2160 Model readRawModel() throws ModelBuilderException {
2161
2162 readFileModel();
2163 Model model = cache(request.getSource(), RAW, this::doReadRawModel);
2164
2165 result.setRawModel(model);
2166 return model;
2167 }
2168
2169 private Model doReadRawModel() throws ModelBuilderException {
2170 Model rawModel = readFileModel();
2171
2172 if (!MODEL_VERSION_4_0_0.equals(rawModel.getModelVersion()) && isBuildRequest()) {
2173 rawModel = transformFileToRaw(rawModel);
2174 }
2175
2176 for (var transformer : transformers) {
2177 rawModel = transformer.transformRawModel(rawModel);
2178 }
2179
2180 modelValidator.validateRawModel(
2181 session,
2182 rawModel,
2183 isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
2184 this);
2185
2186 if (hasFatalErrors()) {
2187 throw newModelBuilderException();
2188 }
2189
2190 return rawModel;
2191 }
2192
2193
2194
2195
2196 private record ParentModelWithProfiles(Model model, List<Profile> activatedProfiles) {}
2197
2198
2199
2200
2201 Model readAsParentModel(DefaultProfileActivationContext profileActivationContext, Set<String> parentChain)
2202 throws ModelBuilderException {
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218 Map<DefaultProfileActivationContext.Record, ParentModelWithProfiles> parentsPerContext =
2219 cache(request.getSource(), externalOrigin ? PARENT_EXTERNAL : PARENT, ConcurrentHashMap::new);
2220
2221 for (Map.Entry<DefaultProfileActivationContext.Record, ParentModelWithProfiles> e :
2222 parentsPerContext.entrySet()) {
2223 if (e.getKey().matches(profileActivationContext)) {
2224 ParentModelWithProfiles cached = e.getValue();
2225
2226
2227
2228
2229 if (profileActivationContext.record != null) {
2230 replayRecordIntoContext(e.getKey(), profileActivationContext);
2231 }
2232
2233
2234 addActivePomProfiles(ModelProblemUtils.toId(cached.model()), cached.activatedProfiles());
2235 return cached.model();
2236 }
2237 }
2238
2239
2240
2241
2242
2243
2244 DefaultProfileActivationContext ctx = profileActivationContext.start();
2245 ParentModelWithProfiles modelWithProfiles = doReadAsParentModel(ctx, parentChain);
2246 DefaultProfileActivationContext.Record record = ctx.stop();
2247 replayRecordIntoContext(record, profileActivationContext);
2248
2249 parentsPerContext.put(record, modelWithProfiles);
2250
2251 addActivePomProfiles(
2252 ModelProblemUtils.toId(modelWithProfiles.model()), modelWithProfiles.activatedProfiles());
2253 return modelWithProfiles.model();
2254 }
2255
2256 private ParentModelWithProfiles doReadAsParentModel(
2257 DefaultProfileActivationContext childProfileActivationContext, Set<String> parentChain)
2258 throws ModelBuilderException {
2259 Model raw = readRawModel();
2260 Model parentData = readParent(raw, raw.getParent(), childProfileActivationContext, parentChain);
2261 Model parent = new DefaultInheritanceAssembler(new DefaultInheritanceAssembler.InheritanceModelMerger() {
2262 @Override
2263 protected void mergeModel_Modules(
2264 Model.Builder builder,
2265 Model target,
2266 Model source,
2267 boolean sourceDominant,
2268 Map<Object, Object> context) {}
2269
2270 @Override
2271 protected void mergeModel_Subprojects(
2272 Model.Builder builder,
2273 Model target,
2274 Model source,
2275 boolean sourceDominant,
2276 Map<Object, Object> context) {}
2277 })
2278 .assembleModelInheritance(raw, parentData, request, this);
2279
2280
2281
2282
2283
2284
2285
2286
2287 List<Profile> parentActivePomProfiles =
2288 getActiveProfiles(parent.getProfiles(), childProfileActivationContext);
2289
2290
2291 Model injectedParentModel = profileInjector
2292 .injectProfiles(parent, parentActivePomProfiles, request, this)
2293 .withProfiles(List.of());
2294
2295
2296 return new ParentModelWithProfiles(injectedParentModel.withParent(null), parentActivePomProfiles);
2297 }
2298
2299 private Model importDependencyManagement(Model model, Collection<String> importIds) {
2300 DependencyManagement depMgmt = model.getDependencyManagement();
2301
2302 if (depMgmt == null) {
2303 return model;
2304 }
2305
2306 String importing = model.getGroupId() + ':' + model.getArtifactId() + ':' + model.getVersion();
2307
2308 importIds.add(importing);
2309
2310 List<DependencyManagement> importMgmts = null;
2311
2312 List<Dependency> deps = new ArrayList<>(depMgmt.getDependencies());
2313 for (Iterator<Dependency> it = deps.iterator(); it.hasNext(); ) {
2314 Dependency dependency = it.next();
2315
2316 if (!(("pom".equals(dependency.getType()) && "import".equals(dependency.getScope()))
2317 || "bom".equals(dependency.getType()))) {
2318 continue;
2319 }
2320
2321 it.remove();
2322
2323 DependencyManagement importMgmt = loadDependencyManagement(dependency, importIds);
2324
2325 if (importMgmt != null) {
2326 if (importMgmts == null) {
2327 importMgmts = new ArrayList<>();
2328 }
2329
2330 importMgmts.add(importMgmt);
2331 }
2332 }
2333
2334 importIds.remove(importing);
2335
2336 model = model.withDependencyManagement(
2337 model.getDependencyManagement().withDependencies(deps));
2338
2339 return dependencyManagementImporter.importManagement(
2340 model, importMgmts, request, deduplicatingImportProblemCollector());
2341 }
2342
2343 private ModelProblemCollector deduplicatingImportProblemCollector() {
2344 return new DeduplicatingImportProblemCollector();
2345 }
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355 private class DeduplicatingImportProblemCollector implements ModelProblemCollector {
2356 @Override
2357 public ProblemCollector<ModelProblem> getProblemCollector() {
2358 return ModelBuilderSessionState.this.getProblemCollector();
2359 }
2360
2361 @Override
2362 public void add(
2363 BuilderProblem.Severity severity,
2364 ModelProblem.Version version,
2365 String message,
2366 InputLocation location,
2367 Exception exception) {
2368 if (severity == Severity.WARNING && location != null && location.getSource() != null) {
2369 var source = location.getSource();
2370 String sourceLocation = source.getLocation();
2371 ImportWarningKey key = new ImportWarningKey(
2372 message,
2373 sourceLocation,
2374 source.getModelId(),
2375 location.getLineNumber(),
2376 location.getColumnNumber());
2377 if (!reportedImportWarnings.add(key)) {
2378 return;
2379 }
2380 ProblemCollector<ModelProblem> collector =
2381 sourceLocation != null ? reactorProblemCollectors.get(sourceLocation) : null;
2382 if (collector != null) {
2383 collector.reportProblem(new DefaultModelProblem(
2384 message,
2385 severity,
2386 version,
2387 sourceLocation,
2388 location.getLineNumber(),
2389 location.getColumnNumber(),
2390 source.getModelId(),
2391 exception));
2392 return;
2393 }
2394 }
2395 ModelBuilderSessionState.this.add(severity, version, message, location, exception);
2396 }
2397
2398 @Override
2399 public ModelBuilderException newModelBuilderException() {
2400 return ModelBuilderSessionState.this.newModelBuilderException();
2401 }
2402
2403 @Override
2404 public void setSource(String location) {
2405 ModelBuilderSessionState.this.setSource(location);
2406 }
2407
2408 @Override
2409 public void setSource(Model model) {
2410 ModelBuilderSessionState.this.setSource(model);
2411 }
2412
2413 @Override
2414 public String getSource() {
2415 return ModelBuilderSessionState.this.getSource();
2416 }
2417
2418 @Override
2419 public void setRootModel(Model model) {
2420 ModelBuilderSessionState.this.setRootModel(model);
2421 }
2422
2423 @Override
2424 public Model getRootModel() {
2425 return ModelBuilderSessionState.this.getRootModel();
2426 }
2427 }
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437 private void registerReactorProblemCollector(
2438 ModelSource source, ProblemCollector<ModelProblem> problemCollector) {
2439 if (source.getLocation() != null) {
2440 reactorProblemCollectors.put(source.getLocation(), problemCollector);
2441 }
2442 if (source.getPath() != null) {
2443 reactorProblemCollectors.put(source.getPath().toUri().toString(), problemCollector);
2444 }
2445 }
2446
2447 private DependencyManagement loadDependencyManagement(Dependency dependency, Collection<String> importIds) {
2448 String groupId = dependency.getGroupId();
2449 String artifactId = dependency.getArtifactId();
2450 String version = dependency.getVersion();
2451
2452 if (groupId == null || groupId.isEmpty()) {
2453 add(
2454 Severity.ERROR,
2455 Version.BASE,
2456 "'dependencyManagement.dependencies.dependency.groupId' for " + dependency.getManagementKey()
2457 + " is missing.",
2458 dependency.getLocation(""));
2459 return null;
2460 }
2461 if (artifactId == null || artifactId.isEmpty()) {
2462 add(
2463 Severity.ERROR,
2464 Version.BASE,
2465 "'dependencyManagement.dependencies.dependency.artifactId' for " + dependency.getManagementKey()
2466 + " is missing.",
2467 dependency.getLocation(""));
2468 return null;
2469 }
2470 if (version == null || version.isEmpty()) {
2471 add(
2472 Severity.ERROR,
2473 Version.BASE,
2474 "'dependencyManagement.dependencies.dependency.version' for " + dependency.getManagementKey()
2475 + " is missing.",
2476 dependency.getLocation(""));
2477 return null;
2478 }
2479
2480 String imported = groupId + ':' + artifactId + ':' + version;
2481
2482 if (importIds.contains(imported)) {
2483 StringBuilder message =
2484 new StringBuilder("The dependencies of type=pom and with scope=import form a cycle: ");
2485 for (String modelId : importIds) {
2486 message.append(modelId).append(" -> ");
2487 }
2488 message.append(imported);
2489 add(Severity.ERROR, Version.BASE, message.toString());
2490 return null;
2491 }
2492
2493 Model importModel = cache(
2494 repositories,
2495 groupId,
2496 artifactId,
2497 version,
2498 null,
2499 IMPORT,
2500 () -> doLoadDependencyManagement(dependency, groupId, artifactId, version, importIds));
2501 DependencyManagement importMgmt = importModel != null ? importModel.getDependencyManagement() : null;
2502 if (importMgmt == null) {
2503 importMgmt = DependencyManagement.newInstance();
2504 }
2505
2506
2507 List<Exclusion> exclusions = dependency.getExclusions();
2508 if (importMgmt != null && !exclusions.isEmpty()) {
2509
2510 List<Dependency> dependencies = importMgmt.getDependencies().stream()
2511 .filter(candidate -> exclusions.stream().noneMatch(exclusion -> match(exclusion, candidate)))
2512 .map(candidate -> addExclusions(candidate, exclusions))
2513 .collect(Collectors.toList());
2514 importMgmt = importMgmt.withDependencies(dependencies);
2515 }
2516
2517 return DependencyManagement.newBuilder(importMgmt, true)
2518 .importedFrom(dependency.getLocation(""))
2519 .build();
2520 }
2521
2522 @SuppressWarnings("checkstyle:parameternumber")
2523 private Model doLoadDependencyManagement(
2524 Dependency dependency,
2525 String groupId,
2526 String artifactId,
2527 String version,
2528 Collection<String> importIds) {
2529 Model importModel;
2530 ModelSource importSource;
2531 boolean repositoryResolved = false;
2532 try {
2533 importSource = resolveReactorModel(groupId, artifactId, version);
2534 if (importSource == null) {
2535 importSource = modelResolver.resolveModel(
2536 request.getSession(), repositories, dependency, new AtomicReference<>());
2537 repositoryResolved = true;
2538 }
2539 } catch (ModelBuilderException | ModelResolverException e) {
2540 StringBuilder buffer = new StringBuilder(256);
2541 buffer.append("Non-resolvable import POM");
2542 if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
2543 buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
2544 }
2545 buffer.append(": ").append(e.getMessage());
2546
2547 add(Severity.ERROR, Version.BASE, buffer.toString(), dependency.getLocation(""), e);
2548 return null;
2549 }
2550
2551 Path rootDirectory;
2552 try {
2553 rootDirectory = request.getSession().getRootDirectory();
2554 } catch (IllegalStateException e) {
2555 rootDirectory = null;
2556 }
2557 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT && rootDirectory != null) {
2558 Path sourcePath = importSource.getPath();
2559 if (sourcePath != null && sourcePath.startsWith(rootDirectory)) {
2560 add(
2561 Severity.WARNING,
2562 Version.BASE,
2563 "BOM imports from within reactor should be avoided",
2564 dependency.getLocation(""));
2565 }
2566 }
2567
2568 final ModelBuilderResult importResult;
2569 try {
2570 ModelBuilderRequest importRequest = ModelBuilderRequest.builder()
2571 .session(request.getSession())
2572 .requestType(ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY)
2573 .systemProperties(request.getSystemProperties())
2574 .userProperties(request.getUserProperties())
2575 .source(importSource)
2576 .repositories(repositories)
2577 .build();
2578 ModelBuilderSessionState modelBuilderSession = derive(importRequest);
2579
2580 modelBuilderSession.buildEffectiveModel(importIds);
2581 importResult = modelBuilderSession.result;
2582 } catch (ModelBuilderException e) {
2583 return null;
2584 }
2585
2586 importModel = importResult.getEffectiveModel();
2587
2588 if (repositoryResolved) {
2589 importModel = rejectSystemScopeFromRepositoryImport(importModel, dependency);
2590 }
2591
2592 return importModel;
2593 }
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605 private Model rejectSystemScopeFromRepositoryImport(Model importModel, Dependency dependency) {
2606 DependencyManagement importMgmt = importModel != null ? importModel.getDependencyManagement() : null;
2607 if (importMgmt == null) {
2608 return importModel;
2609 }
2610 String offending = importMgmt.getDependencies().stream()
2611 .filter(DefaultModelBuilder::usesSystemScope)
2612 .map(Dependency::getManagementKey)
2613 .collect(Collectors.joining(", "));
2614 if (offending.isEmpty()) {
2615 return importModel;
2616 }
2617 String allow = request.getUserProperties()
2618 .getOrDefault(
2619 Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE,
2620 request.getSystemProperties()
2621 .get(Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE));
2622 if (Boolean.parseBoolean(allow)) {
2623 add(
2624 Severity.WARNING,
2625 Version.V41,
2626 "The import POM " + ModelProblemUtils.toId(importModel)
2627 + " declares 'system' scope or 'systemPath' for " + offending
2628 + "; importing it because the '"
2629 + Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE
2630 + "' user property is set to 'true'.",
2631 dependency.getLocation(""));
2632 return importModel;
2633 }
2634 add(
2635 Severity.WARNING,
2636 Version.V41,
2637 "The import POM " + ModelProblemUtils.toId(importModel)
2638 + " was resolved from a repository and declares 'system' scope or 'systemPath' for "
2639 + offending + "; these entries are not imported. Remove the 'system' scope from the"
2640 + " imported POM, or set the '"
2641 + Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE
2642 + "' user property to 'true' to import them as before.",
2643 dependency.getLocation(""));
2644 List<Dependency> retained = importMgmt.getDependencies().stream()
2645 .filter(d -> !usesSystemScope(d))
2646 .collect(Collectors.toList());
2647 return importModel.withDependencyManagement(importMgmt.withDependencies(retained));
2648 }
2649
2650 ModelSource resolveReactorModel(String groupId, String artifactId, String version)
2651 throws ModelBuilderException {
2652 Set<ModelSource> sources = mappedSources.get(new GAKey(groupId, artifactId));
2653 if (sources != null) {
2654 for (ModelSource source : sources) {
2655 Model model = derive(source).readRawModel();
2656 if (Objects.equals(getVersion(model), version)) {
2657 return source;
2658 }
2659 }
2660
2661 }
2662 return null;
2663 }
2664
2665 private <T> T cache(
2666 List<RemoteRepository> repositories,
2667 String groupId,
2668 String artifactId,
2669 String version,
2670 String classifier,
2671 String tag,
2672 Supplier<T> supplier) {
2673 RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(session, request);
2674 try {
2675 RgavCacheKey r = new RgavCacheKey(
2676 session, trace.mvnTrace(), repositories, groupId, artifactId, version, classifier, tag);
2677 SourceResponse<RgavCacheKey, T> response =
2678 InternalSession.from(session).request(r, tr -> new SourceResponse<>(tr, supplier.get()));
2679 return response.response;
2680 } finally {
2681 RequestTraceHelper.exit(trace);
2682 }
2683 }
2684
2685 private <T> T cache(Source source, String tag, Supplier<T> supplier) throws ModelBuilderException {
2686 RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(session, request);
2687 try {
2688 SourceCacheKey r = new SourceCacheKey(session, trace.mvnTrace(), source, tag);
2689 SourceResponse<SourceCacheKey, T> response =
2690 InternalSession.from(session).request(r, tr -> new SourceResponse<>(tr, supplier.get()));
2691 return response.response;
2692 } finally {
2693 RequestTraceHelper.exit(trace);
2694 }
2695 }
2696
2697 boolean isBuildRequest() {
2698 return request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT
2699 || request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_EFFECTIVE
2700 || request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER;
2701 }
2702
2703 boolean isBuildRequestWithActivation() {
2704 return request.getRequestType() != ModelBuilderRequest.RequestType.BUILD_CONSUMER;
2705 }
2706
2707
2708
2709
2710
2711
2712 private void replayRecordIntoContext(
2713 DefaultProfileActivationContext.Record cachedRecord, DefaultProfileActivationContext targetContext) {
2714 if (targetContext.record == null) {
2715 return;
2716 }
2717
2718
2719
2720 DefaultProfileActivationContext.Record targetRecord = targetContext.record;
2721
2722
2723 cachedRecord.usedActiveProfiles.forEach(targetRecord.usedActiveProfiles::putIfAbsent);
2724
2725
2726 cachedRecord.usedInactiveProfiles.forEach(targetRecord.usedInactiveProfiles::putIfAbsent);
2727
2728
2729 cachedRecord.usedSystemProperties.forEach(targetRecord.usedSystemProperties::putIfAbsent);
2730
2731
2732 cachedRecord.usedUserProperties.forEach(targetRecord.usedUserProperties::putIfAbsent);
2733
2734
2735 cachedRecord.usedModelProperties.forEach(targetRecord.usedModelProperties::putIfAbsent);
2736
2737
2738 cachedRecord.usedModelInfos.forEach(targetRecord.usedModelInfos::putIfAbsent);
2739
2740
2741 cachedRecord.usedExists.forEach(targetRecord.usedExists::putIfAbsent);
2742 }
2743 }
2744
2745 @SuppressWarnings("deprecation")
2746 private static List<String> getSubprojects(Model activated) {
2747 List<String> subprojects = activated.getSubprojects();
2748 if (subprojects.isEmpty()) {
2749 subprojects = activated.getModules();
2750 }
2751 return subprojects;
2752 }
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762 @SuppressWarnings("deprecation")
2763 private static boolean hasSubprojectsDefined(Model model) {
2764 return !model.getSubprojects().isEmpty() || !model.getModules().isEmpty();
2765 }
2766
2767 @Override
2768 public Model buildRawModel(ModelBuilderRequest request) throws ModelBuilderException {
2769 RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(request.getSession(), request);
2770 try {
2771 ModelBuilderSessionState build = new ModelBuilderSessionState(request);
2772 Model model = build.readRawModel();
2773 if (build.hasErrors()) {
2774 throw build.newModelBuilderException();
2775 }
2776 return model;
2777 } finally {
2778 RequestTraceHelper.exit(trace);
2779 }
2780 }
2781
2782 static String getGroupId(Model model) {
2783 String groupId = model.getGroupId();
2784 if (groupId == null && model.getParent() != null) {
2785 groupId = model.getParent().getGroupId();
2786 }
2787 return groupId;
2788 }
2789
2790 static String getVersion(Model model) {
2791 String version = model.getVersion();
2792 if (version == null && model.getParent() != null) {
2793 version = model.getParent().getVersion();
2794 }
2795 return version;
2796 }
2797
2798
2799
2800
2801
2802
2803
2804 static boolean isExternalOrigin(ModelBuilderRequest request) {
2805 return request.getRequestType() == ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY
2806 && request.getSource() != null
2807 && request.getSource().getModelId() != null;
2808 }
2809
2810 static boolean usesSystemScope(Dependency dependency) {
2811 return "system".equals(dependency.getScope())
2812 || (dependency.getSystemPath() != null
2813 && !dependency.getSystemPath().isEmpty());
2814 }
2815
2816 private DefaultProfileActivationContext getProfileActivationContext(ModelBuilderRequest request, Model model) {
2817 return new DefaultProfileActivationContext(
2818 pathTranslator,
2819 rootLocator,
2820 interpolator,
2821 request.getActiveProfileIds(),
2822 request.getInactiveProfileIds(),
2823 request.getSystemProperties(),
2824 request.getUserProperties(),
2825 model);
2826 }
2827
2828 private List<Activation> getProfileActivations(Model model) {
2829 return model.getProfiles().stream().map(Profile::getActivation).collect(Collectors.toList());
2830 }
2831
2832 private Model injectProfileActivations(Model model, List<Activation> activations) {
2833 List<Profile> profiles = new ArrayList<>();
2834 boolean modified = false;
2835 for (int i = 0; i < model.getProfiles().size(); i++) {
2836 Profile profile = model.getProfiles().get(i);
2837 Activation activation = profile.getActivation();
2838 if (activation != null) {
2839
2840 profile = profile.withActivation(activations.get(i));
2841 modified = true;
2842 }
2843 profiles.add(profile);
2844 }
2845 return modified ? model.withProfiles(profiles) : model;
2846 }
2847
2848 private Model interpolateModel(Model model, ModelBuilderRequest request, ModelProblemCollector problems) {
2849 Model interpolatedModel =
2850 modelInterpolator.interpolateModel(model, model.getProjectDirectory(), request, problems);
2851 if (interpolatedModel.getParent() != null) {
2852 Map<String, String> map1 = request.getSession().getUserProperties();
2853 Map<String, String> map2 = model.getProperties();
2854 Map<String, String> map3 = request.getSession().getSystemProperties();
2855 UnaryOperator<String> cb = Interpolator.chain(map1::get, map2::get, map3::get);
2856 try {
2857 String interpolated =
2858 interpolator.interpolate(interpolatedModel.getParent().getVersion(), cb);
2859 interpolatedModel = interpolatedModel.withParent(
2860 interpolatedModel.getParent().withVersion(interpolated));
2861 } catch (Exception e) {
2862 problems.add(
2863 Severity.ERROR,
2864 Version.BASE,
2865 "Failed to interpolate field: "
2866 + interpolatedModel.getParent().getVersion()
2867 + " on class: ",
2868 e);
2869 }
2870 }
2871 interpolatedModel = interpolatedModel.withPomFile(model.getPomFile());
2872 return interpolatedModel;
2873 }
2874
2875 private boolean rawChildVersionReferencesParent(String rawChildModelVersion) {
2876 return rawChildModelVersion.equals("${pom.version}")
2877 || rawChildModelVersion.equals("${project.version}")
2878 || rawChildModelVersion.equals("${pom.parent.version}")
2879 || rawChildModelVersion.equals("${project.parent.version}");
2880 }
2881
2882 private Model getSuperModel(String modelVersion) {
2883 return superPomProvider.getSuperPom(modelVersion);
2884 }
2885
2886 private static org.apache.maven.api.model.Dependency addExclusions(
2887 org.apache.maven.api.model.Dependency candidate, List<Exclusion> exclusions) {
2888 return candidate.withExclusions(Stream.concat(candidate.getExclusions().stream(), exclusions.stream())
2889 .toList());
2890 }
2891
2892 private boolean match(Exclusion exclusion, Dependency candidate) {
2893 return match(exclusion.getGroupId(), candidate.getGroupId())
2894 && match(exclusion.getArtifactId(), candidate.getArtifactId());
2895 }
2896
2897 private boolean match(String match, String text) {
2898 return match.equals("*") || match.equals(text);
2899 }
2900
2901 private boolean containsCoordinates(String message, String groupId, String artifactId, String version) {
2902 return message != null
2903 && (groupId == null || message.contains(groupId))
2904 && (artifactId == null || message.contains(artifactId))
2905 && (version == null || message.contains(version));
2906 }
2907
2908 record GAKey(String groupId, String artifactId) {}
2909
2910
2911
2912
2913
2914
2915 private record ImportWarningKey(
2916 String message, String sourceLocation, String sourceModelId, int lineNumber, int columnNumber) {}
2917
2918 public record RgavCacheKey(
2919 Session session,
2920 RequestTrace trace,
2921 List<RemoteRepository> repositories,
2922 String groupId,
2923 String artifactId,
2924 String version,
2925 String classifier,
2926 String tag)
2927 implements Request<Session> {
2928 @Nonnull
2929 @Override
2930 public Session getSession() {
2931 return session;
2932 }
2933
2934 @Nullable
2935 @Override
2936 public RequestTrace getTrace() {
2937 return trace;
2938 }
2939
2940 @Override
2941 public boolean equals(Object o) {
2942 return o instanceof RgavCacheKey that
2943 && Objects.equals(tag, that.tag)
2944 && Objects.equals(groupId, that.groupId)
2945 && Objects.equals(version, that.version)
2946 && Objects.equals(artifactId, that.artifactId)
2947 && Objects.equals(classifier, that.classifier)
2948 && Objects.equals(repositories, that.repositories);
2949 }
2950
2951 @Override
2952 public int hashCode() {
2953 return Objects.hash(repositories, groupId, artifactId, version, classifier, tag);
2954 }
2955
2956 @Override
2957 public String toString() {
2958 StringBuilder sb = new StringBuilder();
2959 sb.append(getClass().getSimpleName()).append("[").append("gav='");
2960 if (groupId != null) {
2961 sb.append(groupId);
2962 }
2963 sb.append(":");
2964 if (artifactId != null) {
2965 sb.append(artifactId);
2966 }
2967 sb.append(":");
2968 if (version != null) {
2969 sb.append(version);
2970 }
2971 sb.append(":");
2972 if (classifier != null) {
2973 sb.append(classifier);
2974 }
2975 sb.append("', tag='");
2976 sb.append(tag);
2977 sb.append("']");
2978 return sb.toString();
2979 }
2980 }
2981
2982 public record SourceCacheKey(Session session, RequestTrace trace, Source source, String tag)
2983 implements Request<Session>, CacheMetadata {
2984 @Nonnull
2985 @Override
2986 public Session getSession() {
2987 return session;
2988 }
2989
2990 @Nullable
2991 @Override
2992 public RequestTrace getTrace() {
2993 return trace;
2994 }
2995
2996 @Override
2997 public CacheRetention getCacheRetention() {
2998 return source instanceof CacheMetadata cacheMetadata ? cacheMetadata.getCacheRetention() : null;
2999 }
3000
3001 @Override
3002 public boolean equals(Object o) {
3003 return o instanceof SourceCacheKey that
3004 && Objects.equals(tag, that.tag)
3005 && Objects.equals(source, that.source);
3006 }
3007
3008 @Override
3009 public int hashCode() {
3010 return Objects.hash(source, tag);
3011 }
3012
3013 @Override
3014 public String toString() {
3015 return getClass().getSimpleName() + "[" + "location=" + source.getLocation() + ", tag=" + tag + ", path="
3016 + source.getPath() + ']';
3017 }
3018 }
3019
3020 public static class SourceResponse<R extends Request<?>, T> implements Result<R> {
3021 private final R request;
3022 private final T response;
3023
3024 SourceResponse(R request, T response) {
3025 this.request = request;
3026 this.response = response;
3027 }
3028
3029 @Nonnull
3030 @Override
3031 public R getRequest() {
3032 return request;
3033 }
3034 }
3035
3036 static class InterningTransformer implements XmlReaderRequest.Transformer {
3037 static final Set<String> DEFAULT_CONTEXTS = Set.of(
3038
3039 "groupId",
3040 "artifactId",
3041 "version",
3042 "namespaceUri",
3043 "packaging",
3044
3045
3046 "scope",
3047 "type",
3048 "classifier",
3049
3050
3051 "phase",
3052 "goal",
3053 "execution",
3054
3055
3056 "layout",
3057 "policy",
3058 "checksumPolicy",
3059 "updatePolicy",
3060
3061
3062 "modelVersion",
3063 "name",
3064 "url",
3065 "system",
3066 "distribution",
3067 "status",
3068
3069
3070 "connection",
3071 "developerConnection",
3072 "tag",
3073
3074
3075 "id",
3076 "inherited",
3077 "optional");
3078
3079 private final Set<String> contexts;
3080
3081
3082
3083
3084 InterningTransformer() {
3085 this.contexts = DEFAULT_CONTEXTS;
3086 }
3087
3088
3089
3090
3091
3092
3093 InterningTransformer(Session session) {
3094 this.contexts = parseContextsFromSession(session);
3095 }
3096
3097 private Set<String> parseContextsFromSession(Session session) {
3098 String contextsProperty = session.getUserProperties().get(Constants.MAVEN_MODEL_BUILDER_INTERNS);
3099 if (contextsProperty == null) {
3100 contextsProperty = session.getSystemProperties().get(Constants.MAVEN_MODEL_BUILDER_INTERNS);
3101 }
3102
3103 if (contextsProperty == null || contextsProperty.trim().isEmpty()) {
3104 return DEFAULT_CONTEXTS;
3105 }
3106
3107 return Arrays.stream(contextsProperty.split(","))
3108 .map(String::trim)
3109 .filter(s -> !s.isEmpty())
3110 .collect(Collectors.toSet());
3111 }
3112
3113 @Override
3114 public String transform(String input, String context) {
3115 return input != null && contexts.contains(context) ? input.intern() : input;
3116 }
3117
3118
3119
3120
3121
3122 Set<String> getContexts() {
3123 return contexts;
3124 }
3125 }
3126
3127 private static <T, A> List<T> map(List<T> resources, BiFunction<T, A, T> mapper, A argument) {
3128 List<T> newResources = null;
3129 if (resources != null) {
3130 for (int i = 0; i < resources.size(); i++) {
3131 T resource = resources.get(i);
3132 T newResource = mapper.apply(resource, argument);
3133 if (newResource != resource) {
3134 if (newResources == null) {
3135 newResources = new ArrayList<>(resources);
3136 }
3137 newResources.set(i, newResource);
3138 }
3139 }
3140 }
3141 return newResources;
3142 }
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152 private static boolean isParentWithinRootDirectory(Path parentPath, Path rootDirectory) {
3153 if (parentPath == null || rootDirectory == null) {
3154 return true;
3155 }
3156
3157 try {
3158 Path normalizedParent = parentPath.toAbsolutePath().normalize();
3159 Path normalizedRoot = rootDirectory.toAbsolutePath().normalize();
3160
3161
3162 return normalizedParent.startsWith(normalizedRoot);
3163 } catch (Exception e) {
3164
3165 return true;
3166 }
3167 }
3168 }