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