View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven;
20  
21  import javax.inject.Inject;
22  
23  import java.io.File;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.List;
27  import java.util.Properties;
28  
29  import org.apache.maven.api.Session;
30  import org.apache.maven.artifact.Artifact;
31  import org.apache.maven.artifact.InvalidRepositoryException;
32  import org.apache.maven.artifact.repository.ArtifactRepository;
33  import org.apache.maven.bridge.MavenRepositorySystem;
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.impl.InternalSession;
39  import org.apache.maven.impl.resolver.MavenSessionBuilderSupplier;
40  import org.apache.maven.internal.impl.DefaultLookup;
41  import org.apache.maven.internal.impl.DefaultSessionFactory;
42  import org.apache.maven.internal.impl.InternalMavenSession;
43  import org.apache.maven.model.Build;
44  import org.apache.maven.model.Dependency;
45  import org.apache.maven.model.Exclusion;
46  import org.apache.maven.model.Model;
47  import org.apache.maven.model.Plugin;
48  import org.apache.maven.model.Repository;
49  import org.apache.maven.model.RepositoryPolicy;
50  import org.apache.maven.project.DefaultProjectBuildingRequest;
51  import org.apache.maven.project.MavenProject;
52  import org.apache.maven.project.ProjectBuildingRequest;
53  import org.apache.maven.session.scope.internal.SessionScope;
54  import org.codehaus.plexus.PlexusContainer;
55  import org.codehaus.plexus.testing.PlexusTest;
56  import org.codehaus.plexus.util.FileUtils;
57  import org.eclipse.aether.RepositorySystem;
58  import org.eclipse.aether.RepositorySystemSession;
59  import org.eclipse.aether.repository.LocalRepository;
60  import org.eclipse.aether.repository.WorkspaceReader;
61  
62  import static org.codehaus.plexus.testing.PlexusExtension.getBasedir;
63  
64  @PlexusTest
65  public abstract class AbstractCoreMavenComponentTestCase {
66  
67      @Inject
68      protected PlexusContainer container;
69  
70      @Inject
71      protected RepositorySystem repositorySystem;
72  
73      @Inject
74      protected MavenRepositorySystem mavenRepositorySystem;
75  
76      @Inject
77      protected org.apache.maven.project.ProjectBuilder projectBuilder;
78  
79      protected abstract String getProjectsDirectory();
80  
81      protected PlexusContainer getContainer() {
82          return container;
83      }
84  
85      protected File getProject(String name) throws Exception {
86          File source = new File(new File(getBasedir(), getProjectsDirectory()), name);
87          File target = new File(new File(getBasedir(), "target"), name);
88          FileUtils.copyDirectoryStructureIfModified(source, target);
89          return new File(target, "pom.xml");
90      }
91  
92      protected MavenExecutionRequest createMavenExecutionRequest(File pom) throws Exception {
93          MavenExecutionRequest request = new DefaultMavenExecutionRequest()
94                  .setRootDirectory(pom != null ? pom.toPath().getParent() : null)
95                  .setPom(pom)
96                  .setProjectPresent(true)
97                  .setShowErrors(true)
98                  .setPluginGroups(Arrays.asList("org.apache.maven.plugins"))
99                  .setLocalRepository(getLocalRepository())
100                 .setRemoteRepositories(getRemoteRepositories())
101                 .setPluginArtifactRepositories(getPluginArtifactRepositories())
102                 .setGoals(Arrays.asList("package"));
103 
104         if (pom != null) {
105             request.setMultiModuleProjectDirectory(pom.getParentFile());
106         }
107 
108         return request;
109     }
110 
111     // layer the creation of a project builder configuration with a request, but this will need to be
112     // a Maven subclass because we don't want to couple maven to the project builder which we need to
113     // separate.
114     protected MavenSession createMavenSession(File pom) throws Exception {
115         return createMavenSession(pom, new Properties());
116     }
117 
118     protected MavenSession createMavenSession(File pom, Properties executionProperties) throws Exception {
119         return createMavenSession(pom, executionProperties, false);
120     }
121 
122     protected MavenSession createMavenSession(File pom, Properties executionProperties, boolean includeModules)
123             throws Exception {
124         MavenExecutionRequest request = createMavenExecutionRequest(pom);
125 
126         ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest()
127                 .setLocalRepository(request.getLocalRepository())
128                 .setRemoteRepositories(request.getRemoteRepositories())
129                 .setPluginArtifactRepositories(request.getPluginArtifactRepositories())
130                 .setSystemProperties(executionProperties)
131                 .setUserProperties(new Properties());
132 
133         initRepoSession(request, configuration);
134 
135         List<MavenProject> projects = new ArrayList<>();
136 
137         if (pom != null) {
138             MavenProject project = projectBuilder.build(pom, configuration).getProject();
139 
140             projects.add(project);
141             if (includeModules) {
142                 for (String module : project.getModules()) {
143                     File modulePom = new File(pom.getParentFile(), module);
144                     if (modulePom.isDirectory()) {
145                         modulePom = new File(modulePom, "pom.xml");
146                     }
147                     projects.add(projectBuilder.build(modulePom, configuration).getProject());
148                 }
149             }
150         } else {
151             MavenProject project = createStubMavenProject();
152             project.setRemoteArtifactRepositories(request.getRemoteRepositories());
153             project.setPluginArtifactRepositories(request.getPluginArtifactRepositories());
154             projects.add(project);
155         }
156 
157         InternalSession iSession = InternalSession.from(configuration.getRepositorySession());
158         InternalMavenSession mSession = InternalMavenSession.from(iSession);
159         MavenSession session = mSession.getMavenSession();
160 
161         session.setProjects(projects);
162         session.setAllProjects(session.getProjects());
163 
164         return session;
165     }
166 
167     protected void initRepoSession(
168             MavenExecutionRequest mavenExecutionRequest, ProjectBuildingRequest projectBuildingRequest)
169             throws Exception {
170         File localRepoDir = new File(projectBuildingRequest.getLocalRepository().getBasedir());
171         LocalRepository localRepo = new LocalRepository(localRepoDir, "simple");
172 
173         RepositorySystemSession session = new MavenSessionBuilderSupplier(repositorySystem, true)
174                 .get()
175                 .withLocalRepositories(localRepo)
176                 .setWorkspaceReader(getWorkspaceReader())
177                 .build();
178         projectBuildingRequest.setRepositorySession(session);
179 
180         DefaultSessionFactory defaultSessionFactory =
181                 new DefaultSessionFactory(repositorySystem, null, new DefaultLookup(container), null);
182 
183         MavenSession mSession = new MavenSession(
184                 container,
185                 projectBuildingRequest.getRepositorySession(),
186                 mavenExecutionRequest,
187                 new DefaultMavenExecutionResult());
188 
189         InternalSession iSession = defaultSessionFactory.newSession(mSession);
190         mSession.setSession(iSession);
191 
192         SessionScope sessionScope = getContainer().lookup(SessionScope.class);
193         sessionScope.enter();
194         sessionScope.seed(MavenSession.class, mSession);
195         sessionScope.seed(Session.class, iSession);
196         sessionScope.seed(InternalMavenSession.class, InternalMavenSession.from(iSession));
197     }
198 
199     /**
200      * The workspace reader of the repository session, none by default.
201      */
202     protected WorkspaceReader getWorkspaceReader() {
203         return null;
204     }
205 
206     protected MavenProject createStubMavenProject() {
207         Model model = new Model();
208         model.setGroupId("org.apache.maven.test");
209         model.setArtifactId("maven-test");
210         model.setVersion("1.0");
211         return new MavenProject(model);
212     }
213 
214     protected List<ArtifactRepository> getRemoteRepositories() throws InvalidRepositoryException {
215         File repoDir = new File(getBasedir(), "src/test/remote-repo").getAbsoluteFile();
216 
217         RepositoryPolicy policy = new RepositoryPolicy();
218         policy.setEnabled(true);
219         policy.setChecksumPolicy("ignore");
220         policy.setUpdatePolicy("always");
221 
222         Repository repository = new Repository();
223         repository.setId(MavenRepositorySystem.DEFAULT_REMOTE_REPO_ID);
224         repository.setUrl("file://" + repoDir.toURI().getPath());
225         repository.setReleases(policy);
226         repository.setSnapshots(policy);
227 
228         return Arrays.asList(MavenRepositorySystem.buildArtifactRepository(repository));
229     }
230 
231     protected List<ArtifactRepository> getPluginArtifactRepositories() throws InvalidRepositoryException {
232         return getRemoteRepositories();
233     }
234 
235     protected ArtifactRepository getLocalRepository() throws InvalidRepositoryException {
236         File repoDir = new File(getBasedir(), "target/local-repo").getAbsoluteFile();
237 
238         return mavenRepositorySystem.createLocalRepository(repoDir);
239     }
240 
241     protected class ProjectBuilder {
242         private MavenProject project;
243 
244         public ProjectBuilder(MavenProject project) {
245             this.project = project;
246         }
247 
248         public ProjectBuilder(String groupId, String artifactId, String version) {
249             Model model = new Model();
250             model.setModelVersion("4.0.0");
251             model.setGroupId(groupId);
252             model.setArtifactId(artifactId);
253             model.setVersion(version);
254             model.setBuild(new Build());
255             project = new MavenProject(model);
256         }
257 
258         public ProjectBuilder setGroupId(String groupId) {
259             project.setGroupId(groupId);
260             return this;
261         }
262 
263         public ProjectBuilder setArtifactId(String artifactId) {
264             project.setArtifactId(artifactId);
265             return this;
266         }
267 
268         public ProjectBuilder setVersion(String version) {
269             project.setVersion(version);
270             return this;
271         }
272 
273         // Dependencies
274         //
275         public ProjectBuilder addDependency(String groupId, String artifactId, String version, String scope) {
276             return addDependency(groupId, artifactId, version, scope, (Exclusion) null);
277         }
278 
279         public ProjectBuilder addDependency(
280                 String groupId, String artifactId, String version, String scope, Exclusion exclusion) {
281             return addDependency(groupId, artifactId, version, scope, null, exclusion);
282         }
283 
284         public ProjectBuilder addDependency(
285                 String groupId, String artifactId, String version, String scope, String systemPath) {
286             return addDependency(groupId, artifactId, version, scope, systemPath, null);
287         }
288 
289         public ProjectBuilder addDependency(
290                 String groupId,
291                 String artifactId,
292                 String version,
293                 String scope,
294                 String systemPath,
295                 Exclusion exclusion) {
296             Dependency d = new Dependency();
297             d.setGroupId(groupId);
298             d.setArtifactId(artifactId);
299             d.setVersion(version);
300             d.setScope(scope);
301 
302             if (systemPath != null && scope.equals(Artifact.SCOPE_SYSTEM)) {
303                 d.setSystemPath(systemPath);
304             }
305 
306             if (exclusion != null) {
307                 d.addExclusion(exclusion);
308             }
309 
310             project.getDependencies().add(d);
311 
312             return this;
313         }
314 
315         // Plugins
316         //
317         public ProjectBuilder addPlugin(Plugin plugin) {
318             project.getBuildPlugins().add(plugin);
319             return this;
320         }
321 
322         public MavenProject get() {
323             return project;
324         }
325     }
326 }