View Javadoc
1   package org.apache.maven.project;
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 static org.hamcrest.Matchers.containsString;
23  import static org.hamcrest.Matchers.empty;
24  import static org.hamcrest.Matchers.hasKey;
25  import static org.hamcrest.Matchers.is;
26  import static org.junit.Assert.assertThat;
27  
28  import java.io.File;
29  import java.nio.file.Files;
30  import java.nio.file.Path;
31  import java.util.ArrayList;
32  import java.util.Collections;
33  import java.util.List;
34  import java.util.Properties;
35  
36  import org.apache.maven.AbstractCoreMavenComponentTestCase;
37  import org.apache.maven.artifact.InvalidArtifactRTException;
38  import org.apache.maven.execution.MavenSession;
39  import org.apache.maven.model.Plugin;
40  import org.apache.maven.model.building.FileModelSource;
41  import org.apache.maven.model.building.ModelBuildingRequest;
42  import org.apache.maven.model.building.ModelProblem;
43  import org.apache.maven.model.building.ModelProblem.Severity;
44  import org.apache.maven.model.building.ModelSource;
45  import org.apache.maven.shared.utils.io.FileUtils;
46  
47  
48  public class ProjectBuilderTest
49      extends AbstractCoreMavenComponentTestCase
50  {
51      @Override
52      protected String getProjectsDirectory()
53      {
54          return "src/test/projects/project-builder";
55      }
56  
57      public void testSystemScopeDependencyIsPresentInTheCompileClasspathElements()
58          throws Exception
59      {
60          File pom = getProject( "it0063" );
61  
62          Properties eps = new Properties();
63          eps.setProperty( "jre.home", new File( pom.getParentFile(), "jdk/jre" ).getPath() );
64  
65          MavenSession session = createMavenSession( pom, eps );
66          MavenProject project = session.getCurrentProject();
67  
68          // Here we will actually not have any artifacts because the ProjectDependenciesResolver is not involved here. So
69          // right now it's not valid to ask for artifacts unless plugins require the artifacts.
70  
71          project.getCompileClasspathElements();
72      }
73  
74      public void testBuildFromModelSource()
75          throws Exception
76      {
77          File pomFile = new File( "src/test/resources/projects/modelsource/module01/pom.xml" );
78          MavenSession mavenSession = createMavenSession( pomFile );
79          ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
80          configuration.setRepositorySession( mavenSession.getRepositorySession() );
81          ModelSource modelSource = new FileModelSource( pomFile );
82          ProjectBuildingResult result =
83              lookup( org.apache.maven.project.ProjectBuilder.class ).build( modelSource, configuration );
84  
85          assertNotNull( result.getProject().getParentFile() );
86      }
87  
88      public void testBuildFromModelSourceResolvesBasedir()
89          throws Exception
90      {
91          File pomFile = new File( "src/test/resources/projects/modelsourcebasedir/pom.xml" );
92          MavenSession mavenSession = createMavenSession( null );
93          ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
94          configuration.setRepositorySession( mavenSession.getRepositorySession() );
95          ModelSource modelSource = new FileModelSource( pomFile );
96          ProjectBuildingResult result =
97              getContainer().lookup( org.apache.maven.project.ProjectBuilder.class ).build( modelSource, configuration );
98  
99          assertEquals( pomFile.getAbsoluteFile(), result.getProject().getModel().getPomFile().getAbsoluteFile() );
100         int errors = 0;
101         for ( ModelProblem p : result.getProblems() )
102         {
103             if ( p.getSeverity() == Severity.ERROR )
104             {
105                 errors++;
106             }
107         }
108         assertEquals( 0, errors );
109     }
110 
111 
112     public void testVersionlessManagedDependency()
113         throws Exception
114     {
115         File pomFile = new File( "src/test/resources/projects/versionless-managed-dependency.xml" );
116         MavenSession mavenSession = createMavenSession( null );
117         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
118         configuration.setRepositorySession( mavenSession.getRepositorySession() );
119 
120         try
121         {
122             lookup( org.apache.maven.project.ProjectBuilder.class ).build( pomFile, configuration );
123             fail();
124         }
125         catch ( ProjectBuildingException e )
126         {
127             // this is expected
128         }
129     }
130 
131     public void testResolveDependencies()
132         throws Exception
133     {
134         File pomFile = new File( "src/test/resources/projects/basic-resolveDependencies.xml" );
135         MavenSession mavenSession = createMavenSession( null );
136         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
137         configuration.setRepositorySession( mavenSession.getRepositorySession() );
138         configuration.setResolveDependencies( true );
139 
140         // single project build entry point
141         ProjectBuildingResult result = lookup( org.apache.maven.project.ProjectBuilder.class ).build( pomFile, configuration );
142         assertEquals( 1, result.getProject().getArtifacts().size() );
143         // multi projects build entry point
144         List<ProjectBuildingResult> results = lookup( org.apache.maven.project.ProjectBuilder.class ).build( Collections.singletonList( pomFile ), false, configuration );
145         assertEquals( 1, results.size() );
146         MavenProject mavenProject = results.get( 0 ).getProject();
147         assertEquals( 1, mavenProject.getArtifacts().size() );
148     }
149 
150     public void testDontResolveDependencies()
151         throws Exception
152     {
153         File pomFile = new File( "src/test/resources/projects/basic-resolveDependencies.xml" );
154         MavenSession mavenSession = createMavenSession( null );
155         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
156         configuration.setRepositorySession( mavenSession.getRepositorySession() );
157         configuration.setResolveDependencies( false );
158 
159         // single project build entry point
160         ProjectBuildingResult result = lookup( org.apache.maven.project.ProjectBuilder.class ).build( pomFile, configuration );
161         assertEquals( 0, result.getProject().getArtifacts().size() );
162         // multi projects build entry point
163         List<ProjectBuildingResult> results = lookup( org.apache.maven.project.ProjectBuilder.class ).build( Collections.singletonList( pomFile ), false, configuration );
164         assertEquals( 1, results.size() );
165         MavenProject mavenProject = results.get( 0 ).getProject();
166         assertEquals( 0, mavenProject.getArtifacts().size() );
167     }
168 
169     public void testReadModifiedPoms() throws Exception {
170         String initialValue = System.setProperty( DefaultProjectBuilder.DISABLE_GLOBAL_MODEL_CACHE_SYSTEM_PROPERTY, Boolean.toString( true ) );
171         // TODO a similar test should be created to test the dependency management (basically all usages
172         // of DefaultModelBuilder.getCache() are affected by MNG-6530
173 
174         Path tempDir = Files.createTempDirectory( null );
175         FileUtils.copyDirectoryStructure ( new File( "src/test/resources/projects/grandchild-check" ), tempDir.toFile() );
176         try
177         {
178             MavenSession mavenSession = createMavenSession( null );
179             ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
180             configuration.setRepositorySession( mavenSession.getRepositorySession() );
181             org.apache.maven.project.ProjectBuilder projectBuilder = lookup( org.apache.maven.project.ProjectBuilder.class );
182             File child = new File( tempDir.toFile(), "child/pom.xml" );
183             // build project once
184             projectBuilder.build( child, configuration );
185             // modify parent
186             File parent = new File( tempDir.toFile(), "pom.xml" );
187             String parentContent = FileUtils.fileRead( parent );
188             parentContent = parentContent.replaceAll( "<packaging>pom</packaging>",
189                     "<packaging>pom</packaging><properties><addedProperty>addedValue</addedProperty></properties>" );
190             FileUtils.fileWrite( parent, "UTF-8", parentContent );
191             // re-build pom with modified parent
192             ProjectBuildingResult result = projectBuilder.build( child, configuration );
193             assertThat( result.getProject().getProperties(), hasKey( (Object) "addedProperty" ) );
194         }
195         finally
196         {
197             if ( initialValue == null )
198             {
199                 System.clearProperty( DefaultProjectBuilder.DISABLE_GLOBAL_MODEL_CACHE_SYSTEM_PROPERTY );
200             }
201             else
202             {
203                 System.setProperty( DefaultProjectBuilder.DISABLE_GLOBAL_MODEL_CACHE_SYSTEM_PROPERTY, initialValue );
204             }
205             FileUtils.deleteDirectory( tempDir.toFile() );
206         }
207     }
208 
209     public void testReadErroneousMavenProjectContainsReference()
210         throws Exception
211     {
212         File pomFile = new File( "src/test/resources/projects/artifactMissingVersion.xml" ).getAbsoluteFile();
213         MavenSession mavenSession = createMavenSession( null );
214         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
215         configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
216         configuration.setRepositorySession( mavenSession.getRepositorySession() );
217         org.apache.maven.project.ProjectBuilder projectBuilder =
218             lookup( org.apache.maven.project.ProjectBuilder.class );
219 
220         // single project build entry point
221         try
222         {
223             projectBuilder.build( pomFile, configuration );
224         }
225         catch ( ProjectBuildingException ex )
226         {
227             assertEquals( 1, ex.getResults().size() );
228             MavenProject project = ex.getResults().get( 0 ).getProject();
229             assertNotNull( project );
230             assertEquals( "testArtifactMissingVersion", project.getArtifactId() );
231             assertEquals( pomFile, project.getFile() );
232         }
233 
234         // multi projects build entry point
235         try
236         {
237             projectBuilder.build( Collections.singletonList( pomFile ), false, configuration );
238         }
239         catch ( ProjectBuildingException ex )
240         {
241             assertEquals( 1, ex.getResults().size() );
242             MavenProject project = ex.getResults().get( 0 ).getProject();
243             assertNotNull( project );
244             assertEquals( "testArtifactMissingVersion", project.getArtifactId() );
245             assertEquals( pomFile, project.getFile() );
246         }
247     }
248 
249     public void testReadInvalidPom()
250         throws Exception
251     {
252         File pomFile = new File( "src/test/resources/projects/badPom.xml" ).getAbsoluteFile();
253         MavenSession mavenSession = createMavenSession( null );
254         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
255         configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
256         configuration.setRepositorySession( mavenSession.getRepositorySession() );
257         org.apache.maven.project.ProjectBuilder projectBuilder =
258             lookup( org.apache.maven.project.ProjectBuilder.class );
259 
260         // single project build entry point
261         try
262         {
263             projectBuilder.build( pomFile, configuration );
264         }
265         catch ( InvalidArtifactRTException iarte )
266         {
267             assertThat( iarte.getMessage(), containsString( "The groupId cannot be empty." ) );
268         }
269 
270         // multi projects build entry point
271         try
272         {
273             projectBuilder.build( Collections.singletonList( pomFile ), false, configuration );
274         }
275         catch ( ProjectBuildingException ex )
276         {
277             assertEquals( 1, ex.getResults().size() );
278             MavenProject project = ex.getResults().get( 0 ).getProject();
279             assertNotNull( project );
280             assertNotSame( 0, ex.getResults().get( 0 ).getProblems().size() );
281         }
282     }
283 
284     public void testReadParentAndChildWithRegularVersionSetParentFile()
285         throws Exception
286     {
287         List<File> toRead = new ArrayList<>( 2 );
288         File parentPom = getProject( "MNG-6723" );
289         toRead.add( parentPom );
290         toRead.add( new File( parentPom.getParentFile(), "child/pom.xml" ) );
291         MavenSession mavenSession = createMavenSession( null );
292         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
293         configuration.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
294         configuration.setRepositorySession( mavenSession.getRepositorySession() );
295         org.apache.maven.project.ProjectBuilder projectBuilder =
296             lookup( org.apache.maven.project.ProjectBuilder.class );
297 
298         // read poms separately
299         boolean parentFileWasFoundOnChild = false;
300         for ( File file : toRead )
301         {
302             List<ProjectBuildingResult> results = projectBuilder.build( Collections.singletonList( file ), false, configuration );
303             assertResultShowNoError( results );
304             MavenProject project = findChildProject( results );
305             if ( project != null )
306             {
307                 assertEquals( parentPom, project.getParentFile() );
308                 parentFileWasFoundOnChild = true;
309             }
310         }
311         assertTrue( parentFileWasFoundOnChild );
312 
313         // read projects together
314         List<ProjectBuildingResult> results = projectBuilder.build( toRead, false, configuration );
315         assertResultShowNoError( results );
316         assertEquals( parentPom, findChildProject( results ).getParentFile() );
317         Collections.reverse( toRead );
318         results = projectBuilder.build( toRead, false, configuration );
319         assertResultShowNoError( results );
320         assertEquals( parentPom, findChildProject( results ).getParentFile() );
321     }
322 
323     private MavenProject findChildProject( List<ProjectBuildingResult> results )
324     {
325         for ( ProjectBuildingResult result : results )
326         {
327             if ( result.getPomFile().getParentFile().getName().equals( "child" ) )
328             {
329                 return result.getProject();
330             }
331         }
332         return null;
333     }
334 
335     private void assertResultShowNoError( List<ProjectBuildingResult> results )
336     {
337         for ( ProjectBuildingResult result : results )
338         {
339             assertThat( result.getProblems(), is( empty() ) );
340             assertNotNull( result.getProject() );
341         }
342     }
343 
344     public void testBuildProperties()
345             throws Exception
346     {
347         File file = new File( getProject( "MNG-6716" ).getParentFile(), "project/pom.xml" );
348         MavenSession mavenSession = createMavenSession( null );
349         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
350         configuration.setRepositorySession( mavenSession.getRepositorySession() );
351         configuration.setResolveDependencies( true );
352         List<ProjectBuildingResult> result = projectBuilder.build( Collections.singletonList( file ), true, configuration );
353         MavenProject project = result.get( 0 ).getProject();
354         // verify a few typical parameters are not duplicated
355         assertEquals( 1, project.getTestCompileSourceRoots().size() );
356         assertEquals( 1, project.getCompileSourceRoots().size() );
357         assertEquals( 1, project.getMailingLists().size() );
358         assertEquals( 1, project.getResources().size() );
359     }
360 
361     public void testPropertyInPluginManagementGroupId()
362             throws Exception
363     {
364         File pom = getProject( "MNG-6983" );
365 
366         MavenSession session = createMavenSession( pom );
367         MavenProject project = session.getCurrentProject();
368 
369         for (Plugin buildPlugin : project.getBuildPlugins()) {
370             assertNotNull( "Missing version for build plugin " + buildPlugin.getKey(), buildPlugin.getVersion() );
371         }
372     }
373 }