1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.enforcer.rules.utils;
20
21 import java.util.Collection;
22 import java.util.Set;
23 import java.util.stream.Collectors;
24
25 import org.apache.commons.lang3.StringUtils;
26 import org.apache.maven.RepositoryUtils;
27 import org.apache.maven.artifact.Artifact;
28 import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
29 import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
30 import org.eclipse.aether.graph.DependencyNode;
31
32 import static java.util.Optional.ofNullable;
33
34
35
36
37
38
39 public final class ArtifactUtils {
40
41
42
43
44
45
46
47
48
49
50 public static Artifact toArtifact(DependencyNode node) {
51 Artifact artifact = RepositoryUtils.toArtifact(node.getArtifact());
52 ofNullable(node.getDependency()).ifPresent(dependency -> {
53 ofNullable(dependency.getScope()).ifPresent(artifact::setScope);
54 artifact.setOptional(dependency.isOptional());
55 });
56 return artifact;
57 }
58
59
60
61
62
63
64
65
66
67 public static Set<Artifact> filterDependencyArtifacts(Set<Artifact> dependencies, Collection<String> patterns)
68 throws EnforcerRuleException {
69 try {
70 return ofNullable(patterns)
71 .map(collection -> collection.stream()
72 .map(p -> p.split(":"))
73 .map(StringUtils::stripAll)
74 .map(arr -> String.join(":", arr))
75 .flatMap(pattern ->
76 dependencies.stream().filter(artifact -> compareDependency(pattern, artifact)))
77 .collect(Collectors.toSet()))
78 .orElse(null);
79 } catch (IllegalArgumentException e) {
80 if (e.getCause() instanceof InvalidVersionSpecificationException) {
81 throw new EnforcerRuleException(e.getMessage());
82 }
83 throw e;
84 }
85 }
86
87
88
89
90
91
92
93
94 public static boolean matchDependencyArtifact(Artifact artifact, Collection<String> patterns) {
95 try {
96 return ofNullable(patterns)
97 .map(collection -> collection.stream()
98 .map(p -> p.split(":"))
99 .map(StringUtils::stripAll)
100 .map(arr -> String.join(":", arr))
101 .anyMatch(pattern -> compareDependency(pattern, artifact)))
102 .orElse(false);
103 } catch (IllegalArgumentException e) {
104 if (e.getCause() instanceof InvalidVersionSpecificationException) {
105 throw new IllegalArgumentException(e.getMessage());
106 }
107 throw e;
108 }
109 }
110
111
112
113
114
115
116
117
118
119 public static boolean compareDependency(String pattern, Artifact artifact) {
120 return new ArtifactMatcher.Pattern(pattern).match(artifact);
121 }
122 }