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