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.internal.impl.resolver;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.nio.file.Files;
24  import java.nio.file.Path;
25  import java.util.ArrayList;
26  import java.util.Collections;
27  import java.util.HashMap;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Objects;
31  
32  import org.apache.maven.api.di.Inject;
33  import org.apache.maven.api.di.Named;
34  import org.apache.maven.api.di.Singleton;
35  import org.apache.maven.api.metadata.Snapshot;
36  import org.apache.maven.api.metadata.SnapshotVersion;
37  import org.apache.maven.api.metadata.Versioning;
38  import org.apache.maven.metadata.v4.MetadataStaxReader;
39  import org.eclipse.aether.RepositoryCache;
40  import org.eclipse.aether.RepositoryEvent;
41  import org.eclipse.aether.RepositoryEvent.EventType;
42  import org.eclipse.aether.RepositorySystemSession;
43  import org.eclipse.aether.RequestTrace;
44  import org.eclipse.aether.SyncContext;
45  import org.eclipse.aether.artifact.Artifact;
46  import org.eclipse.aether.impl.MetadataResolver;
47  import org.eclipse.aether.impl.RepositoryEventDispatcher;
48  import org.eclipse.aether.impl.VersionResolver;
49  import org.eclipse.aether.metadata.DefaultMetadata;
50  import org.eclipse.aether.metadata.Metadata;
51  import org.eclipse.aether.repository.ArtifactRepository;
52  import org.eclipse.aether.repository.LocalRepository;
53  import org.eclipse.aether.repository.RemoteRepository;
54  import org.eclipse.aether.repository.WorkspaceReader;
55  import org.eclipse.aether.repository.WorkspaceRepository;
56  import org.eclipse.aether.resolution.MetadataRequest;
57  import org.eclipse.aether.resolution.MetadataResult;
58  import org.eclipse.aether.resolution.VersionRequest;
59  import org.eclipse.aether.resolution.VersionResolutionException;
60  import org.eclipse.aether.resolution.VersionResult;
61  import org.eclipse.aether.spi.synccontext.SyncContextFactory;
62  import org.eclipse.aether.util.ConfigUtils;
63  
64  /**
65   */
66  @Named
67  @Singleton
68  public class DefaultVersionResolver implements VersionResolver {
69  
70      private static final String MAVEN_METADATA_XML = "maven-metadata.xml";
71  
72      private static final String RELEASE = "RELEASE";
73  
74      private static final String LATEST = "LATEST";
75  
76      private static final String SNAPSHOT = "SNAPSHOT";
77  
78      private final MetadataResolver metadataResolver;
79      private final SyncContextFactory syncContextFactory;
80      private final RepositoryEventDispatcher repositoryEventDispatcher;
81  
82      @Inject
83      public DefaultVersionResolver(
84              MetadataResolver metadataResolver,
85              SyncContextFactory syncContextFactory,
86              RepositoryEventDispatcher repositoryEventDispatcher) {
87          this.metadataResolver = Objects.requireNonNull(metadataResolver, "metadataResolver cannot be null");
88          this.syncContextFactory = Objects.requireNonNull(syncContextFactory, "syncContextFactory cannot be null");
89          this.repositoryEventDispatcher =
90                  Objects.requireNonNull(repositoryEventDispatcher, "repositoryEventDispatcher cannot be null");
91      }
92  
93      @SuppressWarnings("checkstyle:methodlength")
94      @Override
95      public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request)
96              throws VersionResolutionException {
97          RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
98  
99          Artifact artifact = request.getArtifact();
100 
101         String version = artifact.getVersion();
102 
103         VersionResult result = new VersionResult(request);
104 
105         Key cacheKey = null;
106         RepositoryCache cache = session.getCache();
107         if (cache != null && !ConfigUtils.getBoolean(session, false, "aether.versionResolver.noCache")) {
108             cacheKey = new Key(session, request);
109 
110             Object obj = cache.get(session, cacheKey);
111             if (obj instanceof Record) {
112                 Record record = (Record) obj;
113                 result.setVersion(record.version);
114                 result.setRepository(
115                         getRepository(session, request.getRepositories(), record.repoClass, record.repoId));
116                 return result;
117             }
118         }
119 
120         Metadata metadata;
121 
122         if (RELEASE.equals(version)) {
123             metadata = new DefaultMetadata(
124                     artifact.getGroupId(), artifact.getArtifactId(), MAVEN_METADATA_XML, Metadata.Nature.RELEASE);
125         } else if (LATEST.equals(version)) {
126             metadata = new DefaultMetadata(
127                     artifact.getGroupId(),
128                     artifact.getArtifactId(),
129                     MAVEN_METADATA_XML,
130                     Metadata.Nature.RELEASE_OR_SNAPSHOT);
131         } else if (version.endsWith(SNAPSHOT)) {
132             WorkspaceReader workspace = session.getWorkspaceReader();
133             if (workspace != null && workspace.findVersions(artifact).contains(version)) {
134                 metadata = null;
135                 result.setRepository(workspace.getRepository());
136             } else {
137                 metadata = new DefaultMetadata(
138                         artifact.getGroupId(),
139                         artifact.getArtifactId(),
140                         version,
141                         MAVEN_METADATA_XML,
142                         Metadata.Nature.SNAPSHOT);
143             }
144         } else {
145             metadata = null;
146         }
147 
148         if (metadata == null) {
149             result.setVersion(version);
150         } else {
151             List<MetadataRequest> metadataReqs =
152                     new ArrayList<>(request.getRepositories().size());
153 
154             metadataReqs.add(new MetadataRequest(metadata, null, request.getRequestContext()));
155 
156             for (RemoteRepository repository : request.getRepositories()) {
157                 MetadataRequest metadataRequest =
158                         new MetadataRequest(metadata, repository, request.getRequestContext());
159                 metadataRequest.setDeleteLocalCopyIfMissing(true);
160                 metadataRequest.setFavorLocalRepository(true);
161                 metadataRequest.setTrace(trace);
162                 metadataReqs.add(metadataRequest);
163             }
164 
165             List<MetadataResult> metadataResults = metadataResolver.resolveMetadata(session, metadataReqs);
166 
167             Map<String, VersionInfo> infos = new HashMap<>();
168 
169             for (MetadataResult metadataResult : metadataResults) {
170                 result.addException(metadataResult.getException());
171 
172                 ArtifactRepository repository = metadataResult.getRequest().getRepository();
173                 if (repository == null) {
174                     repository = session.getLocalRepository();
175                 }
176 
177                 Versioning v = readVersions(session, trace, metadataResult.getMetadata(), repository, result);
178                 merge(artifact, infos, v, repository);
179             }
180 
181             if (RELEASE.equals(version)) {
182                 resolve(result, infos, RELEASE);
183             } else if (LATEST.equals(version)) {
184                 if (!resolve(result, infos, LATEST)) {
185                     resolve(result, infos, RELEASE);
186                 }
187 
188                 if (result.getVersion() != null && result.getVersion().endsWith(SNAPSHOT)) {
189                     VersionRequest subRequest = new VersionRequest();
190                     subRequest.setArtifact(artifact.setVersion(result.getVersion()));
191                     if (result.getRepository() instanceof RemoteRepository) {
192                         RemoteRepository r = (RemoteRepository) result.getRepository();
193                         subRequest.setRepositories(Collections.singletonList(r));
194                     } else {
195                         subRequest.setRepositories(request.getRepositories());
196                     }
197                     VersionResult subResult = resolveVersion(session, subRequest);
198                     result.setVersion(subResult.getVersion());
199                     result.setRepository(subResult.getRepository());
200                     for (Exception exception : subResult.getExceptions()) {
201                         result.addException(exception);
202                     }
203                 }
204             } else {
205                 String key = SNAPSHOT + getKey(artifact.getClassifier(), artifact.getExtension());
206                 merge(infos, SNAPSHOT, key);
207                 if (!resolve(result, infos, key)) {
208                     result.setVersion(version);
209                 }
210             }
211 
212             if (result.getVersion() == null || result.getVersion().isEmpty()) {
213                 throw new VersionResolutionException(result);
214             }
215         }
216 
217         if (cacheKey != null && metadata != null && isSafelyCacheable(session, artifact)) {
218             cache.put(session, cacheKey, new Record(result.getVersion(), result.getRepository()));
219         }
220 
221         return result;
222     }
223 
224     private boolean resolve(VersionResult result, Map<String, VersionInfo> infos, String key) {
225         VersionInfo info = infos.get(key);
226         if (info != null) {
227             result.setVersion(info.version);
228             result.setRepository(info.repository);
229         }
230         return info != null;
231     }
232 
233     private Versioning readVersions(
234             RepositorySystemSession session,
235             RequestTrace trace,
236             Metadata metadata,
237             ArtifactRepository repository,
238             VersionResult result) {
239         Versioning versioning = null;
240         try {
241             if (metadata != null) {
242                 try (SyncContext syncContext = syncContextFactory.newInstance(session, true)) {
243                     syncContext.acquire(null, Collections.singleton(metadata));
244 
245                     if (metadata.getPath() != null && Files.exists(metadata.getPath())) {
246                         try (InputStream in = Files.newInputStream(metadata.getPath())) {
247                             versioning =
248                                     new MetadataStaxReader().read(in, false).getVersioning();
249 
250                             /*
251                             NOTE: Users occasionally misuse the id "local" for remote repos which screws up the metadata
252                             of the local repository. This is especially troublesome during snapshot resolution so we try
253                             to handle that gracefully.
254                              */
255                             if (versioning != null
256                                     && repository instanceof LocalRepository
257                                     && versioning.getSnapshot() != null
258                                     && versioning.getSnapshot().getBuildNumber() > 0) {
259                                 versioning = Versioning.newBuilder()
260                                         .lastUpdated(versioning.getLastUpdated())
261                                         .snapshot(Snapshot.newBuilder()
262                                                 .localCopy(true)
263                                                 .build())
264                                         .build();
265                                 throw new IOException("Snapshot information corrupted with remote repository data"
266                                         + ", please verify that no remote repository uses the id '"
267                                         + repository.getId() + "'");
268                             }
269                         }
270                     }
271                 }
272             }
273         } catch (Exception e) {
274             invalidMetadata(session, trace, metadata, repository, e);
275             result.addException(e);
276         }
277 
278         return (versioning != null) ? versioning : Versioning.newInstance();
279     }
280 
281     private void invalidMetadata(
282             RepositorySystemSession session,
283             RequestTrace trace,
284             Metadata metadata,
285             ArtifactRepository repository,
286             Exception exception) {
287         RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INVALID);
288         event.setTrace(trace);
289         event.setMetadata(metadata);
290         event.setException(exception);
291         event.setRepository(repository);
292 
293         repositoryEventDispatcher.dispatch(event.build());
294     }
295 
296     private void merge(
297             Artifact artifact, Map<String, VersionInfo> infos, Versioning versioning, ArtifactRepository repository) {
298         if (versioning.getRelease() != null && !versioning.getRelease().isEmpty()) {
299             merge(RELEASE, infos, versioning.getLastUpdated(), versioning.getRelease(), repository);
300         }
301 
302         if (versioning.getLatest() != null && !versioning.getLatest().isEmpty()) {
303             merge(LATEST, infos, versioning.getLastUpdated(), versioning.getLatest(), repository);
304         }
305 
306         for (SnapshotVersion sv : versioning.getSnapshotVersions()) {
307             if (sv.getVersion() != null && !sv.getVersion().isEmpty()) {
308                 String key = getKey(sv.getClassifier(), sv.getExtension());
309                 merge(SNAPSHOT + key, infos, sv.getUpdated(), sv.getVersion(), repository);
310             }
311         }
312 
313         Snapshot snapshot = versioning.getSnapshot();
314         if (snapshot != null && versioning.getSnapshotVersions().isEmpty()) {
315             String version = artifact.getVersion();
316             if (snapshot.getTimestamp() != null && snapshot.getBuildNumber() > 0) {
317                 String qualifier = snapshot.getTimestamp() + '-' + snapshot.getBuildNumber();
318                 version = version.substring(0, version.length() - SNAPSHOT.length()) + qualifier;
319             }
320             merge(SNAPSHOT, infos, versioning.getLastUpdated(), version, repository);
321         }
322     }
323 
324     private void merge(
325             String key,
326             Map<String, VersionInfo> infos,
327             String timestamp,
328             String version,
329             ArtifactRepository repository) {
330         VersionInfo info = infos.get(key);
331         if (info == null) {
332             info = new VersionInfo(timestamp, version, repository);
333             infos.put(key, info);
334         } else if (info.isOutdated(timestamp)) {
335             info.version = version;
336             info.repository = repository;
337             info.timestamp = timestamp;
338         }
339     }
340 
341     private void merge(Map<String, VersionInfo> infos, String srcKey, String dstKey) {
342         VersionInfo srcInfo = infos.get(srcKey);
343         VersionInfo dstInfo = infos.get(dstKey);
344 
345         if (dstInfo == null
346                 || (srcInfo != null
347                         && dstInfo.isOutdated(srcInfo.timestamp)
348                         && srcInfo.repository != dstInfo.repository)) {
349             infos.put(dstKey, srcInfo);
350         }
351     }
352 
353     private String getKey(String classifier, String extension) {
354         return (classifier == null ? "" : classifier.trim()) + ':' + (extension == null ? "" : extension.trim());
355     }
356 
357     private ArtifactRepository getRepository(
358             RepositorySystemSession session, List<RemoteRepository> repositories, Class<?> repoClass, String repoId) {
359         if (repoClass != null) {
360             if (WorkspaceRepository.class.isAssignableFrom(repoClass)) {
361                 return session.getWorkspaceReader().getRepository();
362             } else if (LocalRepository.class.isAssignableFrom(repoClass)) {
363                 return session.getLocalRepository();
364             } else {
365                 for (RemoteRepository repository : repositories) {
366                     if (repoId.equals(repository.getId())) {
367                         return repository;
368                     }
369                 }
370             }
371         }
372         return null;
373     }
374 
375     private boolean isSafelyCacheable(RepositorySystemSession session, Artifact artifact) {
376         /*
377          * The workspace/reactor is in flux so we better not assume definitive information for any of its
378          * artifacts/projects.
379          */
380 
381         WorkspaceReader workspace = session.getWorkspaceReader();
382         if (workspace == null) {
383             return true;
384         }
385 
386         Artifact pomArtifact = ArtifactDescriptorUtils.toPomArtifact(artifact);
387 
388         return workspace.findArtifact(pomArtifact) == null;
389     }
390 
391     private static class VersionInfo {
392 
393         String timestamp;
394 
395         String version;
396 
397         ArtifactRepository repository;
398 
399         VersionInfo(String timestamp, String version, ArtifactRepository repository) {
400             this.timestamp = (timestamp != null) ? timestamp : "";
401             this.version = version;
402             this.repository = repository;
403         }
404 
405         boolean isOutdated(String timestamp) {
406             return timestamp != null && timestamp.compareTo(this.timestamp) > 0;
407         }
408     }
409 
410     private static class Key {
411 
412         private final String groupId;
413 
414         private final String artifactId;
415 
416         private final String classifier;
417 
418         private final String extension;
419 
420         private final String version;
421 
422         private final String context;
423 
424         private final Path localRepo;
425 
426         private final WorkspaceRepository workspace;
427 
428         private final List<RemoteRepository> repositories;
429 
430         private final int hashCode;
431 
432         Key(RepositorySystemSession session, VersionRequest request) {
433             Artifact artifact = request.getArtifact();
434             groupId = artifact.getGroupId();
435             artifactId = artifact.getArtifactId();
436             classifier = artifact.getClassifier();
437             extension = artifact.getExtension();
438             version = artifact.getVersion();
439             localRepo = session.getLocalRepository().getBasePath();
440             WorkspaceReader reader = session.getWorkspaceReader();
441             workspace = (reader != null) ? reader.getRepository() : null;
442             repositories = new ArrayList<>(request.getRepositories().size());
443             boolean repoMan = false;
444             for (RemoteRepository repository : request.getRepositories()) {
445                 if (repository.isRepositoryManager()) {
446                     repoMan = true;
447                     repositories.addAll(repository.getMirroredRepositories());
448                 } else {
449                     repositories.add(repository);
450                 }
451             }
452             context = repoMan ? request.getRequestContext() : "";
453 
454             int hash = 17;
455             hash = hash * 31 + groupId.hashCode();
456             hash = hash * 31 + artifactId.hashCode();
457             hash = hash * 31 + classifier.hashCode();
458             hash = hash * 31 + extension.hashCode();
459             hash = hash * 31 + version.hashCode();
460             hash = hash * 31 + localRepo.hashCode();
461             hash = hash * 31 + repositories.hashCode();
462             hashCode = hash;
463         }
464 
465         @Override
466         public boolean equals(Object obj) {
467             if (obj == this) {
468                 return true;
469             } else if (obj == null || !getClass().equals(obj.getClass())) {
470                 return false;
471             }
472 
473             Key that = (Key) obj;
474             return artifactId.equals(that.artifactId)
475                     && groupId.equals(that.groupId)
476                     && classifier.equals(that.classifier)
477                     && extension.equals(that.extension)
478                     && version.equals(that.version)
479                     && context.equals(that.context)
480                     && localRepo.equals(that.localRepo)
481                     && Objects.equals(workspace, that.workspace)
482                     && repositories.equals(that.repositories);
483         }
484 
485         @Override
486         public int hashCode() {
487             return hashCode;
488         }
489     }
490 
491     private static class Record {
492         final String version;
493 
494         final String repoId;
495 
496         final Class<?> repoClass;
497 
498         Record(String version, ArtifactRepository repository) {
499             this.version = version;
500             if (repository != null) {
501                 repoId = repository.getId();
502                 repoClass = repository.getClass();
503             } else {
504                 repoId = null;
505                 repoClass = null;
506             }
507         }
508     }
509 }