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.cli.internal;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  
24  import java.io.File;
25  import java.util.ArrayList;
26  import java.util.Collections;
27  import java.util.List;
28  import java.util.NoSuchElementException;
29  import java.util.Set;
30  import java.util.stream.Collectors;
31  
32  import org.apache.maven.RepositoryUtils;
33  import org.apache.maven.api.Service;
34  import org.apache.maven.api.Session;
35  import org.apache.maven.api.model.Plugin;
36  import org.apache.maven.api.services.ArtifactCoordinatesFactory;
37  import org.apache.maven.api.services.ArtifactManager;
38  import org.apache.maven.api.services.ArtifactResolver;
39  import org.apache.maven.api.services.RepositoryFactory;
40  import org.apache.maven.api.services.VersionParser;
41  import org.apache.maven.api.services.VersionRangeResolver;
42  import org.apache.maven.cli.internal.extension.model.CoreExtension;
43  import org.apache.maven.execution.DefaultMavenExecutionResult;
44  import org.apache.maven.execution.MavenExecutionRequest;
45  import org.apache.maven.execution.MavenSession;
46  import org.apache.maven.extension.internal.CoreExports;
47  import org.apache.maven.extension.internal.CoreExtensionEntry;
48  import org.apache.maven.internal.impl.DefaultArtifactCoordinatesFactory;
49  import org.apache.maven.internal.impl.DefaultArtifactManager;
50  import org.apache.maven.internal.impl.DefaultArtifactResolver;
51  import org.apache.maven.internal.impl.DefaultModelVersionParser;
52  import org.apache.maven.internal.impl.DefaultRepositoryFactory;
53  import org.apache.maven.internal.impl.DefaultSession;
54  import org.apache.maven.internal.impl.DefaultVersionParser;
55  import org.apache.maven.internal.impl.DefaultVersionRangeResolver;
56  import org.apache.maven.internal.impl.InternalSession;
57  import org.apache.maven.plugin.PluginResolutionException;
58  import org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver;
59  import org.apache.maven.resolver.MavenChainedWorkspaceReader;
60  import org.apache.maven.resolver.RepositorySystemSessionFactory;
61  import org.codehaus.plexus.DefaultPlexusContainer;
62  import org.codehaus.plexus.PlexusContainer;
63  import org.codehaus.plexus.classworlds.ClassWorld;
64  import org.codehaus.plexus.classworlds.realm.ClassRealm;
65  import org.codehaus.plexus.interpolation.InterpolationException;
66  import org.codehaus.plexus.interpolation.Interpolator;
67  import org.codehaus.plexus.interpolation.MapBasedValueSource;
68  import org.codehaus.plexus.interpolation.StringSearchInterpolator;
69  import org.eclipse.aether.RepositorySystem;
70  import org.eclipse.aether.RepositorySystemSession;
71  import org.eclipse.aether.RepositorySystemSession.CloseableSession;
72  import org.eclipse.aether.artifact.Artifact;
73  import org.eclipse.aether.graph.DependencyFilter;
74  import org.eclipse.aether.internal.impl.DefaultChecksumPolicyProvider;
75  import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager;
76  import org.eclipse.aether.internal.impl.DefaultUpdatePolicyAnalyzer;
77  import org.eclipse.aether.repository.RemoteRepository;
78  import org.eclipse.aether.repository.WorkspaceReader;
79  import org.eclipse.aether.resolution.ArtifactResult;
80  import org.eclipse.aether.resolution.DependencyResult;
81  import org.eclipse.aether.util.filter.ExclusionsDependencyFilter;
82  import org.eclipse.aether.util.version.GenericVersionScheme;
83  import org.eclipse.sisu.Nullable;
84  import org.slf4j.Logger;
85  import org.slf4j.LoggerFactory;
86  
87  /**
88   * BootstrapCoreExtensionManager
89   */
90  @Named
91  public class BootstrapCoreExtensionManager {
92      public static final String STRATEGY_PARENT_FIRST = "parent-first";
93      public static final String STRATEGY_PLUGIN = "plugin";
94      public static final String STRATEGY_SELF_FIRST = "self-first";
95  
96      private final Logger log = LoggerFactory.getLogger(getClass());
97  
98      private final DefaultPluginDependenciesResolver pluginDependenciesResolver;
99  
100     private final RepositorySystemSessionFactory repositorySystemSessionFactory;
101 
102     private final CoreExports coreExports;
103 
104     private final ClassWorld classWorld;
105 
106     private final ClassRealm parentRealm;
107 
108     private final WorkspaceReader ideWorkspaceReader;
109 
110     private final RepositorySystem repoSystem;
111 
112     @Inject
113     public BootstrapCoreExtensionManager(
114             DefaultPluginDependenciesResolver pluginDependenciesResolver,
115             RepositorySystemSessionFactory repositorySystemSessionFactory,
116             CoreExports coreExports,
117             PlexusContainer container,
118             @Nullable @Named("ide") WorkspaceReader ideWorkspaceReader,
119             RepositorySystem repoSystem) {
120         this.pluginDependenciesResolver = pluginDependenciesResolver;
121         this.repositorySystemSessionFactory = repositorySystemSessionFactory;
122         this.coreExports = coreExports;
123         this.classWorld = ((DefaultPlexusContainer) container).getClassWorld();
124         this.parentRealm = container.getContainerRealm();
125         this.ideWorkspaceReader = ideWorkspaceReader;
126         this.repoSystem = repoSystem;
127     }
128 
129     public List<CoreExtensionEntry> loadCoreExtensions(
130             MavenExecutionRequest request, Set<String> providedArtifacts, List<CoreExtension> extensions)
131             throws Exception {
132         try (CloseableSession repoSession = repositorySystemSessionFactory
133                 .newRepositorySessionBuilder(request)
134                 .setWorkspaceReader(new MavenChainedWorkspaceReader(request.getWorkspaceReader(), ideWorkspaceReader))
135                 .build()) {
136             MavenSession mSession = new MavenSession(repoSession, request, new DefaultMavenExecutionResult());
137             InternalSession iSession = new SimpleSession(mSession, repoSystem, null);
138             InternalSession.associate(repoSession, iSession);
139 
140             List<RemoteRepository> repositories = RepositoryUtils.toRepos(request.getPluginArtifactRepositories());
141             Interpolator interpolator = createInterpolator(request);
142 
143             return resolveCoreExtensions(repoSession, repositories, providedArtifacts, extensions, interpolator);
144         }
145     }
146 
147     private List<CoreExtensionEntry> resolveCoreExtensions(
148             RepositorySystemSession repoSession,
149             List<RemoteRepository> repositories,
150             Set<String> providedArtifacts,
151             List<CoreExtension> configuration,
152             Interpolator interpolator)
153             throws Exception {
154         List<CoreExtensionEntry> extensions = new ArrayList<>();
155 
156         DependencyFilter dependencyFilter = new ExclusionsDependencyFilter(providedArtifacts);
157 
158         for (CoreExtension extension : configuration) {
159             List<Artifact> artifacts =
160                     resolveExtension(extension, repoSession, repositories, dependencyFilter, interpolator);
161             if (!artifacts.isEmpty()) {
162                 extensions.add(createExtension(extension, artifacts));
163             }
164         }
165 
166         return Collections.unmodifiableList(extensions);
167     }
168 
169     private CoreExtensionEntry createExtension(CoreExtension extension, List<Artifact> artifacts) throws Exception {
170         String realmId = "coreExtension>" + extension.getGroupId() + ":" + extension.getArtifactId() + ":"
171                 + extension.getVersion();
172         final ClassRealm realm = classWorld.newRealm(realmId, null);
173         Set<String> providedArtifacts = Collections.emptySet();
174         String classLoadingStrategy = extension.getClassLoadingStrategy();
175         if (STRATEGY_PARENT_FIRST.equals(classLoadingStrategy)) {
176             realm.importFrom(parentRealm, "");
177         } else if (STRATEGY_PLUGIN.equals(classLoadingStrategy)) {
178             coreExports.getExportedPackages().forEach((p, cl) -> realm.importFrom(cl, p));
179             providedArtifacts = coreExports.getExportedArtifacts();
180         } else if (STRATEGY_SELF_FIRST.equals(classLoadingStrategy)) {
181             realm.setParentRealm(parentRealm);
182         } else {
183             throw new IllegalArgumentException("Unsupported class-loading strategy '"
184                     + classLoadingStrategy + "'. Supported values are: " + STRATEGY_PARENT_FIRST
185                     + ", " + STRATEGY_PLUGIN + " and " + STRATEGY_SELF_FIRST);
186         }
187         log.debug("Populating class realm {}", realm.getId());
188         for (Artifact artifact : artifacts) {
189             String id = artifact.getGroupId() + ":" + artifact.getArtifactId();
190             if (providedArtifacts.contains(id)) {
191                 log.debug("  Excluded {}", id);
192             } else {
193                 File file = artifact.getFile();
194                 log.debug("  Included {} located at {}", id, file);
195                 realm.addURL(file.toURI().toURL());
196             }
197         }
198         return CoreExtensionEntry.discoverFrom(
199                 realm,
200                 Collections.singleton(artifacts.get(0).getFile()),
201                 extension.getGroupId() + ":" + extension.getArtifactId(),
202                 extension.getConfiguration());
203     }
204 
205     private List<Artifact> resolveExtension(
206             CoreExtension extension,
207             RepositorySystemSession repoSession,
208             List<RemoteRepository> repositories,
209             DependencyFilter dependencyFilter,
210             Interpolator interpolator)
211             throws ExtensionResolutionException {
212         try {
213             /* TODO: Enhance the PluginDependenciesResolver to provide a
214              * resolveCoreExtension method which uses a CoreExtension
215              * object instead of a Plugin as this makes no sense.
216              */
217             Plugin plugin = Plugin.newBuilder()
218                     .groupId(interpolator.interpolate(extension.getGroupId()))
219                     .artifactId(interpolator.interpolate(extension.getArtifactId()))
220                     .version(interpolator.interpolate(extension.getVersion()))
221                     .build();
222 
223             DependencyResult result = pluginDependenciesResolver.resolveCoreExtension(
224                     new org.apache.maven.model.Plugin(plugin), dependencyFilter, repositories, repoSession);
225             return result.getArtifactResults().stream()
226                     .filter(ArtifactResult::isResolved)
227                     .map(ArtifactResult::getArtifact)
228                     .collect(Collectors.toList());
229         } catch (PluginResolutionException | InterpolationException e) {
230             throw new ExtensionResolutionException(extension, e);
231         }
232     }
233 
234     private static Interpolator createInterpolator(MavenExecutionRequest request) {
235         StringSearchInterpolator interpolator = new StringSearchInterpolator();
236         interpolator.addValueSource(new MapBasedValueSource(request.getUserProperties()));
237         interpolator.addValueSource(new MapBasedValueSource(request.getSystemProperties()));
238         return interpolator;
239     }
240 
241     static class SimpleSession extends DefaultSession {
242         SimpleSession(
243                 MavenSession session,
244                 RepositorySystem repositorySystem,
245                 List<org.apache.maven.api.RemoteRepository> repositories) {
246             super(session, repositorySystem, repositories, null, null, null);
247         }
248 
249         @Override
250         protected Session newSession(
251                 MavenSession mavenSession, List<org.apache.maven.api.RemoteRepository> repositories) {
252             return new SimpleSession(mavenSession, getRepositorySystem(), repositories);
253         }
254 
255         @Override
256         public <T extends Service> T getService(Class<T> clazz) throws NoSuchElementException {
257             if (clazz == ArtifactCoordinatesFactory.class) {
258                 return (T) new DefaultArtifactCoordinatesFactory();
259             } else if (clazz == VersionParser.class) {
260                 return (T) new DefaultVersionParser(new DefaultModelVersionParser(new GenericVersionScheme()));
261             } else if (clazz == VersionRangeResolver.class) {
262                 return (T) new DefaultVersionRangeResolver(repositorySystem);
263             } else if (clazz == ArtifactResolver.class) {
264                 return (T) new DefaultArtifactResolver();
265             } else if (clazz == ArtifactManager.class) {
266                 return (T) new DefaultArtifactManager(this);
267             } else if (clazz == RepositoryFactory.class) {
268                 return (T) new DefaultRepositoryFactory(new DefaultRemoteRepositoryManager(
269                         new DefaultUpdatePolicyAnalyzer(), new DefaultChecksumPolicyProvider()));
270                 // } else if (clazz == ModelResolver.class) {
271                 //    return (T) new DefaultModelResolver();
272             }
273             throw new NoSuchElementException("No service for " + clazz.getName());
274         }
275     }
276 }