1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.internal.impl;
20
21 import java.util.List;
22 import java.util.Optional;
23
24 import org.apache.maven.api.Repository;
25 import org.apache.maven.api.Version;
26 import org.apache.maven.api.di.Inject;
27 import org.apache.maven.api.di.Named;
28 import org.apache.maven.api.di.Singleton;
29 import org.apache.maven.api.services.VersionResolver;
30 import org.apache.maven.api.services.VersionResolverException;
31 import org.apache.maven.api.services.VersionResolverRequest;
32 import org.apache.maven.api.services.VersionResolverResult;
33 import org.eclipse.aether.RepositorySystem;
34 import org.eclipse.aether.resolution.VersionRequest;
35 import org.eclipse.aether.resolution.VersionResolutionException;
36 import org.eclipse.aether.resolution.VersionResult;
37
38 import static org.apache.maven.internal.impl.Utils.nonNull;
39
40 @Named
41 @Singleton
42 public class DefaultVersionResolver implements VersionResolver {
43
44 private final RepositorySystem repositorySystem;
45
46 @Inject
47 public DefaultVersionResolver(RepositorySystem repositorySystem) {
48 this.repositorySystem = repositorySystem;
49 }
50
51 @Override
52 public VersionResolverResult resolve(VersionResolverRequest request) throws VersionResolverException {
53 nonNull(request, "request");
54 InternalSession session = InternalSession.from(request.getSession());
55
56 try {
57 VersionResult res = repositorySystem.resolveVersion(
58 session.getSession(),
59 new VersionRequest(
60 session.toArtifact(request.getArtifactCoordinates()),
61 session.toRepositories(session.getRemoteRepositories()),
62 null));
63
64 return new VersionResolverResult() {
65 @Override
66 public List<Exception> getExceptions() {
67 return res.getExceptions();
68 }
69
70 @Override
71 public Version getVersion() {
72 return session.parseVersion(res.getVersion());
73 }
74
75 @Override
76 public Optional<Repository> getRepository() {
77 if (res.getRepository() instanceof org.eclipse.aether.repository.LocalRepository) {
78 return Optional.of(new DefaultLocalRepository(
79 (org.eclipse.aether.repository.LocalRepository) res.getRepository()));
80 } else if (res.getRepository() instanceof org.eclipse.aether.repository.RemoteRepository) {
81 return Optional.of(new DefaultRemoteRepository(
82 (org.eclipse.aether.repository.RemoteRepository) res.getRepository()));
83 } else {
84 return Optional.empty();
85 }
86 }
87 };
88 } catch (VersionResolutionException e) {
89 throw new VersionResolverException("Unable to resolve version", e);
90 }
91 }
92 }