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 delegatingLocalRepository) {
306                 LocalArtifactRepository orig = delegatingLocalRepository.getIdeWorkspace();
307 
308                 delegatingLocalRepository.setIdeWorkspace(ideWorkspace);
309 
310                 try {
311                     return artifactResolver.resolve(request);
312                 } finally {
313                     delegatingLocalRepository.setIdeWorkspace(orig);
314                 }
315             } else {
316                 ArtifactRepository localRepository = request.getLocalRepository();
317                 DelegatingLocalArtifactRepository delegatingLocalRepository =
318                         new DelegatingLocalArtifactRepository(localRepository);
319                 delegatingLocalRepository.setIdeWorkspace(ideWorkspace);
320                 request.setLocalRepository(delegatingLocalRepository);
321                 try {
322                     return artifactResolver.resolve(request);
323                 } finally {
324                     request.setLocalRepository(localRepository);
325                 }
326             }
327         } catch (ComponentLookupException e) {
328             // no ide workspace artifact resolution
329         }
330 
331         return artifactResolver.resolve(request);
332     }
333 
334     //    public void addProxy( String protocol, String host, int port, String username, String password,
335     //                          String nonProxyHosts )
336     //    {
337     //        ProxyInfo proxyInfo = new ProxyInfo();
338     //        proxyInfo.setHost( host );
339     //        proxyInfo.setType( protocol );
340     //        proxyInfo.setPort( port );
341     //        proxyInfo.setNonProxyHosts( nonProxyHosts );
342     //        proxyInfo.setUserName( username );
343     //        proxyInfo.setPassword( password );
344     //
345     //        proxies.put( protocol, proxyInfo );
346     //
347     //        wagonManager.addProxy( protocol, host, port, username, password, nonProxyHosts );
348     //    }
349 
350     public List<ArtifactRepository> getEffectiveRepositories(List<ArtifactRepository> repositories) {
351         if (repositories == null) {
352             return null;
353         }
354 
355         Map<String, List<ArtifactRepository>> reposByKey = new LinkedHashMap<>();
356 
357         for (ArtifactRepository repository : repositories) {
358             String key = repository.getId();
359 
360             List<ArtifactRepository> aliasedRepos = reposByKey.computeIfAbsent(key, k -> new ArrayList<>());
361 
362             aliasedRepos.add(repository);
363         }
364 
365         List<ArtifactRepository> effectiveRepositories = new ArrayList<>();
366 
367         for (List<ArtifactRepository> aliasedRepos : reposByKey.values()) {
368             List<ArtifactRepository> mirroredRepos = new ArrayList<>();
369 
370             List<ArtifactRepositoryPolicy> releasePolicies = new ArrayList<>(aliasedRepos.size());
371 
372             for (ArtifactRepository aliasedRepo : aliasedRepos) {
373                 releasePolicies.add(aliasedRepo.getReleases());
374                 mirroredRepos.addAll(aliasedRepo.getMirroredRepositories());
375             }
376 
377             ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy(releasePolicies);
378 
379             List<ArtifactRepositoryPolicy> snapshotPolicies = new ArrayList<>(aliasedRepos.size());
380 
381             for (ArtifactRepository aliasedRepo : aliasedRepos) {
382                 snapshotPolicies.add(aliasedRepo.getSnapshots());
383             }
384 
385             ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy(snapshotPolicies);
386 
387             ArtifactRepository aliasedRepo = aliasedRepos.get(0);
388 
389             ArtifactRepository effectiveRepository = createArtifactRepository(
390                     aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), snapshotPolicy, releasePolicy);
391 
392             effectiveRepository.setAuthentication(aliasedRepo.getAuthentication());
393 
394             effectiveRepository.setProxy(aliasedRepo.getProxy());
395 
396             effectiveRepository.setMirroredRepositories(mirroredRepos);
397 
398             effectiveRepository.setBlocked(aliasedRepo.isBlocked());
399 
400             effectiveRepositories.add(effectiveRepository);
401         }
402 
403         return effectiveRepositories;
404     }
405 
406     private ArtifactRepositoryPolicy getEffectivePolicy(Collection<ArtifactRepositoryPolicy> policies) {
407         ArtifactRepositoryPolicy effectivePolicy = null;
408 
409         for (ArtifactRepositoryPolicy policy : policies) {
410             if (effectivePolicy == null) {
411                 effectivePolicy = new ArtifactRepositoryPolicy(policy);
412             } else {
413                 effectivePolicy.merge(policy);
414             }
415         }
416 
417         return effectivePolicy;
418     }
419 
420     public Mirror getMirror(ArtifactRepository repository, List<Mirror> mirrors) {
421         return mirrorSelector.getMirror(repository, mirrors);
422     }
423 
424     public void injectMirror(List<ArtifactRepository> repositories, List<Mirror> mirrors) {
425         if (repositories != null && mirrors != null) {
426             for (ArtifactRepository repository : repositories) {
427                 Mirror mirror = getMirror(repository, mirrors);
428                 injectMirror(repository, mirror);
429             }
430         }
431     }
432 
433     private Mirror getMirror(RepositorySystemSession session, ArtifactRepository repository) {
434         if (session != null) {
435             org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector();
436             if (selector != null) {
437                 RemoteRepository repo = selector.getMirror(RepositoryUtils.toRepo(repository));
438                 if (repo != null) {
439                     Mirror mirror = new Mirror();
440                     mirror.setId(repo.getId());
441                     mirror.setUrl(repo.getUrl());
442                     mirror.setLayout(repo.getContentType());
443                     mirror.setBlocked(repo.isBlocked());
444                     return mirror;
445                 }
446             }
447         }
448         return null;
449     }
450 
451     public void injectMirror(RepositorySystemSession session, List<ArtifactRepository> repositories) {
452         if (repositories != null && session != null) {
453             for (ArtifactRepository repository : repositories) {
454                 Mirror mirror = getMirror(session, repository);
455                 injectMirror(repository, mirror);
456             }
457         }
458     }
459 
460     private void injectMirror(ArtifactRepository repository, Mirror mirror) {
461         if (mirror != null) {
462             ArtifactRepository original = createArtifactRepository(
463                     repository.getId(),
464                     repository.getUrl(),
465                     repository.getLayout(),
466                     repository.getSnapshots(),
467                     repository.getReleases());
468 
469             repository.setMirroredRepositories(Collections.singletonList(original));
470 
471             repository.setId(mirror.getId());
472             repository.setUrl(mirror.getUrl());
473 
474             if (mirror.getLayout() != null && !mirror.getLayout().isEmpty()) {
475                 repository.setLayout(getLayout(mirror.getLayout()));
476             }
477 
478             repository.setBlocked(mirror.isBlocked());
479         }
480     }
481 
482     public void injectAuthentication(List<ArtifactRepository> repositories, List<Server> servers) {
483         if (repositories != null) {
484             Map<String, Server> serversById = new HashMap<>();
485 
486             if (servers != null) {
487                 for (Server server : servers) {
488                     if (!serversById.containsKey(server.getId())) {
489                         serversById.put(server.getId(), server);
490                     }
491                 }
492             }
493 
494             for (ArtifactRepository repository : repositories) {
495                 Server server = serversById.get(repository.getId());
496 
497                 if (server != null) {
498                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
499                     SettingsDecryptionResult result = settingsDecrypter.decrypt(request);
500                     server = result.getServer();
501 
502                     if (logger.isDebugEnabled()) {
503                         for (SettingsProblem problem : result.getProblems()) {
504                             logger.debug(problem.getMessage(), problem.getException());
505                         }
506                     }
507 
508                     Authentication authentication = new Authentication(server.getUsername(), server.getPassword());
509                     authentication.setPrivateKey(server.getPrivateKey());
510                     authentication.setPassphrase(server.getPassphrase());
511 
512                     repository.setAuthentication(authentication);
513                 } else {
514                     repository.setAuthentication(null);
515                 }
516             }
517         }
518     }
519 
520     private Authentication getAuthentication(RepositorySystemSession session, ArtifactRepository repository) {
521         if (session != null) {
522             AuthenticationSelector selector = session.getAuthenticationSelector();
523             if (selector != null) {
524                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
525                 org.eclipse.aether.repository.Authentication auth = selector.getAuthentication(repo);
526                 if (auth != null) {
527                     repo = new RemoteRepository.Builder(repo)
528                             .setAuthentication(auth)
529                             .build();
530                     AuthenticationContext authCtx = AuthenticationContext.forRepository(session, repo);
531                     Authentication result = new Authentication(
532                             authCtx.get(AuthenticationContext.USERNAME), authCtx.get(AuthenticationContext.PASSWORD));
533                     result.setPrivateKey(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH));
534                     result.setPassphrase(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE));
535                     authCtx.close();
536                     return result;
537                 }
538             }
539         }
540         return null;
541     }
542 
543     public void injectAuthentication(RepositorySystemSession session, List<ArtifactRepository> repositories) {
544         if (repositories != null && session != null) {
545             for (ArtifactRepository repository : repositories) {
546                 repository.setAuthentication(getAuthentication(session, repository));
547             }
548         }
549     }
550 
551     private org.apache.maven.settings.Proxy getProxy(
552             ArtifactRepository repository, List<org.apache.maven.settings.Proxy> proxies) {
553         if (proxies != null && repository.getProtocol() != null) {
554             for (org.apache.maven.settings.Proxy proxy : proxies) {
555                 if (proxy.isActive() && repository.getProtocol().equalsIgnoreCase(proxy.getProtocol())) {
556                     if (proxy.getNonProxyHosts() != null
557                             && !proxy.getNonProxyHosts().isEmpty()) {
558                         ProxyInfo pi = new ProxyInfo();
559                         pi.setNonProxyHosts(proxy.getNonProxyHosts());
560 
561                         org.apache.maven.wagon.repository.Repository repo =
562                                 new org.apache.maven.wagon.repository.Repository(
563                                         repository.getId(), repository.getUrl());
564 
565                         if (!ProxyUtils.validateNonProxyHosts(pi, repo.getHost())) {
566                             return proxy;
567                         }
568                     } else {
569                         return proxy;
570                     }
571                 }
572             }
573         }
574 
575         return null;
576     }
577 
578     public void injectProxy(List<ArtifactRepository> repositories, List<org.apache.maven.settings.Proxy> proxies) {
579         if (repositories != null) {
580             for (ArtifactRepository repository : repositories) {
581                 org.apache.maven.settings.Proxy proxy = getProxy(repository, proxies);
582 
583                 if (proxy != null) {
584                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(proxy);
585                     SettingsDecryptionResult result = settingsDecrypter.decrypt(request);
586                     proxy = result.getProxy();
587 
588                     if (logger.isDebugEnabled()) {
589                         for (SettingsProblem problem : result.getProblems()) {
590                             logger.debug(problem.getMessage(), problem.getException());
591                         }
592                     }
593 
594                     Proxy p = new Proxy();
595                     p.setHost(proxy.getHost());
596                     p.setProtocol(proxy.getProtocol());
597                     p.setPort(proxy.getPort());
598                     p.setNonProxyHosts(proxy.getNonProxyHosts());
599                     p.setUserName(proxy.getUsername());
600                     p.setPassword(proxy.getPassword());
601 
602                     repository.setProxy(p);
603                 } else {
604                     repository.setProxy(null);
605                 }
606             }
607         }
608     }
609 
610     private Proxy getProxy(RepositorySystemSession session, ArtifactRepository repository) {
611         if (session != null) {
612             ProxySelector selector = session.getProxySelector();
613             if (selector != null) {
614                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
615                 org.eclipse.aether.repository.Proxy proxy = selector.getProxy(repo);
616                 if (proxy != null) {
617                     Proxy p = new Proxy();
618                     p.setHost(proxy.getHost());
619                     p.setProtocol(proxy.getType());
620                     p.setPort(proxy.getPort());
621                     if (proxy.getAuthentication() != null) {
622                         repo = new RemoteRepository.Builder(repo)
623                                 .setProxy(proxy)
624                                 .build();
625                         AuthenticationContext authCtx = AuthenticationContext.forProxy(session, repo);
626                         p.setUserName(authCtx.get(AuthenticationContext.USERNAME));
627                         p.setPassword(authCtx.get(AuthenticationContext.PASSWORD));
628                         p.setNtlmDomain(authCtx.get(AuthenticationContext.NTLM_DOMAIN));
629                         p.setNtlmHost(authCtx.get(AuthenticationContext.NTLM_WORKSTATION));
630                         authCtx.close();
631                     }
632                     return p;
633                 }
634             }
635         }
636         return null;
637     }
638 
639     public void injectProxy(RepositorySystemSession session, List<ArtifactRepository> repositories) {
640         if (repositories != null && session != null) {
641             for (ArtifactRepository repository : repositories) {
642                 repository.setProxy(getProxy(session, repository));
643             }
644         }
645     }
646 
647     public void retrieve(
648             ArtifactRepository repository,
649             File destination,
650             String remotePath,
651             ArtifactTransferListener transferListener)
652             throws ArtifactTransferFailedException, ArtifactDoesNotExistException {
653         try {
654             wagonManager.getRemoteFile(
655                     repository,
656                     destination,
657                     remotePath,
658                     TransferListenerAdapter.newAdapter(transferListener),
659                     ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN,
660                     true);
661         } catch (org.apache.maven.wagon.TransferFailedException e) {
662             throw new ArtifactTransferFailedException(getMessage(e, "Error transferring artifact."), e);
663         } catch (org.apache.maven.wagon.ResourceDoesNotExistException e) {
664             throw new ArtifactDoesNotExistException(getMessage(e, "Requested artifact does not exist."), e);
665         }
666     }
667 
668     public void publish(
669             ArtifactRepository repository, File source, String remotePath, ArtifactTransferListener transferListener)
670             throws ArtifactTransferFailedException {
671         try {
672             wagonManager.putRemoteFile(
673                     repository, source, remotePath, TransferListenerAdapter.newAdapter(transferListener));
674         } catch (org.apache.maven.wagon.TransferFailedException e) {
675             throw new ArtifactTransferFailedException(getMessage(e, "Error transferring artifact."), e);
676         }
677     }
678 
679     //
680     // Artifact Repository Creation
681     //
682     public ArtifactRepository buildArtifactRepository(Repository repo) throws InvalidRepositoryException {
683         if (repo != null) {
684             String id = repo.getId();
685 
686             if (id == null || id.isEmpty()) {
687                 throw new InvalidRepositoryException("Repository identifier missing", "");
688             }
689 
690             String url = repo.getUrl();
691 
692             if (url == null || url.isEmpty()) {
693                 throw new InvalidRepositoryException("URL missing for repository " + id, id);
694             }
695 
696             ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy(repo.getSnapshots());
697 
698             ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy(repo.getReleases());
699 
700             return createArtifactRepository(id, url, getLayout(repo.getLayout()), snapshots, releases);
701         } else {
702             return null;
703         }
704     }
705 
706     private ArtifactRepository createRepository(
707             String url,
708             String repositoryId,
709             boolean releases,
710             String releaseUpdates,
711             boolean snapshots,
712             String snapshotUpdates,
713             String checksumPolicy) {
714         ArtifactRepositoryPolicy snapshotsPolicy =
715                 new ArtifactRepositoryPolicy(snapshots, snapshotUpdates, checksumPolicy);
716 
717         ArtifactRepositoryPolicy releasesPolicy =
718                 new ArtifactRepositoryPolicy(releases, releaseUpdates, checksumPolicy);
719 
720         return createArtifactRepository(repositoryId, url, null, snapshotsPolicy, releasesPolicy);
721     }
722 
723     public ArtifactRepository createArtifactRepository(
724             String repositoryId,
725             String url,
726             ArtifactRepositoryLayout repositoryLayout,
727             ArtifactRepositoryPolicy snapshots,
728             ArtifactRepositoryPolicy releases) {
729         if (repositoryLayout == null) {
730             repositoryLayout = layouts.get("default");
731         }
732         return artifactRepositoryFactory.createArtifactRepository(
733                 repositoryId, url, repositoryLayout, snapshots, releases);
734     }
735 
736     private static String getMessage(Throwable error, String def) {
737         if (error == null) {
738             return def;
739         }
740         String msg = error.getMessage();
741         if (msg != null && !msg.isEmpty()) {
742             return msg;
743         }
744         return getMessage(error.getCause(), def);
745     }
746 
747     private ArtifactRepositoryLayout getLayout(String id) {
748         ArtifactRepositoryLayout layout = layouts.get(id);
749 
750         if (layout == null) {
751             layout = new UnknownRepositoryLayout(id, layouts.get("default"));
752         }
753 
754         return layout;
755     }
756 
757     /**
758      * In the future, the legacy system might encounter repository types for which no layout components exists because
759      * the actual communication with the repository happens via a repository connector. As a minimum, the legacy system
760      * needs to retain the id of this layout so that the content type of the remote repository can still be accurately
761      * described.
762      */
763     static class UnknownRepositoryLayout implements ArtifactRepositoryLayout {
764 
765         private final String id;
766 
767         private final ArtifactRepositoryLayout fallback;
768 
769         UnknownRepositoryLayout(String id, ArtifactRepositoryLayout fallback) {
770             this.id = id;
771             this.fallback = fallback;
772         }
773 
774         public String getId() {
775             return id;
776         }
777 
778         public String pathOf(Artifact artifact) {
779             return fallback.pathOf(artifact);
780         }
781 
782         public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
783             return fallback.pathOfLocalRepositoryMetadata(metadata, repository);
784         }
785 
786         public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) {
787             return fallback.pathOfRemoteRepositoryMetadata(metadata);
788         }
789 
790         @Override
791         public String toString() {
792             return getId();
793         }
794     }
795 }