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.api.plugin.testing.stubs;
20  
21  import java.net.URI;
22  import java.nio.file.Path;
23  import java.nio.file.Paths;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.HashMap;
27  import java.util.Map;
28  import java.util.Optional;
29  import java.util.Properties;
30  
31  import org.apache.maven.api.Artifact;
32  import org.apache.maven.api.LocalRepository;
33  import org.apache.maven.api.Project;
34  import org.apache.maven.api.RemoteRepository;
35  import org.apache.maven.api.Session;
36  import org.apache.maven.api.model.Model;
37  import org.apache.maven.api.model.Repository;
38  import org.apache.maven.api.services.ArtifactDeployer;
39  import org.apache.maven.api.services.ArtifactDeployerRequest;
40  import org.apache.maven.api.services.ArtifactFactory;
41  import org.apache.maven.api.services.ArtifactFactoryRequest;
42  import org.apache.maven.api.services.ArtifactInstaller;
43  import org.apache.maven.api.services.ArtifactInstallerRequest;
44  import org.apache.maven.api.services.ArtifactManager;
45  import org.apache.maven.api.services.LocalRepositoryManager;
46  import org.apache.maven.api.services.ProjectBuilder;
47  import org.apache.maven.api.services.ProjectBuilderRequest;
48  import org.apache.maven.api.services.ProjectBuilderResult;
49  import org.apache.maven.api.services.ProjectManager;
50  import org.apache.maven.api.services.RepositoryFactory;
51  import org.apache.maven.api.services.xml.ModelXmlFactory;
52  import org.apache.maven.internal.impl.DefaultModelXmlFactory;
53  import org.apache.maven.model.v4.MavenStaxReader;
54  import org.mockito.ArgumentMatchers;
55  
56  import static org.mockito.ArgumentMatchers.any;
57  import static org.mockito.ArgumentMatchers.anyString;
58  import static org.mockito.ArgumentMatchers.same;
59  import static org.mockito.Mockito.doAnswer;
60  import static org.mockito.Mockito.doReturn;
61  import static org.mockito.Mockito.mock;
62  import static org.mockito.Mockito.when;
63  import static org.mockito.Mockito.withSettings;
64  
65  /**
66   *
67   */
68  public class SessionStub {
69  
70      public static Session getMockSession(String localRepo) {
71          LocalRepository localRepository = mock(LocalRepository.class);
72          when(localRepository.getId()).thenReturn("local");
73          when(localRepository.getPath()).thenReturn(Paths.get(localRepo));
74          return getMockSession(localRepository);
75      }
76  
77      public static Session getMockSession(LocalRepository localRepository) {
78          Session session = mock(Session.class);
79  
80          RepositoryFactory repositoryFactory = mock(RepositoryFactory.class);
81          when(repositoryFactory.createRemote(any(Repository.class))).thenAnswer(iom -> {
82              Repository repository = iom.getArgument(0, Repository.class);
83              return repositoryFactory.createRemote(repository.getId(), repository.getUrl());
84          });
85          when(repositoryFactory.createRemote(anyString(), anyString())).thenAnswer(iom -> {
86              String id = iom.getArgument(0, String.class);
87              String url = iom.getArgument(1, String.class);
88              RemoteRepository remoteRepository =
89                      mock(RemoteRepository.class, withSettings().lenient());
90              when(remoteRepository.getId()).thenReturn(id);
91              when(remoteRepository.getUrl()).thenReturn(url);
92              when(remoteRepository.getProtocol()).thenReturn(URI.create(url).getScheme());
93              return remoteRepository;
94          });
95  
96          LocalRepositoryManager localRepositoryManager = mock(LocalRepositoryManager.class);
97          when(localRepositoryManager.getPathForLocalArtifact(any(), any(), any()))
98                  .thenAnswer(iom -> {
99                      LocalRepository localRepo = iom.getArgument(1, LocalRepository.class);
100                     Artifact artifact = iom.getArgument(2, Artifact.class);
101                     return localRepo.getPath().resolve(getPathForArtifact(artifact, true));
102                 });
103 
104         ArtifactInstaller artifactInstaller = mock(ArtifactInstaller.class);
105         doAnswer(iom -> {
106                     artifactInstaller.install(ArtifactInstallerRequest.build(
107                             iom.getArgument(0, Session.class), iom.getArgument(1, Collection.class)));
108                     return null;
109                 })
110                 .when(artifactInstaller)
111                 .install(any(Session.class), ArgumentMatchers.<Collection<Artifact>>any());
112 
113         ArtifactDeployer artifactDeployer = mock(ArtifactDeployer.class);
114         doAnswer(iom -> {
115                     artifactDeployer.deploy(ArtifactDeployerRequest.build(
116                             iom.getArgument(0, Session.class),
117                             iom.getArgument(1, RemoteRepository.class),
118                             iom.getArgument(2, Collection.class)));
119                     return null;
120                 })
121                 .when(artifactDeployer)
122                 .deploy(any(), any(), any());
123 
124         ArtifactManager artifactManager = mock(ArtifactManager.class);
125         Map<Artifact, Path> paths = new HashMap<>();
126         doAnswer(iom -> {
127                     paths.put(iom.getArgument(0), iom.getArgument(1));
128                     return null;
129                 })
130                 .when(artifactManager)
131                 .setPath(any(), any());
132         doAnswer(iom -> Optional.ofNullable(paths.get(iom.getArgument(0, Artifact.class))))
133                 .when(artifactManager)
134                 .getPath(any());
135 
136         ProjectManager projectManager = mock(ProjectManager.class);
137         Map<Project, Collection<Artifact>> attachedArtifacts = new HashMap<>();
138         doAnswer(iom -> {
139                     Project project = iom.getArgument(1, Project.class);
140                     String type = iom.getArgument(2, String.class);
141                     Path path = iom.getArgument(3, Path.class);
142                     Artifact artifact = session.createArtifact(
143                             project.getGroupId(), project.getArtifactId(), project.getVersion(), null, null, type);
144                     artifactManager.setPath(artifact, path);
145                     attachedArtifacts
146                             .computeIfAbsent(project, p -> new ArrayList<>())
147                             .add(artifact);
148                     return null;
149                 })
150                 .when(projectManager)
151                 .attachArtifact(same(session), any(Project.class), any(), any());
152         doAnswer(iom -> {
153                     Project project = iom.getArgument(0, Project.class);
154                     Artifact artifact = iom.getArgument(1, Artifact.class);
155                     Path path = iom.getArgument(2, Path.class);
156                     artifactManager.setPath(artifact, path);
157                     attachedArtifacts
158                             .computeIfAbsent(project, p -> new ArrayList<>())
159                             .add(artifact);
160                     return null;
161                 })
162                 .when(projectManager)
163                 .attachArtifact(any(Project.class), any(Artifact.class), any(Path.class));
164         when(projectManager.getAttachedArtifacts(any()))
165                 .then(iom ->
166                         attachedArtifacts.computeIfAbsent(iom.getArgument(0, Project.class), p -> new ArrayList<>()));
167 
168         ArtifactFactory artifactFactory = mock(ArtifactFactory.class);
169         when(artifactFactory.create(any())).then(iom -> {
170             ArtifactFactoryRequest request = iom.getArgument(0, ArtifactFactoryRequest.class);
171             String classifier = request.getClassifier();
172             String extension = request.getExtension();
173             String type = request.getType();
174             if (classifier == null) {
175                 classifier = "";
176             }
177             if (extension == null) {
178                 extension = type != null ? type : "";
179             }
180             return new ArtifactStub(
181                     request.getGroupId(), request.getArtifactId(), classifier, request.getVersion(), extension);
182         });
183 
184         ProjectBuilder projectBuilder = mock(ProjectBuilder.class);
185         when(projectBuilder.build(any(ProjectBuilderRequest.class))).then(iom -> {
186             ProjectBuilderRequest request = iom.getArgument(0, ProjectBuilderRequest.class);
187             ProjectBuilderResult result = mock(ProjectBuilderResult.class);
188             Model model = new MavenStaxReader().read(request.getSource().get().openStream());
189             ProjectStub projectStub = new ProjectStub();
190             projectStub.setModel(model);
191             ArtifactStub artifactStub = new ArtifactStub(
192                     model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging());
193             projectStub.setArtifact(artifactStub);
194             when(result.getProject()).thenReturn(Optional.of(projectStub));
195             return result;
196         });
197 
198         Properties sysProps = new Properties();
199         Properties usrProps = new Properties();
200         doReturn(sysProps).when(session).getSystemProperties();
201         doReturn(usrProps).when(session).getUserProperties();
202 
203         when(session.getLocalRepository()).thenReturn(localRepository);
204         when(session.getService(RepositoryFactory.class)).thenReturn(repositoryFactory);
205         when(session.getService(ProjectBuilder.class)).thenReturn(projectBuilder);
206         when(session.getService(LocalRepositoryManager.class)).thenReturn(localRepositoryManager);
207         when(session.getService(ProjectManager.class)).thenReturn(projectManager);
208         when(session.getService(ArtifactManager.class)).thenReturn(artifactManager);
209         when(session.getService(ArtifactInstaller.class)).thenReturn(artifactInstaller);
210         when(session.getService(ArtifactDeployer.class)).thenReturn(artifactDeployer);
211         when(session.getService(ArtifactFactory.class)).thenReturn(artifactFactory);
212         when(session.getService(ModelXmlFactory.class)).thenReturn(new DefaultModelXmlFactory());
213 
214         when(session.getPathForLocalArtifact(any(Artifact.class)))
215                 .then(iom -> localRepositoryManager.getPathForLocalArtifact(
216                         session, session.getLocalRepository(), iom.getArgument(0, Artifact.class)));
217         when(session.createArtifact(any(), any(), any(), any(), any(), any())).thenAnswer(iom -> {
218             String groupId = iom.getArgument(0, String.class);
219             String artifactId = iom.getArgument(1, String.class);
220             String version = iom.getArgument(2, String.class);
221             String classifier = iom.getArgument(3, String.class);
222             String extension = iom.getArgument(4, String.class);
223             String type = iom.getArgument(5, String.class);
224             return session.getService(ArtifactFactory.class)
225                     .create(ArtifactFactoryRequest.builder()
226                             .session(session)
227                             .groupId(groupId)
228                             .artifactId(artifactId)
229                             .version(version)
230                             .classifier(classifier)
231                             .extension(extension)
232                             .type(type)
233                             .build());
234         });
235         when(session.createArtifact(any(), any(), any(), any())).thenAnswer(iom -> {
236             String groupId = iom.getArgument(0, String.class);
237             String artifactId = iom.getArgument(1, String.class);
238             String version = iom.getArgument(2, String.class);
239             String extension = iom.getArgument(3, String.class);
240             return session.getService(ArtifactFactory.class)
241                     .create(ArtifactFactoryRequest.builder()
242                             .session(session)
243                             .groupId(groupId)
244                             .artifactId(artifactId)
245                             .version(version)
246                             .extension(extension)
247                             .build());
248         });
249         when(session.createRemoteRepository(anyString(), anyString())).thenAnswer(iom -> {
250             String id = iom.getArgument(0, String.class);
251             String url = iom.getArgument(1, String.class);
252             return session.getService(RepositoryFactory.class).createRemote(id, url);
253         });
254         doAnswer(iom -> artifactManager.getPath(iom.getArgument(0, Artifact.class)))
255                 .when(session)
256                 .getArtifactPath(any());
257 
258         when(session.withLocalRepository(any()))
259                 .thenAnswer(iom -> getMockSession(iom.getArgument(0, LocalRepository.class)));
260         return session;
261     }
262 
263     static String getPathForArtifact(Artifact artifact, boolean local) {
264         StringBuilder path = new StringBuilder(128);
265         path.append(artifact.getGroupId().replace('.', '/')).append('/');
266         path.append(artifact.getArtifactId()).append('/');
267         path.append(artifact.getVersion()).append('/');
268         path.append(artifact.getArtifactId()).append('-');
269         path.append(artifact.getVersion());
270         if (artifact.getClassifier().length() > 0) {
271             path.append('-').append(artifact.getClassifier());
272         }
273         if (artifact.getExtension().length() > 0) {
274             path.append('.').append(artifact.getExtension());
275         }
276         return path.toString();
277     }
278 }