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