001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.internal.impl;
020
021import javax.inject.Inject;
022import javax.inject.Named;
023import javax.inject.Singleton;
024
025import java.io.File;
026import java.io.IOException;
027import java.util.ArrayList;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Iterator;
031import java.util.List;
032import java.util.Map;
033import java.util.concurrent.atomic.AtomicBoolean;
034
035import org.eclipse.aether.RepositoryEvent;
036import org.eclipse.aether.RepositoryEvent.EventType;
037import org.eclipse.aether.RepositorySystemSession;
038import org.eclipse.aether.RequestTrace;
039import org.eclipse.aether.SyncContext;
040import org.eclipse.aether.artifact.Artifact;
041import org.eclipse.aether.artifact.ArtifactProperties;
042import org.eclipse.aether.impl.ArtifactResolver;
043import org.eclipse.aether.impl.OfflineController;
044import org.eclipse.aether.impl.RemoteRepositoryFilterManager;
045import org.eclipse.aether.impl.RemoteRepositoryManager;
046import org.eclipse.aether.impl.RepositoryConnectorProvider;
047import org.eclipse.aether.impl.RepositoryEventDispatcher;
048import org.eclipse.aether.impl.UpdateCheck;
049import org.eclipse.aether.impl.UpdateCheckManager;
050import org.eclipse.aether.impl.VersionResolver;
051import org.eclipse.aether.repository.ArtifactRepository;
052import org.eclipse.aether.repository.LocalArtifactRegistration;
053import org.eclipse.aether.repository.LocalArtifactRequest;
054import org.eclipse.aether.repository.LocalArtifactResult;
055import org.eclipse.aether.repository.LocalRepository;
056import org.eclipse.aether.repository.LocalRepositoryManager;
057import org.eclipse.aether.repository.RemoteRepository;
058import org.eclipse.aether.repository.RepositoryPolicy;
059import org.eclipse.aether.repository.WorkspaceReader;
060import org.eclipse.aether.resolution.ArtifactRequest;
061import org.eclipse.aether.resolution.ArtifactResolutionException;
062import org.eclipse.aether.resolution.ArtifactResult;
063import org.eclipse.aether.resolution.ResolutionErrorPolicy;
064import org.eclipse.aether.resolution.VersionRequest;
065import org.eclipse.aether.resolution.VersionResolutionException;
066import org.eclipse.aether.resolution.VersionResult;
067import org.eclipse.aether.spi.connector.ArtifactDownload;
068import org.eclipse.aether.spi.connector.RepositoryConnector;
069import org.eclipse.aether.spi.connector.filter.RemoteRepositoryFilter;
070import org.eclipse.aether.spi.io.FileProcessor;
071import org.eclipse.aether.spi.locator.Service;
072import org.eclipse.aether.spi.locator.ServiceLocator;
073import org.eclipse.aether.spi.resolution.ArtifactResolverPostProcessor;
074import org.eclipse.aether.spi.synccontext.SyncContextFactory;
075import org.eclipse.aether.transfer.ArtifactFilteredOutException;
076import org.eclipse.aether.transfer.ArtifactNotFoundException;
077import org.eclipse.aether.transfer.ArtifactTransferException;
078import org.eclipse.aether.transfer.NoRepositoryConnectorException;
079import org.eclipse.aether.transfer.RepositoryOfflineException;
080import org.eclipse.aether.util.ConfigUtils;
081import org.slf4j.Logger;
082import org.slf4j.LoggerFactory;
083
084import static java.util.Objects.requireNonNull;
085
086/**
087 *
088 */
089@Singleton
090@Named
091public class DefaultArtifactResolver implements ArtifactResolver, Service {
092
093    /**
094     * Configuration to enable "snapshot normalization", downloaded snapshots from remote with timestamped file names
095     * will have file names converted back to baseVersion. Default: {@code true}.
096     */
097    private static final String CONFIG_PROP_SNAPSHOT_NORMALIZATION = "aether.artifactResolver.snapshotNormalization";
098
099    /**
100     * Configuration to enable "interoperability" with Simple LRM, but this breaks RRF feature, hence this configuration
101     * is IGNORED when RRF is used, and is warmly recommended to leave it disabled even if no RRF is being used.
102     * Default: {@code false}.
103     */
104    private static final String CONFIG_PROP_SIMPLE_LRM_INTEROP = "aether.artifactResolver.simpleLrmInterop";
105
106    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultArtifactResolver.class);
107
108    private FileProcessor fileProcessor;
109
110    private RepositoryEventDispatcher repositoryEventDispatcher;
111
112    private VersionResolver versionResolver;
113
114    private UpdateCheckManager updateCheckManager;
115
116    private RepositoryConnectorProvider repositoryConnectorProvider;
117
118    private RemoteRepositoryManager remoteRepositoryManager;
119
120    private SyncContextFactory syncContextFactory;
121
122    private OfflineController offlineController;
123
124    private Map<String, ArtifactResolverPostProcessor> artifactResolverPostProcessors;
125
126    private RemoteRepositoryFilterManager remoteRepositoryFilterManager;
127
128    public DefaultArtifactResolver() {
129        // enables default constructor
130    }
131
132    @SuppressWarnings("checkstyle:parameternumber")
133    @Inject
134    DefaultArtifactResolver(
135            FileProcessor fileProcessor,
136            RepositoryEventDispatcher repositoryEventDispatcher,
137            VersionResolver versionResolver,
138            UpdateCheckManager updateCheckManager,
139            RepositoryConnectorProvider repositoryConnectorProvider,
140            RemoteRepositoryManager remoteRepositoryManager,
141            SyncContextFactory syncContextFactory,
142            OfflineController offlineController,
143            Map<String, ArtifactResolverPostProcessor> artifactResolverPostProcessors,
144            RemoteRepositoryFilterManager remoteRepositoryFilterManager) {
145        setFileProcessor(fileProcessor);
146        setRepositoryEventDispatcher(repositoryEventDispatcher);
147        setVersionResolver(versionResolver);
148        setUpdateCheckManager(updateCheckManager);
149        setRepositoryConnectorProvider(repositoryConnectorProvider);
150        setRemoteRepositoryManager(remoteRepositoryManager);
151        setSyncContextFactory(syncContextFactory);
152        setOfflineController(offlineController);
153        setArtifactResolverPostProcessors(artifactResolverPostProcessors);
154        setRemoteRepositoryFilterManager(remoteRepositoryFilterManager);
155    }
156
157    public void initService(ServiceLocator locator) {
158        setFileProcessor(locator.getService(FileProcessor.class));
159        setRepositoryEventDispatcher(locator.getService(RepositoryEventDispatcher.class));
160        setVersionResolver(locator.getService(VersionResolver.class));
161        setUpdateCheckManager(locator.getService(UpdateCheckManager.class));
162        setRepositoryConnectorProvider(locator.getService(RepositoryConnectorProvider.class));
163        setRemoteRepositoryManager(locator.getService(RemoteRepositoryManager.class));
164        setSyncContextFactory(locator.getService(SyncContextFactory.class));
165        setOfflineController(locator.getService(OfflineController.class));
166        setArtifactResolverPostProcessors(Collections.emptyMap());
167        setRemoteRepositoryFilterManager(locator.getService(RemoteRepositoryFilterManager.class));
168    }
169
170    /**
171     * @deprecated not used any more since MRESOLVER-36 move to slf4j, added back in MRESOLVER-64 for compatibility
172     */
173    @Deprecated
174    public DefaultArtifactResolver setLoggerFactory(org.eclipse.aether.spi.log.LoggerFactory loggerFactory) {
175        // this.logger = NullLoggerFactory.getSafeLogger( loggerFactory, getClass() );
176        return this;
177    }
178
179    public DefaultArtifactResolver setFileProcessor(FileProcessor fileProcessor) {
180        this.fileProcessor = requireNonNull(fileProcessor, "file processor cannot be null");
181        return this;
182    }
183
184    public DefaultArtifactResolver setRepositoryEventDispatcher(RepositoryEventDispatcher repositoryEventDispatcher) {
185        this.repositoryEventDispatcher =
186                requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null");
187        return this;
188    }
189
190    public DefaultArtifactResolver setVersionResolver(VersionResolver versionResolver) {
191        this.versionResolver = requireNonNull(versionResolver, "version resolver cannot be null");
192        return this;
193    }
194
195    public DefaultArtifactResolver setUpdateCheckManager(UpdateCheckManager updateCheckManager) {
196        this.updateCheckManager = requireNonNull(updateCheckManager, "update check manager cannot be null");
197        return this;
198    }
199
200    public DefaultArtifactResolver setRepositoryConnectorProvider(
201            RepositoryConnectorProvider repositoryConnectorProvider) {
202        this.repositoryConnectorProvider =
203                requireNonNull(repositoryConnectorProvider, "repository connector provider cannot be null");
204        return this;
205    }
206
207    public DefaultArtifactResolver setRemoteRepositoryManager(RemoteRepositoryManager remoteRepositoryManager) {
208        this.remoteRepositoryManager =
209                requireNonNull(remoteRepositoryManager, "remote repository provider cannot be null");
210        return this;
211    }
212
213    public DefaultArtifactResolver setSyncContextFactory(SyncContextFactory syncContextFactory) {
214        this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null");
215        return this;
216    }
217
218    public DefaultArtifactResolver setOfflineController(OfflineController offlineController) {
219        this.offlineController = requireNonNull(offlineController, "offline controller cannot be null");
220        return this;
221    }
222
223    public DefaultArtifactResolver setArtifactResolverPostProcessors(
224            Map<String, ArtifactResolverPostProcessor> artifactResolverPostProcessors) {
225        this.artifactResolverPostProcessors =
226                requireNonNull(artifactResolverPostProcessors, "artifact resolver post-processors cannot be null");
227        return this;
228    }
229
230    public DefaultArtifactResolver setRemoteRepositoryFilterManager(
231            RemoteRepositoryFilterManager remoteRepositoryFilterManager) {
232        this.remoteRepositoryFilterManager =
233                requireNonNull(remoteRepositoryFilterManager, "remote repository filter manager cannot be null");
234        return this;
235    }
236
237    public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request)
238            throws ArtifactResolutionException {
239        requireNonNull(session, "session cannot be null");
240        requireNonNull(session, "session cannot be null");
241
242        return resolveArtifacts(session, Collections.singleton(request)).get(0);
243    }
244
245    public List<ArtifactResult> resolveArtifacts(
246            RepositorySystemSession session, Collection<? extends ArtifactRequest> requests)
247            throws ArtifactResolutionException {
248        requireNonNull(session, "session cannot be null");
249        requireNonNull(session, "session cannot be null");
250        try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) {
251            Collection<Artifact> artifacts = new ArrayList<>(requests.size());
252            for (ArtifactRequest request : requests) {
253                if (request.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null) != null) {
254                    continue;
255                }
256                artifacts.add(request.getArtifact());
257            }
258
259            syncContext.acquire(artifacts, null);
260
261            return resolve(session, requests);
262        }
263    }
264
265    @SuppressWarnings("checkstyle:methodlength")
266    private List<ArtifactResult> resolve(
267            RepositorySystemSession session, Collection<? extends ArtifactRequest> requests)
268            throws ArtifactResolutionException {
269        List<ArtifactResult> results = new ArrayList<>(requests.size());
270        boolean failures = false;
271        final boolean simpleLrmInterop = ConfigUtils.getBoolean(session, false, CONFIG_PROP_SIMPLE_LRM_INTEROP);
272
273        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
274        WorkspaceReader workspace = session.getWorkspaceReader();
275
276        List<ResolutionGroup> groups = new ArrayList<>();
277        // filter != null: means "filtering applied", if null no filtering applied (behave as before)
278        RemoteRepositoryFilter filter = remoteRepositoryFilterManager.getRemoteRepositoryFilter(session);
279
280        for (ArtifactRequest request : requests) {
281            RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
282
283            ArtifactResult result = new ArtifactResult(request);
284            results.add(result);
285
286            Artifact artifact = request.getArtifact();
287
288            artifactResolving(session, trace, artifact);
289
290            String localPath = artifact.getProperty(ArtifactProperties.LOCAL_PATH, null);
291            if (localPath != null) {
292                // unhosted artifact, just validate file
293                File file = new File(localPath);
294                if (!file.isFile()) {
295                    failures = true;
296                    result.addException(new ArtifactNotFoundException(artifact, null));
297                } else {
298                    artifact = artifact.setFile(file);
299                    result.setArtifact(artifact);
300                    artifactResolved(session, trace, artifact, null, result.getExceptions());
301                }
302                continue;
303            }
304
305            List<RemoteRepository> remoteRepositories = request.getRepositories();
306            List<RemoteRepository> filteredRemoteRepositories = new ArrayList<>(remoteRepositories);
307            if (filter != null) {
308                for (RemoteRepository repository : remoteRepositories) {
309                    RemoteRepositoryFilter.Result filterResult = filter.acceptArtifact(repository, artifact);
310                    if (!filterResult.isAccepted()) {
311                        result.addException(
312                                new ArtifactFilteredOutException(artifact, repository, filterResult.reasoning()));
313                        filteredRemoteRepositories.remove(repository);
314                    }
315                }
316            }
317
318            VersionResult versionResult;
319            try {
320                VersionRequest versionRequest =
321                        new VersionRequest(artifact, filteredRemoteRepositories, request.getRequestContext());
322                versionRequest.setTrace(trace);
323                versionResult = versionResolver.resolveVersion(session, versionRequest);
324            } catch (VersionResolutionException e) {
325                result.addException(e);
326                continue;
327            }
328
329            artifact = artifact.setVersion(versionResult.getVersion());
330
331            if (versionResult.getRepository() != null) {
332                if (versionResult.getRepository() instanceof RemoteRepository) {
333                    filteredRemoteRepositories =
334                            Collections.singletonList((RemoteRepository) versionResult.getRepository());
335                } else {
336                    filteredRemoteRepositories = Collections.emptyList();
337                }
338            }
339
340            if (workspace != null) {
341                File file = workspace.findArtifact(artifact);
342                if (file != null) {
343                    artifact = artifact.setFile(file);
344                    result.setArtifact(artifact);
345                    result.setRepository(workspace.getRepository());
346                    artifactResolved(session, trace, artifact, result.getRepository(), null);
347                    continue;
348                }
349            }
350
351            LocalArtifactResult local = lrm.find(
352                    session,
353                    new LocalArtifactRequest(artifact, filteredRemoteRepositories, request.getRequestContext()));
354            result.setLocalArtifactResult(local);
355            boolean found = (filter != null && local.isAvailable()) || isLocallyInstalled(local, versionResult);
356            // with filtering it is availability that drives logic
357            // without filtering it is simply presence of file that drives the logic
358            // "interop" logic with simple LRM leads to RRF breakage: hence is ignored when filtering in effect
359            if (found) {
360                if (local.getRepository() != null) {
361                    result.setRepository(local.getRepository());
362                } else {
363                    result.setRepository(lrm.getRepository());
364                }
365
366                try {
367                    artifact = artifact.setFile(getFile(session, artifact, local.getFile()));
368                    result.setArtifact(artifact);
369                    artifactResolved(session, trace, artifact, result.getRepository(), null);
370                } catch (ArtifactTransferException e) {
371                    result.addException(e);
372                }
373                if (filter == null && simpleLrmInterop && !local.isAvailable()) {
374                    /*
375                     * NOTE: Interop with simple local repository: An artifact installed by a simple local repo
376                     * manager will not show up in the repository tracking file of the enhanced local repository.
377                     * If however the maven-metadata-local.xml tells us the artifact was installed locally, we
378                     * sync the repository tracking file.
379                     */
380                    lrm.add(session, new LocalArtifactRegistration(artifact));
381                }
382
383                continue;
384            }
385
386            if (local.getFile() != null) {
387                LOGGER.info(
388                        "Artifact {} is present in the local repository, but cached from a remote repository ID that is unavailable in current build context, verifying that is downloadable from {}",
389                        artifact,
390                        remoteRepositories);
391            }
392
393            LOGGER.debug("Resolving artifact {} from {}", artifact, remoteRepositories);
394            AtomicBoolean resolved = new AtomicBoolean(false);
395            Iterator<ResolutionGroup> groupIt = groups.iterator();
396            for (RemoteRepository repo : filteredRemoteRepositories) {
397                if (!repo.getPolicy(artifact.isSnapshot()).isEnabled()) {
398                    continue;
399                }
400
401                try {
402                    Utils.checkOffline(session, offlineController, repo);
403                } catch (RepositoryOfflineException e) {
404                    Exception exception = new ArtifactNotFoundException(
405                            artifact,
406                            repo,
407                            "Cannot access " + repo.getId() + " ("
408                                    + repo.getUrl() + ") in offline mode and the artifact " + artifact
409                                    + " has not been downloaded from it before.",
410                            e);
411                    result.addException(exception);
412                    continue;
413                }
414
415                ResolutionGroup group = null;
416                while (groupIt.hasNext()) {
417                    ResolutionGroup t = groupIt.next();
418                    if (t.matches(repo)) {
419                        group = t;
420                        break;
421                    }
422                }
423                if (group == null) {
424                    group = new ResolutionGroup(repo);
425                    groups.add(group);
426                    groupIt = Collections.emptyIterator();
427                }
428                group.items.add(new ResolutionItem(trace, artifact, resolved, result, local, repo));
429            }
430        }
431
432        for (ResolutionGroup group : groups) {
433            performDownloads(session, group);
434        }
435
436        for (ArtifactResolverPostProcessor artifactResolverPostProcessor : artifactResolverPostProcessors.values()) {
437            artifactResolverPostProcessor.postProcess(session, results);
438        }
439
440        for (ArtifactResult result : results) {
441            ArtifactRequest request = result.getRequest();
442
443            Artifact artifact = result.getArtifact();
444            if (artifact == null || artifact.getFile() == null) {
445                failures = true;
446                if (result.getExceptions().isEmpty()) {
447                    Exception exception = new ArtifactNotFoundException(request.getArtifact(), null);
448                    result.addException(exception);
449                }
450                RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
451                artifactResolved(session, trace, request.getArtifact(), null, result.getExceptions());
452            }
453        }
454
455        if (failures) {
456            throw new ArtifactResolutionException(results);
457        }
458
459        return results;
460    }
461
462    private boolean isLocallyInstalled(LocalArtifactResult lar, VersionResult vr) {
463        if (lar.isAvailable()) {
464            return true;
465        }
466        if (lar.getFile() != null) {
467            if (vr.getRepository() instanceof LocalRepository) {
468                // resolution of (snapshot) version found locally installed artifact
469                return true;
470            } else if (vr.getRepository() == null
471                    && lar.getRequest().getRepositories().isEmpty()) {
472                // resolution of version range found locally installed artifact
473                return true;
474            }
475        }
476        return false;
477    }
478
479    private File getFile(RepositorySystemSession session, Artifact artifact, File file)
480            throws ArtifactTransferException {
481        if (artifact.isSnapshot()
482                && !artifact.getVersion().equals(artifact.getBaseVersion())
483                && ConfigUtils.getBoolean(session, true, CONFIG_PROP_SNAPSHOT_NORMALIZATION)) {
484            String name = file.getName().replace(artifact.getVersion(), artifact.getBaseVersion());
485            File dst = new File(file.getParent(), name);
486
487            boolean copy = dst.length() != file.length() || dst.lastModified() != file.lastModified();
488            if (copy) {
489                try {
490                    fileProcessor.copy(file, dst);
491                    dst.setLastModified(file.lastModified());
492                } catch (IOException e) {
493                    throw new ArtifactTransferException(artifact, null, e);
494                }
495            }
496
497            file = dst;
498        }
499
500        return file;
501    }
502
503    private void performDownloads(RepositorySystemSession session, ResolutionGroup group) {
504        List<ArtifactDownload> downloads = gatherDownloads(session, group);
505        if (downloads.isEmpty()) {
506            return;
507        }
508
509        for (ArtifactDownload download : downloads) {
510            artifactDownloading(session, download.getTrace(), download.getArtifact(), group.repository);
511        }
512
513        try {
514            try (RepositoryConnector connector =
515                    repositoryConnectorProvider.newRepositoryConnector(session, group.repository)) {
516                connector.get(downloads, null);
517            }
518        } catch (NoRepositoryConnectorException e) {
519            for (ArtifactDownload download : downloads) {
520                download.setException(new ArtifactTransferException(download.getArtifact(), group.repository, e));
521            }
522        }
523
524        evaluateDownloads(session, group);
525    }
526
527    private List<ArtifactDownload> gatherDownloads(RepositorySystemSession session, ResolutionGroup group) {
528        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
529        List<ArtifactDownload> downloads = new ArrayList<>();
530
531        for (ResolutionItem item : group.items) {
532            Artifact artifact = item.artifact;
533
534            if (item.resolved.get()) {
535                // resolved in previous resolution group
536                continue;
537            }
538
539            ArtifactDownload download = new ArtifactDownload();
540            download.setArtifact(artifact);
541            download.setRequestContext(item.request.getRequestContext());
542            download.setListener(SafeTransferListener.wrap(session));
543            download.setTrace(item.trace);
544            if (item.local.getFile() != null) {
545                download.setFile(item.local.getFile());
546                download.setExistenceCheck(true);
547            } else {
548                String path =
549                        lrm.getPathForRemoteArtifact(artifact, group.repository, item.request.getRequestContext());
550                download.setFile(new File(lrm.getRepository().getBasedir(), path));
551            }
552
553            boolean snapshot = artifact.isSnapshot();
554            RepositoryPolicy policy = remoteRepositoryManager.getPolicy(session, group.repository, !snapshot, snapshot);
555
556            int errorPolicy = Utils.getPolicy(session, artifact, group.repository);
557            if ((errorPolicy & ResolutionErrorPolicy.CACHE_ALL) != 0) {
558                UpdateCheck<Artifact, ArtifactTransferException> check = new UpdateCheck<>();
559                check.setItem(artifact);
560                check.setFile(download.getFile());
561                check.setFileValid(false);
562                check.setRepository(group.repository);
563                check.setPolicy(policy.getUpdatePolicy());
564                item.updateCheck = check;
565                updateCheckManager.checkArtifact(session, check);
566                if (!check.isRequired()) {
567                    item.result.addException(check.getException());
568                    continue;
569                }
570            }
571
572            download.setChecksumPolicy(policy.getChecksumPolicy());
573            download.setRepositories(item.repository.getMirroredRepositories());
574            downloads.add(download);
575            item.download = download;
576        }
577
578        return downloads;
579    }
580
581    private void evaluateDownloads(RepositorySystemSession session, ResolutionGroup group) {
582        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
583
584        for (ResolutionItem item : group.items) {
585            ArtifactDownload download = item.download;
586            if (download == null) {
587                continue;
588            }
589
590            Artifact artifact = download.getArtifact();
591            if (download.getException() == null) {
592                item.resolved.set(true);
593                item.result.setRepository(group.repository);
594                try {
595                    artifact = artifact.setFile(getFile(session, artifact, download.getFile()));
596                    item.result.setArtifact(artifact);
597
598                    lrm.add(
599                            session,
600                            new LocalArtifactRegistration(artifact, group.repository, download.getSupportedContexts()));
601                } catch (ArtifactTransferException e) {
602                    download.setException(e);
603                    item.result.addException(e);
604                }
605            } else {
606                item.result.addException(download.getException());
607            }
608
609            /*
610             * NOTE: Touch after registration with local repo to ensure concurrent resolution is not rejected with
611             * "already updated" via session data when actual update to local repo is still pending.
612             */
613            if (item.updateCheck != null) {
614                item.updateCheck.setException(download.getException());
615                updateCheckManager.touchArtifact(session, item.updateCheck);
616            }
617
618            artifactDownloaded(session, download.getTrace(), artifact, group.repository, download.getException());
619            if (download.getException() == null) {
620                artifactResolved(session, download.getTrace(), artifact, group.repository, null);
621            }
622        }
623    }
624
625    private void artifactResolving(RepositorySystemSession session, RequestTrace trace, Artifact artifact) {
626        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_RESOLVING);
627        event.setTrace(trace);
628        event.setArtifact(artifact);
629
630        repositoryEventDispatcher.dispatch(event.build());
631    }
632
633    private void artifactResolved(
634            RepositorySystemSession session,
635            RequestTrace trace,
636            Artifact artifact,
637            ArtifactRepository repository,
638            List<Exception> exceptions) {
639        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_RESOLVED);
640        event.setTrace(trace);
641        event.setArtifact(artifact);
642        event.setRepository(repository);
643        event.setExceptions(exceptions);
644        if (artifact != null) {
645            event.setFile(artifact.getFile());
646        }
647
648        repositoryEventDispatcher.dispatch(event.build());
649    }
650
651    private void artifactDownloading(
652            RepositorySystemSession session, RequestTrace trace, Artifact artifact, RemoteRepository repository) {
653        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_DOWNLOADING);
654        event.setTrace(trace);
655        event.setArtifact(artifact);
656        event.setRepository(repository);
657
658        repositoryEventDispatcher.dispatch(event.build());
659    }
660
661    private void artifactDownloaded(
662            RepositorySystemSession session,
663            RequestTrace trace,
664            Artifact artifact,
665            RemoteRepository repository,
666            Exception exception) {
667        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_DOWNLOADED);
668        event.setTrace(trace);
669        event.setArtifact(artifact);
670        event.setRepository(repository);
671        event.setException(exception);
672        if (artifact != null) {
673            event.setFile(artifact.getFile());
674        }
675
676        repositoryEventDispatcher.dispatch(event.build());
677    }
678
679    static class ResolutionGroup {
680
681        final RemoteRepository repository;
682
683        final List<ResolutionItem> items = new ArrayList<>();
684
685        ResolutionGroup(RemoteRepository repository) {
686            this.repository = repository;
687        }
688
689        boolean matches(RemoteRepository repo) {
690            return repository.getUrl().equals(repo.getUrl())
691                    && repository.getContentType().equals(repo.getContentType())
692                    && repository.isRepositoryManager() == repo.isRepositoryManager();
693        }
694    }
695
696    static class ResolutionItem {
697
698        final RequestTrace trace;
699
700        final ArtifactRequest request;
701
702        final ArtifactResult result;
703
704        final LocalArtifactResult local;
705
706        final RemoteRepository repository;
707
708        final Artifact artifact;
709
710        final AtomicBoolean resolved;
711
712        ArtifactDownload download;
713
714        UpdateCheck<Artifact, ArtifactTransferException> updateCheck;
715
716        ResolutionItem(
717                RequestTrace trace,
718                Artifact artifact,
719                AtomicBoolean resolved,
720                ArtifactResult result,
721                LocalArtifactResult local,
722                RemoteRepository repository) {
723            this.trace = trace;
724            this.artifact = artifact;
725            this.resolved = resolved;
726            this.result = result;
727            this.request = result.getRequest();
728            this.local = local;
729            this.repository = repository;
730        }
731    }
732}