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