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
76
77
78
79
80 public void execute( EnforcerRuleHelper theHelper )
81 throws EnforcerRuleException
82 {
83 List<String> missingProfiles = new ArrayList<String>();
84 try
85 {
86 MavenProject project = (MavenProject) theHelper.evaluate( "${project}" );
87 if ( StringUtils.isNotEmpty( profiles ) )
88 {
89 String[] profs = profiles.split( "," );
90 for ( String profile : profs )
91 {
92 if ( !isProfileActive( project, profile ) )
93 {
94 missingProfiles.add( profile );
95 }
96 }
97
98 boolean fail = false;
99 if ( !missingProfiles.isEmpty() )
100 {
101 if ( all || missingProfiles.size() == profs.length )
102 {
103 fail = true;
104 }
105 }
106
107 if ( fail )
108 {
109 String message = getMessage();
110 StringBuilder buf = new StringBuilder();
111 if ( message != null )
112 {
113 buf.append( message + "\n" );
114 }
115
116 for ( String profile : missingProfiles )
117 {
118 buf.append( "Profile \"" + profile + "\" is not activated.\n" );
119 }
120
121 throw new EnforcerRuleException( buf.toString() );
122 }
123
124 }
125
126 }
127 catch ( ExpressionEvaluationException e )
128 {
129 throw new EnforcerRuleException( "Unable to retrieve the project.", e );
130 }
131
132 }
133
134
135
136
137
138
139
140
141 protected boolean isProfileActive( MavenProject project, String profileName )
142 {
143 @SuppressWarnings( "unchecked" )
144 List<Profile> activeProfiles = project.getActiveProfiles();
145 if ( activeProfiles != null && !activeProfiles.isEmpty() )
146 {
147 for ( Profile profile : activeProfiles )
148 {
149 if ( profile.getId().equals( profileName ) )
150 {
151 return true;
152 }
153 }
154 }
155
156 return false;
157 }
158 }