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.ArrayList;
23  import java.util.Collections;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.Properties;
27  
28  import org.apache.maven.AbstractCoreMavenComponentTestCase;
29  import org.apache.maven.artifact.Artifact;
30  import org.apache.maven.artifact.ArtifactUtils;
31  import org.apache.maven.artifact.repository.ArtifactRepository;
32  import org.apache.maven.execution.DefaultMavenExecutionRequest;
33  import org.apache.maven.execution.DefaultMavenExecutionResult;
34  import org.apache.maven.execution.MavenExecutionRequest;
35  import org.apache.maven.execution.MavenSession;
36  import org.apache.maven.model.Build;
37  import org.apache.maven.model.Dependency;
38  import org.apache.maven.model.Model;
39  import org.apache.maven.plugin.descriptor.MojoDescriptor;
40  import org.apache.maven.plugin.descriptor.PluginDescriptor;
41  import org.apache.maven.project.DuplicateProjectException;
42  import org.apache.maven.project.MavenProject;
43  import org.apache.maven.repository.RepositorySystem;
44  import org.codehaus.plexus.MutablePlexusContainer;
45  import org.codehaus.plexus.PlexusContainer;
46  import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
47  import org.codehaus.plexus.util.dag.CycleDetectedException;
48  
49  /**
50   * @author Jason van Zyl
51   */
52  public class PluginParameterExpressionEvaluatorTest extends AbstractCoreMavenComponentTestCase {
53      private static final String FS = File.separator;
54  
55      private RepositorySystem factory;
56  
57      public void setUp() throws Exception {
58          super.setUp();
59          factory = lookup(RepositorySystem.class);
60      }
61  
62      @Override
63      protected void tearDown() throws Exception {
64          factory = null;
65          super.tearDown();
66      }
67  
68      public void testPluginDescriptorExpressionReference() throws Exception {
69          MojoExecution exec = newMojoExecution();
70  
71          MavenSession session = newMavenSession();
72  
73          Object result = new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin}");
74  
75          System.out.println("Result: " + result);
76  
77          assertSame(
78                  "${plugin} expression does not return plugin descriptor.",
79                  exec.getMojoDescriptor().getPluginDescriptor(),
80                  result);
81      }
82  
83      public void testPluginArtifactsExpressionReference() throws Exception {
84          MojoExecution exec = newMojoExecution();
85  
86          Artifact depArtifact = createArtifact("group", "artifact", "1");
87  
88          List<Artifact> deps = new ArrayList<>();
89          deps.add(depArtifact);
90  
91          exec.getMojoDescriptor().getPluginDescriptor().setArtifacts(deps);
92  
93          MavenSession session = newMavenSession();
94  
95          @SuppressWarnings("unchecked")
96          List<Artifact> depResults =
97                  (List<Artifact>) new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin.artifacts}");
98  
99          System.out.println("Result: " + depResults);
100 
101         assertNotNull(depResults);
102         assertEquals(1, depResults.size());
103         assertSame("dependency artifact is wrong.", depArtifact, depResults.get(0));
104     }
105 
106     public void testPluginArtifactMapExpressionReference() throws Exception {
107         MojoExecution exec = newMojoExecution();
108 
109         Artifact depArtifact = createArtifact("group", "artifact", "1");
110 
111         List<Artifact> deps = new ArrayList<>();
112         deps.add(depArtifact);
113 
114         exec.getMojoDescriptor().getPluginDescriptor().setArtifacts(deps);
115 
116         MavenSession session = newMavenSession();
117 
118         @SuppressWarnings("unchecked")
119         Map<String, Artifact> depResults = (Map<String, Artifact>)
120                 new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin.artifactMap}");
121 
122         System.out.println("Result: " + depResults);
123 
124         assertNotNull(depResults);
125         assertEquals(1, depResults.size());
126         assertSame(
127                 "dependency artifact is wrong.",
128                 depArtifact,
129                 depResults.get(ArtifactUtils.versionlessKey(depArtifact)));
130     }
131 
132     public void testPluginArtifactIdExpressionReference() throws Exception {
133         MojoExecution exec = newMojoExecution();
134 
135         MavenSession session = newMavenSession();
136 
137         Object result = new PluginParameterExpressionEvaluator(session, exec).evaluate("${plugin.artifactId}");
138 
139         System.out.println("Result: " + result);
140 
141         assertSame(
142                 "${plugin.artifactId} expression does not return plugin descriptor's artifactId.",
143                 exec.getMojoDescriptor().getPluginDescriptor().getArtifactId(),
144                 result);
145     }
146 
147     public void testValueExtractionWithAPomValueContainingAPath() throws Exception {
148         String expected = getTestFile("target/test-classes/target/classes").getCanonicalPath();
149 
150         Build build = new Build();
151         build.setDirectory(expected.substring(0, expected.length() - "/classes".length()));
152 
153         Model model = new Model();
154         model.setBuild(build);
155 
156         MavenProject project = new MavenProject(model);
157         project.setFile(new File("pom.xml").getCanonicalFile());
158 
159         ExpressionEvaluator expressionEvaluator = createExpressionEvaluator(project, null, new Properties());
160 
161         Object value = expressionEvaluator.evaluate("${project.build.directory}/classes");
162         String actual = new File(value.toString()).getCanonicalPath();
163 
164         assertEquals(expected, actual);
165     }
166 
167     public void testEscapedVariablePassthrough() throws Exception {
168         String var = "${var}";
169 
170         Model model = new Model();
171         model.setVersion("1");
172 
173         MavenProject project = new MavenProject(model);
174 
175         ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties());
176 
177         Object value = ee.evaluate("$" + var);
178 
179         assertEquals(var, value);
180     }
181 
182     public void testEscapedVariablePassthroughInLargerExpression() throws Exception {
183         String var = "${var}";
184         String key = var + " with version: ${project.version}";
185 
186         Model model = new Model();
187         model.setVersion("1");
188 
189         MavenProject project = new MavenProject(model);
190 
191         ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties());
192 
193         Object value = ee.evaluate("$" + key);
194 
195         assertEquals("${var} with version: 1", value);
196     }
197 
198     public void testMultipleSubExpressionsInLargerExpression() throws Exception {
199         String key = "${project.artifactId} with version: ${project.version}";
200 
201         Model model = new Model();
202         model.setArtifactId("test");
203         model.setVersion("1");
204 
205         MavenProject project = new MavenProject(model);
206 
207         ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties());
208 
209         Object value = ee.evaluate(key);
210 
211         assertEquals("test with version: 1", value);
212     }
213 
214     public void testMissingPOMPropertyRefInLargerExpression() throws Exception {
215         String expr = "/path/to/someproject-${baseVersion}";
216 
217         MavenProject project = new MavenProject(new Model());
218 
219         ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties());
220 
221         Object value = ee.evaluate(expr);
222 
223         assertEquals(expr, value);
224     }
225 
226     public void testPOMPropertyExtractionWithMissingProject_WithDotNotation() throws Exception {
227         String key = "m2.name";
228         String checkValue = "value";
229 
230         Properties properties = new Properties();
231         properties.setProperty(key, checkValue);
232 
233         Model model = new Model();
234         model.setProperties(properties);
235 
236         MavenProject project = new MavenProject(model);
237 
238         ExpressionEvaluator ee = createExpressionEvaluator(project, null, new Properties());
239 
240         Object value = ee.evaluate("${" + key + "}");
241 
242         assertEquals(checkValue, value);
243     }
244 
245     public void testBasedirExtractionWithMissingProject() throws Exception {
246         ExpressionEvaluator ee = createExpressionEvaluator(null, null, new Properties());
247 
248         Object value = ee.evaluate("${basedir}");
249 
250         assertEquals(System.getProperty("user.dir"), value);
251     }
252 
253     public void testValueExtractionFromSystemPropertiesWithMissingProject() throws Exception {
254         String sysprop = "PPEET_sysprop1";
255 
256         Properties executionProperties = new Properties();
257 
258         if (executionProperties.getProperty(sysprop) == null) {
259             executionProperties.setProperty(sysprop, "value");
260         }
261 
262         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
263 
264         Object value = ee.evaluate("${" + sysprop + "}");
265 
266         assertEquals("value", value);
267     }
268 
269     public void testValueExtractionOfMissingPrefixedProperty() throws Exception {
270         Properties executionProperties = new Properties();
271 
272         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
273 
274         Object value = ee.evaluate("prefix-${PPEET_nonexisting_p_property}");
275 
276         assertEquals("prefix-${PPEET_nonexisting_p_property}", value);
277     }
278 
279     public void testValueExtractionOfMissingSuffixedProperty() throws Exception {
280         Properties executionProperties = new Properties();
281 
282         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
283 
284         Object value = ee.evaluate("${PPEET_nonexisting_s_property}-suffix");
285 
286         assertEquals("${PPEET_nonexisting_s_property}-suffix", value);
287     }
288 
289     public void testValueExtractionOfMissingPrefixedSuffixedProperty() throws Exception {
290         Properties executionProperties = new Properties();
291 
292         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
293 
294         Object value = ee.evaluate("prefix-${PPEET_nonexisting_ps_property}-suffix");
295 
296         assertEquals("prefix-${PPEET_nonexisting_ps_property}-suffix", value);
297     }
298 
299     public void testValueExtractionOfMissingProperty() throws Exception {
300         Properties executionProperties = new Properties();
301 
302         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
303 
304         Object value = ee.evaluate("${PPEET_nonexisting_property}");
305 
306         assertNull(value);
307     }
308 
309     public void testValueExtractionFromSystemPropertiesWithMissingProject_WithDotNotation() throws Exception {
310         String sysprop = "PPEET.sysprop2";
311 
312         Properties executionProperties = new Properties();
313 
314         if (executionProperties.getProperty(sysprop) == null) {
315             executionProperties.setProperty(sysprop, "value");
316         }
317 
318         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
319 
320         Object value = ee.evaluate("${" + sysprop + "}");
321 
322         assertEquals("value", value);
323     }
324 
325     @SuppressWarnings("deprecation")
326     private static MavenSession createSession(PlexusContainer container, ArtifactRepository repo, Properties properties)
327             throws CycleDetectedException, DuplicateProjectException {
328         MavenExecutionRequest request = new DefaultMavenExecutionRequest()
329                 .setSystemProperties(properties)
330                 .setGoals(Collections.<String>emptyList())
331                 .setBaseDirectory(new File(""))
332                 .setLocalRepository(repo);
333 
334         return new MavenSession(
335                 container, request, new DefaultMavenExecutionResult(), Collections.<MavenProject>emptyList());
336     }
337 
338     public void testLocalRepositoryExtraction() throws Exception {
339         ExpressionEvaluator expressionEvaluator =
340                 createExpressionEvaluator(createDefaultProject(), null, new Properties());
341         Object value = expressionEvaluator.evaluate("${localRepository}");
342 
343         assertEquals("local", ((ArtifactRepository) value).getId());
344     }
345 
346     public void testTwoExpressions() throws Exception {
347         Build build = new Build();
348         build.setDirectory("expected-directory");
349         build.setFinalName("expected-finalName");
350 
351         Model model = new Model();
352         model.setBuild(build);
353 
354         ExpressionEvaluator expressionEvaluator =
355                 createExpressionEvaluator(new MavenProject(model), null, new Properties());
356 
357         Object value = expressionEvaluator.evaluate("${project.build.directory}" + FS + "${project.build.finalName}");
358 
359         assertEquals("expected-directory" + File.separatorChar + "expected-finalName", value);
360     }
361 
362     public void testShouldExtractPluginArtifacts() throws Exception {
363         PluginDescriptor pd = new PluginDescriptor();
364 
365         Artifact artifact = createArtifact("testGroup", "testArtifact", "1.0");
366 
367         pd.setArtifacts(Collections.singletonList(artifact));
368 
369         ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), pd, new Properties());
370 
371         Object value = ee.evaluate("${plugin.artifacts}");
372 
373         assertTrue(value instanceof List);
374 
375         @SuppressWarnings("unchecked")
376         List<Artifact> artifacts = (List<Artifact>) value;
377 
378         assertEquals(1, artifacts.size());
379 
380         Artifact result = artifacts.get(0);
381 
382         assertEquals("testGroup", result.getGroupId());
383     }
384 
385     private MavenProject createDefaultProject() {
386         return new MavenProject(new Model());
387     }
388 
389     private ExpressionEvaluator createExpressionEvaluator(
390             MavenProject project, PluginDescriptor pluginDescriptor, Properties executionProperties) throws Exception {
391         ArtifactRepository repo = factory.createDefaultLocalRepository();
392 
393         MutablePlexusContainer container = (MutablePlexusContainer) getContainer();
394         MavenSession session = createSession(container, repo, executionProperties);
395         session.setCurrentProject(project);
396 
397         MojoDescriptor mojo = new MojoDescriptor();
398         mojo.setPluginDescriptor(pluginDescriptor);
399         mojo.setGoal("goal");
400 
401         MojoExecution mojoExecution = new MojoExecution(mojo);
402 
403         return new PluginParameterExpressionEvaluator(session, mojoExecution);
404     }
405 
406     protected Artifact createArtifact(String groupId, String artifactId, String version) throws Exception {
407         Dependency dependency = new Dependency();
408         dependency.setGroupId(groupId);
409         dependency.setArtifactId(artifactId);
410         dependency.setVersion(version);
411         dependency.setType("jar");
412         dependency.setScope("compile");
413 
414         return factory.createDependencyArtifact(dependency);
415     }
416 
417     private MojoExecution newMojoExecution() {
418         PluginDescriptor pd = new PluginDescriptor();
419         pd.setArtifactId("my-plugin");
420         pd.setGroupId("org.myco.plugins");
421         pd.setVersion("1");
422 
423         MojoDescriptor md = new MojoDescriptor();
424         md.setPluginDescriptor(pd);
425 
426         pd.addComponentDescriptor(md);
427 
428         return new MojoExecution(md);
429     }
430 
431     private MavenSession newMavenSession() throws Exception {
432         return createMavenSession(null);
433     }
434 
435     @Override
436     protected String getProjectsDirectory() {
437         // TODO Auto-generated method stub
438         return null;
439     }
440 }