1 package org.apache.maven.plugins.enforcer;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.ArrayList;
23 import java.util.List;
24
25 import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
26 import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
27 import org.apache.maven.model.Profile;
28 import org.apache.maven.project.MavenProject;
29 import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
30 import org.codehaus.plexus.util.StringUtils;
31
32
33
34
35
36
37 public class RequireActiveProfile
38 extends AbstractNonCacheableEnforcerRule
39 {
40
41
42
43
44
45
46 private String profiles = null;
47
48
49
50
51
52
53 private boolean all = true;
54
55 public final String getProfiles()
56 {
57 return profiles;
58 }
59
60 public final void setProfiles( String profiles )
61 {
62 this.profiles = profiles;
63 }
64
65 public final boolean isAll()
66 {
67 return all;
68 }
69
70 public final void setAll( boolean all )
71 {
72 this.all = all;
73 }
74
75 @Override
76 public void execute( EnforcerRuleHelper theHelper )
77 throws EnforcerRuleException
78 {
79 List<String> missingProfiles = new ArrayList<String>();
80 try
81 {
82 MavenProject project = (MavenProject) theHelper.evaluate( "${project}" );
83 if ( StringUtils.isNotEmpty( profiles ) )
84 {
85 String[] profs = profiles.split( "," );
86 for ( String profile : profs )
87 {
88 if ( !isProfileActive( project, profile ) )
89 {
90 missingProfiles.add( profile );
91 }
92 }
93
94 boolean fail = false;
95 if ( !missingProfiles.isEmpty() )
96 {
97 if ( all || missingProfiles.size() == profs.length )
98 {
99 fail = true;
100 }
101 }
102
103 if ( fail )
104 {
105 String message = getMessage();
106 StringBuilder buf = new StringBuilder();
107 if ( message != null )
108 {
109 buf.append( message + System.lineSeparator() );
110 }
111
112 for ( String profile : missingProfiles )
113 {
114 buf.append( "Profile \"" + profile + "\" is not activated." + System.lineSeparator() );
115 }
116
117 throw new EnforcerRuleException( buf.toString() );
118 }
119
120 }
121
122 }
123 catch ( ExpressionEvaluationException e )
124 {
125 throw new EnforcerRuleException( "Unable to retrieve the project.", e );
126 }
127
128 }
129
130
131
132
133
134
135
136
137 protected boolean isProfileActive( MavenProject project, String profileName )
138 {
139 List<Profile> activeProfiles = project.getActiveProfiles();
140 if ( activeProfiles != null && !activeProfiles.isEmpty() )
141 {
142 for ( Profile profile : activeProfiles )
143 {
144 if ( profile.getId().equals( profileName ) )
145 {
146 return true;
147 }
148 }
149 }
150
151 return false;
152 }
153 }