View Javadoc
1   package org.apache.maven.script.ant;
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.ByteArrayOutputStream;
23  import java.io.File;
24  import java.io.IOException;
25  import java.io.InputStreamReader;
26  import java.io.PrintStream;
27  import java.io.Reader;
28  import java.net.URISyntaxException;
29  import java.net.URL;
30  import java.util.ArrayList;
31  import java.util.Collections;
32  import java.util.HashMap;
33  import java.util.List;
34  import java.util.Map;
35  import junit.framework.TestCase;
36  import org.apache.maven.artifact.Artifact;
37  import org.apache.maven.execution.MavenSession;
38  import org.apache.maven.model.Build;
39  import org.apache.maven.model.Model;
40  import org.apache.maven.plugin.MojoExecution;
41  import org.apache.maven.plugin.MojoExecutionException;
42  import org.apache.maven.plugin.descriptor.MojoDescriptor;
43  import org.apache.maven.plugin.descriptor.PluginDescriptor;
44  import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder;
45  import org.apache.maven.project.MavenProject;
46  import org.apache.maven.project.path.PathTranslator;
47  import org.apache.tools.ant.BuildEvent;
48  import org.apache.tools.ant.BuildListener;
49  import org.codehaus.plexus.archiver.ArchiverException;
50  import org.codehaus.plexus.archiver.jar.JarArchiver;
51  import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
52  import org.codehaus.plexus.component.factory.ComponentInstantiationException;
53  import org.codehaus.plexus.component.factory.ant.AntScriptInvoker;
54  import org.codehaus.plexus.component.repository.ComponentRequirement;
55  import org.codehaus.plexus.configuration.PlexusConfigurationException;
56  import org.codehaus.plexus.logging.Logger;
57  import org.codehaus.plexus.logging.console.ConsoleLogger;
58  import org.codehaus.plexus.util.IOUtil;
59  import static org.easymock.EasyMock.createMock;
60  import static org.easymock.EasyMock.expect;
61  import static org.easymock.EasyMock.replay;
62  import static org.easymock.EasyMock.verify;
63  
64  public class AntMojoWrapperTest
65      extends TestCase
66  {
67  
68      public void test2xStylePlugin()
69          throws PlexusConfigurationException, IOException, ComponentInstantiationException, MojoExecutionException,
70          ComponentConfigurationException, ArchiverException, URISyntaxException
71      {
72          String pluginXml = "META-INF/maven/plugin-2.1.xml";
73  
74          List<String> messages = run( pluginXml, true );
75  
76          assertPresence( messages, "Unpacked Ant build scripts (in Maven build directory).", false );
77          assertPresence( messages, "Maven parameter expression evaluator for Ant properties.", false );
78          assertPresence( messages, "Maven standard project-based classpath references.", false );
79          assertPresence( messages, "Maven standard plugin-based classpath references.", false );
80          assertPresence( messages,
81                          "Maven project, session, mojo-execution, or path-translation parameter information is", false );
82          assertPresence( messages, "maven-script-ant < 2.1.0, or used maven-plugin-tools-ant < 2.2 during release",
83                          false );
84  
85          assertPresence( messages, "path-is-missing", false );
86      }
87  
88      public void test20StylePlugin()
89          throws PlexusConfigurationException, IOException, ComponentInstantiationException, MojoExecutionException,
90          ComponentConfigurationException, ArchiverException, URISyntaxException
91      {
92          String pluginXml = "META-INF/maven/plugin-2.0.xml";
93  
94          List<String> messages = run( pluginXml, false );
95  
96          assertPresence( messages, "Unpacked Ant build scripts (in Maven build directory).", true );
97          assertPresence( messages, "Maven parameter expression evaluator for Ant properties.", true );
98          assertPresence( messages, "Maven standard project-based classpath references.", true );
99          assertPresence( messages, "Maven standard plugin-based classpath references.", true );
100         assertPresence( messages,
101                         "Maven project, session, mojo-execution, or path-translation parameter information is", true );
102         assertPresence( messages, "maven-script-ant < 2.1.0, or used maven-plugin-tools-ant < 2.2 during release", true );
103 
104         assertPresence( messages, "path-is-missing", true );
105     }
106 
107     private void assertPresence( List<String> messages, String test, boolean shouldBePresent )
108     {
109         for ( String message : messages )
110         {
111             if ( message.contains( test ) )
112             {
113                 if ( !shouldBePresent )
114                 {
115                     fail( "Test string: '" + test + "' was found in output, but SHOULD NOT BE THERE." );
116                 }
117                 return;
118             }
119         }
120 
121         if ( shouldBePresent )
122         {
123             fail( "Test string: '" + test + "' was NOT found in output, but SHOULD BE THERE." );
124         }
125     }
126 
127     private List<String> run( String pluginXml, boolean includeImplied )
128         throws PlexusConfigurationException, IOException, ComponentInstantiationException, MojoExecutionException,
129         ComponentConfigurationException, ArchiverException, URISyntaxException
130     {
131         StackTraceElement stack = new Throwable().getStackTrace()[1];
132         System.out.println( "\n\nRunning: " + stack.getMethodName() + "\n\n" );
133 
134         URL resource = Thread.currentThread().getContextClassLoader().getResource( pluginXml );
135 
136         if ( resource == null )
137         {
138             fail( "plugin descriptor not found: '" + pluginXml + "'." );
139         }
140 
141         Reader reader = null;
142         PluginDescriptor pd;
143         try
144         {
145             reader = new InputStreamReader( resource.openStream() );
146             pd = new PluginDescriptorBuilder().build( reader, pluginXml );
147             reader.close();
148             reader = null;
149         }
150         finally
151         {
152             IOUtil.close( reader );
153         }
154 
155         Map<String, Object> config = new HashMap<String, Object>();
156         config.put( "basedir", new File( "." ).getAbsoluteFile() );
157         config.put( "messageLevel", "info" );
158 
159         MojoDescriptor md = pd.getMojo( "test" );
160 
161         AntMojoWrapper wrapper =
162             new AntMojoWrapper( new AntScriptInvoker( md, Thread.currentThread().getContextClassLoader() ) );
163 
164         wrapper.enableLogging( new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ) );
165 
166         Artifact artifact = createMock( Artifact.class );
167         PathTranslator pt = createMock( PathTranslator.class );
168 
169         if ( includeImplied )
170         {
171             // TODO As of JDK 7, replace with Paths.get( resource.toURI() ).toFile()
172             File pluginXmlFile = new File( resource.toURI() );
173 
174             File jarFile = File.createTempFile( "AntMojoWrapperTest.", ".test.jar" );
175             jarFile.deleteOnExit();
176 
177             JarArchiver archiver = new JarArchiver();
178             archiver.enableLogging( new ConsoleLogger( Logger.LEVEL_ERROR, "archiver" ) );
179             archiver.setDestFile( jarFile );
180             archiver.addFile( pluginXmlFile, pluginXml );
181             archiver.createArchive();
182 
183             expect( artifact.getFile() ).andReturn( jarFile ).anyTimes();
184             expect( artifact.getGroupId() ).andReturn( "groupId" ).anyTimes();
185             expect( artifact.getArtifactId() ).andReturn( "artifactId" ).anyTimes();
186             expect( artifact.getVersion() ).andReturn( "1" ).anyTimes();
187             expect( artifact.getId() ).andReturn( "groupId:artifactId:jar:1" ).anyTimes();
188             expect( artifact.getClassifier() ).andReturn( null ).anyTimes();
189 
190             Model model = new Model();
191 
192             Build build = new Build();
193             build.setDirectory( "target" );
194 
195             model.setBuild( build );
196 
197             MavenProject project = new MavenProject( model );
198             project.setFile( new File( "pom.xml" ).getAbsoluteFile() );
199 
200             replay( artifact, pt );
201 
202             pd.setPluginArtifact( artifact );
203             pd.setArtifacts( Collections.singletonList( artifact ) );
204 
205             config.put( "project", project );
206             config.put( "session", new MavenSession( null, null, null, null, null, null, null, null, null, null ) );
207             config.put( "mojoExecution", new MojoExecution( md ) );
208 
209             ComponentRequirement cr = new ComponentRequirement();
210             cr.setRole( PathTranslator.class.getName() );
211 
212             wrapper.addComponentRequirement( cr, pt );
213         }
214 
215         wrapper.setComponentConfiguration( config );
216 
217         TestBuildListener tbl = new TestBuildListener();
218         wrapper.getAntProject().addBuildListener( tbl );
219         
220         PrintStream oldOut = System.out;
221         
222         ByteArrayOutputStream baos = new ByteArrayOutputStream();
223         try
224         {
225             System.setOut( new PrintStream( baos ) );
226 
227             wrapper.execute();
228         }
229         finally
230         {
231             System.setOut( oldOut );
232         }
233 
234         System.out.println( "\n\n" + stack.getMethodName() + " executed; verifying...\n\n" );
235 
236         if ( includeImplied )
237         {
238             verify( artifact, pt );
239         }
240 
241         List<String> messages = new ArrayList<String>();
242         if ( !tbl.messages.isEmpty() )
243         {
244             messages.addAll( tbl.messages );
245         }
246         
247         messages.add( new String( baos.toByteArray() ) );
248         
249         return messages;
250     }
251 
252     private static final class TestBuildListener
253         implements BuildListener
254     {
255         private List<String> messages = new ArrayList<String>();
256 
257         public void buildFinished( BuildEvent arg0 )
258         {
259         }
260 
261         public void buildStarted( BuildEvent arg0 )
262         {
263         }
264 
265         public void messageLogged( BuildEvent event )
266         {
267             messages.add( event.getMessage() );
268         }
269 
270         public void targetFinished( BuildEvent arg0 )
271         {
272         }
273 
274         public void targetStarted( BuildEvent arg0 )
275         {
276         }
277 
278         public void taskFinished( BuildEvent arg0 )
279         {
280         }
281 
282         public void taskStarted( BuildEvent arg0 )
283         {
284         }
285     };
286 
287 }