1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.basepom.inline.mojo;
15
16 import static com.google.common.base.Preconditions.checkNotNull;
17 import static com.google.common.base.Preconditions.checkState;
18
19 import java.util.List;
20 import java.util.Objects;
21 import java.util.Optional;
22
23 import com.google.common.base.Splitter;
24 import org.apache.maven.artifact.Artifact;
25 import org.eclipse.aether.graph.Dependency;
26 import org.eclipse.aether.graph.DependencyNode;
27
28 public final class ArtifactIdentifier {
29
30 private final String artifactId;
31 private final String groupId;
32
33 public ArtifactIdentifier(String artifact) {
34 checkNotNull(artifact, "artifact is null");
35 List<String> elements = Splitter.on(':').trimResults().splitToList(artifact);
36 checkState(elements.size() == 2, "artifact format is <groupId>:<artifactId> (got %s)", artifact);
37 this.groupId = elements.get(0);
38 this.artifactId = elements.get(1);
39 }
40
41 public ArtifactIdentifier(Dependency dependency) {
42 checkNotNull(dependency, "dependency is null");
43
44 this.groupId = dependency.getArtifact().getGroupId();
45 this.artifactId = dependency.getArtifact().getArtifactId();
46 }
47
48 public ArtifactIdentifier(Artifact artifact) {
49 this.groupId = artifact.getGroupId();
50 this.artifactId = artifact.getArtifactId();
51 }
52
53 public ArtifactIdentifier(DependencyNode dependencyNode) {
54 checkNotNull(dependencyNode, "dependencyNode is null");
55
56 this.groupId = dependencyNode.getArtifact().getGroupId();
57 this.artifactId = dependencyNode.getArtifact().getArtifactId();
58 }
59
60 public String getArtifactId() {
61 return artifactId;
62 }
63
64 public String getGroupId() {
65 return groupId;
66 }
67
68 public boolean matchDependency(Dependency dependency) {
69 return Optional.ofNullable(dependency)
70 .map(Dependency::getArtifact)
71 .map(a -> match(a.getGroupId(), a.getArtifactId()))
72 .orElse(false);
73 }
74
75 public boolean matchArtifact(Artifact artifact) {
76 return Optional.of(artifact)
77 .map(a -> match(a.getGroupId(), a.getArtifactId()))
78 .orElse(false);
79 }
80
81 private boolean match(String groupId, String artifactId) {
82 return (getArtifactId().equals("*") || getArtifactId().equals(artifactId))
83 && (getGroupId().equals("*") || getGroupId().equals(groupId));
84 }
85
86 @Override
87 public boolean equals(Object o) {
88 if (this == o) {
89 return true;
90 }
91 if (o == null || getClass() != o.getClass()) {
92 return false;
93 }
94 ArtifactIdentifier that = (ArtifactIdentifier) o;
95 return artifactId.equals(that.artifactId) && groupId.equals(that.groupId);
96 }
97
98 @Override
99 public int hashCode() {
100 return Objects.hash(artifactId, groupId);
101 }
102
103 @Override
104 public String toString() {
105 return String.format("%s:%s", groupId, artifactId);
106 }
107 }