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 testValueExtractionFromSystemPropertiesWithMissingProject_WithDotNotation() throws Exception {
270         String sysprop = "PPEET.sysprop2";
271 
272         Properties executionProperties = new Properties();
273 
274         if (executionProperties.getProperty(sysprop) == null) {
275             executionProperties.setProperty(sysprop, "value");
276         }
277 
278         ExpressionEvaluator ee = createExpressionEvaluator(null, null, executionProperties);
279 
280         Object value = ee.evaluate("${" + sysprop + "}");
281 
282         assertEquals("value", value);
283     }
284 
285     @SuppressWarnings("deprecation")
286     private static MavenSession createSession(PlexusContainer container, ArtifactRepository repo, Properties properties)
287             throws CycleDetectedException, DuplicateProjectException {
288         MavenExecutionRequest request = new DefaultMavenExecutionRequest()
289                 .setSystemProperties(properties)
290                 .setGoals(Collections.<String>emptyList())
291                 .setBaseDirectory(new File(""))
292                 .setLocalRepository(repo);
293 
294         return new MavenSession(
295                 container, request, new DefaultMavenExecutionResult(), Collections.<MavenProject>emptyList());
296     }
297 
298     public void testLocalRepositoryExtraction() throws Exception {
299         ExpressionEvaluator expressionEvaluator =
300                 createExpressionEvaluator(createDefaultProject(), null, new Properties());
301         Object value = expressionEvaluator.evaluate("${localRepository}");
302 
303         assertEquals("local", ((ArtifactRepository) value).getId());
304     }
305 
306     public void testTwoExpressions() throws Exception {
307         Build build = new Build();
308         build.setDirectory("expected-directory");
309         build.setFinalName("expected-finalName");
310 
311         Model model = new Model();
312         model.setBuild(build);
313 
314         ExpressionEvaluator expressionEvaluator =
315                 createExpressionEvaluator(new MavenProject(model), null, new Properties());
316 
317         Object value = expressionEvaluator.evaluate("${project.build.directory}" + FS + "${project.build.finalName}");
318 
319         assertEquals("expected-directory" + File.separatorChar + "expected-finalName", value);
320     }
321 
322     public void testShouldExtractPluginArtifacts() throws Exception {
323         PluginDescriptor pd = new PluginDescriptor();
324 
325         Artifact artifact = createArtifact("testGroup", "testArtifact", "1.0");
326 
327         pd.setArtifacts(Collections.singletonList(artifact));
328 
329         ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), pd, new Properties());
330 
331         Object value = ee.evaluate("${plugin.artifacts}");
332 
333         assertTrue(value instanceof List);
334 
335         @SuppressWarnings("unchecked")
336         List<Artifact> artifacts = (List<Artifact>) value;
337 
338         assertEquals(1, artifacts.size());
339 
340         Artifact result = artifacts.get(0);
341 
342         assertEquals("testGroup", result.getGroupId());
343     }
344 
345     private MavenProject createDefaultProject() {
346         return new MavenProject(new Model());
347     }
348 
349     private ExpressionEvaluator createExpressionEvaluator(
350             MavenProject project, PluginDescriptor pluginDescriptor, Properties executionProperties) throws Exception {
351         ArtifactRepository repo = factory.createDefaultLocalRepository();
352 
353         MutablePlexusContainer container = (MutablePlexusContainer) getContainer();
354         MavenSession session = createSession(container, repo, executionProperties);
355         session.setCurrentProject(project);
356 
357         MojoDescriptor mojo = new MojoDescriptor();
358         mojo.setPluginDescriptor(pluginDescriptor);
359         mojo.setGoal("goal");
360 
361         MojoExecution mojoExecution = new MojoExecution(mojo);
362 
363         return new PluginParameterExpressionEvaluator(session, mojoExecution);
364     }
365 
366     protected Artifact createArtifact(String groupId, String artifactId, String version) throws Exception {
367         Dependency dependency = new Dependency();
368         dependency.setGroupId(groupId);
369         dependency.setArtifactId(artifactId);
370         dependency.setVersion(version);
371         dependency.setType("jar");
372         dependency.setScope("compile");
373 
374         return factory.createDependencyArtifact(dependency);
375     }
376 
377     private MojoExecution newMojoExecution() {
378         PluginDescriptor pd = new PluginDescriptor();
379         pd.setArtifactId("my-plugin");
380         pd.setGroupId("org.myco.plugins");
381         pd.setVersion("1");
382 
383         MojoDescriptor md = new MojoDescriptor();
384         md.setPluginDescriptor(pd);
385 
386         pd.addComponentDescriptor(md);
387 
388         return new MojoExecution(md);
389     }
390 
391     private MavenSession newMavenSession() throws Exception {
392         return createMavenSession(null);
393     }
394 
395     @Override
396     protected String getProjectsDirectory() {
397         // TODO Auto-generated method stub
398         return null;
399     }
400 }