View Javadoc

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