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             effectiveRepositories.add( effectiveRepository );
450         }
451 
452         return effectiveRepositories;
453     }
454 
455     private ArtifactRepositoryPolicy getEffectivePolicy( Collection<ArtifactRepositoryPolicy> policies )
456     {
457         ArtifactRepositoryPolicy effectivePolicy = null;
458 
459         for ( ArtifactRepositoryPolicy policy : policies )
460         {
461             if ( effectivePolicy == null )
462             {
463                 effectivePolicy = new ArtifactRepositoryPolicy( policy );
464             }
465             else
466             {
467                 effectivePolicy.merge( policy );
468             }
469         }
470 
471         return effectivePolicy;
472     }
473 
474     public Mirror getMirror( ArtifactRepository repository, List<Mirror> mirrors )
475     {
476         return mirrorSelector.getMirror( repository, mirrors );
477     }
478 
479     public void injectMirror( List<ArtifactRepository> repositories, List<Mirror> mirrors )
480     {
481         if ( repositories != null && mirrors != null )
482         {
483             for ( ArtifactRepository repository : repositories )
484             {
485                 Mirror mirror = getMirror( repository, mirrors );
486                 injectMirror( repository, mirror );
487             }
488         }
489     }
490 
491     private Mirror getMirror( RepositorySystemSession session, ArtifactRepository repository )
492     {
493         if ( session != null )
494         {
495             org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector();
496             if ( selector != null )
497             {
498                 RemoteRepository repo = selector.getMirror( RepositoryUtils.toRepo( repository ) );
499                 if ( repo != null )
500                 {
501                     Mirror mirror = new Mirror();
502                     mirror.setId( repo.getId() );
503                     mirror.setUrl( repo.getUrl() );
504                     mirror.setLayout( repo.getContentType() );
505                     return mirror;
506                 }
507             }
508         }
509         return null;
510     }
511 
512     public void injectMirror( RepositorySystemSession session, List<ArtifactRepository> repositories )
513     {
514         if ( repositories != null && session != null )
515         {
516             for ( ArtifactRepository repository : repositories )
517             {
518                 Mirror mirror = getMirror( session, repository );
519                 injectMirror( repository, mirror );
520             }
521         }
522     }
523 
524     private void injectMirror( ArtifactRepository repository, Mirror mirror )
525     {
526         if ( mirror != null )
527         {
528             ArtifactRepository original =
529                 createArtifactRepository( repository.getId(), repository.getUrl(), repository.getLayout(),
530                                           repository.getSnapshots(), repository.getReleases() );
531 
532             repository.setMirroredRepositories( Collections.singletonList( original ) );
533 
534             repository.setId( mirror.getId() );
535             repository.setUrl( mirror.getUrl() );
536 
537             if ( StringUtils.isNotEmpty( mirror.getLayout() ) )
538             {
539                 repository.setLayout( getLayout( mirror.getLayout() ) );
540             }
541         }
542     }
543 
544     public void injectAuthentication( List<ArtifactRepository> repositories, List<Server> servers )
545     {
546         if ( repositories != null )
547         {
548             Map<String, Server> serversById = new HashMap<>();
549 
550             if ( servers != null )
551             {
552                 for ( Server server : servers )
553                 {
554                     if ( !serversById.containsKey( server.getId() ) )
555                     {
556                         serversById.put( server.getId(), server );
557                     }
558                 }
559             }
560 
561             for ( ArtifactRepository repository : repositories )
562             {
563                 Server server = serversById.get( repository.getId() );
564 
565                 if ( server != null )
566                 {
567                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest( server );
568                     SettingsDecryptionResult result = settingsDecrypter.decrypt( request );
569                     server = result.getServer();
570 
571                     if ( logger.isDebugEnabled() )
572                     {
573                         for ( SettingsProblem problem : result.getProblems() )
574                         {
575                             logger.debug( problem.getMessage(), problem.getException() );
576                         }
577                     }
578 
579                     Authentication authentication = new Authentication( server.getUsername(), server.getPassword() );
580                     authentication.setPrivateKey( server.getPrivateKey() );
581                     authentication.setPassphrase( server.getPassphrase() );
582 
583                     repository.setAuthentication( authentication );
584                 }
585                 else
586                 {
587                     repository.setAuthentication( null );
588                 }
589             }
590         }
591     }
592 
593     private Authentication getAuthentication( RepositorySystemSession session, ArtifactRepository repository )
594     {
595         if ( session != null )
596         {
597             AuthenticationSelector selector = session.getAuthenticationSelector();
598             if ( selector != null )
599             {
600                 RemoteRepository repo = RepositoryUtils.toRepo( repository );
601                 org.eclipse.aether.repository.Authentication auth = selector.getAuthentication( repo );
602                 if ( auth != null )
603                 {
604                     repo = new RemoteRepository.Builder( repo ).setAuthentication( auth ).build();
605                     AuthenticationContext authCtx = AuthenticationContext.forRepository( session, repo );
606                     Authentication result =
607                         new Authentication( authCtx.get( AuthenticationContext.USERNAME ),
608                                             authCtx.get( AuthenticationContext.PASSWORD ) );
609                     result.setPrivateKey( authCtx.get( AuthenticationContext.PRIVATE_KEY_PATH ) );
610                     result.setPassphrase( authCtx.get( AuthenticationContext.PRIVATE_KEY_PASSPHRASE ) );
611                     authCtx.close();
612                     return result;
613                 }
614             }
615         }
616         return null;
617     }
618 
619     public void injectAuthentication( RepositorySystemSession session, List<ArtifactRepository> repositories )
620     {
621         if ( repositories != null && session != null )
622         {
623             for ( ArtifactRepository repository : repositories )
624             {
625                 repository.setAuthentication( getAuthentication( session, repository ) );
626             }
627         }
628     }
629 
630     private org.apache.maven.settings.Proxy getProxy( ArtifactRepository repository,
631                                                       List<org.apache.maven.settings.Proxy> proxies )
632     {
633         if ( proxies != null && repository.getProtocol() != null )
634         {
635             for ( org.apache.maven.settings.Proxy proxy : proxies )
636             {
637                 if ( proxy.isActive() && repository.getProtocol().equalsIgnoreCase( proxy.getProtocol() ) )
638                 {
639                     if ( StringUtils.isNotEmpty( proxy.getNonProxyHosts() ) )
640                     {
641                         ProxyInfo pi = new ProxyInfo();
642                         pi.setNonProxyHosts( proxy.getNonProxyHosts() );
643 
644                         org.apache.maven.wagon.repository.Repository repo =
645                             new org.apache.maven.wagon.repository.Repository( repository.getId(), repository.getUrl() );
646 
647                         if ( !ProxyUtils.validateNonProxyHosts( pi, repo.getHost() ) )
648                         {
649                             return proxy;
650                         }
651                     }
652                     else
653                     {
654                         return proxy;
655                     }
656                 }
657             }
658         }
659 
660         return null;
661     }
662 
663     public void injectProxy( List<ArtifactRepository> repositories, List<org.apache.maven.settings.Proxy> proxies )
664     {
665         if ( repositories != null )
666         {
667             for ( ArtifactRepository repository : repositories )
668             {
669                 org.apache.maven.settings.Proxy proxy = getProxy( repository, proxies );
670 
671                 if ( proxy != null )
672                 {
673                     SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest( proxy );
674                     SettingsDecryptionResult result = settingsDecrypter.decrypt( request );
675                     proxy = result.getProxy();
676 
677                     if ( logger.isDebugEnabled() )
678                     {
679                         for ( SettingsProblem problem : result.getProblems() )
680                         {
681                             logger.debug( problem.getMessage(), problem.getException() );
682                         }
683                     }
684 
685                     Proxy p = new Proxy();
686                     p.setHost( proxy.getHost() );
687                     p.setProtocol( proxy.getProtocol() );
688                     p.setPort( proxy.getPort() );
689                     p.setNonProxyHosts( proxy.getNonProxyHosts() );
690                     p.setUserName( proxy.getUsername() );
691                     p.setPassword( proxy.getPassword() );
692 
693                     repository.setProxy( p );
694                 }
695                 else
696                 {
697                     repository.setProxy( null );
698                 }
699             }
700         }
701     }
702 
703     private Proxy getProxy( RepositorySystemSession session, ArtifactRepository repository )
704     {
705         if ( session != null )
706         {
707             ProxySelector selector = session.getProxySelector();
708             if ( selector != null )
709             {
710                 RemoteRepository repo = RepositoryUtils.toRepo( repository );
711                 org.eclipse.aether.repository.Proxy proxy = selector.getProxy( repo );
712                 if ( proxy != null )
713                 {
714                     Proxy p = new Proxy();
715                     p.setHost( proxy.getHost() );
716                     p.setProtocol( proxy.getType() );
717                     p.setPort( proxy.getPort() );
718                     if ( proxy.getAuthentication() != null )
719                     {
720                         repo = new RemoteRepository.Builder( repo ).setProxy( proxy ).build();
721                         AuthenticationContext authCtx = AuthenticationContext.forProxy( session, repo );
722                         p.setUserName( authCtx.get( AuthenticationContext.USERNAME ) );
723                         p.setPassword( authCtx.get( AuthenticationContext.PASSWORD ) );
724                         p.setNtlmDomain( authCtx.get( AuthenticationContext.NTLM_DOMAIN ) );
725                         p.setNtlmHost( authCtx.get( AuthenticationContext.NTLM_WORKSTATION ) );
726                         authCtx.close();
727                     }
728                     return p;
729                 }
730             }
731         }
732         return null;
733     }
734 
735     public void injectProxy( RepositorySystemSession session, List<ArtifactRepository> repositories )
736     {
737         if ( repositories != null && session != null )
738         {
739             for ( ArtifactRepository repository : repositories )
740             {
741                 repository.setProxy( getProxy( session, repository ) );
742             }
743         }
744     }
745 
746     public void retrieve( ArtifactRepository repository, File destination, String remotePath,
747                           ArtifactTransferListener transferListener )
748         throws ArtifactTransferFailedException, ArtifactDoesNotExistException
749     {
750         try
751         {
752             wagonManager.getRemoteFile( repository, destination, remotePath,
753                                         TransferListenerAdapter.newAdapter( transferListener ),
754                                         ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN, true );
755         }
756         catch ( org.apache.maven.wagon.TransferFailedException e )
757         {
758             throw new ArtifactTransferFailedException( getMessage( e, "Error transferring artifact." ), e );
759         }
760         catch ( org.apache.maven.wagon.ResourceDoesNotExistException e )
761         {
762             throw new ArtifactDoesNotExistException( getMessage( e, "Requested artifact does not exist." ), e );
763         }
764     }
765 
766     public void publish( ArtifactRepository repository, File source, String remotePath,
767                          ArtifactTransferListener transferListener )
768         throws ArtifactTransferFailedException
769     {
770         try
771         {
772             wagonManager.putRemoteFile( repository, source, remotePath,
773                                         TransferListenerAdapter.newAdapter( transferListener ) );
774         }
775         catch ( org.apache.maven.wagon.TransferFailedException e )
776         {
777             throw new ArtifactTransferFailedException( getMessage( e, "Error transferring artifact." ), e );
778         }
779     }
780 
781     //
782     // Artifact Repository Creation
783     //
784     public ArtifactRepository buildArtifactRepository( Repository repo )
785         throws InvalidRepositoryException
786     {
787         if ( repo != null )
788         {
789             String id = repo.getId();
790 
791             if ( StringUtils.isEmpty( id ) )
792             {
793                 throw new InvalidRepositoryException( "Repository identifier missing", "" );
794             }
795 
796             String url = repo.getUrl();
797 
798             if ( StringUtils.isEmpty( url ) )
799             {
800                 throw new InvalidRepositoryException( "URL missing for repository " + id, id );
801             }
802 
803             ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy( repo.getSnapshots() );
804 
805             ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy( repo.getReleases() );
806 
807             return createArtifactRepository( id, url, getLayout( repo.getLayout() ), snapshots, releases );
808         }
809         else
810         {
811             return null;
812         }
813     }
814 
815     private ArtifactRepository createRepository( String url, String repositoryId, boolean releases,
816                                                  String releaseUpdates, boolean snapshots, String snapshotUpdates,
817                                                  String checksumPolicy )
818     {
819         ArtifactRepositoryPolicy snapshotsPolicy =
820             new ArtifactRepositoryPolicy( snapshots, snapshotUpdates, checksumPolicy );
821 
822         ArtifactRepositoryPolicy releasesPolicy =
823             new ArtifactRepositoryPolicy( releases, releaseUpdates, checksumPolicy );
824 
825         return createArtifactRepository( repositoryId, url, null, snapshotsPolicy, releasesPolicy );
826     }
827 
828     public ArtifactRepository createArtifactRepository( String repositoryId, String url,
829                                                         ArtifactRepositoryLayout repositoryLayout,
830                                                         ArtifactRepositoryPolicy snapshots,
831                                                         ArtifactRepositoryPolicy releases )
832     {
833         if ( repositoryLayout == null )
834         {
835             repositoryLayout = layouts.get( "default" );
836         }
837 
838         ArtifactRepository artifactRepository =
839             artifactRepositoryFactory.createArtifactRepository( repositoryId, url, repositoryLayout, snapshots,
840                                                                 releases );
841 
842         return artifactRepository;
843     }
844 
845     private static String getMessage( Throwable error, String def )
846     {
847         if ( error == null )
848         {
849             return def;
850         }
851         String msg = error.getMessage();
852         if ( StringUtils.isNotEmpty( msg ) )
853         {
854             return msg;
855         }
856         return getMessage( error.getCause(), def );
857     }
858 
859     private ArtifactRepositoryLayout getLayout( String id )
860     {
861         ArtifactRepositoryLayout layout = layouts.get( id );
862 
863         if ( layout == null )
864         {
865             layout = new UnknownRepositoryLayout( id, layouts.get( "default" ) );
866         }
867 
868         return layout;
869     }
870 
871     /**
872      * In the future, the legacy system might encounter repository types for which no layout components exists because
873      * the actual communication with the repository happens via a repository connector. As a minimum, the legacy system
874      * needs to retain the id of this layout so that the content type of the remote repository can still be accurately
875      * described.
876      */
877     static class UnknownRepositoryLayout
878         implements ArtifactRepositoryLayout
879     {
880 
881         private final String id;
882 
883         private final ArtifactRepositoryLayout fallback;
884 
885         public UnknownRepositoryLayout( String id, ArtifactRepositoryLayout fallback )
886         {
887             this.id = id;
888             this.fallback = fallback;
889         }
890 
891         public String getId()
892         {
893             return id;
894         }
895 
896         public String pathOf( Artifact artifact )
897         {
898             return fallback.pathOf( artifact );
899         }
900 
901         public String pathOfLocalRepositoryMetadata( ArtifactMetadata metadata, ArtifactRepository repository )
902         {
903             return fallback.pathOfLocalRepositoryMetadata( metadata, repository );
904         }
905 
906         public String pathOfRemoteRepositoryMetadata( ArtifactMetadata metadata )
907         {
908             return fallback.pathOfRemoteRepositoryMetadata( metadata );
909         }
910 
911         @Override
912         public String toString()
913         {
914             return getId();
915         }
916 
917     }
918 
919 }