001    package org.apache.maven.plugin;
002    
003    /*
004     * Licensed to the Apache Software Foundation (ASF) under one
005     * or more contributor license agreements.  See the NOTICE file
006     * distributed with this work for additional information
007     * regarding copyright ownership.  The ASF licenses this file
008     * to you under the Apache License, Version 2.0 (the
009     * "License"); you may not use this file except in compliance
010     * with the License.  You may obtain a copy of the License at
011     *
012     *  http://www.apache.org/licenses/LICENSE-2.0
013     *
014     * Unless required by applicable law or agreed to in writing,
015     * software distributed under the License is distributed on an
016     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017     * KIND, either express or implied.  See the License for the
018     * specific language governing permissions and limitations
019     * under the License.
020     */
021    
022    import java.io.File;
023    import java.util.ArrayList;
024    import java.util.Collections;
025    import java.util.List;
026    import java.util.Map;
027    import java.util.Properties;
028    
029    import org.apache.maven.AbstractCoreMavenComponentTestCase;
030    import org.apache.maven.artifact.Artifact;
031    import org.apache.maven.artifact.ArtifactUtils;
032    import org.apache.maven.artifact.factory.ArtifactFactory;
033    import org.apache.maven.artifact.repository.ArtifactRepository;
034    import org.apache.maven.execution.DefaultMavenExecutionRequest;
035    import org.apache.maven.execution.DefaultMavenExecutionResult;
036    import org.apache.maven.execution.MavenExecutionRequest;
037    import org.apache.maven.execution.MavenSession;
038    import org.apache.maven.model.Build;
039    import org.apache.maven.model.Dependency;
040    import org.apache.maven.model.Model;
041    import org.apache.maven.plugin.descriptor.MojoDescriptor;
042    import org.apache.maven.plugin.descriptor.PluginDescriptor;
043    import org.apache.maven.project.DuplicateProjectException;
044    import org.apache.maven.project.MavenProject;
045    import org.apache.maven.repository.RepositorySystem;
046    import org.codehaus.plexus.MutablePlexusContainer;
047    import org.codehaus.plexus.PlexusContainer;
048    import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
049    import org.codehaus.plexus.util.dag.CycleDetectedException;
050    
051    /**
052     * @author Jason van Zyl
053     */
054    public class PluginParameterExpressionEvaluatorTest
055        extends AbstractCoreMavenComponentTestCase
056    {
057        private static final String FS = System.getProperty( "file.separator" );
058    
059        private RepositorySystem factory;
060    
061        public void setUp()
062            throws Exception
063        {
064            super.setUp();
065            factory = lookup( RepositorySystem.class );
066        }
067    
068        @Override
069        protected void tearDown()
070            throws Exception
071        {
072            factory = null;
073            super.tearDown();
074        }
075    
076        public void testPluginDescriptorExpressionReference()
077            throws Exception
078        {
079            MojoExecution exec = newMojoExecution();
080    
081            MavenSession session = newMavenSession();
082    
083            Object result = new PluginParameterExpressionEvaluator( session, exec ).evaluate( "${plugin}" );
084    
085            System.out.println( "Result: " + result );
086    
087            assertSame( "${plugin} expression does not return plugin descriptor.",
088                        exec.getMojoDescriptor().getPluginDescriptor(),
089                        result );
090        }
091    
092        public void testPluginArtifactsExpressionReference()
093            throws Exception
094        {
095            MojoExecution exec = newMojoExecution();
096    
097            Artifact depArtifact = createArtifact( "group", "artifact", "1" );
098    
099            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    }