/
DefaultModelBuilder.java
1342 lines (1103 loc) · 55.7 KB
/
DefaultModelBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.maven.model.building;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Activation;
import org.apache.maven.model.Build;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.InputLocation;
import org.apache.maven.model.InputLocationTracker;
import org.apache.maven.model.InputSource;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.Profile;
import org.apache.maven.model.Repository;
import org.apache.maven.model.building.ModelProblem.Severity;
import org.apache.maven.model.building.ModelProblem.Version;
import org.apache.maven.model.composition.DependencyManagementImporter;
import org.apache.maven.model.inheritance.InheritanceAssembler;
import org.apache.maven.model.interpolation.ModelInterpolator;
import org.apache.maven.model.io.ModelParseException;
import org.apache.maven.model.management.DependencyManagementInjector;
import org.apache.maven.model.management.PluginManagementInjector;
import org.apache.maven.model.normalization.ModelNormalizer;
import org.apache.maven.model.path.ModelPathTranslator;
import org.apache.maven.model.path.ModelUrlNormalizer;
import org.apache.maven.model.path.ProfileActivationFilePathInterpolator;
import org.apache.maven.model.plugin.LifecycleBindingsInjector;
import org.apache.maven.model.plugin.PluginConfigurationExpander;
import org.apache.maven.model.plugin.ReportConfigurationExpander;
import org.apache.maven.model.plugin.ReportingConverter;
import org.apache.maven.model.profile.DefaultProfileActivationContext;
import org.apache.maven.model.profile.ProfileActivationContext;
import org.apache.maven.model.profile.ProfileInjector;
import org.apache.maven.model.profile.ProfileSelector;
import org.apache.maven.model.resolution.InvalidRepositoryException;
import org.apache.maven.model.resolution.ModelResolver;
import org.apache.maven.model.resolution.UnresolvableModelException;
import org.apache.maven.model.resolution.WorkspaceModelResolver;
import org.apache.maven.model.superpom.SuperPomProvider;
import org.apache.maven.model.validation.ModelValidator;
import org.codehaus.plexus.interpolation.InterpolationException;
import org.codehaus.plexus.interpolation.MapBasedValueSource;
import org.codehaus.plexus.interpolation.RegexBasedInterpolator;
import org.codehaus.plexus.interpolation.StringSearchInterpolator;
import org.codehaus.plexus.util.StringUtils;
import org.eclipse.sisu.Nullable;
import static org.apache.maven.model.building.Result.error;
import static org.apache.maven.model.building.Result.newResult;
/**
* @author Benjamin Bentmann
*/
@Named
@Singleton
public class DefaultModelBuilder implements ModelBuilder {
@Inject
private ModelProcessor modelProcessor;
@Inject
private ModelValidator modelValidator;
@Inject
private ModelNormalizer modelNormalizer;
@Inject
private ModelInterpolator modelInterpolator;
@Inject
private ModelPathTranslator modelPathTranslator;
@Inject
private ModelUrlNormalizer modelUrlNormalizer;
@Inject
private SuperPomProvider superPomProvider;
@Inject
private InheritanceAssembler inheritanceAssembler;
@Inject
private ProfileSelector profileSelector;
@Inject
private ProfileInjector profileInjector;
@Inject
private PluginManagementInjector pluginManagementInjector;
@Inject
private DependencyManagementInjector dependencyManagementInjector;
@Inject
private DependencyManagementImporter dependencyManagementImporter;
@Inject
@Nullable
private LifecycleBindingsInjector lifecycleBindingsInjector;
@Inject
private PluginConfigurationExpander pluginConfigurationExpander;
@Inject
private ReportConfigurationExpander reportConfigurationExpander;
@Inject
private ReportingConverter reportingConverter;
@Inject
private ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator;
public DefaultModelBuilder setModelProcessor(ModelProcessor modelProcessor) {
this.modelProcessor = modelProcessor;
return this;
}
public DefaultModelBuilder setModelValidator(ModelValidator modelValidator) {
this.modelValidator = modelValidator;
return this;
}
public DefaultModelBuilder setModelNormalizer(ModelNormalizer modelNormalizer) {
this.modelNormalizer = modelNormalizer;
return this;
}
public DefaultModelBuilder setModelInterpolator(ModelInterpolator modelInterpolator) {
this.modelInterpolator = modelInterpolator;
return this;
}
public DefaultModelBuilder setModelPathTranslator(ModelPathTranslator modelPathTranslator) {
this.modelPathTranslator = modelPathTranslator;
return this;
}
public DefaultModelBuilder setModelUrlNormalizer(ModelUrlNormalizer modelUrlNormalizer) {
this.modelUrlNormalizer = modelUrlNormalizer;
return this;
}
public DefaultModelBuilder setSuperPomProvider(SuperPomProvider superPomProvider) {
this.superPomProvider = superPomProvider;
return this;
}
public DefaultModelBuilder setProfileSelector(ProfileSelector profileSelector) {
this.profileSelector = profileSelector;
return this;
}
public DefaultModelBuilder setProfileInjector(ProfileInjector profileInjector) {
this.profileInjector = profileInjector;
return this;
}
public DefaultModelBuilder setInheritanceAssembler(InheritanceAssembler inheritanceAssembler) {
this.inheritanceAssembler = inheritanceAssembler;
return this;
}
public DefaultModelBuilder setDependencyManagementImporter(DependencyManagementImporter depMgmtImporter) {
this.dependencyManagementImporter = depMgmtImporter;
return this;
}
public DefaultModelBuilder setDependencyManagementInjector(DependencyManagementInjector depMgmtInjector) {
this.dependencyManagementInjector = depMgmtInjector;
return this;
}
public DefaultModelBuilder setLifecycleBindingsInjector(LifecycleBindingsInjector lifecycleBindingsInjector) {
this.lifecycleBindingsInjector = lifecycleBindingsInjector;
return this;
}
public DefaultModelBuilder setPluginConfigurationExpander(PluginConfigurationExpander pluginConfigurationExpander) {
this.pluginConfigurationExpander = pluginConfigurationExpander;
return this;
}
public DefaultModelBuilder setPluginManagementInjector(PluginManagementInjector pluginManagementInjector) {
this.pluginManagementInjector = pluginManagementInjector;
return this;
}
public DefaultModelBuilder setReportConfigurationExpander(ReportConfigurationExpander reportConfigurationExpander) {
this.reportConfigurationExpander = reportConfigurationExpander;
return this;
}
public DefaultModelBuilder setReportingConverter(ReportingConverter reportingConverter) {
this.reportingConverter = reportingConverter;
return this;
}
public DefaultModelBuilder setProfileActivationFilePathInterpolator(
ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator) {
this.profileActivationFilePathInterpolator = profileActivationFilePathInterpolator;
return this;
}
@SuppressWarnings("checkstyle:methodlength")
@Override
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
return build(request, new LinkedHashSet<String>());
}
@SuppressWarnings("checkstyle:methodlength")
protected ModelBuildingResult build(ModelBuildingRequest request, Collection<String> importIds)
throws ModelBuildingException {
// phase 1
DefaultModelBuildingResult result = new DefaultModelBuildingResult();
DefaultModelProblemCollector problems = new DefaultModelProblemCollector(result);
// read and validate raw model
Model inputModel = request.getRawModel();
if (inputModel == null) {
inputModel = readModel(request.getModelSource(), request.getPomFile(), request, problems);
}
// profile activation
DefaultProfileActivationContext profileActivationContext = getProfileActivationContext(request, inputModel);
problems.setSource("(external profiles)");
List<Profile> activeExternalProfiles =
profileSelector.getActiveProfiles(request.getProfiles(), profileActivationContext, problems);
result.setActiveExternalProfiles(activeExternalProfiles);
if (!activeExternalProfiles.isEmpty()) {
Properties profileProps = new Properties();
for (Profile profile : activeExternalProfiles) {
profileProps.putAll(profile.getProperties());
}
profileProps.putAll(profileActivationContext.getUserProperties());
profileActivationContext.setUserProperties(profileProps);
}
problems.setRootModel(inputModel);
ModelData resultData = new ModelData(request.getModelSource(), inputModel);
ModelData superData = new ModelData(null, getSuperModel());
Collection<String> parentIds = new LinkedHashSet<>();
List<ModelData> lineage = new ArrayList<>();
for (ModelData currentData = resultData; currentData != null; ) {
lineage.add(currentData);
Model rawModel = currentData.getModel();
currentData.setRawModel(rawModel);
Model tmpModel = rawModel.clone();
currentData.setModel(tmpModel);
problems.setSource(tmpModel);
// model normalization
modelNormalizer.mergeDuplicates(tmpModel, request, problems);
profileActivationContext.setProjectProperties(tmpModel.getProperties());
Map<String, Activation> interpolatedActivations =
getInterpolatedActivations(rawModel, profileActivationContext, problems);
injectProfileActivations(tmpModel, interpolatedActivations);
List<Profile> activePomProfiles =
profileSelector.getActiveProfiles(tmpModel.getProfiles(), profileActivationContext, problems);
Set<String> activeProfileIds =
activePomProfiles.stream().map(Profile::getId).collect(Collectors.toSet());
currentData.setActiveProfiles(rawModel.getProfiles().stream()
.filter(p -> activeProfileIds.contains(p.getId()))
.collect(Collectors.toList()));
// profile injection
for (Profile activeProfile : activePomProfiles) {
profileInjector.injectProfile(tmpModel, activeProfile, request, problems);
}
if (currentData == resultData) {
for (Profile activeProfile : activeExternalProfiles) {
profileInjector.injectProfile(tmpModel, activeProfile, request, problems);
}
}
if (currentData == superData) {
break;
}
configureResolver(request.getModelResolver(), tmpModel, problems);
ModelData parentData = readParent(tmpModel, currentData.getSource(), request, problems);
if (parentData == null) {
currentData = superData;
} else if (currentData == resultData) { // First iteration - add initial id after version resolution.
currentData.setGroupId(
currentData.getRawModel().getGroupId() == null
? parentData.getGroupId()
: currentData.getRawModel().getGroupId());
currentData.setVersion(
currentData.getRawModel().getVersion() == null
? parentData.getVersion()
: currentData.getRawModel().getVersion());
currentData.setArtifactId(currentData.getRawModel().getArtifactId());
parentIds.add(currentData.getId());
// Reset - only needed for 'getId'.
currentData.setGroupId(null);
currentData.setArtifactId(null);
currentData.setVersion(null);
currentData = parentData;
} else if (!parentIds.add(parentData.getId())) {
String message = "The parents form a cycle: ";
for (String modelId : parentIds) {
message += modelId + " -> ";
}
message += parentData.getId();
problems.add(new ModelProblemCollectorRequest(ModelProblem.Severity.FATAL, ModelProblem.Version.BASE)
.setMessage(message));
throw problems.newModelBuildingException();
} else {
currentData = parentData;
}
}
problems.setSource(inputModel);
checkPluginVersions(lineage, request, problems);
// inheritance assembly
assembleInheritance(lineage, request, problems);
Model resultModel = resultData.getModel();
problems.setSource(resultModel);
problems.setRootModel(resultModel);
// model interpolation
resultModel = interpolateModel(resultModel, request, problems);
resultData.setModel(resultModel);
if (resultModel.getParent() != null) {
final ModelData parentData = lineage.get(1);
if (parentData.getVersion() == null || parentData.getVersion().contains("${")) {
final Model interpolatedParent = interpolateModel(parentData.getModel(), request, problems);
// parentData.setModel( interpolatedParent );
parentData.setVersion(interpolatedParent.getVersion());
}
}
// url normalization
modelUrlNormalizer.normalize(resultModel, request);
// Now the fully interpolated model is available: reconfigure the resolver
configureResolver(request.getModelResolver(), resultModel, problems, true);
resultData.setGroupId(resultModel.getGroupId());
resultData.setArtifactId(resultModel.getArtifactId());
resultData.setVersion(resultModel.getVersion());
result.setEffectiveModel(resultModel);
for (ModelData currentData : lineage) {
String modelId = (currentData != superData) ? currentData.getId() : "";
result.addModelId(modelId);
result.setActivePomProfiles(modelId, currentData.getActiveProfiles());
result.setRawModel(modelId, currentData.getRawModel());
}
if (!request.isTwoPhaseBuilding()) {
build(request, result, importIds);
}
return result;
}
@FunctionalInterface
private interface InterpolateString {
String apply(String s) throws InterpolationException;
}
private Map<String, Activation> getInterpolatedActivations(
Model rawModel, DefaultProfileActivationContext context, DefaultModelProblemCollector problems) {
Map<String, Activation> interpolatedActivations = getProfileActivations(rawModel, true);
if (interpolatedActivations.isEmpty()) {
return Collections.emptyMap();
}
RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
interpolator.addValueSource(new MapBasedValueSource(context.getProjectProperties()));
interpolator.addValueSource(new MapBasedValueSource(context.getUserProperties()));
interpolator.addValueSource(new MapBasedValueSource(context.getSystemProperties()));
class Interpolation {
final InputLocationTracker target;
final InterpolateString impl;
Interpolation(InputLocationTracker target, InterpolateString impl) {
this.target = target;
this.impl = impl;
}
void performFor(String value, String locationKey, Consumer<String> mutator) {
if (StringUtils.isEmpty(value)) {
return;
}
try {
mutator.accept(impl.apply(value));
} catch (InterpolationException e) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Failed to interpolate value " + value + ": " + e.getMessage())
.setLocation(target.getLocation(locationKey))
.setException(e));
}
}
}
for (Activation activation : interpolatedActivations.values()) {
Optional<Activation> a = Optional.of(activation);
a.map(Activation::getFile).ifPresent(fa -> {
Interpolation nt =
new Interpolation(fa, s -> profileActivationFilePathInterpolator.interpolate(s, context));
nt.performFor(fa.getExists(), "exists", fa::setExists);
nt.performFor(fa.getMissing(), "missing", fa::setMissing);
});
a.map(Activation::getOs).ifPresent(oa -> {
Interpolation nt = new Interpolation(oa, interpolator::interpolate);
nt.performFor(oa.getArch(), "arch", oa::setArch);
nt.performFor(oa.getFamily(), "family", oa::setFamily);
nt.performFor(oa.getName(), "name", oa::setName);
nt.performFor(oa.getVersion(), "version", oa::setVersion);
});
a.map(Activation::getProperty).ifPresent(pa -> {
Interpolation nt = new Interpolation(pa, interpolator::interpolate);
nt.performFor(pa.getName(), "name", pa::setName);
nt.performFor(pa.getValue(), "value", pa::setValue);
});
a.map(Activation::getJdk).ifPresent(ja -> new Interpolation(activation, interpolator::interpolate)
.performFor(ja, "jdk", activation::setJdk));
}
return interpolatedActivations;
}
@Override
public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result)
throws ModelBuildingException {
return build(request, result, new LinkedHashSet<String>());
}
private ModelBuildingResult build(
ModelBuildingRequest request, ModelBuildingResult result, Collection<String> imports)
throws ModelBuildingException {
// phase 2
Model resultModel = result.getEffectiveModel();
DefaultModelProblemCollector problems = new DefaultModelProblemCollector(result);
problems.setSource(resultModel);
problems.setRootModel(resultModel);
// model path translation
modelPathTranslator.alignToBaseDirectory(resultModel, resultModel.getProjectDirectory(), request);
// plugin management injection
pluginManagementInjector.injectManagement(resultModel, request, problems);
fireEvent(resultModel, request, problems, ModelBuildingEventCatapult.BUILD_EXTENSIONS_ASSEMBLED);
if (request.isProcessPlugins()) {
if (lifecycleBindingsInjector == null) {
throw new IllegalStateException("lifecycle bindings injector is missing");
}
// lifecycle bindings injection
lifecycleBindingsInjector.injectLifecycleBindings(resultModel, request, problems);
}
// dependency management import
importDependencyManagement(resultModel, request, problems, imports);
// dependency management injection
dependencyManagementInjector.injectManagement(resultModel, request, problems);
modelNormalizer.injectDefaultValues(resultModel, request, problems);
if (request.isProcessPlugins()) {
// reports configuration
reportConfigurationExpander.expandPluginConfiguration(resultModel, request, problems);
// reports conversion to decoupled site plugin
reportingConverter.convertReporting(resultModel, request, problems);
// plugins configuration
pluginConfigurationExpander.expandPluginConfiguration(resultModel, request, problems);
}
// effective model validation
modelValidator.validateEffectiveModel(resultModel, request, problems);
if (hasModelErrors(problems)) {
throw problems.newModelBuildingException();
}
return result;
}
@Override
public Result<? extends Model> buildRawModel(File pomFile, int validationLevel, boolean locationTracking) {
final ModelBuildingRequest request = new DefaultModelBuildingRequest()
.setValidationLevel(validationLevel)
.setLocationTracking(locationTracking);
final DefaultModelProblemCollector collector =
new DefaultModelProblemCollector(new DefaultModelBuildingResult());
try {
return newResult(readModel(null, pomFile, request, collector), collector.getProblems());
} catch (ModelBuildingException e) {
return error(collector.getProblems());
}
}
private Model readModel(
ModelSource modelSource, File pomFile, ModelBuildingRequest request, DefaultModelProblemCollector problems)
throws ModelBuildingException {
Model model;
if (modelSource == null) {
if (pomFile != null) {
modelSource = new FileModelSource(pomFile);
} else {
throw new NullPointerException("neither pomFile nor modelSource can be null");
}
}
problems.setSource(modelSource.getLocation());
try {
boolean strict = request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0;
InputSource source = request.isLocationTracking() ? new InputSource() : null;
Map<String, Object> options = new HashMap<>();
options.put(ModelProcessor.IS_STRICT, strict);
options.put(ModelProcessor.INPUT_SOURCE, source);
options.put(ModelProcessor.SOURCE, modelSource);
try {
model = modelProcessor.read(modelSource.getInputStream(), options);
} catch (ModelParseException e) {
if (!strict) {
throw e;
}
options.put(ModelProcessor.IS_STRICT, Boolean.FALSE);
try {
model = modelProcessor.read(modelSource.getInputStream(), options);
} catch (ModelParseException ne) {
// still unreadable even in non-strict mode, rethrow original error
throw e;
}
if (pomFile != null) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.V20)
.setMessage("Malformed POM " + modelSource.getLocation() + ": " + e.getMessage())
.setException(e));
} else {
problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20)
.setMessage("Malformed POM " + modelSource.getLocation() + ": " + e.getMessage())
.setException(e));
}
}
if (source != null) {
source.setModelId(ModelProblemUtils.toId(model));
source.setLocation(modelSource.getLocation());
}
} catch (ModelParseException e) {
problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
.setMessage("Non-parseable POM " + modelSource.getLocation() + ": " + e.getMessage())
.setException(e));
throw problems.newModelBuildingException();
} catch (IOException e) {
String msg = e.getMessage();
if (msg == null || msg.length() <= 0) {
// NOTE: There's java.nio.charset.MalformedInputException and sun.io.MalformedInputException
if (e.getClass().getName().endsWith("MalformedInputException")) {
msg = "Some input bytes do not match the file encoding.";
} else {
msg = e.getClass().getSimpleName();
}
}
problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE)
.setMessage("Non-readable POM " + modelSource.getLocation() + ": " + msg)
.setException(e));
throw problems.newModelBuildingException();
}
model.setPomFile(pomFile);
problems.setSource(model);
modelValidator.validateRawModel(model, request, problems);
if (hasFatalErrors(problems)) {
throw problems.newModelBuildingException();
}
return model;
}
private DefaultProfileActivationContext getProfileActivationContext(ModelBuildingRequest request, Model rawModel) {
DefaultProfileActivationContext context = new DefaultProfileActivationContext();
context.setActiveProfileIds(request.getActiveProfileIds());
context.setInactiveProfileIds(request.getInactiveProfileIds());
context.setSystemProperties(request.getSystemProperties());
// enrich user properties with project packaging
Properties userProperties = request.getUserProperties();
userProperties.computeIfAbsent(
(Object) ProfileActivationContext.PROPERTY_NAME_PACKAGING, (p) -> (Object) rawModel.getPackaging());
context.setUserProperties(userProperties);
context.setProjectDirectory(
(request.getPomFile() != null) ? request.getPomFile().getParentFile() : null);
return context;
}
private void configureResolver(ModelResolver modelResolver, Model model, DefaultModelProblemCollector problems) {
configureResolver(modelResolver, model, problems, false);
}
private void configureResolver(
ModelResolver modelResolver,
Model model,
DefaultModelProblemCollector problems,
boolean replaceRepositories) {
if (modelResolver == null) {
return;
}
problems.setSource(model);
List<Repository> repositories = model.getRepositories();
for (Repository repository : repositories) {
try {
modelResolver.addRepository(repository, replaceRepositories);
} catch (InvalidRepositoryException e) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Invalid repository " + repository.getId() + ": " + e.getMessage())
.setLocation(repository.getLocation(""))
.setException(e));
}
}
}
private void checkPluginVersions(
List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems) {
if (request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
return;
}
Map<String, Plugin> plugins = new HashMap<>();
Map<String, String> versions = new HashMap<>();
Map<String, String> managedVersions = new HashMap<>();
for (int i = lineage.size() - 1; i >= 0; i--) {
Model model = lineage.get(i).getModel();
Build build = model.getBuild();
if (build != null) {
for (Plugin plugin : build.getPlugins()) {
String key = plugin.getKey();
if (versions.get(key) == null) {
versions.put(key, plugin.getVersion());
plugins.put(key, plugin);
}
}
PluginManagement mgmt = build.getPluginManagement();
if (mgmt != null) {
for (Plugin plugin : mgmt.getPlugins()) {
String key = plugin.getKey();
if (managedVersions.get(key) == null) {
managedVersions.put(key, plugin.getVersion());
}
}
}
}
}
for (String key : versions.keySet()) {
if (versions.get(key) == null && managedVersions.get(key) == null) {
InputLocation location = plugins.get(key).getLocation("");
problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20)
.setMessage("'build.plugins.plugin.version' for " + key + " is missing.")
.setLocation(location));
}
}
}
private void assembleInheritance(
List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems) {
for (int i = lineage.size() - 2; i >= 0; i--) {
Model parent = lineage.get(i + 1).getModel();
Model child = lineage.get(i).getModel();
inheritanceAssembler.assembleModelInheritance(child, parent, request, problems);
}
}
private Map<String, Activation> getProfileActivations(Model model, boolean clone) {
Map<String, Activation> activations = new HashMap<>();
for (Profile profile : model.getProfiles()) {
Activation activation = profile.getActivation();
if (activation == null) {
continue;
}
if (clone) {
activation = activation.clone();
}
activations.put(profile.getId(), activation);
}
return activations;
}
private void injectProfileActivations(Model model, Map<String, Activation> activations) {
for (Profile profile : model.getProfiles()) {
Activation activation = profile.getActivation();
if (activation == null) {
continue;
}
// restore activation
profile.setActivation(activations.get(profile.getId()));
}
}
private Model interpolateModel(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {
// save profile activations before interpolation, since they are evaluated with limited scope
Map<String, Activation> originalActivations = getProfileActivations(model, true);
Model interpolatedModel =
modelInterpolator.interpolateModel(model, model.getProjectDirectory(), request, problems);
if (interpolatedModel.getParent() != null) {
StringSearchInterpolator ssi = new StringSearchInterpolator();
ssi.addValueSource(new MapBasedValueSource(request.getUserProperties()));
ssi.addValueSource(new MapBasedValueSource(model.getProperties()));
ssi.addValueSource(new MapBasedValueSource(request.getSystemProperties()));
try {
String interpolated =
ssi.interpolate(interpolatedModel.getParent().getVersion());
interpolatedModel.getParent().setVersion(interpolated);
} catch (Exception e) {
ModelProblemCollectorRequest mpcr = new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Failed to interpolate field: "
+ interpolatedModel.getParent().getVersion()
+ " on class: ")
.setException(e);
problems.add(mpcr);
}
}
interpolatedModel.setPomFile(model.getPomFile());
// restore profiles with file activation to their value before full interpolation
injectProfileActivations(model, originalActivations);
return interpolatedModel;
}
private ModelData readParent(
Model childModel,
ModelSource childSource,
ModelBuildingRequest request,
DefaultModelProblemCollector problems)
throws ModelBuildingException {
ModelData parentData;
Parent parent = childModel.getParent();
if (parent != null) {
String groupId = parent.getGroupId();
String artifactId = parent.getArtifactId();
String version = parent.getVersion();
parentData = getCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.RAW);
if (parentData == null) {
parentData = readParentLocally(childModel, childSource, request, problems);
if (parentData == null) {
parentData = readParentExternally(childModel, request, problems);
}
putCache(request.getModelCache(), groupId, artifactId, version, ModelCacheTag.RAW, parentData);
} else {
/*
* NOTE: This is a sanity check of the cache hit. If the cached parent POM was locally resolved, the
* child's <relativePath> should point at that parent, too. If it doesn't, we ignore the cache and
* resolve externally, to mimic the behavior if the cache didn't exist in the first place. Otherwise,
* the cache would obscure a bad POM.
*/
File pomFile = parentData.getModel().getPomFile();
if (pomFile != null) {
FileModelSource pomSource = new FileModelSource(pomFile);
ModelSource expectedParentSource = getParentPomFile(childModel, childSource);
if (expectedParentSource == null
|| (expectedParentSource instanceof ModelSource2
&& !pomSource.equals(expectedParentSource))) {
parentData = readParentExternally(childModel, request, problems);
}
}
}
Model parentModel = parentData.getModel();
if (!"pom".equals(parentModel.getPackaging())) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Invalid packaging for parent POM " + ModelProblemUtils.toSourceHint(parentModel)
+ ", must be \"pom\" but is \"" + parentModel.getPackaging() + "\"")
.setLocation(parentModel.getLocation("packaging")));
}
} else {
parentData = null;
}
return parentData;
}
private ModelData readParentLocally(
Model childModel,
ModelSource childSource,
ModelBuildingRequest request,
DefaultModelProblemCollector problems)
throws ModelBuildingException {
final Parent parent = childModel.getParent();
final ModelSource candidateSource;
final Model candidateModel;
final WorkspaceModelResolver resolver = request.getWorkspaceModelResolver();
if (resolver == null) {
candidateSource = getParentPomFile(childModel, childSource);
if (candidateSource == null) {
return null;
}
File pomFile = null;
if (candidateSource instanceof FileModelSource) {
pomFile = ((FileModelSource) candidateSource).getPomFile();
}
candidateModel = readModel(candidateSource, pomFile, request, problems);
} else {
try {
candidateModel =
resolver.resolveRawModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
} catch (UnresolvableModelException e) {
problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.BASE) //
.setMessage(e.getMessage().toString())
.setLocation(parent.getLocation(""))
.setException(e));
throw problems.newModelBuildingException();
}
if (candidateModel == null) {
return null;
}
candidateSource = new FileModelSource(candidateModel.getPomFile());
}
//
// TODO jvz Why isn't all this checking the job of the duty of the workspace resolver, we know that we
// have a model that is suitable, yet more checks are done here and the one for the version is problematic
// before because with parents as ranges it will never work in this scenario.
//
String groupId = candidateModel.getGroupId();
if (groupId == null && candidateModel.getParent() != null) {
groupId = candidateModel.getParent().getGroupId();
}
String artifactId = candidateModel.getArtifactId();
String version = candidateModel.getVersion();
if (version == null && candidateModel.getParent() != null) {
version = candidateModel.getParent().getVersion();
}
if (groupId == null
|| !groupId.equals(parent.getGroupId())
|| artifactId == null
|| !artifactId.equals(parent.getArtifactId())) {
StringBuilder buffer = new StringBuilder(256);
buffer.append("'parent.relativePath'");
if (childModel != problems.getRootModel()) {
buffer.append(" of POM ").append(ModelProblemUtils.toSourceHint(childModel));
}
buffer.append(" points at ").append(groupId).append(':').append(artifactId);
buffer.append(" instead of ").append(parent.getGroupId()).append(':');
buffer.append(parent.getArtifactId()).append(", please verify your project structure");
problems.setSource(childModel);
problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.BASE)
.setMessage(buffer.toString())
.setLocation(parent.getLocation("")));
return null;
}
if (version != null && parent.getVersion() != null && !version.equals(parent.getVersion())) {
try {
VersionRange parentRange = VersionRange.createFromVersionSpec(parent.getVersion());
if (!parentRange.hasRestrictions()) {
// the parent version is not a range, we have version skew, drop back to resolution from repo
return null;
}
if (!parentRange.containsVersion(new DefaultArtifactVersion(version))) {
// version skew drop back to resolution from the repository
return null;
}
// Validate versions aren't inherited when using parent ranges the same way as when read externally.
String rawChildModelVersion = childModel.getVersion();
if (rawChildModelVersion == null) {
// Message below is checked for in the MNG-2199 core IT.
problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
.setMessage("Version must be a constant")
.setLocation(childModel.getLocation("")));
} else {
if (rawChildVersionReferencesParent(rawChildModelVersion)) {
// Message below is checked for in the MNG-2199 core IT.
problems.add(new ModelProblemCollectorRequest(Severity.FATAL, Version.V31)
.setMessage("Version must be a constant")
.setLocation(childModel.getLocation("version")));
}
}
// MNG-2199: What else to check here ?
} catch (InvalidVersionSpecificationException e) {
// invalid version range, so drop back to resolution from the repository
return null;
}
}
//
// Here we just need to know that a version is fine to use but this validation we can do in our workspace
// resolver.
//