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;
20
21 import javax.inject.Inject;
22 import javax.inject.Named;
23
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28
29 import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
30 import org.apache.maven.project.MavenProject;
31
32
33
34
35
36
37 @Named("requireActiveProfile")
38 public final class RequireActiveProfile extends AbstractStandardEnforcerRule {
39
40
41
42 private String profiles = null;
43
44
45
46 private boolean all = true;
47
48 private final MavenProject project;
49
50 @Inject
51 public RequireActiveProfile(MavenProject project) {
52 this.project = Objects.requireNonNull(project);
53 }
54
55 public String getProfiles() {
56 return profiles;
57 }
58
59 public void setProfiles(String profiles) {
60 this.profiles = profiles;
61 }
62
63 public boolean isAll() {
64 return all;
65 }
66
67 public void setAll(boolean all) {
68 this.all = all;
69 }
70
71 @Override
72 public void execute() throws EnforcerRuleException {
73 List<String> missingProfiles = new ArrayList<>();
74 if (profiles != null && !profiles.isEmpty()) {
75 String[] profileIds = profiles.split(",");
76 for (String profileId : profileIds) {
77 if (!isProfileActive(project, profileId)) {
78 missingProfiles.add(profileId);
79 }
80 }
81
82 boolean fail = false;
83 if (!missingProfiles.isEmpty()) {
84 if (all || missingProfiles.size() == profileIds.length) {
85 fail = true;
86 }
87 }
88
89 if (fail) {
90 String message = getMessage();
91 StringBuilder buf = new StringBuilder();
92 if (message != null) {
93 buf.append(message + System.lineSeparator());
94 }
95
96 for (String profile : missingProfiles) {
97 buf.append("Profile \"" + profile + "\" is not activated." + System.lineSeparator());
98 }
99
100 throw new EnforcerRuleException(buf.toString());
101 }
102 }
103 }
104
105
106
107
108
109
110
111
112 private boolean isProfileActive(MavenProject project, String profileId) {
113 for (Map.Entry<String, List<String>> entry :
114 project.getInjectedProfileIds().entrySet()) {
115 if (entry.getValue().contains(profileId)) {
116 return true;
117 }
118 }
119 return false;
120 }
121
122 @Override
123 public String toString() {
124 return String.format("RequireActiveProfile[message=%s, profiles=%s, all=%b]", getMessage(), profiles, all);
125 }
126 }