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.bridge;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.io.File;
26  import java.net.MalformedURLException;
27  import java.net.URL;
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.Collections;
31  import java.util.HashSet;
32  import java.util.LinkedHashMap;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.Properties;
36  import java.util.Set;
37  
38  import org.apache.maven.RepositoryUtils;
39  import org.apache.maven.artifact.Artifact;
40  import org.apache.maven.artifact.DefaultArtifact;
41  import org.apache.maven.artifact.InvalidRepositoryException;
42  import org.apache.maven.artifact.handler.ArtifactHandler;
43  import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
44  import org.apache.maven.artifact.metadata.ArtifactMetadata;
45  import org.apache.maven.artifact.repository.ArtifactRepository;
46  import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
47  import org.apache.maven.artifact.repository.Authentication;
48  import org.apache.maven.artifact.repository.MavenArtifactRepository;
49  import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
50  import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout2;
51  import org.apache.maven.artifact.resolver.filter.ExclusionArtifactFilter;
52  import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
53  import org.apache.maven.artifact.versioning.VersionRange;
54  import org.apache.maven.execution.MavenExecutionRequest;
55  import org.apache.maven.model.Dependency;
56  import org.apache.maven.model.Plugin;
57  import org.apache.maven.model.Repository;
58  import org.apache.maven.model.interpolation.ModelInterpolator;
59  import org.apache.maven.repository.Proxy;
60  import org.apache.maven.repository.RepositorySystem;
61  import org.apache.maven.settings.Mirror;
62  import org.codehaus.plexus.util.StringUtils;
63  import org.eclipse.aether.RepositorySystemSession;
64  import org.eclipse.aether.repository.AuthenticationContext;
65  import org.eclipse.aether.repository.AuthenticationSelector;
66  import org.eclipse.aether.repository.ProxySelector;
67  import org.eclipse.aether.repository.RemoteRepository;
68  import org.slf4j.Logger;
69  import org.slf4j.LoggerFactory;
70  
71  /**
72   * @author Jason van Zyl
73   * @since 3.2.3
74   */
75  @Singleton
76  @Named("default")
77  public class MavenRepositorySystem {
78  
79      // Singleton instance for static deprecated methods
80      private static MavenRepositorySystem instance;
81  
82      private static final Logger LOGGER = LoggerFactory.getLogger(MavenRepositorySystem.class);
83  
84      @Inject
85      private ArtifactHandlerManager artifactHandlerManager;
86  
87      @Inject
88      private Map<String, ArtifactRepositoryLayout> layouts;
89  
90      MavenRepositorySystem() {
91          instance = this;
92      }
93  
94      // DefaultProjectBuilder
95      public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) {
96          return createArtifactX(groupId, artifactId, version, scope, type);
97      }
98  
99      // DefaultProjectBuilder
100     public Artifact createProjectArtifact(String groupId, String artifactId, String metaVersionId) {
101         return createProjectArtifactX(groupId, artifactId, metaVersionId);
102     }
103 
104     // DefaultProjectBuilder
105     public Artifact createDependencyArtifact(Dependency d) {
106         if (d.getVersion() == null) {
107             return null;
108         }
109 
110         VersionRange versionRange;
111         try {
112             versionRange = VersionRange.createFromVersionSpec(d.getVersion());
113         } catch (InvalidVersionSpecificationException e) {
114             return null;
115         }
116 
117         Artifact artifact = createDependencyArtifactX(
118                 d.getGroupId(),
119                 d.getArtifactId(),
120                 versionRange,
121                 d.getType(),
122                 d.getClassifier(),
123                 d.getScope(),
124                 d.isOptional());
125 
126         if (Artifact.SCOPE_SYSTEM.equals(d.getScope()) && d.getSystemPath() != null) {
127             artifact.setFile(new File(d.getSystemPath()));
128         }
129 
130         if (!d.getExclusions().isEmpty()) {
131             artifact.setDependencyFilter(new ExclusionArtifactFilter(d.getExclusions()));
132         }
133 
134         return artifact;
135     }
136 
137     // DefaultProjectBuilder
138     public Artifact createExtensionArtifact(String groupId, String artifactId, String version) {
139         VersionRange versionRange;
140         try {
141             versionRange = VersionRange.createFromVersionSpec(version);
142         } catch (InvalidVersionSpecificationException e) {
143             return null;
144         }
145 
146         return createExtensionArtifactX(groupId, artifactId, versionRange);
147     }
148 
149     // DefaultProjectBuilder
150     public Artifact createParentArtifact(String groupId, String artifactId, String version) {
151         return createParentArtifactX(groupId, artifactId, version);
152     }
153 
154     // DefaultProjectBuilder
155     public Artifact createPluginArtifact(Plugin plugin) {
156         VersionRange versionRange;
157         try {
158             String version = plugin.getVersion();
159             if (StringUtils.isEmpty(version)) {
160                 version = "RELEASE";
161             }
162             versionRange = VersionRange.createFromVersionSpec(version);
163         } catch (InvalidVersionSpecificationException e) {
164             return null;
165         }
166 
167         return createPluginArtifactX(plugin.getGroupId(), plugin.getArtifactId(), versionRange);
168     }
169 
170     public void injectMirror(List<ArtifactRepository> repositories, List<Mirror> mirrors) {
171         if (repositories != null && mirrors != null) {
172             for (ArtifactRepository repository : repositories) {
173                 Mirror mirror = getMirror(repository, mirrors);
174                 injectMirror(repository, mirror);
175             }
176         }
177     }
178 
179     private Mirror getMirror(RepositorySystemSession session, ArtifactRepository repository) {
180         if (session != null) {
181             org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector();
182             if (selector != null) {
183                 RemoteRepository repo = selector.getMirror(RepositoryUtils.toRepo(repository));
184                 if (repo != null) {
185                     Mirror mirror = new Mirror();
186                     mirror.setId(repo.getId());
187                     mirror.setUrl(repo.getUrl());
188                     mirror.setLayout(repo.getContentType());
189                     mirror.setBlocked(repo.isBlocked());
190                     return mirror;
191                 }
192             }
193         }
194         return null;
195     }
196 
197     public void injectMirror(RepositorySystemSession session, List<ArtifactRepository> repositories) {
198         if (repositories != null && session != null) {
199             for (ArtifactRepository repository : repositories) {
200                 Mirror mirror = getMirror(session, repository);
201                 injectMirror(repository, mirror);
202             }
203         }
204     }
205 
206     private void injectMirror(ArtifactRepository repository, Mirror mirror) {
207         if (mirror != null) {
208             ArtifactRepository original = createArtifactRepository(
209                     repository.getId(),
210                     repository.getUrl(),
211                     repository.getLayout(),
212                     repository.getSnapshots(),
213                     repository.getReleases());
214 
215             repository.setMirroredRepositories(Collections.singletonList(original));
216 
217             repository.setId(mirror.getId());
218             repository.setUrl(mirror.getUrl());
219 
220             if (StringUtils.isNotEmpty(mirror.getLayout())) {
221                 repository.setLayout(getLayout(mirror.getId(), mirror.getLayout()));
222             }
223 
224             repository.setBlocked(mirror.isBlocked());
225         }
226     }
227 
228     private Authentication getAuthentication(RepositorySystemSession session, ArtifactRepository repository) {
229         if (session != null) {
230             AuthenticationSelector selector = session.getAuthenticationSelector();
231             if (selector != null) {
232                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
233                 org.eclipse.aether.repository.Authentication auth = selector.getAuthentication(repo);
234                 if (auth != null) {
235                     repo = new RemoteRepository.Builder(repo)
236                             .setAuthentication(auth)
237                             .build();
238                     try (AuthenticationContext authCtx = AuthenticationContext.forRepository(session, repo)) {
239                         Authentication result = new Authentication(
240                                 authCtx.get(AuthenticationContext.USERNAME),
241                                 authCtx.get(AuthenticationContext.PASSWORD));
242                         result.setPrivateKey(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH));
243                         result.setPassphrase(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE));
244                         return result;
245                     }
246                 }
247             }
248         }
249         return null;
250     }
251 
252     public void injectAuthentication(RepositorySystemSession session, List<ArtifactRepository> repositories) {
253         if (repositories != null && session != null) {
254             for (ArtifactRepository repository : repositories) {
255                 repository.setAuthentication(getAuthentication(session, repository));
256             }
257         }
258     }
259 
260     private Proxy getProxy(RepositorySystemSession session, ArtifactRepository repository) {
261         if (session != null) {
262             ProxySelector selector = session.getProxySelector();
263             if (selector != null) {
264                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
265                 org.eclipse.aether.repository.Proxy proxy = selector.getProxy(repo);
266                 if (proxy != null) {
267                     Proxy p = new Proxy();
268                     p.setHost(proxy.getHost());
269                     p.setProtocol(proxy.getType());
270                     p.setPort(proxy.getPort());
271                     if (proxy.getAuthentication() != null) {
272                         repo = new RemoteRepository.Builder(repo)
273                                 .setProxy(proxy)
274                                 .build();
275                         try (AuthenticationContext authCtx = AuthenticationContext.forProxy(session, repo)) {
276                             p.setUserName(authCtx.get(AuthenticationContext.USERNAME));
277                             p.setPassword(authCtx.get(AuthenticationContext.PASSWORD));
278                             p.setNtlmDomain(authCtx.get(AuthenticationContext.NTLM_DOMAIN));
279                             p.setNtlmHost(authCtx.get(AuthenticationContext.NTLM_WORKSTATION));
280                         }
281                     }
282                     return p;
283                 }
284             }
285         }
286         return null;
287     }
288 
289     public void injectProxy(RepositorySystemSession session, List<ArtifactRepository> repositories) {
290         if (repositories != null && session != null) {
291             for (ArtifactRepository repository : repositories) {
292                 repository.setProxy(getProxy(session, repository));
293             }
294         }
295     }
296 
297     private ArtifactRepositoryLayout getLayout(String repoId, String layoutId) {
298         ArtifactRepositoryLayout layout = layouts.get(layoutId);
299 
300         if (layout == null) {
301             LOGGER.debug("No layout '{}' found for repository id '{}'", layoutId, repoId);
302             layout = new UnknownRepositoryLayout(layoutId, layouts.get("default"));
303         }
304 
305         return layout;
306     }
307 
308     //
309     // Taken from LegacyRepositorySystem
310     //
311 
312     public static org.apache.maven.model.Repository fromSettingsRepository(
313             org.apache.maven.settings.Repository settingsRepository) {
314         org.apache.maven.model.Repository modelRepository = new org.apache.maven.model.Repository();
315         modelRepository.setId(settingsRepository.getId());
316         modelRepository.setLayout(settingsRepository.getLayout());
317         modelRepository.setName(settingsRepository.getName());
318         modelRepository.setUrl(settingsRepository.getUrl());
319         modelRepository.setReleases(fromSettingsRepositoryPolicy(settingsRepository.getReleases()));
320         modelRepository.setSnapshots(fromSettingsRepositoryPolicy(settingsRepository.getSnapshots()));
321         return modelRepository;
322     }
323 
324     public static org.apache.maven.model.RepositoryPolicy fromSettingsRepositoryPolicy(
325             org.apache.maven.settings.RepositoryPolicy settingsRepositoryPolicy) {
326         org.apache.maven.model.RepositoryPolicy modelRepositoryPolicy = new org.apache.maven.model.RepositoryPolicy();
327         if (settingsRepositoryPolicy != null) {
328             modelRepositoryPolicy.setEnabled(settingsRepositoryPolicy.isEnabled());
329             modelRepositoryPolicy.setUpdatePolicy(settingsRepositoryPolicy.getUpdatePolicy());
330             modelRepositoryPolicy.setChecksumPolicy(settingsRepositoryPolicy.getChecksumPolicy());
331         }
332         return modelRepositoryPolicy;
333     }
334 
335     /**
336      * @deprecated use a service method {@link #buildArtifactRepositoryFromRepo(org.apache.maven.settings.Repository)} instead
337      */
338     @Deprecated
339     public static ArtifactRepository buildArtifactRepository(org.apache.maven.settings.Repository repo)
340             throws InvalidRepositoryException {
341         return instance.buildArtifactRepositoryFromRepo(repo);
342     }
343 
344     /**
345      * @since 3.9.12
346      */
347     public ArtifactRepository buildArtifactRepositoryFromRepo(org.apache.maven.settings.Repository repo)
348             throws InvalidRepositoryException {
349         return buildArtifactRepositoryFromRepo(fromSettingsRepository(repo));
350     }
351 
352     /**
353      * @deprecated use a service method {@link #buildArtifactRepositoryFromRepo(Repository)} instead
354      */
355     @Deprecated
356     public static ArtifactRepository buildArtifactRepository(org.apache.maven.model.Repository repo)
357             throws InvalidRepositoryException {
358         return instance.buildArtifactRepositoryFromRepo(repo);
359     }
360 
361     /**
362      * @since 3.9.12
363      */
364     public ArtifactRepository buildArtifactRepositoryFromRepo(org.apache.maven.model.Repository repo)
365             throws InvalidRepositoryException {
366         if (repo != null) {
367             String id = repo.getId();
368 
369             if (StringUtils.isEmpty(id)) {
370                 throw new InvalidRepositoryException("Repository identifier missing", "");
371             }
372 
373             String url = repo.getUrl();
374 
375             if (StringUtils.isEmpty(url)) {
376                 throw new InvalidRepositoryException("URL missing for repository " + id, id);
377             }
378 
379             ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy(repo.getSnapshots());
380 
381             ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy(repo.getReleases());
382 
383             ArtifactRepositoryLayout layout = getLayout(repo.getId(), repo.getLayout());
384 
385             return createArtifactRepository(id, url, layout, snapshots, releases);
386         } else {
387             return null;
388         }
389     }
390 
391     public static ArtifactRepositoryPolicy buildArtifactRepositoryPolicy(
392             org.apache.maven.model.RepositoryPolicy policy) {
393         boolean enabled = true;
394 
395         String updatePolicy = null;
396 
397         String checksumPolicy = null;
398 
399         if (policy != null) {
400             enabled = policy.isEnabled();
401 
402             if (policy.getUpdatePolicy() != null) {
403                 updatePolicy = policy.getUpdatePolicy();
404             }
405             if (policy.getChecksumPolicy() != null) {
406                 checksumPolicy = policy.getChecksumPolicy();
407             }
408         }
409 
410         return new ArtifactRepositoryPolicy(enabled, updatePolicy, checksumPolicy);
411     }
412 
413     public ArtifactRepository createArtifactRepository(
414             String id,
415             String url,
416             String layoutId,
417             ArtifactRepositoryPolicy snapshots,
418             ArtifactRepositoryPolicy releases)
419             throws Exception {
420         ArtifactRepositoryLayout layout = layouts.get(layoutId);
421 
422         checkLayout(id, layoutId, layout);
423 
424         return createArtifactRepository(id, url, layout, snapshots, releases);
425     }
426 
427     private void checkLayout(String repositoryId, String layoutId, ArtifactRepositoryLayout layout) throws Exception {
428         if (layout == null) {
429             throw new Exception(
430                     String.format("Cannot find ArtifactRepositoryLayout instance for: %s %s", layoutId, repositoryId));
431         }
432     }
433 
434     public static ArtifactRepository createArtifactRepository(
435             String id,
436             String url,
437             ArtifactRepositoryLayout repositoryLayout,
438             ArtifactRepositoryPolicy snapshots,
439             ArtifactRepositoryPolicy releases) {
440         if (snapshots == null) {
441             snapshots = new ArtifactRepositoryPolicy();
442         }
443 
444         if (releases == null) {
445             releases = new ArtifactRepositoryPolicy();
446         }
447 
448         ArtifactRepository repository;
449         if (repositoryLayout instanceof ArtifactRepositoryLayout2) {
450             repository = ((ArtifactRepositoryLayout2) repositoryLayout)
451                     .newMavenArtifactRepository(id, url, snapshots, releases);
452         } else {
453             repository = new MavenArtifactRepository(id, url, repositoryLayout, snapshots, releases);
454         }
455 
456         return repository;
457     }
458 
459     // ArtifactFactory
460     private Artifact createArtifactX(String groupId, String artifactId, String version, String scope, String type) {
461         return createArtifactX(groupId, artifactId, version, scope, type, null, null);
462     }
463 
464     private Artifact createDependencyArtifactX(
465             String groupId,
466             String artifactId,
467             VersionRange versionRange,
468             String type,
469             String classifier,
470             String scope,
471             boolean optional) {
472         return createArtifactX(groupId, artifactId, versionRange, type, classifier, scope, null, optional);
473     }
474 
475     private Artifact createProjectArtifactX(String groupId, String artifactId, String version) {
476         return createProjectArtifactX(groupId, artifactId, version, null);
477     }
478 
479     private Artifact createParentArtifactX(String groupId, String artifactId, String version) {
480         return createProjectArtifactX(groupId, artifactId, version);
481     }
482 
483     private Artifact createPluginArtifactX(String groupId, String artifactId, VersionRange versionRange) {
484         return createArtifactX(groupId, artifactId, versionRange, "maven-plugin", null, Artifact.SCOPE_RUNTIME, null);
485     }
486 
487     private Artifact createProjectArtifactX(String groupId, String artifactId, String version, String scope) {
488         return createArtifactX(groupId, artifactId, version, scope, "pom");
489     }
490 
491     private Artifact createExtensionArtifactX(String groupId, String artifactId, VersionRange versionRange) {
492         return createArtifactX(groupId, artifactId, versionRange, "jar", null, Artifact.SCOPE_RUNTIME, null);
493     }
494 
495     private Artifact createArtifactX(
496             String groupId,
497             String artifactId,
498             String version,
499             String scope,
500             String type,
501             String classifier,
502             String inheritedScope) {
503         VersionRange versionRange = null;
504         if (version != null) {
505             versionRange = VersionRange.createFromVersion(version);
506         }
507         return createArtifactX(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope);
508     }
509 
510     private Artifact createArtifactX(
511             String groupId,
512             String artifactId,
513             VersionRange versionRange,
514             String type,
515             String classifier,
516             String scope,
517             String inheritedScope) {
518         return createArtifactX(groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, false);
519     }
520 
521     @SuppressWarnings("checkstyle:parameternumber")
522     private Artifact createArtifactX(
523             String groupId,
524             String artifactId,
525             VersionRange versionRange,
526             String type,
527             String classifier,
528             String scope,
529             String inheritedScope,
530             boolean optional) {
531         String desiredScope = Artifact.SCOPE_RUNTIME;
532 
533         if (inheritedScope == null) {
534             desiredScope = scope;
535         } else if (Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_PROVIDED.equals(scope)) {
536             return null;
537         } else if (Artifact.SCOPE_COMPILE.equals(scope) && Artifact.SCOPE_COMPILE.equals(inheritedScope)) {
538             // added to retain compile artifactScope. Remove if you want compile inherited as runtime
539             desiredScope = Artifact.SCOPE_COMPILE;
540         }
541 
542         if (Artifact.SCOPE_TEST.equals(inheritedScope)) {
543             desiredScope = Artifact.SCOPE_TEST;
544         }
545 
546         if (Artifact.SCOPE_PROVIDED.equals(inheritedScope)) {
547             desiredScope = Artifact.SCOPE_PROVIDED;
548         }
549 
550         if (Artifact.SCOPE_SYSTEM.equals(scope)) {
551             // system scopes come through unchanged...
552             desiredScope = Artifact.SCOPE_SYSTEM;
553         }
554 
555         ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type);
556 
557         return new DefaultArtifact(
558                 groupId, artifactId, versionRange, desiredScope, type, classifier, handler, optional);
559     }
560 
561     //
562     // Code taken from LegacyRepositorySystem
563     //
564 
565     public ArtifactRepository createDefaultRemoteRepository(MavenExecutionRequest request) throws Exception {
566         return createRepository(
567                 determineDefaultRemoteRepositoryUrl(request),
568                 RepositorySystem.DEFAULT_REMOTE_REPO_ID,
569                 true,
570                 ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
571                 false,
572                 ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
573                 ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
574     }
575 
576     private String determineDefaultRemoteRepositoryUrl(MavenExecutionRequest request) {
577         Properties effective = new Properties();
578         effective.putAll(request.getSystemProperties());
579         effective.putAll(request.getUserProperties());
580         return effective.getProperty(
581                 ModelInterpolator.MAVEN_REPO_CENTRAL_KEY, ModelInterpolator.DEFAULT_MAVEN_REPO_CENTRAL_URL);
582     }
583 
584     public ArtifactRepository createRepository(
585             String url,
586             String repositoryId,
587             boolean releases,
588             String releaseUpdates,
589             boolean snapshots,
590             String snapshotUpdates,
591             String checksumPolicy)
592             throws Exception {
593         ArtifactRepositoryPolicy snapshotsPolicy =
594                 new ArtifactRepositoryPolicy(snapshots, snapshotUpdates, checksumPolicy);
595 
596         ArtifactRepositoryPolicy releasesPolicy =
597                 new ArtifactRepositoryPolicy(releases, releaseUpdates, checksumPolicy);
598 
599         return createArtifactRepository(repositoryId, url, "default", snapshotsPolicy, releasesPolicy);
600     }
601 
602     public Set<String> getRepoIds(List<ArtifactRepository> repositories) {
603         Set<String> repoIds = new HashSet<>();
604 
605         if (repositories != null) {
606             for (ArtifactRepository repository : repositories) {
607                 repoIds.add(repository.getId());
608             }
609         }
610 
611         return repoIds;
612     }
613 
614     /**
615      * Source from org.apache.maven.repository.legacy.LegacyRepositorySystem#getEffectiveRepositories
616      *
617      * @param repositories
618      * @return
619      * @since 3.6.1
620      */
621     public List<ArtifactRepository> getEffectiveRepositories(List<ArtifactRepository> repositories) {
622         if (repositories == null) {
623             return null;
624         }
625 
626         Map<String, List<ArtifactRepository>> reposByKey = new LinkedHashMap<>();
627 
628         for (ArtifactRepository repository : repositories) {
629             String key = repository.getId();
630 
631             List<ArtifactRepository> aliasedRepos = reposByKey.get(key);
632 
633             if (aliasedRepos == null) {
634                 aliasedRepos = new ArrayList<>();
635                 reposByKey.put(key, aliasedRepos);
636             }
637 
638             aliasedRepos.add(repository);
639         }
640 
641         List<ArtifactRepository> effectiveRepositories = new ArrayList<>();
642 
643         for (List<ArtifactRepository> aliasedRepos : reposByKey.values()) {
644             List<ArtifactRepository> mirroredRepos = new ArrayList<>();
645 
646             List<ArtifactRepositoryPolicy> releasePolicies = new ArrayList<>(aliasedRepos.size());
647 
648             for (ArtifactRepository aliasedRepo : aliasedRepos) {
649                 releasePolicies.add(aliasedRepo.getReleases());
650                 mirroredRepos.addAll(aliasedRepo.getMirroredRepositories());
651             }
652 
653             ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy(releasePolicies);
654 
655             List<ArtifactRepositoryPolicy> snapshotPolicies = new ArrayList<>(aliasedRepos.size());
656 
657             for (ArtifactRepository aliasedRepo : aliasedRepos) {
658                 snapshotPolicies.add(aliasedRepo.getSnapshots());
659             }
660 
661             ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy(snapshotPolicies);
662 
663             ArtifactRepository aliasedRepo = aliasedRepos.get(0);
664 
665             ArtifactRepository effectiveRepository = createArtifactRepository(
666                     aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), snapshotPolicy, releasePolicy);
667 
668             effectiveRepository.setAuthentication(aliasedRepo.getAuthentication());
669 
670             effectiveRepository.setProxy(aliasedRepo.getProxy());
671 
672             effectiveRepository.setMirroredRepositories(mirroredRepos);
673 
674             effectiveRepository.setBlocked(aliasedRepo.isBlocked());
675 
676             effectiveRepositories.add(effectiveRepository);
677         }
678 
679         return effectiveRepositories;
680     }
681 
682     private ArtifactRepositoryPolicy getEffectivePolicy(Collection<ArtifactRepositoryPolicy> policies) {
683         ArtifactRepositoryPolicy effectivePolicy = null;
684 
685         for (ArtifactRepositoryPolicy policy : policies) {
686             if (effectivePolicy == null) {
687                 effectivePolicy = new ArtifactRepositoryPolicy(policy);
688             } else {
689                 effectivePolicy.merge(policy);
690             }
691         }
692 
693         return effectivePolicy;
694     }
695 
696     public ArtifactRepository createLocalRepository(MavenExecutionRequest request, File localRepository)
697             throws Exception {
698         return createRepository(
699                 "file://" + localRepository.toURI().getRawPath(),
700                 RepositorySystem.DEFAULT_LOCAL_REPO_ID,
701                 true,
702                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
703                 true,
704                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
705                 ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
706     }
707 
708     private static final String WILDCARD = "*";
709 
710     private static final String EXTERNAL_WILDCARD = "external:*";
711 
712     private static final String EXTERNAL_HTTP_WILDCARD = "external:http:*";
713 
714     public static Mirror getMirror(ArtifactRepository repository, List<Mirror> mirrors) {
715         String repoId = repository.getId();
716 
717         if (repoId != null && mirrors != null) {
718             for (Mirror mirror : mirrors) {
719                 if (repoId.equals(mirror.getMirrorOf()) && matchesLayout(repository, mirror)) {
720                     return mirror;
721                 }
722             }
723 
724             for (Mirror mirror : mirrors) {
725                 if (matchPattern(repository, mirror.getMirrorOf()) && matchesLayout(repository, mirror)) {
726                     return mirror;
727                 }
728             }
729         }
730 
731         return null;
732     }
733 
734     /**
735      * This method checks if the pattern matches the originalRepository. Valid patterns:
736      * <ul>
737      * <li>{@code *} (since 2.0.5)= everything,</li>
738      * <li>{@code external:*}  (since 2.0.9)= everything not on the localhost and not file based,</li>
739      * <li>{@code external:http:*} (since 3.8.0)= any repository not on the localhost using HTTP,</li>
740      * <li>{@code repo,repo1}  (since 2.0.9)= {@code repo} or {@code repo1},</li>
741      * <li>{@code *,!repo1} (since 2.0.9)= everything except {@code repo1}.</li>
742      * </ul>
743      *
744      * @param originalRepository to compare for a match.
745      * @param pattern used for match.
746      * @return true if the repository is a match to this pattern.
747      */
748     static boolean matchPattern(ArtifactRepository originalRepository, String pattern) {
749         boolean result = false;
750         String originalId = originalRepository.getId();
751 
752         // simple checks first to short circuit processing below.
753         if (WILDCARD.equals(pattern) || pattern.equals(originalId)) {
754             result = true;
755         } else {
756             // process the list
757             String[] repos = pattern.split(",");
758             for (String repo : repos) {
759                 // see if this is a negative match
760                 if (repo.length() > 1 && repo.startsWith("!")) {
761                     if (repo.substring(1).equals(originalId)) {
762                         // explicitly exclude. Set result and stop processing.
763                         result = false;
764                         break;
765                     }
766                 }
767                 // check for exact match
768                 else if (repo.equals(originalId)) {
769                     result = true;
770                     break;
771                 }
772                 // check for external:*
773                 else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) {
774                     result = true;
775                     // don't stop processing in case a future segment explicitly excludes this repo
776                 }
777                 // check for external:http:*
778                 else if (EXTERNAL_HTTP_WILDCARD.equals(repo) && isExternalHttpRepo(originalRepository)) {
779                     result = true;
780                     // don't stop processing in case a future segment explicitly excludes this repo
781                 } else if (WILDCARD.equals(repo)) {
782                     result = true;
783                     // don't stop processing in case a future segment explicitly excludes this repo
784                 }
785             }
786         }
787         return result;
788     }
789 
790     /**
791      * Checks the URL to see if this repository refers to an external repository
792      *
793      * @param originalRepository
794      * @return true if external.
795      */
796     static boolean isExternalRepo(ArtifactRepository originalRepository) {
797         try {
798             URL url = new URL(originalRepository.getUrl());
799             return !(isLocal(url.getHost()) || url.getProtocol().equals("file"));
800         } catch (MalformedURLException e) {
801             // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
802             return false;
803         }
804     }
805 
806     private static boolean isLocal(String host) {
807         return "localhost".equals(host) || "127.0.0.1".equals(host);
808     }
809 
810     /**
811      * Checks the URL to see if this repository refers to a non-localhost repository using HTTP.
812      *
813      * @param originalRepository
814      * @return true if external.
815      */
816     static boolean isExternalHttpRepo(ArtifactRepository originalRepository) {
817         try {
818             URL url = new URL(originalRepository.getUrl());
819             return ("http".equalsIgnoreCase(url.getProtocol())
820                             || "dav".equalsIgnoreCase(url.getProtocol())
821                             || "dav:http".equalsIgnoreCase(url.getProtocol())
822                             || "dav+http".equalsIgnoreCase(url.getProtocol()))
823                     && !isLocal(url.getHost());
824         } catch (MalformedURLException e) {
825             // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
826             return false;
827         }
828     }
829 
830     static boolean matchesLayout(ArtifactRepository repository, Mirror mirror) {
831         return matchesLayout(RepositoryUtils.getLayout(repository), mirror.getMirrorOfLayouts());
832     }
833 
834     /**
835      * Checks whether the layouts configured for a mirror match with the layout of the repository.
836      *
837      * @param repoLayout The layout of the repository, may be {@code null}.
838      * @param mirrorLayout The layouts supported by the mirror, may be {@code null}.
839      * @return {@code true} if the layouts associated with the mirror match the layout of the original repository,
840      *         {@code false} otherwise.
841      */
842     static boolean matchesLayout(String repoLayout, String mirrorLayout) {
843         boolean result = false;
844 
845         // simple checks first to short circuit processing below.
846         if (StringUtils.isEmpty(mirrorLayout) || WILDCARD.equals(mirrorLayout)) {
847             result = true;
848         } else if (mirrorLayout.equals(repoLayout)) {
849             result = true;
850         } else {
851             // process the list
852             String[] layouts = mirrorLayout.split(",");
853             for (String layout : layouts) {
854                 // see if this is a negative match
855                 if (layout.length() > 1 && layout.startsWith("!")) {
856                     if (layout.substring(1).equals(repoLayout)) {
857                         // explicitly exclude. Set result and stop processing.
858                         result = false;
859                         break;
860                     }
861                 }
862                 // check for exact match
863                 else if (layout.equals(repoLayout)) {
864                     result = true;
865                     break;
866                 } else if (WILDCARD.equals(layout)) {
867                     result = true;
868                     // don't stop processing in case a future segment explicitly excludes this repo
869                 }
870             }
871         }
872 
873         return result;
874     }
875 
876     /**
877      * In the future, the legacy system might encounter repository types for which no layout components exists because
878      * the actual communication with the repository happens via a repository connector. As a minimum, the legacy system
879      * needs to retain the id of this layout so that the content type of the remote repository can still be accurately
880      * described.
881      */
882     static class UnknownRepositoryLayout implements ArtifactRepositoryLayout {
883 
884         private final String id;
885 
886         private final ArtifactRepositoryLayout fallback;
887 
888         UnknownRepositoryLayout(String id, ArtifactRepositoryLayout fallback) {
889             this.id = id;
890             this.fallback = fallback;
891         }
892 
893         public String getId() {
894             return id;
895         }
896 
897         public String pathOf(Artifact artifact) {
898             return fallback.pathOf(artifact);
899         }
900 
901         public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
902             return fallback.pathOfLocalRepositoryMetadata(metadata, repository);
903         }
904 
905         public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) {
906             return fallback.pathOfRemoteRepositoryMetadata(metadata);
907         }
908 
909         @Override
910         public String toString() {
911             return getId();
912         }
913     }
914 }