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 submodules 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.computeIfAbsent(key, k -> new ArrayList<>());
362 
363             aliasedRepos.add(repository);
364         }
365 
366         List<ArtifactRepository> effectiveRepositories = new ArrayList<>();
367 
368         for (List<ArtifactRepository> aliasedRepos : reposByKey.values()) {
369             List<ArtifactRepository> mirroredRepos = new ArrayList<>();
370 
371             List<ArtifactRepositoryPolicy> releasePolicies = new ArrayList<>(aliasedRepos.size());
372 
373             for (ArtifactRepository aliasedRepo : aliasedRepos) {
374                 releasePolicies.add(aliasedRepo.getReleases());
375                 mirroredRepos.addAll(aliasedRepo.getMirroredRepositories());
376             }
377 
378             ArtifactRepositoryPolicy releasePolicy = getEffectivePolicy(releasePolicies);
379 
380             List<ArtifactRepositoryPolicy> snapshotPolicies = new ArrayList<>(aliasedRepos.size());
381 
382             for (ArtifactRepository aliasedRepo : aliasedRepos) {
383                 snapshotPolicies.add(aliasedRepo.getSnapshots());
384             }
385 
386             ArtifactRepositoryPolicy snapshotPolicy = getEffectivePolicy(snapshotPolicies);
387 
388             ArtifactRepository aliasedRepo = aliasedRepos.get(0);
389 
390             ArtifactRepository effectiveRepository = createArtifactRepository(
391                     aliasedRepo.getId(), aliasedRepo.getUrl(), aliasedRepo.getLayout(), snapshotPolicy, releasePolicy);
392 
393             effectiveRepository.setAuthentication(aliasedRepo.getAuthentication());
394 
395             effectiveRepository.setProxy(aliasedRepo.getProxy());
396 
397             effectiveRepository.setMirroredRepositories(mirroredRepos);
398 
399             effectiveRepository.setBlocked(aliasedRepo.isBlocked());
400 
401             effectiveRepositories.add(effectiveRepository);
402         }
403 
404         return effectiveRepositories;
405     }
406 
407     private ArtifactRepositoryPolicy getEffectivePolicy(Collection<ArtifactRepositoryPolicy> policies) {
408         ArtifactRepositoryPolicy effectivePolicy = null;
409 
410         for (ArtifactRepositoryPolicy policy : policies) {
411             if (effectivePolicy == null) {
412                 effectivePolicy = new ArtifactRepositoryPolicy(policy);
413             } else {
414                 effectivePolicy.merge(policy);
415             }
416         }
417 
418         return effectivePolicy;
419     }
420 
421     public Mirror getMirror(ArtifactRepository repository, List<Mirror> mirrors) {
422         return mirrorSelector.getMirror(repository, mirrors);
423     }
424 
425     public void injectMirror(List<ArtifactRepository> repositories, List<Mirror> mirrors) {
426         if (repositories != null && mirrors != null) {
427             for (ArtifactRepository repository : repositories) {
428                 Mirror mirror = getMirror(repository, mirrors);
429                 injectMirror(repository, mirror);
430             }
431         }
432     }
433 
434     private Mirror getMirror(RepositorySystemSession session, ArtifactRepository repository) {
435         if (session != null) {
436             org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector();
437             if (selector != null) {
438                 RemoteRepository repo = selector.getMirror(RepositoryUtils.toRepo(repository));
439                 if (repo != null) {
440                     Mirror mirror = new Mirror();
441                     mirror.setId(repo.getId());
442                     mirror.setUrl(repo.getUrl());
443                     mirror.setLayout(repo.getContentType());
444                     mirror.setBlocked(repo.isBlocked());
445                     return mirror;
446                 }
447             }
448         }
449         return null;
450     }
451 
452     public void injectMirror(RepositorySystemSession session, List<ArtifactRepository> repositories) {
453         if (repositories != null && session != null) {
454             for (ArtifactRepository repository : repositories) {
455                 Mirror mirror = getMirror(session, repository);
456                 injectMirror(repository, mirror);
457             }
458         }
459     }
460 
461     private void injectMirror(ArtifactRepository repository, Mirror mirror) {
462         if (mirror != null) {
463             ArtifactRepository original = createArtifactRepository(
464                     repository.getId(),
465                     repository.getUrl(),
466                     repository.getLayout(),
467                     repository.getSnapshots(),
468                     repository.getReleases());
469 
470             repository.setMirroredRepositories(Collections.singletonList(original));
471 
472             repository.setId(mirror.getId());
473             repository.setUrl(mirror.getUrl());
474 
475             if (StringUtils.isNotEmpty(mirror.getLayout())) {
476                 repository.setLayout(getLayout(mirror.getLayout()));
477             }
478 
479             repository.setBlocked(mirror.isBlocked());
480         }
481     }
482 
483     public void injectAuthentication(List<ArtifactRepository> repositories, List<Server> servers) {
484         if (repositories != null) {
485             Map<String, Server> serversById = new HashMap<>();
486 
487             if (servers != null) {
488                 for (Server server : servers) {
489                     if (!serversById.containsKey(server.getId())) {
490                         serversById.put(server.getId(), server);
491                     }
492                 }
493             }
494 
495             for (ArtifactRepository repository : repositories) {
496                 Server server = serversById.get(repository.getId());
497 
498                 if (server != null) {
499                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
500                     SettingsDecryptionResult result = settingsDecrypter.decrypt(request);
501                     server = result.getServer();
502 
503                     if (logger.isDebugEnabled()) {
504                         for (SettingsProblem problem : result.getProblems()) {
505                             logger.debug(problem.getMessage(), problem.getException());
506                         }
507                     }
508 
509                     Authentication authentication = new Authentication(server.getUsername(), server.getPassword());
510                     authentication.setPrivateKey(server.getPrivateKey());
511                     authentication.setPassphrase(server.getPassphrase());
512 
513                     repository.setAuthentication(authentication);
514                 } else {
515                     repository.setAuthentication(null);
516                 }
517             }
518         }
519     }
520 
521     private Authentication getAuthentication(RepositorySystemSession session, ArtifactRepository repository) {
522         if (session != null) {
523             AuthenticationSelector selector = session.getAuthenticationSelector();
524             if (selector != null) {
525                 RemoteRepository repo = RepositoryUtils.toRepo(repository);
526                 org.eclipse.aether.repository.Authentication auth = selector.getAuthentication(repo);
527                 if (auth != null) {
528                     repo = new RemoteRepository.Builder(repo)
529                             .setAuthentication(auth)
530                             .build();
531                     AuthenticationContext authCtx = AuthenticationContext.forRepository(session, repo);
532                     Authentication result = new Authentication(
533                             authCtx.get(AuthenticationContext.USERNAME), authCtx.get(AuthenticationContext.PASSWORD));
534                     result.setPrivateKey(authCtx.get(AuthenticationContext.PRIVATE_KEY_PATH));
535                     result.setPassphrase(authCtx.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE));
536                     authCtx.close();
537                     return result;
538                 }
539             }
540         }
541         return null;
542     }
543 
544     public void injectAuthentication(RepositorySystemSession session, List<ArtifactRepository> repositories) {
545         if (repositories != null && session != null) {
546             for (ArtifactRepository repository : repositories) {
547                 repository.setAuthentication(getAuthentication(session, repository));
548             }
549         }
550     }
551 
552     private org.apache.maven.settings.Proxy getProxy(
553             ArtifactRepository repository, List<org.apache.maven.settings.Proxy> proxies) {
554         if (proxies != null && repository.getProtocol() != null) {
555             for (org.apache.maven.settings.Proxy proxy : proxies) {
556                 if (proxy.isActive() && repository.getProtocol().equalsIgnoreCase(proxy.getProtocol())) {
557                     if (StringUtils.isNotEmpty(proxy.getNonProxyHosts())) {
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 (StringUtils.isEmpty(id)) {
687                 throw new InvalidRepositoryException("Repository identifier missing", "");
688             }
689 
690             String url = repo.getUrl();
691 
692             if (StringUtils.isEmpty(url)) {
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 (StringUtils.isNotEmpty(msg)) {
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 }