View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugin;
20  
21  import java.io.File;
22  import java.nio.file.Path;
23  import java.nio.file.Paths;
24  import java.util.Optional;
25  import java.util.Properties;
26  
27  import org.apache.maven.api.Project;
28  import org.apache.maven.api.Session;
29  import org.apache.maven.internal.impl.DefaultMojoExecution;
30  import org.apache.maven.internal.impl.DefaultSession;
31  import org.apache.maven.plugin.descriptor.MojoDescriptor;
32  import org.apache.maven.plugin.descriptor.PluginDescriptor;
33  import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
34  import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator;
35  import org.codehaus.plexus.util.introspection.ReflectionValueExtractor;
36  
37  /**
38   * Evaluator for plugin parameters expressions. Content surrounded by <code>${</code> and <code>}</code> is evaluated.
39   * Recognized values are:
40   * <table border="1">
41   * <caption>Expression matrix</caption>
42   * <tr><th>expression</th>                     <th></th>               <th>evaluation result</th></tr>
43   * <tr><td><code>session</code></td>           <td></td>               <td>the actual {@link Session}</td></tr>
44   * <tr><td><code>session.*</code></td>         <td>(since Maven 3)</td><td></td></tr>
45   * <tr><td><code>localRepository</code></td>   <td></td>
46   *                                             <td>{@link Session#getLocalRepository()}</td></tr>
47   * <tr><td><code>reactorProjects</code></td>   <td></td>               <td>{@link Session#getProjects()}</td></tr>
48   * <tr><td><code>project</code></td>           <td></td>
49   *                                 <td>{@link org.apache.maven.execution.MavenSession#getCurrentProject()}</td></tr>
50   * <tr><td><code>project.*</code></td>         <td></td>               <td></td></tr>
51   * <tr><td><code>pom.*</code></td>             <td>(since Maven 3)</td><td>same as <code>project.*</code></td></tr>
52   * <tr><td><code>executedProject</code></td>   <td></td>
53   *                                 <td>{@link org.apache.maven.project.MavenProject#getExecutionProject()}</td></tr>
54   * <tr><td><code>settings</code></td>          <td></td>               <td>{@link Session#getSettings()}</td></tr>
55   * <tr><td><code>settings.*</code></td>        <td></td>               <td></td></tr>
56   * <tr><td><code>basedir</code></td>           <td></td>
57   *                                 <td>{@link Session#getExecutionRootDirectory()} or
58   *                                                 <code>System.getProperty( "user.dir" )</code> if null</td></tr>
59   * <tr><td><code>mojoExecution</code></td>     <td></td>               <td>the actual {@link MojoExecution}</td></tr>
60   * <tr><td><code>mojo</code></td>              <td>(since Maven 3)</td><td>same as <code>mojoExecution</code></td></tr>
61   * <tr><td><code>mojo.*</code></td>            <td>(since Maven 3)</td><td></td></tr>
62   * <tr><td><code>plugin</code></td>            <td>(since Maven 3)</td>
63   *                             <td>{@link MojoExecution#getMojoDescriptor()}.{@link MojoDescriptor#getPluginDescriptor()
64   *                                 getPluginDescriptor()}</td></tr>
65   * <tr><td><code>plugin.*</code></td>          <td></td>               <td></td></tr>
66   * <tr><td><code>*</code></td>                 <td></td>               <td>user properties</td></tr>
67   * <tr><td><code>*</code></td>                 <td></td>               <td>system properties</td></tr>
68   * <tr><td><code>*</code></td>                 <td></td>               <td>project properties</td></tr>
69   * </table>
70   * <i>Notice:</i> <code>reports</code> was supported in Maven 2.x but was removed in Maven 3
71   *
72   * @author Jason van Zyl
73   * @see Session
74   * @see MojoExecution
75   */
76  public class PluginParameterExpressionEvaluatorV4 implements TypeAwareExpressionEvaluator {
77      private Session session;
78  
79      private MojoExecution mojoExecution;
80  
81      private Project project;
82  
83      private Path basedir;
84  
85      private Properties properties;
86  
87      public PluginParameterExpressionEvaluatorV4(Session session, Project project) {
88          this(session, project, null);
89      }
90  
91      public PluginParameterExpressionEvaluatorV4(Session session, Project project, MojoExecution mojoExecution) {
92          this.session = session;
93          this.mojoExecution = mojoExecution;
94          this.properties = new Properties();
95          this.project = project;
96  
97          //
98          // Maven4: We may want to evaluate how this is used but we add these separate as the
99          // getExecutionProperties is deprecated in MavenSession.
100         //
101         this.properties.putAll(session.getUserProperties());
102         this.properties.putAll(session.getSystemProperties());
103 
104         Path basedir = null;
105 
106         if (project != null) {
107             Optional<Path> projectFile = project.getBasedir();
108 
109             // this should always be the case for non-super POM instances...
110             if (projectFile.isPresent()) {
111                 basedir = projectFile.get().toAbsolutePath();
112             }
113         }
114 
115         if (basedir == null) {
116             basedir = session.getExecutionRootDirectory();
117         }
118 
119         if (basedir == null) {
120             basedir = Paths.get(System.getProperty("user.dir"));
121         }
122 
123         this.basedir = basedir;
124     }
125 
126     @Override
127     public Object evaluate(String expr) throws ExpressionEvaluationException {
128         return evaluate(expr, null);
129     }
130 
131     @Override
132     @SuppressWarnings("checkstyle:methodlength")
133     public Object evaluate(String expr, Class<?> type) throws ExpressionEvaluationException {
134         Object value = null;
135 
136         if (expr == null) {
137             return null;
138         }
139 
140         String expression = stripTokens(expr);
141         if (expression.equals(expr)) {
142             int index = expr.indexOf("${");
143             if (index >= 0) {
144                 int lastIndex = expr.indexOf('}', index);
145                 if (lastIndex >= 0) {
146                     String retVal = expr.substring(0, index);
147 
148                     if ((index > 0) && (expr.charAt(index - 1) == '$')) {
149                         retVal += expr.substring(index + 1, lastIndex + 1);
150                     } else {
151                         Object subResult = evaluate(expr.substring(index, lastIndex + 1));
152 
153                         if (subResult != null) {
154                             retVal += subResult;
155                         } else {
156                             retVal += "$" + expr.substring(index + 1, lastIndex + 1);
157                         }
158                     }
159 
160                     retVal += evaluate(expr.substring(lastIndex + 1));
161                     return retVal;
162                 }
163             }
164 
165             // Was not an expression
166             return expression.replace("$$", "$");
167         }
168 
169         if ("localRepository".equals(expression)) {
170             // TODO: v4
171             value = session.getLocalRepository();
172         } else if ("session".equals(expression)) {
173             value = session;
174         } else if (expression.startsWith("session")) {
175             // TODO: v4
176             try {
177                 int pathSeparator = expression.indexOf('/');
178 
179                 if (pathSeparator > 0) {
180                     String pathExpression = expression.substring(1, pathSeparator);
181                     value = ReflectionValueExtractor.evaluate(pathExpression, session);
182                     value = value + expression.substring(pathSeparator);
183                 } else {
184                     value = ReflectionValueExtractor.evaluate(expression.substring(1), session);
185                 }
186             } catch (Exception e) {
187                 // TODO don't catch exception
188                 throw new ExpressionEvaluationException(
189                         "Error evaluating plugin parameter expression: " + expression, e);
190             }
191         } else if ("reactorProjects".equals(expression)) {
192             value = session.getProjects();
193         } else if ("project".equals(expression)) {
194             value = project;
195         } else if ("executedProject".equals(expression)) {
196             value = ((DefaultSession) session)
197                     .getProject(((DefaultSession) session)
198                             .getMavenSession()
199                             .getCurrentProject()
200                             .getExecutionProject());
201         } else if (expression.startsWith("project") || expression.startsWith("pom")) {
202             // TODO: v4
203             try {
204                 int pathSeparator = expression.indexOf('/');
205 
206                 if (pathSeparator > 0) {
207                     String pathExpression = expression.substring(0, pathSeparator);
208                     value = ReflectionValueExtractor.evaluate(pathExpression, project);
209                     value = value + expression.substring(pathSeparator);
210                 } else {
211                     value = ReflectionValueExtractor.evaluate(expression.substring(1), project);
212                 }
213             } catch (Exception e) {
214                 // TODO don't catch exception
215                 throw new ExpressionEvaluationException(
216                         "Error evaluating plugin parameter expression: " + expression, e);
217             }
218         } else if (expression.equals("repositorySystemSession")) {
219             // TODO: v4
220         } else if (expression.equals("mojo") || expression.equals("mojoExecution")) {
221             value = new DefaultMojoExecution(mojoExecution);
222         } else if (expression.startsWith("mojo")) {
223             // TODO: v4
224             try {
225                 int pathSeparator = expression.indexOf('/');
226 
227                 if (pathSeparator > 0) {
228                     String pathExpression = expression.substring(1, pathSeparator);
229                     value = ReflectionValueExtractor.evaluate(pathExpression, mojoExecution);
230                     value = value + expression.substring(pathSeparator);
231                 } else {
232                     value = ReflectionValueExtractor.evaluate(expression.substring(1), mojoExecution);
233                 }
234             } catch (Exception e) {
235                 // TODO don't catch exception
236                 throw new ExpressionEvaluationException(
237                         "Error evaluating plugin parameter expression: " + expression, e);
238             }
239         } else if (expression.equals("plugin")) {
240             // TODO: v4
241             value = mojoExecution.getMojoDescriptor().getPluginDescriptor();
242         } else if (expression.startsWith("plugin")) {
243             // TODO: v4
244             try {
245                 int pathSeparator = expression.indexOf('/');
246 
247                 PluginDescriptor pluginDescriptor =
248                         mojoExecution.getMojoDescriptor().getPluginDescriptor();
249 
250                 if (pathSeparator > 0) {
251                     String pathExpression = expression.substring(1, pathSeparator);
252                     value = ReflectionValueExtractor.evaluate(pathExpression, pluginDescriptor);
253                     value = value + expression.substring(pathSeparator);
254                 } else {
255                     value = ReflectionValueExtractor.evaluate(expression.substring(1), pluginDescriptor);
256                 }
257             } catch (Exception e) {
258                 throw new ExpressionEvaluationException(
259                         "Error evaluating plugin parameter expression: " + expression, e);
260             }
261         } else if ("settings".equals(expression)) {
262             value = session.getSettings();
263         } else if (expression.startsWith("settings")) {
264             try {
265                 int pathSeparator = expression.indexOf('/');
266 
267                 if (pathSeparator > 0) {
268                     String pathExpression = expression.substring(1, pathSeparator);
269                     value = ReflectionValueExtractor.evaluate(pathExpression, session.getSettings());
270                     value = value + expression.substring(pathSeparator);
271                 } else {
272                     value = ReflectionValueExtractor.evaluate(expression.substring(1), session.getSettings());
273                 }
274             } catch (Exception e) {
275                 // TODO don't catch exception
276                 throw new ExpressionEvaluationException(
277                         "Error evaluating plugin parameter expression: " + expression, e);
278             }
279         } else if ("basedir".equals(expression)) {
280             value = basedir.toString();
281         } else if (expression.startsWith("basedir")) {
282             int pathSeparator = expression.indexOf('/');
283 
284             if (pathSeparator > 0) {
285                 value = basedir.toString() + expression.substring(pathSeparator);
286             }
287         }
288 
289         /*
290          * MNG-4312: We neither have reserved all of the above magic expressions nor is their set fixed/well-known (it
291          * gets occasionally extended by newer Maven versions). This imposes the risk for existing plugins to
292          * unintentionally use such a magic expression for an ordinary property. So here we check whether we
293          * ended up with a magic value that is not compatible with the type of the configured mojo parameter (a string
294          * could still be converted by the configurator so we leave those alone). If so, back off to evaluating the
295          * expression from properties only.
296          */
297         if (value != null && type != null && !(value instanceof String) && !isTypeCompatible(type, value)) {
298             value = null;
299         }
300 
301         if (value == null) {
302             // The CLI should win for defining properties
303 
304             if (properties != null) {
305                 // We will attempt to get nab a property as a way to specify a parameter
306                 // to a plugin. My particular case here is allowing the surefire plugin
307                 // to run a single test so I want to specify that class on the cli as
308                 // a parameter.
309 
310                 value = properties.getProperty(expression);
311             }
312 
313             if ((value == null) && ((project != null) && (project.getModel().getProperties() != null))) {
314                 value = project.getModel().getProperties().get(expression);
315             }
316         }
317 
318         if (value instanceof String) {
319             // TODO without #, this could just be an evaluate call...
320 
321             String val = (String) value;
322 
323             int exprStartDelimiter = val.indexOf("${");
324 
325             if (exprStartDelimiter >= 0) {
326                 if (exprStartDelimiter > 0) {
327                     value = val.substring(0, exprStartDelimiter) + evaluate(val.substring(exprStartDelimiter));
328                 } else {
329                     value = evaluate(val.substring(exprStartDelimiter));
330                 }
331             }
332         }
333 
334         return value;
335     }
336 
337     private static boolean isTypeCompatible(Class<?> type, Object value) {
338         if (type.isInstance(value)) {
339             return true;
340         }
341         // likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid
342         return ((type.isPrimitive() || type.getName().startsWith("java.lang."))
343                 && value.getClass().getName().startsWith("java.lang."));
344     }
345 
346     private String stripTokens(String expr) {
347         if (expr.startsWith("${") && (expr.indexOf('}') == expr.length() - 1)) {
348             expr = expr.substring(2, expr.length() - 1);
349         }
350         return expr;
351     }
352 
353     @Override
354     public File alignToBaseDirectory(File file) {
355         // TODO Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a
356         // similar component for re-usage
357         if (file != null) {
358             if (file.isAbsolute()) {
359                 // path was already absolute, just normalize file separator and we're done
360             } else if (file.getPath().startsWith(File.separator)) {
361                 // drive-relative Windows path, don't align with project directory but with drive root
362                 file = file.getAbsoluteFile();
363             } else {
364                 // an ordinary relative path, align with project directory
365                 file = basedir.resolve(file.getPath())
366                         .normalize()
367                         .toAbsolutePath()
368                         .toFile();
369             }
370         }
371         return file;
372     }
373 }