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