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