View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.model.validation;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.io.File;
26  import java.util.Arrays;
27  import java.util.Deque;
28  import java.util.HashMap;
29  import java.util.HashSet;
30  import java.util.Iterator;
31  import java.util.LinkedList;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.Objects;
35  import java.util.Optional;
36  import java.util.Set;
37  import java.util.concurrent.ConcurrentHashMap;
38  import java.util.function.Consumer;
39  import java.util.function.Supplier;
40  import java.util.regex.Matcher;
41  import java.util.regex.Pattern;
42  import java.util.stream.Collectors;
43  import java.util.stream.StreamSupport;
44  
45  import org.apache.maven.model.Activation;
46  import org.apache.maven.model.Build;
47  import org.apache.maven.model.BuildBase;
48  import org.apache.maven.model.Dependency;
49  import org.apache.maven.model.DependencyManagement;
50  import org.apache.maven.model.DistributionManagement;
51  import org.apache.maven.model.Exclusion;
52  import org.apache.maven.model.InputLocation;
53  import org.apache.maven.model.InputLocationTracker;
54  import org.apache.maven.model.Model;
55  import org.apache.maven.model.Parent;
56  import org.apache.maven.model.Plugin;
57  import org.apache.maven.model.PluginExecution;
58  import org.apache.maven.model.PluginManagement;
59  import org.apache.maven.model.Profile;
60  import org.apache.maven.model.ReportPlugin;
61  import org.apache.maven.model.Reporting;
62  import org.apache.maven.model.Repository;
63  import org.apache.maven.model.Resource;
64  import org.apache.maven.model.building.ModelBuildingRequest;
65  import org.apache.maven.model.building.ModelProblem.Severity;
66  import org.apache.maven.model.building.ModelProblem.Version;
67  import org.apache.maven.model.building.ModelProblemCollector;
68  import org.apache.maven.model.building.ModelProblemCollectorRequest;
69  import org.apache.maven.model.interpolation.ModelVersionProcessor;
70  import org.codehaus.plexus.util.StringUtils;
71  
72  /**
73   * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a>
74   */
75  @Named
76  @Singleton
77  public class DefaultModelValidator implements ModelValidator {
78      public static final String BUILD_ALLOW_EXPRESSION_IN_EFFECTIVE_PROJECT_VERSION =
79              "maven.build.allowExpressionInEffectiveProjectVersion";
80  
81      private static final Pattern CI_FRIENDLY_EXPRESSION = Pattern.compile("\\$\\{(.+?)}");
82      private static final Pattern EXPRESSION_PROJECT_NAME_PATTERN = Pattern.compile("\\$\\{(project.+?)}");
83  
84      // see below; multiple fields depend on this field
85      private static final String ILLEGAL_FS_CHARS = "\\/:\"<>|?*";
86  
87      private static final String ILLEGAL_RELATIVE_PATH_FS_CHARS =
88              ILLEGAL_FS_CHARS.replace("\\", "").replace("/", "");
89  
90      private static final String ILLEGAL_VERSION_CHARS = ILLEGAL_FS_CHARS;
91  
92      private static final String ILLEGAL_REPO_ID_CHARS = ILLEGAL_FS_CHARS;
93  
94      private static final String EMPTY = "";
95  
96      // Thread-safe set required because class is @Singleton and validIds is accessed concurrently
97      // See: https://github.com/apache/maven/issues/11618
98      private final Set<String> validIds = ConcurrentHashMap.newKeySet();
99  
100     private ModelVersionProcessor versionProcessor;
101 
102     @Inject
103     public DefaultModelValidator(ModelVersionProcessor versionProcessor) {
104         this.versionProcessor = versionProcessor;
105     }
106 
107     @SuppressWarnings("checkstyle:methodlength")
108     @Override
109     public void validateRawModel(Model m, ModelBuildingRequest request, ModelProblemCollector problems) {
110         Parent parent = m.getParent();
111         if (parent != null) {
112             validateStringNotEmpty(
113                     "parent.groupId", problems, Severity.FATAL, Version.BASE, parent.getGroupId(), parent);
114 
115             validateStringNotEmpty(
116                     "parent.artifactId", problems, Severity.FATAL, Version.BASE, parent.getArtifactId(), parent);
117 
118             validateStringNotEmpty(
119                     "parent.version", problems, Severity.FATAL, Version.BASE, parent.getVersion(), parent);
120 
121             if (equals(parent.getGroupId(), m.getGroupId()) && equals(parent.getArtifactId(), m.getArtifactId())) {
122                 addViolation(
123                         problems,
124                         Severity.FATAL,
125                         Version.BASE,
126                         "parent.artifactId",
127                         null,
128                         "must be changed"
129                                 + ", the parent element cannot have the same groupId:artifactId as the project.",
130                         parent);
131             }
132 
133             if (equals("LATEST", parent.getVersion()) || equals("RELEASE", parent.getVersion())) {
134                 addViolation(
135                         problems,
136                         Severity.WARNING,
137                         Version.BASE,
138                         "parent.version",
139                         null,
140                         "is either LATEST or RELEASE (both of them are being deprecated)",
141                         parent);
142             }
143         }
144 
145         if (request.getValidationLevel() == ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL) {
146             // profiles: they are essential for proper model building (may contribute profiles, dependencies...)
147             HashSet<String> minProfileIds = new HashSet<>();
148             for (Profile profile : m.getProfiles()) {
149                 if (!minProfileIds.add(profile.getId())) {
150                     addViolation(
151                             problems,
152                             Severity.WARNING,
153                             Version.BASE,
154                             "profiles.profile.id",
155                             null,
156                             "Duplicate activation for profile " + profile.getId(),
157                             profile);
158                 }
159             }
160         } else if (request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
161             Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
162 
163             // [MNG-8129] Validate that relativePath does not contain characters reserved on Windows (NTFS).
164             // These cause InvalidPathException in Maven 4 when resolved via java.nio.file.Path, and typically
165             // indicate the user put a GAV coordinate (e.g. "g:a:v") instead of an actual filesystem path.
166             if (parent != null
167                     && parent.getRelativePath() != null
168                     && !parent.getRelativePath().isEmpty()) {
169                 validateBannedCharacters(
170                         "parent.",
171                         "relativePath",
172                         problems,
173                         errOn30,
174                         Version.BASE,
175                         parent.getRelativePath(),
176                         null,
177                         parent,
178                         ILLEGAL_RELATIVE_PATH_FS_CHARS);
179             }
180 
181             // [MNG-6074] Maven should produce an error if no model version has been set in a POM file used to build an
182             // effective model.
183             //
184             // As of 3.4, the model version is mandatory even in raw models. The XML element still is optional in the
185             // XML schema and this will not change anytime soon. We do not want to build effective models based on
186             // models without a version starting with 3.4.
187             validateStringNotEmpty("modelVersion", problems, Severity.ERROR, Version.V20, m.getModelVersion(), m);
188 
189             validateModelVersion(problems, m.getModelVersion(), m, "4.0.0");
190 
191             validateStringNoExpression("groupId", problems, Severity.WARNING, Version.V20, m.getGroupId(), m);
192             if (parent == null) {
193                 validateStringNotEmpty("groupId", problems, Severity.FATAL, Version.V20, m.getGroupId(), m);
194             }
195 
196             validateStringNoExpression("artifactId", problems, Severity.WARNING, Version.V20, m.getArtifactId(), m);
197             validateStringNotEmpty("artifactId", problems, Severity.FATAL, Version.V20, m.getArtifactId(), m);
198 
199             validateVersionNoExpression("version", problems, Severity.WARNING, Version.V20, m.getVersion(), m);
200             if (parent == null) {
201                 validateStringNotEmpty("version", problems, Severity.FATAL, Version.V20, m.getVersion(), m);
202             }
203 
204             validate20RawDependencies(problems, m.getDependencies(), "dependencies.dependency.", EMPTY, request);
205 
206             validate20RawDependenciesSelfReferencing(
207                     problems, m, m.getDependencies(), "dependencies.dependency", request);
208 
209             if (m.getDependencyManagement() != null) {
210                 validate20RawDependencies(
211                         problems,
212                         m.getDependencyManagement().getDependencies(),
213                         "dependencyManagement.dependencies.dependency.",
214                         EMPTY,
215                         request);
216             }
217 
218             validateRawRepositories(problems, m.getRepositories(), "repositories.repository.", EMPTY, request);
219 
220             validateRawRepositories(
221                     problems, m.getPluginRepositories(), "pluginRepositories.pluginRepository.", EMPTY, request);
222 
223             Build build = m.getBuild();
224             if (build != null) {
225                 validate20RawPlugins(problems, build.getPlugins(), "build.plugins.plugin.", EMPTY, request);
226 
227                 PluginManagement mgmt = build.getPluginManagement();
228                 if (mgmt != null) {
229                     validate20RawPlugins(
230                             problems, mgmt.getPlugins(), "build.pluginManagement.plugins.plugin.", EMPTY, request);
231                 }
232             }
233 
234             Set<String> profileIds = new HashSet<>();
235 
236             for (Profile profile : m.getProfiles()) {
237                 String prefix = "profiles.profile[" + profile.getId() + "].";
238 
239                 if (!profileIds.add(profile.getId())) {
240                     addViolation(
241                             problems,
242                             errOn30,
243                             Version.V20,
244                             "profiles.profile.id",
245                             null,
246                             "must be unique but found duplicate profile with id " + profile.getId(),
247                             profile);
248                 }
249 
250                 validate30RawProfileActivation(problems, profile.getActivation(), prefix);
251 
252                 validate20RawDependencies(
253                         problems, profile.getDependencies(), prefix, "dependencies.dependency.", request);
254 
255                 if (profile.getDependencyManagement() != null) {
256                     validate20RawDependencies(
257                             problems,
258                             profile.getDependencyManagement().getDependencies(),
259                             prefix,
260                             "dependencyManagement.dependencies.dependency.",
261                             request);
262                 }
263 
264                 validateRawRepositories(
265                         problems, profile.getRepositories(), prefix, "repositories.repository.", request);
266 
267                 validateRawRepositories(
268                         problems,
269                         profile.getPluginRepositories(),
270                         prefix,
271                         "pluginRepositories.pluginRepository.",
272                         request);
273 
274                 BuildBase buildBase = profile.getBuild();
275                 if (buildBase != null) {
276                     validate20RawPlugins(problems, buildBase.getPlugins(), prefix, "plugins.plugin.", request);
277 
278                     PluginManagement mgmt = buildBase.getPluginManagement();
279                     if (mgmt != null) {
280                         validate20RawPlugins(
281                                 problems, mgmt.getPlugins(), prefix, "pluginManagement.plugins.plugin.", request);
282                     }
283                 }
284             }
285         }
286     }
287 
288     private void validate30RawProfileActivation(ModelProblemCollector problems, Activation activation, String prefix) {
289         if (activation == null) {
290             return;
291         }
292         class ActivationFrame {
293             String location;
294             Optional<? extends InputLocationTracker> parent;
295 
296             ActivationFrame(String location, Optional<? extends InputLocationTracker> parent) {
297                 this.location = location;
298                 this.parent = parent;
299             }
300         }
301         final Deque<ActivationFrame> stk = new LinkedList<>();
302 
303         final Supplier<String> pathSupplier = () -> {
304             final boolean parallel = false;
305             return StreamSupport.stream(((Iterable<ActivationFrame>) stk::descendingIterator).spliterator(), parallel)
306                     .map(f -> f.location)
307                     .collect(Collectors.joining("."));
308         };
309         final Supplier<InputLocation> locationSupplier = () -> {
310             if (stk.size() < 2) {
311                 return null;
312             }
313             Iterator<ActivationFrame> f = stk.iterator();
314 
315             String location = f.next().location;
316             ActivationFrame parent = f.next();
317 
318             return parent.parent.map(p -> p.getLocation(location)).orElse(null);
319         };
320         final Consumer<String> validator = s -> {
321             if (hasProjectExpression(s)) {
322                 String path = pathSupplier.get();
323                 Matcher matcher = EXPRESSION_PROJECT_NAME_PATTERN.matcher(s);
324                 while (matcher.find()) {
325                     String propertyName = matcher.group(0);
326 
327                     if (path.startsWith("activation.file.")
328                             && ("${project.basedir}".equals(propertyName)
329                                     || "${project.rootDirectory}".equals(propertyName))) {
330                         continue;
331                     }
332                     addViolation(
333                             problems,
334                             Severity.WARNING,
335                             Version.V30,
336                             prefix + path,
337                             null,
338                             "Failed to interpolate profile activation property " + s + ": " + propertyName
339                                     + " expressions are not supported during profile activation.",
340                             locationSupplier.get());
341                 }
342             }
343         };
344         Optional<Activation> root = Optional.of(activation);
345         stk.push(new ActivationFrame("activation", root));
346         root.map(Activation::getFile).ifPresent(fa -> {
347             stk.push(new ActivationFrame("file", Optional.of(fa)));
348             stk.push(new ActivationFrame("exists", Optional.empty()));
349             validator.accept(fa.getExists());
350             stk.peek().location = "missing";
351             validator.accept(fa.getMissing());
352             stk.pop();
353             stk.pop();
354         });
355         root.map(Activation::getOs).ifPresent(oa -> {
356             stk.push(new ActivationFrame("os", Optional.of(oa)));
357             stk.push(new ActivationFrame("arch", Optional.empty()));
358             validator.accept(oa.getArch());
359             stk.peek().location = "family";
360             validator.accept(oa.getFamily());
361             stk.peek().location = "name";
362             validator.accept(oa.getName());
363             stk.peek().location = "version";
364             validator.accept(oa.getVersion());
365             stk.pop();
366             stk.pop();
367         });
368         root.map(Activation::getProperty).ifPresent(pa -> {
369             stk.push(new ActivationFrame("property", Optional.of(pa)));
370             stk.push(new ActivationFrame("name", Optional.empty()));
371             validator.accept(pa.getName());
372             stk.peek().location = "value";
373             validator.accept(pa.getValue());
374             stk.pop();
375             stk.pop();
376         });
377         root.map(Activation::getJdk).ifPresent(jdk -> {
378             stk.push(new ActivationFrame("jdk", Optional.empty()));
379             validator.accept(jdk);
380             stk.pop();
381         });
382     }
383 
384     private void validate20RawPlugins(
385             ModelProblemCollector problems,
386             List<Plugin> plugins,
387             String prefix,
388             String prefix2,
389             ModelBuildingRequest request) {
390         Severity errOn31 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1);
391 
392         Map<String, Plugin> index = new HashMap<>();
393 
394         for (Plugin plugin : plugins) {
395             if (plugin.getGroupId() == null
396                     || (plugin.getGroupId() != null
397                             && plugin.getGroupId().trim().isEmpty())) {
398                 addViolation(
399                         problems,
400                         Severity.FATAL,
401                         Version.V20,
402                         prefix + prefix2 + "(groupId:artifactId)",
403                         null,
404                         "groupId of a plugin must be defined. ",
405                         plugin);
406             }
407 
408             if (plugin.getArtifactId() == null
409                     || (plugin.getArtifactId() != null
410                             && plugin.getArtifactId().trim().isEmpty())) {
411                 addViolation(
412                         problems,
413                         Severity.FATAL,
414                         Version.V20,
415                         prefix + prefix2 + "(groupId:artifactId)",
416                         null,
417                         "artifactId of a plugin must be defined. ",
418                         plugin);
419             }
420 
421             // This will catch cases like <version></version> or <version/>
422             if (plugin.getVersion() != null && plugin.getVersion().trim().isEmpty()) {
423                 addViolation(
424                         problems,
425                         Severity.FATAL,
426                         Version.V20,
427                         prefix + prefix2 + "(groupId:artifactId)",
428                         null,
429                         "version of a plugin must be defined. ",
430                         plugin);
431             }
432 
433             String key = plugin.getKey();
434 
435             Plugin existing = index.get(key);
436 
437             if (existing != null) {
438                 addViolation(
439                         problems,
440                         errOn31,
441                         Version.V20,
442                         prefix + prefix2 + "(groupId:artifactId)",
443                         null,
444                         "must be unique but found duplicate declaration of plugin " + key,
445                         plugin);
446             } else {
447                 index.put(key, plugin);
448             }
449 
450             Set<String> executionIds = new HashSet<>();
451 
452             for (PluginExecution exec : plugin.getExecutions()) {
453                 if (!executionIds.add(exec.getId())) {
454                     addViolation(
455                             problems,
456                             Severity.ERROR,
457                             Version.V20,
458                             prefix + prefix2 + "[" + plugin.getKey() + "].executions.execution.id",
459                             null,
460                             "must be unique but found duplicate execution with id " + exec.getId(),
461                             exec);
462                 }
463             }
464         }
465     }
466 
467     @Override
468     @SuppressWarnings("checkstyle:MethodLength")
469     public void validateEffectiveModel(Model m, ModelBuildingRequest request, ModelProblemCollector problems) {
470         validateStringNotEmpty("modelVersion", problems, Severity.ERROR, Version.BASE, m.getModelVersion(), m);
471 
472         validateId("groupId", problems, m.getGroupId(), m);
473 
474         validateId("artifactId", problems, m.getArtifactId(), m);
475 
476         validateStringNotEmpty("packaging", problems, Severity.ERROR, Version.BASE, m.getPackaging(), m);
477 
478         if (!m.getModules().isEmpty()) {
479             if (!"pom".equals(m.getPackaging())) {
480                 addViolation(
481                         problems,
482                         Severity.ERROR,
483                         Version.BASE,
484                         "packaging",
485                         null,
486                         "with value '" + m.getPackaging() + "' is invalid. Aggregator projects "
487                                 + "require 'pom' as packaging.",
488                         m);
489             }
490 
491             for (int i = 0, n = m.getModules().size(); i < n; i++) {
492                 String module = m.getModules().get(i);
493                 if (StringUtils.isBlank(module)) {
494                     addViolation(
495                             problems,
496                             Severity.ERROR,
497                             Version.BASE,
498                             "modules.module[" + i + "]",
499                             null,
500                             "has been specified without a path to the project directory.",
501                             m.getLocation("modules"));
502                 }
503             }
504         }
505 
506         validateStringNotEmpty("version", problems, Severity.ERROR, Version.BASE, m.getVersion(), m);
507 
508         Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
509 
510         validateEffectiveDependencies(problems, m, m.getDependencies(), false, request);
511 
512         DependencyManagement mgmt = m.getDependencyManagement();
513         if (mgmt != null) {
514             validateEffectiveDependencies(problems, m, mgmt.getDependencies(), true, request);
515         }
516 
517         if (request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
518             Set<String> modules = new HashSet<>();
519             for (int i = 0, n = m.getModules().size(); i < n; i++) {
520                 String module = m.getModules().get(i);
521                 if (!modules.add(module)) {
522                     addViolation(
523                             problems,
524                             Severity.ERROR,
525                             Version.V20,
526                             "modules.module[" + i + "]",
527                             null,
528                             "specifies duplicate child module " + module,
529                             m.getLocation("modules"));
530                 }
531             }
532 
533             Severity errOn31 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1);
534 
535             validateBannedCharacters(
536                     EMPTY, "version", problems, errOn31, Version.V20, m.getVersion(), null, m, ILLEGAL_VERSION_CHARS);
537             validate20ProperSnapshotVersion("version", problems, errOn31, Version.V20, m.getVersion(), null, m);
538             if (hasExpression(m.getVersion())) {
539                 Severity versionExpressionSeverity = Severity.ERROR;
540                 if (Boolean.parseBoolean(
541                         m.getProperties().getProperty(BUILD_ALLOW_EXPRESSION_IN_EFFECTIVE_PROJECT_VERSION))) {
542                     versionExpressionSeverity = Severity.WARNING;
543                 }
544                 addViolation(
545                         problems,
546                         versionExpressionSeverity,
547                         Version.V20,
548                         "version",
549                         null,
550                         "must be a constant version but is '" + m.getVersion() + "'.",
551                         m);
552             }
553 
554             Build build = m.getBuild();
555             if (build != null) {
556                 for (Plugin p : build.getPlugins()) {
557                     validateStringNotEmpty(
558                             "build.plugins.plugin.artifactId",
559                             problems,
560                             Severity.ERROR,
561                             Version.V20,
562                             p.getArtifactId(),
563                             p);
564 
565                     validateStringNotEmpty(
566                             "build.plugins.plugin.groupId", problems, Severity.ERROR, Version.V20, p.getGroupId(), p);
567 
568                     validate20PluginVersion(
569                             "build.plugins.plugin.version", problems, p.getVersion(), p.getKey(), p, request);
570 
571                     validateBoolean(
572                             "build.plugins.plugin.inherited",
573                             EMPTY,
574                             problems,
575                             errOn30,
576                             Version.V20,
577                             p.getInherited(),
578                             p.getKey(),
579                             p);
580 
581                     validateBoolean(
582                             "build.plugins.plugin.extensions",
583                             EMPTY,
584                             problems,
585                             errOn30,
586                             Version.V20,
587                             p.getExtensions(),
588                             p.getKey(),
589                             p);
590 
591                     validate20EffectivePluginDependencies(problems, p, request);
592                 }
593 
594                 validate20RawResources(problems, build.getResources(), "build.resources.resource.", request);
595 
596                 validate20RawResources(
597                         problems, build.getTestResources(), "build.testResources.testResource.", request);
598             }
599 
600             Reporting reporting = m.getReporting();
601             if (reporting != null) {
602                 for (ReportPlugin p : reporting.getPlugins()) {
603                     validateStringNotEmpty(
604                             "reporting.plugins.plugin.artifactId",
605                             problems,
606                             Severity.ERROR,
607                             Version.V20,
608                             p.getArtifactId(),
609                             p);
610 
611                     validateStringNotEmpty(
612                             "reporting.plugins.plugin.groupId",
613                             problems,
614                             Severity.ERROR,
615                             Version.V20,
616                             p.getGroupId(),
617                             p);
618                 }
619             }
620 
621             for (Repository repository : m.getRepositories()) {
622                 validate20EffectiveRepository(problems, repository, "repositories.repository.", request);
623             }
624 
625             for (Repository repository : m.getPluginRepositories()) {
626                 validate20EffectiveRepository(problems, repository, "pluginRepositories.pluginRepository.", request);
627             }
628 
629             DistributionManagement distMgmt = m.getDistributionManagement();
630             if (distMgmt != null) {
631                 if (distMgmt.getStatus() != null) {
632                     addViolation(
633                             problems,
634                             Severity.ERROR,
635                             Version.V20,
636                             "distributionManagement.status",
637                             null,
638                             "must not be specified.",
639                             distMgmt);
640                 }
641 
642                 validate20EffectiveRepository(
643                         problems, distMgmt.getRepository(), "distributionManagement.repository.", request);
644                 validate20EffectiveRepository(
645                         problems,
646                         distMgmt.getSnapshotRepository(),
647                         "distributionManagement.snapshotRepository.",
648                         request);
649             }
650         }
651     }
652 
653     private void validate20RawDependencies(
654             ModelProblemCollector problems,
655             List<Dependency> dependencies,
656             String prefix,
657             String prefix2,
658             ModelBuildingRequest request) {
659         Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
660         Severity errOn31 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1);
661 
662         Map<String, Dependency> index = new HashMap<>();
663 
664         for (Dependency dependency : dependencies) {
665             String key = dependency.getManagementKey();
666 
667             if ("import".equals(dependency.getScope())) {
668                 if (!"pom".equals(dependency.getType())) {
669                     addViolation(
670                             problems,
671                             Severity.WARNING,
672                             Version.V20,
673                             prefix + prefix2 + "type",
674                             key,
675                             "must be 'pom' to import the managed dependencies.",
676                             dependency);
677                 } else if (StringUtils.isNotEmpty(dependency.getClassifier())) {
678                     addViolation(
679                             problems,
680                             errOn30,
681                             Version.V20,
682                             prefix + prefix2 + "classifier",
683                             key,
684                             "must be empty, imported POM cannot have a classifier.",
685                             dependency);
686                 }
687             } else if ("system".equals(dependency.getScope())) {
688 
689                 if (request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1) {
690                     addViolation(
691                             problems,
692                             Severity.WARNING,
693                             Version.V31,
694                             prefix + prefix2 + "scope",
695                             key,
696                             "declares usage of deprecated 'system' scope ",
697                             dependency);
698                 }
699 
700                 String sysPath = dependency.getSystemPath();
701                 if (StringUtils.isNotEmpty(sysPath)) {
702                     if (!hasExpression(sysPath)) {
703                         addViolation(
704                                 problems,
705                                 Severity.WARNING,
706                                 Version.V20,
707                                 prefix + prefix2 + "systemPath",
708                                 key,
709                                 "should use a variable instead of a hard-coded path " + sysPath,
710                                 dependency);
711                     } else if (sysPath.contains("${basedir}") || sysPath.contains("${project.basedir}")) {
712                         addViolation(
713                                 problems,
714                                 Severity.WARNING,
715                                 Version.V20,
716                                 prefix + prefix2 + "systemPath",
717                                 key,
718                                 "should not point at files within the project directory, " + sysPath
719                                         + " will be unresolvable by dependent projects",
720                                 dependency);
721                     }
722                 }
723             }
724 
725             if (equals("LATEST", dependency.getVersion()) || equals("RELEASE", dependency.getVersion())) {
726                 addViolation(
727                         problems,
728                         Severity.WARNING,
729                         Version.BASE,
730                         prefix + prefix2 + "version",
731                         key,
732                         "is either LATEST or RELEASE (both of them are being deprecated)",
733                         dependency);
734             }
735 
736             Dependency existing = index.get(key);
737 
738             if (existing != null) {
739                 String msg;
740                 if (equals(existing.getVersion(), dependency.getVersion())) {
741                     msg = "duplicate declaration of version " + Objects.toString(dependency.getVersion(), "(?)");
742                 } else {
743                     msg = "version " + Objects.toString(existing.getVersion(), "(?)") + " vs "
744                             + Objects.toString(dependency.getVersion(), "(?)");
745                 }
746 
747                 addViolation(
748                         problems,
749                         errOn31,
750                         Version.V20,
751                         prefix + prefix2 + "(groupId:artifactId:type:classifier)",
752                         null,
753                         "must be unique: " + key + " -> " + msg,
754                         dependency);
755             } else {
756                 index.put(key, dependency);
757             }
758         }
759     }
760 
761     private void validate20RawDependenciesSelfReferencing(
762             ModelProblemCollector problems,
763             Model m,
764             List<Dependency> dependencies,
765             String prefix,
766             ModelBuildingRequest request) {
767         // We only check for groupId/artifactId/version/classifier cause if there is another
768         // module with the same groupId/artifactId/version/classifier this will fail the build
769         // earlier like "Project '...' is duplicated in the reactor.
770         // So it is sufficient to check only groupId/artifactId/version/classifier and not the
771         // packaging type.
772         for (Dependency dependency : dependencies) {
773             String key = dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + dependency.getVersion()
774                     + (dependency.getClassifier() != null ? ":" + dependency.getClassifier() : EMPTY);
775             String mKey = m.getGroupId() + ":" + m.getArtifactId() + ":" + m.getVersion();
776             if (key.equals(mKey)) {
777                 // This means a module which is build has a dependency which has the same
778                 // groupId, artifactId, version and classifier coordinates. This is in consequence
779                 // a self reference or in other words a circular reference which can not being resolved.
780                 addViolation(
781                         problems,
782                         Severity.FATAL,
783                         Version.V31,
784                         prefix + "[" + key + "]",
785                         key,
786                         "is referencing itself.",
787                         dependency);
788             }
789         }
790     }
791 
792     private void validateEffectiveDependencies(
793             ModelProblemCollector problems,
794             Model m,
795             List<Dependency> dependencies,
796             boolean management,
797             ModelBuildingRequest request) {
798         Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
799 
800         String prefix = management ? "dependencyManagement.dependencies.dependency." : "dependencies.dependency.";
801 
802         for (Dependency d : dependencies) {
803             validateEffectiveDependency(problems, d, management, prefix, request);
804 
805             if (request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
806                 validateBoolean(
807                         prefix, "optional", problems, errOn30, Version.V20, d.getOptional(), d.getManagementKey(), d);
808 
809                 if (!management) {
810                     validateVersion(
811                             prefix, "version", problems, errOn30, Version.V20, d.getVersion(), d.getManagementKey(), d);
812 
813                     /*
814                      * TODO Extensions like Flex Mojos use custom scopes like "merged", "internal", "external", etc. In
815                      * order to don't break backward-compat with those, only warn but don't error out.
816                      */
817                     validateEnum(
818                             prefix,
819                             "scope",
820                             problems,
821                             Severity.WARNING,
822                             Version.V20,
823                             d.getScope(),
824                             d.getManagementKey(),
825                             d,
826                             "provided",
827                             "compile",
828                             "compile-only",
829                             "runtime",
830                             "test",
831                             "system");
832 
833                     validateEffectiveModelAgainstDependency(prefix, problems, m, d, request);
834                 } else {
835                     validateEnum(
836                             prefix,
837                             "scope",
838                             problems,
839                             Severity.WARNING,
840                             Version.V20,
841                             d.getScope(),
842                             d.getManagementKey(),
843                             d,
844                             "provided",
845                             "compile",
846                             "compile-only",
847                             "runtime",
848                             "test",
849                             "system",
850                             "import");
851                 }
852             }
853         }
854     }
855 
856     private void validateEffectiveModelAgainstDependency(
857             String prefix, ModelProblemCollector problems, Model m, Dependency d, ModelBuildingRequest request) {
858         String key = d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion()
859                 + (d.getClassifier() != null ? ":" + d.getClassifier() : EMPTY);
860         String mKey = m.getGroupId() + ":" + m.getArtifactId() + ":" + m.getVersion();
861         if (key.equals(mKey)) {
862             // This means a module which is build has a dependency which has the same
863             // groupId, artifactId, version and classifier coordinates. This is in consequence
864             // a self reference or in other words a circular reference which can not being resolved.
865             addViolation(
866                     problems, Severity.FATAL, Version.V31, prefix + "[" + key + "]", key, "is referencing itself.", d);
867         }
868     }
869 
870     private void validate20EffectivePluginDependencies(
871             ModelProblemCollector problems, Plugin plugin, ModelBuildingRequest request) {
872         List<Dependency> dependencies = plugin.getDependencies();
873 
874         if (!dependencies.isEmpty()) {
875             String prefix = "build.plugins.plugin[" + plugin.getKey() + "].dependencies.dependency.";
876 
877             Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
878 
879             for (Dependency d : dependencies) {
880                 validateEffectiveDependency(problems, d, false, prefix, request);
881 
882                 validateVersion(
883                         prefix, "version", problems, errOn30, Version.BASE, d.getVersion(), d.getManagementKey(), d);
884 
885                 validateEnum(
886                         prefix,
887                         "scope",
888                         problems,
889                         errOn30,
890                         Version.BASE,
891                         d.getScope(),
892                         d.getManagementKey(),
893                         d,
894                         "compile",
895                         "runtime",
896                         "system");
897             }
898         }
899     }
900 
901     private void validateEffectiveDependency(
902             ModelProblemCollector problems,
903             Dependency d,
904             boolean management,
905             String prefix,
906             ModelBuildingRequest request) {
907         validateId(
908                 prefix,
909                 "artifactId",
910                 problems,
911                 Severity.ERROR,
912                 Version.BASE,
913                 d.getArtifactId(),
914                 d.getManagementKey(),
915                 d);
916 
917         validateId(prefix, "groupId", problems, Severity.ERROR, Version.BASE, d.getGroupId(), d.getManagementKey(), d);
918 
919         if (!management) {
920             validateStringNotEmpty(
921                     prefix, "type", problems, Severity.ERROR, Version.BASE, d.getType(), d.getManagementKey(), d);
922 
923             validateDependencyVersion(problems, d, prefix);
924         }
925 
926         if ("system".equals(d.getScope())) {
927             String systemPath = d.getSystemPath();
928 
929             if (StringUtils.isEmpty(systemPath)) {
930                 addViolation(
931                         problems,
932                         Severity.ERROR,
933                         Version.BASE,
934                         prefix + "systemPath",
935                         d.getManagementKey(),
936                         "is missing.",
937                         d);
938             } else {
939                 File sysFile = new File(systemPath);
940                 if (!sysFile.isAbsolute()) {
941                     addViolation(
942                             problems,
943                             Severity.ERROR,
944                             Version.BASE,
945                             prefix + "systemPath",
946                             d.getManagementKey(),
947                             "must specify an absolute path but is " + systemPath,
948                             d);
949                 } else if (!sysFile.isFile()) {
950                     String msg = "refers to a non-existing file " + sysFile.getAbsolutePath();
951                     systemPath = systemPath.replace('/', File.separatorChar).replace('\\', File.separatorChar);
952                     String jdkHome =
953                             request.getSystemProperties().getProperty("java.home", EMPTY) + File.separator + "..";
954                     if (systemPath.startsWith(jdkHome)) {
955                         msg += ". Please verify that you run Maven using a JDK and not just a JRE.";
956                     }
957                     addViolation(
958                             problems,
959                             Severity.WARNING,
960                             Version.BASE,
961                             prefix + "systemPath",
962                             d.getManagementKey(),
963                             msg,
964                             d);
965                 }
966             }
967         } else if (StringUtils.isNotEmpty(d.getSystemPath())) {
968             addViolation(
969                     problems,
970                     Severity.ERROR,
971                     Version.BASE,
972                     prefix + "systemPath",
973                     d.getManagementKey(),
974                     "must be omitted." + " This field may only be specified for a dependency with system scope.",
975                     d);
976         }
977 
978         if (request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) {
979             for (Exclusion exclusion : d.getExclusions()) {
980                 if (request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0) {
981                     validateId(
982                             prefix,
983                             "exclusions.exclusion.groupId",
984                             problems,
985                             Severity.WARNING,
986                             Version.V20,
987                             exclusion.getGroupId(),
988                             d.getManagementKey(),
989                             exclusion);
990 
991                     validateId(
992                             prefix,
993                             "exclusions.exclusion.artifactId",
994                             problems,
995                             Severity.WARNING,
996                             Version.V20,
997                             exclusion.getArtifactId(),
998                             d.getManagementKey(),
999                             exclusion);
1000                 } else {
1001                     validateIdWithWildcards(
1002                             prefix,
1003                             "exclusions.exclusion.groupId",
1004                             problems,
1005                             Severity.WARNING,
1006                             Version.V30,
1007                             exclusion.getGroupId(),
1008                             d.getManagementKey(),
1009                             exclusion);
1010 
1011                     validateIdWithWildcards(
1012                             prefix,
1013                             "exclusions.exclusion.artifactId",
1014                             problems,
1015                             Severity.WARNING,
1016                             Version.V30,
1017                             exclusion.getArtifactId(),
1018                             d.getManagementKey(),
1019                             exclusion);
1020                 }
1021             }
1022         }
1023     }
1024 
1025     /**
1026      * @since 3.2.4
1027      */
1028     protected void validateDependencyVersion(ModelProblemCollector problems, Dependency d, String prefix) {
1029         validateStringNotEmpty(
1030                 prefix, "version", problems, Severity.ERROR, Version.BASE, d.getVersion(), d.getManagementKey(), d);
1031     }
1032 
1033     private void validateRawRepositories(
1034             ModelProblemCollector problems,
1035             List<Repository> repositories,
1036             String prefix,
1037             String prefix2,
1038             ModelBuildingRequest request) {
1039         Map<String, Repository> index = new HashMap<>();
1040 
1041         for (Repository repository : repositories) {
1042             validateStringNotEmpty(
1043                     prefix, prefix2, "id", problems, Severity.ERROR, Version.V20, repository.getId(), null, repository);
1044 
1045             validateStringNotEmpty(
1046                     prefix,
1047                     prefix2,
1048                     "[" + repository.getId() + "].url",
1049                     problems,
1050                     Severity.ERROR,
1051                     Version.V20,
1052                     repository.getUrl(),
1053                     null,
1054                     repository);
1055 
1056             String key = repository.getId();
1057 
1058             Repository existing = index.get(key);
1059 
1060             if (existing != null) {
1061                 Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
1062 
1063                 addViolation(
1064                         problems,
1065                         errOn30,
1066                         Version.V20,
1067                         prefix + prefix2 + "id",
1068                         null,
1069                         "must be unique: " + repository.getId() + " -> " + existing.getUrl() + " vs "
1070                                 + repository.getUrl(),
1071                         repository);
1072             } else {
1073                 index.put(key, repository);
1074             }
1075         }
1076     }
1077 
1078     private void validate20EffectiveRepository(
1079             ModelProblemCollector problems, Repository repository, String prefix, ModelBuildingRequest request) {
1080         if (repository != null) {
1081             Severity errOn31 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1);
1082 
1083             validateBannedCharacters(
1084                     prefix,
1085                     "id",
1086                     problems,
1087                     errOn31,
1088                     Version.V20,
1089                     repository.getId(),
1090                     null,
1091                     repository,
1092                     ILLEGAL_REPO_ID_CHARS);
1093 
1094             if ("local".equals(repository.getId())) {
1095                 addViolation(
1096                         problems,
1097                         errOn31,
1098                         Version.V20,
1099                         prefix + "id",
1100                         null,
1101                         "must not be 'local'" + ", this identifier is reserved for the local repository"
1102                                 + ", using it for other repositories will corrupt your repository metadata.",
1103                         repository);
1104             }
1105 
1106             if ("legacy".equals(repository.getLayout())) {
1107                 addViolation(
1108                         problems,
1109                         Severity.WARNING,
1110                         Version.V20,
1111                         prefix + "layout",
1112                         repository.getId(),
1113                         "uses the unsupported value 'legacy', artifact resolution might fail.",
1114                         repository);
1115             }
1116         }
1117     }
1118 
1119     private void validate20RawResources(
1120             ModelProblemCollector problems, List<Resource> resources, String prefix, ModelBuildingRequest request) {
1121         Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
1122 
1123         for (Resource resource : resources) {
1124             validateStringNotEmpty(
1125                     prefix,
1126                     "directory",
1127                     problems,
1128                     Severity.ERROR,
1129                     Version.V20,
1130                     resource.getDirectory(),
1131                     null,
1132                     resource);
1133 
1134             validateBoolean(
1135                     prefix,
1136                     "filtering",
1137                     problems,
1138                     errOn30,
1139                     Version.V20,
1140                     resource.getFiltering(),
1141                     resource.getDirectory(),
1142                     resource);
1143         }
1144     }
1145 
1146     // ----------------------------------------------------------------------
1147     // Field validation
1148     // ----------------------------------------------------------------------
1149 
1150     private boolean validateId(
1151             String fieldName, ModelProblemCollector problems, String id, InputLocationTracker tracker) {
1152         return validateId(EMPTY, fieldName, problems, Severity.ERROR, Version.BASE, id, null, tracker);
1153     }
1154 
1155     @SuppressWarnings("checkstyle:parameternumber")
1156     private boolean validateId(
1157             String prefix,
1158             String fieldName,
1159             ModelProblemCollector problems,
1160             Severity severity,
1161             Version version,
1162             String id,
1163             String sourceHint,
1164             InputLocationTracker tracker) {
1165         if (id != null && validIds.contains(id)) {
1166             return true;
1167         }
1168         if (!validateStringNotEmpty(prefix, fieldName, problems, severity, version, id, sourceHint, tracker)) {
1169             return false;
1170         } else {
1171             if (!isValidId(id)) {
1172                 addViolation(
1173                         problems,
1174                         severity,
1175                         version,
1176                         prefix + fieldName,
1177                         sourceHint,
1178                         "with value '" + id + "' does not match a valid id pattern.",
1179                         tracker);
1180                 return false;
1181             }
1182             validIds.add(id);
1183             return true;
1184         }
1185     }
1186 
1187     private boolean isValidId(String id) {
1188         for (int i = 0; i < id.length(); i++) {
1189             char c = id.charAt(i);
1190             if (!isValidIdCharacter(c)) {
1191                 return false;
1192             }
1193         }
1194         return true;
1195     }
1196 
1197     private boolean isValidIdCharacter(char c) {
1198         return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.';
1199     }
1200 
1201     @SuppressWarnings("checkstyle:parameternumber")
1202     private boolean validateIdWithWildcards(
1203             String prefix,
1204             String fieldName,
1205             ModelProblemCollector problems,
1206             Severity severity,
1207             Version version,
1208             String id,
1209             String sourceHint,
1210             InputLocationTracker tracker) {
1211         if (!validateStringNotEmpty(prefix, fieldName, problems, severity, version, id, sourceHint, tracker)) {
1212             return false;
1213         } else {
1214             if (!isValidIdWithWildCards(id)) {
1215                 addViolation(
1216                         problems,
1217                         severity,
1218                         version,
1219                         prefix + fieldName,
1220                         sourceHint,
1221                         "with value '" + id + "' does not match a valid id pattern.",
1222                         tracker);
1223                 return false;
1224             }
1225             return true;
1226         }
1227     }
1228 
1229     private boolean isValidIdWithWildCards(String id) {
1230         for (int i = 0; i < id.length(); i++) {
1231             char c = id.charAt(i);
1232             if (!isValidIdWithWildCardCharacter(c)) {
1233                 return false;
1234             }
1235         }
1236         return true;
1237     }
1238 
1239     private boolean isValidIdWithWildCardCharacter(char c) {
1240         return isValidIdCharacter(c) || c == '?' || c == '*';
1241     }
1242 
1243     private boolean validateStringNoExpression(
1244             String fieldName,
1245             ModelProblemCollector problems,
1246             Severity severity,
1247             Version version,
1248             String string,
1249             InputLocationTracker tracker) {
1250         if (!hasExpression(string)) {
1251             return true;
1252         }
1253 
1254         addViolation(
1255                 problems,
1256                 severity,
1257                 version,
1258                 fieldName,
1259                 null,
1260                 "contains an expression but should be a constant.",
1261                 tracker);
1262 
1263         return false;
1264     }
1265 
1266     private boolean validateVersionNoExpression(
1267             String fieldName,
1268             ModelProblemCollector problems,
1269             Severity severity,
1270             Version version,
1271             String string,
1272             InputLocationTracker tracker) {
1273         if (!hasExpression(string)) {
1274             return true;
1275         }
1276 
1277         Matcher m = CI_FRIENDLY_EXPRESSION.matcher(string.trim());
1278         while (m.find()) {
1279             String property = m.group(1);
1280             if (!versionProcessor.isValidProperty(property)) {
1281                 addViolation(
1282                         problems,
1283                         severity,
1284                         version,
1285                         fieldName,
1286                         null,
1287                         "contains an expression but should be a constant.",
1288                         tracker);
1289                 return false;
1290             }
1291         }
1292 
1293         return true;
1294     }
1295 
1296     private boolean hasExpression(String value) {
1297         return value != null && value.contains("${");
1298     }
1299 
1300     private boolean hasProjectExpression(String value) {
1301         return value != null && value.contains("${project.");
1302     }
1303 
1304     private boolean validateStringNotEmpty(
1305             String fieldName,
1306             ModelProblemCollector problems,
1307             Severity severity,
1308             Version version,
1309             String string,
1310             InputLocationTracker tracker) {
1311         return validateStringNotEmpty(EMPTY, fieldName, problems, severity, version, string, null, tracker);
1312     }
1313 
1314     /**
1315      * Asserts:
1316      * <p/>
1317      * <ul>
1318      * <li><code>string != null</code>
1319      * <li><code>string.length > 0</code>
1320      * </ul>
1321      */
1322     @SuppressWarnings("checkstyle:parameternumber")
1323     private boolean validateStringNotEmpty(
1324             String prefix,
1325             String prefix2,
1326             String fieldName,
1327             ModelProblemCollector problems,
1328             Severity severity,
1329             Version version,
1330             String string,
1331             String sourceHint,
1332             InputLocationTracker tracker) {
1333         if (!validateNotNull(prefix, prefix2, fieldName, problems, severity, version, string, sourceHint, tracker)) {
1334             return false;
1335         }
1336 
1337         if (!string.isEmpty()) {
1338             return true;
1339         }
1340 
1341         addViolation(problems, severity, version, prefix + prefix2 + fieldName, sourceHint, "is missing.", tracker);
1342 
1343         return false;
1344     }
1345 
1346     /**
1347      * Asserts:
1348      * <p/>
1349      * <ul>
1350      * <li><code>string != null</code>
1351      * <li><code>string.length > 0</code>
1352      * </ul>
1353      */
1354     @SuppressWarnings("checkstyle:parameternumber")
1355     private boolean validateStringNotEmpty(
1356             String prefix,
1357             String fieldName,
1358             ModelProblemCollector problems,
1359             Severity severity,
1360             Version version,
1361             String string,
1362             String sourceHint,
1363             InputLocationTracker tracker) {
1364         if (!validateNotNull(prefix, fieldName, problems, severity, version, string, sourceHint, tracker)) {
1365             return false;
1366         }
1367 
1368         if (string.length() > 0) {
1369             return true;
1370         }
1371 
1372         addViolation(problems, severity, version, prefix + fieldName, sourceHint, "is missing.", tracker);
1373 
1374         return false;
1375     }
1376 
1377     /**
1378      * Asserts:
1379      * <p/>
1380      * <ul>
1381      * <li><code>string != null</code>
1382      * </ul>
1383      */
1384     @SuppressWarnings("checkstyle:parameternumber")
1385     private boolean validateNotNull(
1386             String prefix,
1387             String fieldName,
1388             ModelProblemCollector problems,
1389             Severity severity,
1390             Version version,
1391             Object object,
1392             String sourceHint,
1393             InputLocationTracker tracker) {
1394         if (object != null) {
1395             return true;
1396         }
1397 
1398         addViolation(problems, severity, version, prefix + fieldName, sourceHint, "is missing.", tracker);
1399 
1400         return false;
1401     }
1402 
1403     /**
1404      * Asserts:
1405      * <p/>
1406      * <ul>
1407      * <li><code>string != null</code>
1408      * </ul>
1409      */
1410     @SuppressWarnings("checkstyle:parameternumber")
1411     private boolean validateNotNull(
1412             String prefix,
1413             String prefix2,
1414             String fieldName,
1415             ModelProblemCollector problems,
1416             Severity severity,
1417             Version version,
1418             Object object,
1419             String sourceHint,
1420             InputLocationTracker tracker) {
1421         if (object != null) {
1422             return true;
1423         }
1424 
1425         addViolation(problems, severity, version, prefix + prefix2 + fieldName, sourceHint, "is missing.", tracker);
1426 
1427         return false;
1428     }
1429 
1430     @SuppressWarnings("checkstyle:parameternumber")
1431     private boolean validateBoolean(
1432             String prefix,
1433             String fieldName,
1434             ModelProblemCollector problems,
1435             Severity severity,
1436             Version version,
1437             String string,
1438             String sourceHint,
1439             InputLocationTracker tracker) {
1440         if (string == null || string.length() <= 0) {
1441             return true;
1442         }
1443 
1444         if ("true".equalsIgnoreCase(string) || "false".equalsIgnoreCase(string)) {
1445             return true;
1446         }
1447 
1448         addViolation(
1449                 problems,
1450                 severity,
1451                 version,
1452                 prefix + fieldName,
1453                 sourceHint,
1454                 "must be 'true' or 'false' but is '" + string + "'.",
1455                 tracker);
1456 
1457         return false;
1458     }
1459 
1460     @SuppressWarnings("checkstyle:parameternumber")
1461     private boolean validateEnum(
1462             String prefix,
1463             String fieldName,
1464             ModelProblemCollector problems,
1465             Severity severity,
1466             Version version,
1467             String string,
1468             String sourceHint,
1469             InputLocationTracker tracker,
1470             String... validValues) {
1471         if (string == null || string.length() <= 0) {
1472             return true;
1473         }
1474 
1475         List<String> values = Arrays.asList(validValues);
1476 
1477         if (values.contains(string)) {
1478             return true;
1479         }
1480 
1481         addViolation(
1482                 problems,
1483                 severity,
1484                 version,
1485                 prefix + fieldName,
1486                 sourceHint,
1487                 "must be one of " + values + " but is '" + string + "'.",
1488                 tracker);
1489 
1490         return false;
1491     }
1492 
1493     @SuppressWarnings("checkstyle:parameternumber")
1494     private boolean validateModelVersion(
1495             ModelProblemCollector problems, String string, InputLocationTracker tracker, String... validVersions) {
1496         if (string == null || string.length() <= 0) {
1497             return true;
1498         }
1499 
1500         List<String> values = Arrays.asList(validVersions);
1501 
1502         if (values.contains(string)) {
1503             return true;
1504         }
1505 
1506         boolean newerThanAll = true;
1507         boolean olderThanAll = true;
1508         for (String validValue : validVersions) {
1509             final int comparison = compareModelVersions(validValue, string);
1510             newerThanAll = newerThanAll && comparison < 0;
1511             olderThanAll = olderThanAll && comparison > 0;
1512         }
1513 
1514         if (newerThanAll) {
1515             addViolation(
1516                     problems,
1517                     Severity.FATAL,
1518                     Version.V20,
1519                     "modelVersion",
1520                     null,
1521                     "of '" + string + "' is newer than the versions supported by this version of Maven: " + values
1522                             + ". Building this project requires a newer version of Maven.",
1523                     tracker);
1524 
1525         } else if (olderThanAll) {
1526             // note this will not be hit for Maven 1.x project.xml as it is an incompatible schema
1527             addViolation(
1528                     problems,
1529                     Severity.FATAL,
1530                     Version.V20,
1531                     "modelVersion",
1532                     null,
1533                     "of '" + string + "' is older than the versions supported by this version of Maven: " + values
1534                             + ". Building this project requires an older version of Maven.",
1535                     tracker);
1536 
1537         } else {
1538             addViolation(
1539                     problems,
1540                     Severity.ERROR,
1541                     Version.V20,
1542                     "modelVersion",
1543                     null,
1544                     "must be one of " + values + " but is '" + string + "'.",
1545                     tracker);
1546         }
1547 
1548         return false;
1549     }
1550 
1551     /**
1552      * Compares two model versions.
1553      *
1554      * @param first the first version.
1555      * @param second the second version.
1556      * @return negative if the first version is newer than the second version, zero if they are the same or positive if
1557      * the second version is the newer.
1558      */
1559     private static int compareModelVersions(String first, String second) {
1560         // we use a dedicated comparator because we control our model version scheme.
1561         String[] firstSegments = StringUtils.split(first, ".");
1562         String[] secondSegments = StringUtils.split(second, ".");
1563         for (int i = 0; i < Math.max(firstSegments.length, secondSegments.length); i++) {
1564             int result = Long.valueOf(i < firstSegments.length ? firstSegments[i] : "0")
1565                     .compareTo(Long.valueOf(i < secondSegments.length ? secondSegments[i] : "0"));
1566             if (result != 0) {
1567                 return result;
1568             }
1569         }
1570         return 0;
1571     }
1572 
1573     @SuppressWarnings("checkstyle:parameternumber")
1574     private boolean validateBannedCharacters(
1575             String prefix,
1576             String fieldName,
1577             ModelProblemCollector problems,
1578             Severity severity,
1579             Version version,
1580             String string,
1581             String sourceHint,
1582             InputLocationTracker tracker,
1583             String banned) {
1584         if (string != null) {
1585             for (int i = string.length() - 1; i >= 0; i--) {
1586                 if (banned.indexOf(string.charAt(i)) >= 0) {
1587                     addViolation(
1588                             problems,
1589                             severity,
1590                             version,
1591                             prefix + fieldName,
1592                             sourceHint,
1593                             "must not contain any of these characters " + banned + " but found " + string.charAt(i),
1594                             tracker);
1595                     return false;
1596                 }
1597             }
1598         }
1599 
1600         return true;
1601     }
1602 
1603     @SuppressWarnings("checkstyle:parameternumber")
1604     private boolean validateVersion(
1605             String prefix,
1606             String fieldName,
1607             ModelProblemCollector problems,
1608             Severity severity,
1609             Version version,
1610             String string,
1611             String sourceHint,
1612             InputLocationTracker tracker) {
1613         if (string == null || string.length() <= 0) {
1614             return true;
1615         }
1616 
1617         if (hasExpression(string)) {
1618             addViolation(
1619                     problems,
1620                     severity,
1621                     version,
1622                     prefix + fieldName,
1623                     sourceHint,
1624                     "must be a valid version but is '" + string + "'.",
1625                     tracker);
1626             return false;
1627         }
1628 
1629         return validateBannedCharacters(
1630                 prefix, fieldName, problems, severity, version, string, sourceHint, tracker, ILLEGAL_VERSION_CHARS);
1631     }
1632 
1633     private boolean validate20ProperSnapshotVersion(
1634             String fieldName,
1635             ModelProblemCollector problems,
1636             Severity severity,
1637             Version version,
1638             String string,
1639             String sourceHint,
1640             InputLocationTracker tracker) {
1641         if (string == null || string.length() <= 0) {
1642             return true;
1643         }
1644 
1645         if (string.endsWith("SNAPSHOT") && !string.endsWith("-SNAPSHOT")) {
1646             addViolation(
1647                     problems,
1648                     severity,
1649                     version,
1650                     fieldName,
1651                     sourceHint,
1652                     "uses an unsupported snapshot version format, should be '*-SNAPSHOT' instead.",
1653                     tracker);
1654             return false;
1655         }
1656 
1657         return true;
1658     }
1659 
1660     private boolean validate20PluginVersion(
1661             String fieldName,
1662             ModelProblemCollector problems,
1663             String string,
1664             String sourceHint,
1665             InputLocationTracker tracker,
1666             ModelBuildingRequest request) {
1667         if (string == null) {
1668             // NOTE: The check for missing plugin versions is handled directly by the model builder
1669             return true;
1670         }
1671 
1672         Severity errOn30 = getSeverity(request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0);
1673 
1674         if (!validateVersion(EMPTY, fieldName, problems, errOn30, Version.V20, string, sourceHint, tracker)) {
1675             return false;
1676         }
1677 
1678         if (string.length() <= 0 || "RELEASE".equals(string) || "LATEST".equals(string)) {
1679             addViolation(
1680                     problems,
1681                     errOn30,
1682                     Version.V20,
1683                     fieldName,
1684                     sourceHint,
1685                     "must be a valid version but is '" + string + "'.",
1686                     tracker);
1687             return false;
1688         }
1689 
1690         return true;
1691     }
1692 
1693     private static void addViolation(
1694             ModelProblemCollector problems,
1695             Severity severity,
1696             Version version,
1697             String fieldName,
1698             String sourceHint,
1699             String message,
1700             InputLocationTracker tracker) {
1701         StringBuilder buffer = new StringBuilder(256);
1702         buffer.append('\'').append(fieldName).append('\'');
1703 
1704         if (sourceHint != null) {
1705             buffer.append(" for ").append(sourceHint);
1706         }
1707 
1708         buffer.append(' ').append(message);
1709 
1710         // CHECKSTYLE_OFF: LineLength
1711         problems.add(new ModelProblemCollectorRequest(severity, version)
1712                 .setMessage(buffer.toString())
1713                 .setLocation(getLocation(fieldName, tracker)));
1714         // CHECKSTYLE_ON: LineLength
1715     }
1716 
1717     private static InputLocation getLocation(String fieldName, InputLocationTracker tracker) {
1718         InputLocation location = null;
1719 
1720         if (tracker != null) {
1721             if (fieldName != null) {
1722                 Object key = fieldName;
1723 
1724                 int idx = fieldName.lastIndexOf('.');
1725                 if (idx >= 0) {
1726                     fieldName = fieldName.substring(idx + 1);
1727                     key = fieldName;
1728                 }
1729 
1730                 if (fieldName.endsWith("]")) {
1731                     key = fieldName.substring(fieldName.lastIndexOf('[') + 1, fieldName.length() - 1);
1732                     try {
1733                         key = Integer.valueOf(key.toString());
1734                     } catch (NumberFormatException e) {
1735                         // use key as is
1736                     }
1737                 }
1738 
1739                 location = tracker.getLocation(key);
1740             }
1741 
1742             if (location == null) {
1743                 location = tracker.getLocation(EMPTY);
1744             }
1745         }
1746 
1747         return location;
1748     }
1749 
1750     private static boolean equals(String s1, String s2) {
1751         return StringUtils.clean(s1).equals(StringUtils.clean(s2));
1752     }
1753 
1754     private static Severity getSeverity(ModelBuildingRequest request, int errorThreshold) {
1755         return getSeverity(request.getValidationLevel(), errorThreshold);
1756     }
1757 
1758     private static Severity getSeverity(int validationLevel, int errorThreshold) {
1759         if (validationLevel < errorThreshold) {
1760             return Severity.WARNING;
1761         } else {
1762             return Severity.ERROR;
1763         }
1764     }
1765 }