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