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