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.repository.legacy;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Collection;
25  import java.util.Collections;
26  import java.util.HashMap;
27  import java.util.LinkedHashMap;
28  import java.util.List;
29  import java.util.Map;
30  
31  import org.apache.maven.RepositoryUtils;
32  import org.apache.maven.artifact.Artifact;
33  import org.apache.maven.artifact.InvalidRepositoryException;
34  import org.apache.maven.artifact.factory.ArtifactFactory;
35  import org.apache.maven.artifact.metadata.ArtifactMetadata;
36  import org.apache.maven.artifact.repository.ArtifactRepository;
37  import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
38  import org.apache.maven.artifact.repository.Authentication;
39  import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
40  import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
41  import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
42  import org.apache.maven.artifact.resolver.ArtifactResolver;
43  import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
44  import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
45  import org.apache.maven.artifact.versioning.VersionRange;
46  import org.apache.maven.model.Dependency;
47  import org.apache.maven.model.Exclusion;
48  import org.apache.maven.model.Plugin;
49  import org.apache.maven.model.Repository;
50  import org.apache.maven.model.RepositoryPolicy;
51  import org.apache.maven.repository.ArtifactDoesNotExistException;
52  import org.apache.maven.repository.ArtifactTransferFailedException;
53  import org.apache.maven.repository.ArtifactTransferListener;
54  import org.apache.maven.repository.DelegatingLocalArtifactRepository;
55  import org.apache.maven.repository.LocalArtifactRepository;
56  import org.apache.maven.repository.MirrorSelector;
57  import org.apache.maven.repository.Proxy;
58  import org.apache.maven.repository.RepositorySystem;
59  import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory;
60  import org.apache.maven.settings.Mirror;
61  import org.apache.maven.settings.Server;
62  import org.apache.maven.settings.building.SettingsProblem;
63  import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
64  import org.apache.maven.settings.crypto.SettingsDecrypter;
65  import org.apache.maven.settings.crypto.SettingsDecryptionRequest;
66  import org.apache.maven.settings.crypto.SettingsDecryptionResult;
67  import org.apache.maven.wagon.proxy.ProxyInfo;
68  import org.apache.maven.wagon.proxy.ProxyUtils;
69  import org.codehaus.plexus.PlexusContainer;
70  import org.codehaus.plexus.component.annotations.Component;
71  import org.codehaus.plexus.component.annotations.Requirement;
72  import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
73  import org.codehaus.plexus.logging.Logger;
74  import org.codehaus.plexus.util.StringUtils;
75  import org.eclipse.aether.RepositorySystemSession;
76  import org.eclipse.aether.repository.AuthenticationContext;
77  import org.eclipse.aether.repository.AuthenticationSelector;
78  import org.eclipse.aether.repository.ProxySelector;
79  import org.eclipse.aether.repository.RemoteRepository;
80  
81  /**
82   * @author Jason van Zyl
83   */
84  @Component(role = RepositorySystem.class, hint = "default")
85  public class LegacyRepositorySystem implements RepositorySystem {
86  
87      @Requirement
88      private Logger logger;
89  
90      @Requirement
91      private ArtifactFactory artifactFactory;
92  
93      @Requirement
94      private ArtifactResolver artifactResolver;
95  
96      @Requirement
97      private ArtifactRepositoryFactory artifactRepositoryFactory;
98  
99      @Requirement(role = ArtifactRepositoryLayout.class)
100     private Map<String, ArtifactRepositoryLayout> layouts;
101 
102     @Requirement
103     private WagonManager wagonManager;
104 
105     @Requirement
106     private PlexusContainer plexus;
107 
108     @Requirement
109     private MirrorSelector mirrorSelector;
110 
111     @Requirement
112     private SettingsDecrypter settingsDecrypter;
113 
114     public Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) {
115         return artifactFactory.createArtifact(groupId, artifactId, version, scope, type);
116     }
117 
118     public Artifact createArtifact(String groupId, String artifactId, String version, String packaging) {
119         return artifactFactory.createBuildArtifact(groupId, artifactId, version, packaging);
120     }
121 
122     public Artifact createArtifactWithClassifier(
123             String groupId, String artifactId, String version, String type, String classifier) {
124         return artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);
125     }
126 
127     public Artifact createProjectArtifact(String groupId, String artifactId, String metaVersionId) {
128         return artifactFactory.createProjectArtifact(groupId, artifactId, metaVersionId);
129     }
130 
131     public Artifact createDependencyArtifact(Dependency d) {
132         VersionRange versionRange;
133         try {
134             versionRange = VersionRange.createFromVersionSpec(d.getVersion());
135         } catch (InvalidVersionSpecificationException e) {
136             // MNG-5368: Log a message instead of returning 'null' silently.
137             this.logger.error(
138                     String.format(
139                             "Invalid version specification '%s' creating dependency artifact '%s'.", d.getVersion(), d),
140                     e);
141             return null;
142         }
143 
144         Artifact artifact = artifactFactory.createDependencyArtifact(
145                 d.getGroupId(),
146                 d.getArtifactId(),
147                 versionRange,
148                 d.getType(),
149                 d.getClassifier(),
150                 d.getScope(),
151                 d.isOptional());
152 
153         if (Artifact.SCOPE_SYSTEM.equals(d.getScope()) && d.getSystemPath() != null) {
154             artifact.setFile(new File(d.getSystemPath()));
155         }
156 
157         if (!d.getExclusions().isEmpty()) {
158             List<String> exclusions = new ArrayList<>();
159 
160             for (Exclusion exclusion : d.getExclusions()) {
161                 exclusions.add(exclusion.getGroupId() + ':' + exclusion.getArtifactId());
162             }
163 
164             artifact.setDependencyFilter(new ExcludesArtifactFilter(exclusions));
165         }
166 
167         return artifact;
168     }
169 
170     public Artifact createExtensionArtifact(String groupId, String artifactId, String version) {
171         VersionRange versionRange;
172         try {
173             versionRange = VersionRange.createFromVersionSpec(version);
174         } catch (InvalidVersionSpecificationException e) {
175             // MNG-5368: Log a message instead of returning 'null' silently.
176             this.logger.error(
177                     String.format(
178                             "Invalid version specification '%s' creating extension artifact '%s:%s:%s'.",
179                             version, groupId, artifactId, version),
180                     e);
181 
182             return null;
183         }
184 
185         return artifactFactory.createExtensionArtifact(groupId, artifactId, versionRange);
186     }
187 
188     public Artifact createParentArtifact(String groupId, String artifactId, String version) {
189         return artifactFactory.createParentArtifact(groupId, artifactId, version);
190     }
191 
192     public Artifact createPluginArtifact(Plugin plugin) {
193         String version = plugin.getVersion();
194         if (StringUtils.isEmpty(version)) {
195             version = "RELEASE";
196         }
197 
198         VersionRange versionRange;
199         try {
200             versionRange = VersionRange.createFromVersionSpec(version);
201         } catch (InvalidVersionSpecificationException e) {
202             // MNG-5368: Log a message instead of returning 'null' silently.
203             this.logger.error(
204                     String.format("Invalid version specification '%s' creating plugin artifact '%s'.", version, plugin),
205                     e);
206 
207             return null;
208         }
209 
210         return artifactFactory.createPluginArtifact(plugin.getGroupId(), plugin.getArtifactId(), versionRange);
211     }
212 
213     public ArtifactRepositoryPolicy buildArtifactRepositoryPolicy(RepositoryPolicy policy) {
214         boolean enabled = true;
215 
216         String updatePolicy = null;
217 
218         String checksumPolicy = null;
219 
220         if (policy != null) {
221             enabled = policy.isEnabled();
222 
223             if (policy.getUpdatePolicy() != null) {
224                 updatePolicy = policy.getUpdatePolicy();
225             }
226             if (policy.getChecksumPolicy() != null) {
227                 checksumPolicy = policy.getChecksumPolicy();
228             }
229         }
230 
231         return new ArtifactRepositoryPolicy(enabled, updatePolicy, checksumPolicy);
232     }
233 
234     public ArtifactRepository createDefaultLocalRepository() throws InvalidRepositoryException {
235         return createLocalRepository(RepositorySystem.defaultUserLocalRepository);
236     }
237 
238     public ArtifactRepository createLocalRepository(File localRepository) throws InvalidRepositoryException {
239         return createRepository(
240                 "file://" + localRepository.toURI().getRawPath(),
241                 RepositorySystem.DEFAULT_LOCAL_REPO_ID,
242                 true,
243                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
244                 true,
245                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
246                 ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
247     }
248 
249     public ArtifactRepository createDefaultRemoteRepository() throws InvalidRepositoryException {
250         return createRepository(
251                 RepositorySystem.DEFAULT_REMOTE_REPO_URL,
252                 RepositorySystem.DEFAULT_REMOTE_REPO_ID,
253                 true,
254                 ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
255                 false,
256                 ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
257                 ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
258     }
259 
260     public ArtifactRepository createLocalRepository(String url, String repositoryId) throws IOException {
261         return createRepository(
262                 canonicalFileUrl(url),
263                 repositoryId,
264                 true,
265                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
266                 true,
267                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
268                 ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
269     }
270 
271     private String canonicalFileUrl(String url) throws IOException {
272         if (!url.startsWith("file:")) {
273             url = "file://" + url;
274         } else if (url.startsWith("file:") && !url.startsWith("file://")) {
275             url = "file://" + url.substring("file:".length());
276         }
277 
278         // So now we have an url of the form file://<path>
279 
280         // We want to eliminate any relative path nonsense and lock down the path so we
281         // need to fully resolve it before any sub-modules use the path. This can happen
282         // when you are using a custom settings.xml that contains a relative path entry
283         // for the local repository setting.
284 
285         File localRepository = new File(url.substring("file://".length()));
286 
287         if (!localRepository.isAbsolute()) {
288             url = "file://" + localRepository.getCanonicalPath();
289         }
290 
291         return url;
292     }
293 
294     public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) {
295         /*
296          * Probably is not worth it, but here I make sure I restore request
297          * to its original state.
298          */
299         try {
300             LocalArtifactRepository ideWorkspace =
301                     plexus.lookup(LocalArtifactRepository.class, LocalArtifactRepository.IDE_WORKSPACE);
302 
303             if (request.getLocalRepository() instanceof DelegatingLocalArtifactRepository) {
304                 DelegatingLocalArtifactRepository delegatingLocalRepository =
305                         (DelegatingLocalArtifactRepository) request.getLocalRepository();
306 
307                 LocalArtifactRepository orig = delegatingLocalRepository.getIdeWorkspace();
308 
309                 delegatingLocalRepository.setIdeWorkspace(ideWorkspace);
310 
311                 try {
312                     return artifactResolver.resolve(request);
313                 } finally {
314                     delegatingLocalRepository.setIdeWorkspace(orig);
315                 }
316             } else {
317                 ArtifactRepository localRepository = request.getLocalRepository();
318                 DelegatingLocalArtifactRepository delegatingLocalRepository =
319                         new DelegatingLocalArtifactRepository(localRepository);
320                 delegatingLocalRepository.setIdeWorkspace(ideWorkspace);
321                 request.setLocalRepository(delegatingLocalRepository);
322                 try {
323                     return artifactResolver.resolve(request);
324                 } finally {
325                     request.setLocalRepository(localRepository);
326                 }
327             }
328         } catch (ComponentLookupException e) {
329             // no ide workspace artifact resolution
330         }
331 
332         return artifactResolver.resolve(request);
333     }
334 
335     //    public void addProxy( String protocol, String host, int port, String username, String password,
336     //                          String nonProxyHosts )
337     //    {
338     //        ProxyInfo proxyInfo = new ProxyInfo();
339     //        proxyInfo.setHost( host );
340     //        proxyInfo.setType( protocol );
341     //        proxyInfo.setPort( port );
342     //        proxyInfo.setNonProxyHosts( nonProxyHosts );
343     //        proxyInfo.setUserName( username );
344     //        proxyInfo.setPassword( password );
345     //
346     //        proxies.put( protocol, proxyInfo );
347     //
348     //        wagonManager.addProxy( protocol, host, port, username, password, nonProxyHosts );
349     //    }
350 
351     public List<ArtifactRepository> getEffectiveRepositories(List<ArtifactRepository> repositories) {
352         if (repositories == null) {
353             return null;
354         }
355 
356         Map<String, List<ArtifactRepository>> reposByKey = new LinkedHashMap<>();
357 
358         for (ArtifactRepository repository : repositories) {
359             String key = repository.getId();
360 
361             List<ArtifactRepository> aliasedRepos = reposByKey.get(key);
362 
363             if (aliasedRepos == null) {
364                 aliasedRepos = new ArrayList<>();
365                 reposByKey.put(key, aliasedRepos);
366             }
367 
368             aliasedRepos.add(repository);
369         }
370 
371         List<ArtifactRepository> effectiveRepositories = new ArrayList<>();
372 
373         for (List<ArtifactRepository> aliasedRepos : reposByKey.values()) {
374             List<ArtifactRepository> mirroredRepos = new ArrayList<>();
375 
376             List<ArtifactRepositoryPolicy> releasePolicies = new ArrayList<>(aliasedRepos.size());
377 
378             for (ArtifactRepository aliasedRepo : aliasedRepos) {
379                 releasePolicies.add(aliasedRepo.getReleases());
380                 mirroredRepos.addAll(aliasedRepo.getMirroredRepositories());
381             }
382 
383             ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy(releasePolicies);
384 
385             List<ArtifactRepositoryPolicy> snapshotPolicies = new ArrayList<>(aliasedRepos.size());
386 
387             for (ArtifactRepository aliasedRepo : aliasedRepos) {
388                 snapshotPolicies.add(aliasedRepo.getSnapshots());
389             }
390 
391             ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy(snapshotPolicies);
392 
393             ArtifactRepository aliasedRepo = aliasedRepos.get(0);
394 
395             ArtifactRepository effectiveRepository = createArtifactRepository(
396                     aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), snapshotPolicy, releasePolicy);
397 
398             effectiveRepository.setAuthentication(aliasedRepo.getAuthentication());
399 
400             effectiveRepository.setProxy(aliasedRepo.getProxy());
401 
402             effectiveRepository.setMirroredRepositories(mirroredRepos);
403 
404             effectiveRepository.setBlocked(aliasedRepo.isBlocked());
405 
406             effectiveRepositories.add(effectiveRepository);
407         }
408 
409         return effectiveRepositories;
410     }
411 
412     private ArtifactRepositoryPolicy getEffectivePolicy(Collection<ArtifactRepositoryPolicy> policies) {
413         ArtifactRepositoryPolicy effectivePolicy = null;
414 
415         for (ArtifactRepositoryPolicy policy : policies) {
416             if (effectivePolicy == null) {
417                 effectivePolicy = new ArtifactRepositoryPolicy(policy);
418             } else {
419                 effectivePolicy.merge(policy);
420             }
421         }
422 
423         return effectivePolicy;
424     }
425 
426     public Mirror getMirror(ArtifactRepository repository, List<Mirror> mirrors) {
427         return mirrorSelector.getMirror(repository, mirrors);
428     }
429 
430     public void injectMirror(List<ArtifactRepository> repositories, List<Mirror> mirrors) {
431         if (repositories != null && mirrors != null) {
432             for (ArtifactRepository repository : repositories) {
433                 Mirror mirror = getMirror(repository, mirrors);
434                 injectMirror(repository, mirror);
435             }
436         }
437     }
438 
439     private Mirror getMirror(RepositorySystemSession session, ArtifactRepository repository) {
440         if (session != null) {
441             org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector();
442             if (selector != null) {
443                 RemoteRepository repo = selector.getMirror(RepositoryUtils.toRepo(repository));
444                 if (repo != null) {
445                     Mirror mirror = new Mirror();
446                     mirror.setId(repo.getId());
447                     mirror.setUrl(repo.getUrl());
448                     mirror.setLayout(repo.getContentType());
449                     mirror.setBlocked(repo.isBlocked());
450                     return mirror;
451                 }
452             }
453         }
454         return null;
455     }
456 
457     public void injectMirror(RepositorySystemSession session, List<ArtifactRepository> repositories) {
458         if (repositories != null && session != null) {
459             for (ArtifactRepository repository : repositories) {
460                 Mirror mirror = getMirror(session, repository);
461                 injectMirror(repository, mirror);
462             }
463         }
464     }
465 
466     private void injectMirror(ArtifactRepository repository, Mirror mirror) {
467         if (mirror != null) {
468             ArtifactRepository original = createArtifactRepository(
469                     repository.getId(),
470                     repository.getUrl(),
471                     repository.getLayout(),
472                     repository.getSnapshots(),
473                     repository.getReleases());
474 
475             repository.setMirroredRepositories(Collections.singletonList(original));
476 
477             repository.setId(mirror.getId());
478             repository.setUrl(mirror.getUrl());
479 
480             if (StringUtils.isNotEmpty(mirror.getLayout())) {
481                 repository.setLayout(getLayout(mirror.getLayout()));
482             }
483 
484             repository.setBlocked(mirror.isBlocked());
485         }
486     }
487 
488     public void injectAuthentication(List<ArtifactRepository> repositories, List<Server> servers) {
489         if (repositories != null) {
490             Map<String, Server> serversById = new HashMap<>();
491 
492             if (servers != null) {
493                 for (Server server : servers) {
494                     if (!serversById.containsKey(server.getId())) {
495                         serversById.put(server.getId(), server);
496                     }
497                 }
498             }
499 
500             for (ArtifactRepository repository : repositories) {
501                 Server server = serversById.get(repository.getId());
502 
503                 if (server != null) {
504                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
505                     SettingsDecryptionResult result = settingsDecrypter.decrypt(request);
506                     server = result.getServer();
507 
508                     if (logger.isDebugEnabled()) {
509                         for (SettingsProblem problem : result.getProblems()) {
510                             logger.debug(problem.getMessage(), problem.getException());
511                         }
512                     }
513 
514                     Authentication authentication = new Authentication(server.getUsername(), server.getPassword());
515                     authentication.setPrivateKey(server.getPrivateKey());
516                     authentication.setPassphrase(server.getPassphrase());
517 
518                     repository.setAuthentication(authentication);
519                 } else {
520                     repository.setAuthentication(null);
521                 }
522             }
523         }
524     }
525 
526     private Authentication getAuthentication(RepositorySystemSession session, ArtifactRepository repository) {
527         if (session != null) {
528             AuthenticationSelector selector = session.getAuthenticationSelector();
529             if (selector != null) {
530                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
531                 org.eclipse.aether.repository.Authentication auth = selector.getAuthentication(repo);
532                 if (auth != null) {
533                     repo = new RemoteRepository.Builder(repo)
534                             .setAuthentication(auth)
535                             .build();
536                     AuthenticationContext authCtx = AuthenticationContext.forRepository(session, repo);
537                     Authentication result = new Authentication(
538                             authCtx.get(AuthenticationContext.USERNAME), authCtx.get(AuthenticationContext.PASSWORD));
539                     result.setPrivateKey(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH));
540                     result.setPassphrase(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE));
541                     authCtx.close();
542                     return result;
543                 }
544             }
545         }
546         return null;
547     }
548 
549     public void injectAuthentication(RepositorySystemSession session, List<ArtifactRepository> repositories) {
550         if (repositories != null && session != null) {
551             for (ArtifactRepository repository : repositories) {
552                 repository.setAuthentication(getAuthentication(session, repository));
553             }
554         }
555     }
556 
557     private org.apache.maven.settings.Proxy getProxy(
558             ArtifactRepository repository, List<org.apache.maven.settings.Proxy> proxies) {
559         if (proxies != null && repository.getProtocol() != null) {
560             for (org.apache.maven.settings.Proxy proxy : proxies) {
561                 if (proxy.isActive() && repository.getProtocol().equalsIgnoreCase(proxy.getProtocol())) {
562                     if (StringUtils.isNotEmpty(proxy.getNonProxyHosts())) {
563                         ProxyInfo pi = new ProxyInfo();
564                         pi.setNonProxyHosts(proxy.getNonProxyHosts());
565 
566                         org.apache.maven.wagon.repository.Repository repo =
567                                 new org.apache.maven.wagon.repository.Repository(
568                                         repository.getId(), repository.getUrl());
569 
570                         if (!ProxyUtils.validateNonProxyHosts(pi, repo.getHost())) {
571                             return proxy;
572                         }
573                     } else {
574                         return proxy;
575                     }
576                 }
577             }
578         }
579 
580         return null;
581     }
582 
583     public void injectProxy(List<ArtifactRepository> repositories, List<org.apache.maven.settings.Proxy> proxies) {
584         if (repositories != null) {
585             for (ArtifactRepository repository : repositories) {
586                 org.apache.maven.settings.Proxy proxy = getProxy(repository, proxies);
587 
588                 if (proxy != null) {
589                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(proxy);
590                     SettingsDecryptionResult result = settingsDecrypter.decrypt(request);
591                     proxy = result.getProxy();
592 
593                     if (logger.isDebugEnabled()) {
594                         for (SettingsProblem problem : result.getProblems()) {
595                             logger.debug(problem.getMessage(), problem.getException());
596                         }
597                     }
598 
599                     Proxy p = new Proxy();
600                     p.setHost(proxy.getHost());
601                     p.setProtocol(proxy.getProtocol());
602                     p.setPort(proxy.getPort());
603                     p.setNonProxyHosts(proxy.getNonProxyHosts());
604                     p.setUserName(proxy.getUsername());
605                     p.setPassword(proxy.getPassword());
606 
607                     repository.setProxy(p);
608                 } else {
609                     repository.setProxy(null);
610                 }
611             }
612         }
613     }
614 
615     private Proxy getProxy(RepositorySystemSession session, ArtifactRepository repository) {
616         if (session != null) {
617             ProxySelector selector = session.getProxySelector();
618             if (selector != null) {
619                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
620                 org.eclipse.aether.repository.Proxy proxy = selector.getProxy(repo);
621                 if (proxy != null) {
622                     Proxy p = new Proxy();
623                     p.setHost(proxy.getHost());
624                     p.setProtocol(proxy.getType());
625                     p.setPort(proxy.getPort());
626                     if (proxy.getAuthentication() != null) {
627                         repo = new RemoteRepository.Builder(repo)
628                                 .setProxy(proxy)
629                                 .build();
630                         AuthenticationContext authCtx = AuthenticationContext.forProxy(session, repo);
631                         p.setUserName(authCtx.get(AuthenticationContext.USERNAME));
632                         p.setPassword(authCtx.get(AuthenticationContext.PASSWORD));
633                         p.setNtlmDomain(authCtx.get(AuthenticationContext.NTLM_DOMAIN));
634                         p.setNtlmHost(authCtx.get(AuthenticationContext.NTLM_WORKSTATION));
635                         authCtx.close();
636                     }
637                     return p;
638                 }
639             }
640         }
641         return null;
642     }
643 
644     public void injectProxy(RepositorySystemSession session, List<ArtifactRepository> repositories) {
645         if (repositories != null && session != null) {
646             for (ArtifactRepository repository : repositories) {
647                 repository.setProxy(getProxy(session, repository));
648             }
649         }
650     }
651 
652     public void retrieve(
653             ArtifactRepository repository,
654             File destination,
655             String remotePath,
656             ArtifactTransferListener transferListener)
657             throws ArtifactTransferFailedException, ArtifactDoesNotExistException {
658         try {
659             wagonManager.getRemoteFile(
660                     repository,
661                     destination,
662                     remotePath,
663                     TransferListenerAdapter.newAdapter(transferListener),
664                     ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN,
665                     true);
666         } catch (org.apache.maven.wagon.TransferFailedException e) {
667             throw new ArtifactTransferFailedException(getMessage(e, "Error transferring artifact."), e);
668         } catch (org.apache.maven.wagon.ResourceDoesNotExistException e) {
669             throw new ArtifactDoesNotExistException(getMessage(e, "Requested artifact does not exist."), e);
670         }
671     }
672 
673     public void publish(
674             ArtifactRepository repository, File source, String remotePath, ArtifactTransferListener transferListener)
675             throws ArtifactTransferFailedException {
676         try {
677             wagonManager.putRemoteFile(
678                     repository, source, remotePath, TransferListenerAdapter.newAdapter(transferListener));
679         } catch (org.apache.maven.wagon.TransferFailedException e) {
680             throw new ArtifactTransferFailedException(getMessage(e, "Error transferring artifact."), e);
681         }
682     }
683 
684     //
685     // Artifact Repository Creation
686     //
687     public ArtifactRepository buildArtifactRepository(Repository repo) throws InvalidRepositoryException {
688         if (repo != null) {
689             String id = repo.getId();
690 
691             if (StringUtils.isEmpty(id)) {
692                 throw new InvalidRepositoryException("Repository identifier missing", "");
693             }
694 
695             String url = repo.getUrl();
696 
697             if (StringUtils.isEmpty(url)) {
698                 throw new InvalidRepositoryException("URL missing for repository " + id, id);
699             }
700 
701             ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy(repo.getSnapshots());
702 
703             ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy(repo.getReleases());
704 
705             return createArtifactRepository(id, url, getLayout(repo.getLayout()), snapshots, releases);
706         } else {
707             return null;
708         }
709     }
710 
711     private ArtifactRepository createRepository(
712             String url,
713             String repositoryId,
714             boolean releases,
715             String releaseUpdates,
716             boolean snapshots,
717             String snapshotUpdates,
718             String checksumPolicy) {
719         ArtifactRepositoryPolicy snapshotsPolicy =
720                 new ArtifactRepositoryPolicy(snapshots, snapshotUpdates, checksumPolicy);
721 
722         ArtifactRepositoryPolicy releasesPolicy =
723                 new ArtifactRepositoryPolicy(releases, releaseUpdates, checksumPolicy);
724 
725         return createArtifactRepository(repositoryId, url, null, snapshotsPolicy, releasesPolicy);
726     }
727 
728     public ArtifactRepository createArtifactRepository(
729             String repositoryId,
730             String url,
731             ArtifactRepositoryLayout repositoryLayout,
732             ArtifactRepositoryPolicy snapshots,
733             ArtifactRepositoryPolicy releases) {
734         if (repositoryLayout == null) {
735             repositoryLayout = layouts.get("default");
736         }
737 
738         ArtifactRepository artifactRepository = artifactRepositoryFactory.createArtifactRepository(
739                 repositoryId, url, repositoryLayout, snapshots, releases);
740 
741         return artifactRepository;
742     }
743 
744     private static String getMessage(Throwable error, String def) {
745         if (error == null) {
746             return def;
747         }
748         String msg = error.getMessage();
749         if (StringUtils.isNotEmpty(msg)) {
750             return msg;
751         }
752         return getMessage(error.getCause(), def);
753     }
754 
755     private ArtifactRepositoryLayout getLayout(String id) {
756         ArtifactRepositoryLayout layout = layouts.get(id);
757 
758         if (layout == null) {
759             layout = new UnknownRepositoryLayout(id, layouts.get("default"));
760         }
761 
762         return layout;
763     }
764 
765     /**
766      * In the future, the legacy system might encounter repository types for which no layout components exists because
767      * the actual communication with the repository happens via a repository connector. As a minimum, the legacy system
768      * needs to retain the id of this layout so that the content type of the remote repository can still be accurately
769      * described.
770      */
771     static class UnknownRepositoryLayout implements ArtifactRepositoryLayout {
772 
773         private final String id;
774 
775         private final ArtifactRepositoryLayout fallback;
776 
777         UnknownRepositoryLayout(String id, ArtifactRepositoryLayout fallback) {
778             this.id = id;
779             this.fallback = fallback;
780         }
781 
782         public String getId() {
783             return id;
784         }
785 
786         public String pathOf(Artifact artifact) {
787             return fallback.pathOf(artifact);
788         }
789 
790         public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
791             return fallback.pathOfLocalRepositoryMetadata(metadata, repository);
792         }
793 
794         public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) {
795             return fallback.pathOfRemoteRepositoryMetadata(metadata);
796         }
797 
798         @Override
799         public String toString() {
800             return getId();
801         }
802     }
803 }