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.model.interpolation.reflection.ReflectionValueExtractor;
32  import org.apache.maven.plugin.descriptor.MojoDescriptor;
33  import org.apache.maven.plugin.descriptor.PluginDescriptor;
34  import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
35  import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator;
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#getTopDirectory()} 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   * @see Session
73   * @see MojoExecution
74   */
75  public class PluginParameterExpressionEvaluatorV4 implements TypeAwareExpressionEvaluator {
76      private Session session;
77  
78      private MojoExecution mojoExecution;
79  
80      private Project project;
81  
82      private Path basedir;
83  
84      private Properties properties;
85  
86      public PluginParameterExpressionEvaluatorV4(Session session, Project project) {
87          this(session, project, null);
88      }
89  
90      public PluginParameterExpressionEvaluatorV4(Session session, Project project, MojoExecution mojoExecution) {
91          this.session = session;
92          this.mojoExecution = mojoExecution;
93          this.properties = new Properties();
94          this.project = project;
95  
96          //
97          // Maven4: We may want to evaluate how this is used but we add these separate as the
98          // getExecutionProperties is deprecated in MavenSession.
99          //
100         this.properties.putAll(session.getUserProperties());
101         this.properties.putAll(session.getSystemProperties());
102 
103         Path basedir = null;
104 
105         if (project != null) {
106             Optional<Path> projectFile = project.getBasedir();
107 
108             // this should always be the case for non-super POM instances...
109             if (projectFile.isPresent()) {
110                 basedir = projectFile.get().toAbsolutePath();
111             }
112         }
113 
114         if (basedir == null) {
115             basedir = session.getTopDirectory();
116         }
117 
118         if (basedir == null) {
119             basedir = Paths.get(System.getProperty("user.dir"));
120         }
121 
122         this.basedir = basedir;
123     }
124 
125     @Override
126     public Object evaluate(String expr) throws ExpressionEvaluationException {
127         return evaluate(expr, null);
128     }
129 
130     @Override
131     @SuppressWarnings("checkstyle:methodlength")
132     public Object evaluate(String expr, Class<?> type) throws ExpressionEvaluationException {
133         Object value = null;
134 
135         if (expr == null) {
136             return null;
137         }
138 
139         String expression = stripTokens(expr);
140         if (expression.equals(expr)) {
141             int index = expr.indexOf("${");
142             if (index >= 0) {
143                 int lastIndex = expr.indexOf('}', index);
144                 if (lastIndex >= 0) {
145                     String retVal = expr.substring(0, index);
146 
147                     if ((index > 0) && (expr.charAt(index - 1) == '$')) {
148                         retVal += expr.substring(index + 1, lastIndex + 1);
149                     } else {
150                         Object subResult = evaluate(expr.substring(index, lastIndex + 1));
151 
152                         if (subResult != null) {
153                             retVal += subResult;
154                         } else {
155                             retVal += "$" + expr.substring(index + 1, lastIndex + 1);
156                         }
157                     }
158 
159                     retVal += evaluate(expr.substring(lastIndex + 1));
160                     return retVal;
161                 }
162             }
163 
164             // Was not an expression
165             return expression.replace("$$", "$");
166         }
167 
168         if ("localRepository".equals(expression)) {
169             // TODO: v4
170             value = session.getLocalRepository();
171         } else if ("session".equals(expression)) {
172             value = session;
173         } else if (expression.startsWith("session")) {
174             // TODO: v4
175             try {
176                 int pathSeparator = expression.indexOf('/');
177 
178                 if (pathSeparator > 0) {
179                     String pathExpression = expression.substring(0, pathSeparator);
180                     value = ReflectionValueExtractor.evaluate(pathExpression, session);
181                     if (pathSeparator < expression.length() - 1) {
182                         if (value instanceof Path) {
183                             value = ((Path) value).resolve(expression.substring(pathSeparator + 1));
184                         } else {
185                             value = value + expression.substring(pathSeparator);
186                         }
187                     }
188                 } else {
189                     value = ReflectionValueExtractor.evaluate(expression, session);
190                 }
191             } catch (Exception e) {
192                 // TODO don't catch exception
193                 throw new ExpressionEvaluationException(
194                         "Error evaluating plugin parameter expression: " + expression, e);
195             }
196         } else if ("reactorProjects".equals(expression)) {
197             value = session.getProjects();
198         } else if ("project".equals(expression)) {
199             value = project;
200         } else if ("executedProject".equals(expression)) {
201             value = ((DefaultSession) session)
202                     .getProject(((DefaultSession) session)
203                             .getMavenSession()
204                             .getCurrentProject()
205                             .getExecutionProject());
206         } else if (expression.startsWith("project") || expression.startsWith("pom")) {
207             // TODO: v4
208             try {
209                 int pathSeparator = expression.indexOf('/');
210 
211                 if (pathSeparator > 0) {
212                     String pathExpression = expression.substring(0, pathSeparator);
213                     value = ReflectionValueExtractor.evaluate(pathExpression, project);
214                     value = value + expression.substring(pathSeparator);
215                 } else {
216                     value = ReflectionValueExtractor.evaluate(expression, project);
217                 }
218             } catch (Exception e) {
219                 // TODO don't catch exception
220                 throw new ExpressionEvaluationException(
221                         "Error evaluating plugin parameter expression: " + expression, e);
222             }
223         } else if (expression.equals("repositorySystemSession")) {
224             // TODO: v4
225         } else if (expression.equals("mojo") || expression.equals("mojoExecution")) {
226             value = new DefaultMojoExecution(mojoExecution);
227         } else if (expression.startsWith("mojo")) {
228             // TODO: v4
229             try {
230                 int pathSeparator = expression.indexOf('/');
231 
232                 if (pathSeparator > 0) {
233                     String pathExpression = expression.substring(0, pathSeparator);
234                     value = ReflectionValueExtractor.evaluate(pathExpression, mojoExecution);
235                     value = value + expression.substring(pathSeparator);
236                 } else {
237                     value = ReflectionValueExtractor.evaluate(expression, mojoExecution);
238                 }
239             } catch (Exception e) {
240                 // TODO don't catch exception
241                 throw new ExpressionEvaluationException(
242                         "Error evaluating plugin parameter expression: " + expression, e);
243             }
244         } else if (expression.equals("plugin")) {
245             // TODO: v4
246             value = mojoExecution.getMojoDescriptor().getPluginDescriptor();
247         } else if (expression.startsWith("plugin")) {
248             // TODO: v4
249             try {
250                 int pathSeparator = expression.indexOf('/');
251 
252                 PluginDescriptor pluginDescriptor =
253                         mojoExecution.getMojoDescriptor().getPluginDescriptor();
254 
255                 if (pathSeparator > 0) {
256                     String pathExpression = expression.substring(0, pathSeparator);
257                     value = ReflectionValueExtractor.evaluate(pathExpression, pluginDescriptor);
258                     value = value + expression.substring(pathSeparator);
259                 } else {
260                     value = ReflectionValueExtractor.evaluate(expression, pluginDescriptor);
261                 }
262             } catch (Exception e) {
263                 throw new ExpressionEvaluationException(
264                         "Error evaluating plugin parameter expression: " + expression, e);
265             }
266         } else if ("settings".equals(expression)) {
267             value = session.getSettings();
268         } else if (expression.startsWith("settings")) {
269             try {
270                 int pathSeparator = expression.indexOf('/');
271 
272                 if (pathSeparator > 0) {
273                     String pathExpression = expression.substring(0, pathSeparator);
274                     value = ReflectionValueExtractor.evaluate(pathExpression, session.getSettings());
275                     value = value + expression.substring(pathSeparator);
276                 } else {
277                     value = ReflectionValueExtractor.evaluate(expression, session.getSettings());
278                 }
279             } catch (Exception e) {
280                 // TODO don't catch exception
281                 throw new ExpressionEvaluationException(
282                         "Error evaluating plugin parameter expression: " + expression, e);
283             }
284         } else if ("basedir".equals(expression)) {
285             value = basedir.toString();
286         } else if (expression.startsWith("basedir")) {
287             int pathSeparator = expression.indexOf('/');
288 
289             if (pathSeparator > 0) {
290                 value = basedir.toString() + expression.substring(pathSeparator);
291             }
292         }
293 
294         /*
295          * MNG-4312: We neither have reserved all of the above magic expressions nor is their set fixed/well-known (it
296          * gets occasionally extended by newer Maven versions). This imposes the risk for existing plugins to
297          * unintentionally use such a magic expression for an ordinary property. So here we check whether we
298          * ended up with a magic value that is not compatible with the type of the configured mojo parameter (a string
299          * could still be converted by the configurator so we leave those alone). If so, back off to evaluating the
300          * expression from properties only.
301          */
302         if (value != null && type != null && !(value instanceof String) && !isTypeCompatible(type, value)) {
303             value = null;
304         }
305 
306         if (value == null) {
307             // The CLI should win for defining properties
308 
309             if (properties != null) {
310                 // We will attempt to get nab a property as a way to specify a parameter
311                 // to a plugin. My particular case here is allowing the surefire plugin
312                 // to run a single test so I want to specify that class on the cli as
313                 // a parameter.
314 
315                 value = properties.getProperty(expression);
316             }
317 
318             if ((value == null) && ((project != null) && (project.getModel().getProperties() != null))) {
319                 value = project.getModel().getProperties().get(expression);
320             }
321         }
322 
323         if (value instanceof String) {
324             // TODO without #, this could just be an evaluate call...
325 
326             String val = (String) value;
327 
328             int exprStartDelimiter = val.indexOf("${");
329 
330             if (exprStartDelimiter >= 0) {
331                 if (exprStartDelimiter > 0) {
332                     value = val.substring(0, exprStartDelimiter) + evaluate(val.substring(exprStartDelimiter));
333                 } else {
334                     value = evaluate(val.substring(exprStartDelimiter));
335                 }
336             }
337         }
338 
339         return value;
340     }
341 
342     private static boolean isTypeCompatible(Class<?> type, Object value) {
343         if (type.isInstance(value)) {
344             return true;
345         }
346         // likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid
347         return ((type.isPrimitive() || type.getName().startsWith("java.lang."))
348                 && value.getClass().getName().startsWith("java.lang."));
349     }
350 
351     private String stripTokens(String expr) {
352         if (expr.startsWith("${") && (expr.indexOf('}') == expr.length() - 1)) {
353             expr = expr.substring(2, expr.length() - 1);
354         }
355         return expr;
356     }
357 
358     @Override
359     public File alignToBaseDirectory(File file) {
360         // TODO Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a
361         // similar component for re-usage
362         if (file != null) {
363             if (file.isAbsolute()) {
364                 // path was already absolute, just normalize file separator and we're done
365             } else if (file.getPath().startsWith(File.separator)) {
366                 // drive-relative Windows path, don't align with project directory but with drive root
367                 file = file.getAbsoluteFile();
368             } else {
369                 // an ordinary relative path, align with project directory
370                 file = basedir.resolve(file.getPath())
371                         .normalize()
372                         .toAbsolutePath()
373                         .toFile();
374             }
375         }
376         return file;
377     }
378 }