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