Save This Page
Home » maven-ant-tasks-2.1.0-src » org.apache » maven » artifact » ant » [javadoc | source]
    1   package org.apache.maven.artifact.ant;
    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.io.InputStream;
   25   import java.io.Reader;
   26   import java.io.StringReader;
   27   import java.io.StringWriter;
   28   import java.net.MalformedURLException;
   29   import java.net.URL;
   30   import java.util.ArrayList;
   31   import java.util.Iterator;
   32   import java.util.List;
   33   import java.util.Map;
   34   import java.util.Properties;
   35   
   36   import org.apache.maven.artifact.Artifact;
   37   import org.apache.maven.artifact.factory.ArtifactFactory;
   38   import org.apache.maven.artifact.manager.WagonManager;
   39   import org.apache.maven.artifact.repository.ArtifactRepository;
   40   import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
   41   import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
   42   import org.apache.maven.artifact.repository.DefaultArtifactRepository;
   43   import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
   44   import org.apache.maven.profiles.DefaultProfileManager;
   45   import org.apache.maven.profiles.ProfileManager;
   46   import org.apache.maven.project.DefaultProjectBuilderConfiguration;
   47   import org.apache.maven.project.MavenProject;
   48   import org.apache.maven.project.MavenProjectBuilder;
   49   import org.apache.maven.project.ProjectBuildingException;
   50   import org.apache.maven.settings.Mirror;
   51   import org.apache.maven.settings.RuntimeInfo;
   52   import org.apache.maven.settings.Server;
   53   import org.apache.maven.settings.Settings;
   54   import org.apache.maven.settings.SettingsUtils;
   55   import org.apache.maven.settings.TrackableBase;
   56   import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader;
   57   import org.apache.maven.usability.diagnostics.ErrorDiagnostics;
   58   import org.apache.maven.wagon.Wagon;
   59   import org.apache.tools.ant.BuildException;
   60   import org.apache.tools.ant.Project;
   61   import org.apache.tools.ant.Task;
   62   import org.apache.tools.ant.taskdefs.Execute;
   63   import org.codehaus.classworlds.ClassWorld;
   64   import org.codehaus.classworlds.DuplicateRealmException;
   65   import org.codehaus.plexus.PlexusContainer;
   66   import org.codehaus.plexus.PlexusContainerException;
   67   import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException;
   68   import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
   69   import org.codehaus.plexus.embed.Embedder;
   70   import org.codehaus.plexus.interpolation.EnvarBasedValueSource;
   71   import org.codehaus.plexus.interpolation.RegexBasedInterpolator;
   72   import org.codehaus.plexus.util.IOUtil;
   73   import org.codehaus.plexus.util.ReaderFactory;
   74   import org.codehaus.plexus.util.StringUtils;
   75   import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
   76   
   77   /**
   78    * Base class for artifact tasks.
   79    *
   80    * @author <a href="mailto:brett@apache.org">Brett Porter</a>
   81    * @version $Id: AbstractArtifactTask.java 884311 2009-11-25 22:32:12Z pgier $
   82    */
   83   public abstract class AbstractArtifactTask
   84       extends Task
   85   {
   86       private static final String WILDCARD = "*";
   87   
   88       private static final String EXTERNAL_WILDCARD = "external:*";
   89   
   90       private static ClassLoader plexusClassLoader;
   91   
   92       private File userSettingsFile;
   93   
   94       private File globalSettingsFile;
   95   
   96       private Settings settings;
   97   
   98       private ProfileManager profileManager;
   99   
  100       private PlexusContainer container;
  101   
  102       private Pom pom;
  103   
  104       private String pomRefId;
  105   
  106       private LocalRepository localRepository;
  107   
  108       protected ArtifactRepository createLocalArtifactRepository()
  109       {
  110           ArtifactRepositoryLayout repositoryLayout =
  111               (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, getLocalRepository().getLayout() );
  112   
  113           return new DefaultArtifactRepository( "local", "file://" + getLocalRepository().getPath(), repositoryLayout );
  114       }
  115   
  116       /**
  117        * Create a core-Maven ArtifactRepositoryFactory from a Maven Ant Tasks's RemoteRepository definition,
  118        * eventually configured with authentication and proxy information.
  119        * @param repository the remote repository as defined in Ant
  120        * @return the corresponding ArtifactRepositoryFactory
  121        */
  122       protected ArtifactRepositoryFactory getArtifactRepositoryFactory( RemoteRepository repository )
  123       {
  124           WagonManager manager = (WagonManager) lookup( WagonManager.ROLE );
  125   
  126           Authentication authentication = repository.getAuthentication();
  127           if ( authentication != null )
  128           {
  129               manager.addAuthenticationInfo( repository.getId(), authentication.getUserName(),
  130                                              authentication.getPassword(), authentication.getPrivateKey(),
  131                                              authentication.getPassphrase() );
  132           }
  133   
  134           Proxy proxy = repository.getProxy();
  135           if ( proxy != null )
  136           {
  137               manager.addProxy( proxy.getType(), proxy.getHost(), proxy.getPort(), proxy.getUserName(),
  138                                 proxy.getPassword(), proxy.getNonProxyHosts() );
  139           }
  140   
  141           return (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE );
  142       }
  143   
  144       protected void releaseArtifactRepositoryFactory( ArtifactRepositoryFactory repositoryFactory )
  145       {
  146           try
  147           {
  148               getContainer().release( repositoryFactory );
  149           }
  150           catch ( ComponentLifecycleException e )
  151           {
  152               // TODO: Warn the user, or not?
  153           }
  154       }
  155   
  156       /**
  157        * Create a core-Maven ArtifactRepository from a Maven Ant Tasks's RemoteRepository definition.
  158        * @param repository the remote repository as defined in Ant
  159        * @return the corresponding ArtifactRepository
  160        */
  161       protected ArtifactRepository createRemoteArtifactRepository( RemoteRepository repository )
  162       {
  163           ArtifactRepositoryLayout repositoryLayout =
  164               (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, repository.getLayout() );
  165   
  166           ArtifactRepositoryFactory repositoryFactory = null;
  167   
  168           ArtifactRepository artifactRepository;
  169   
  170           try
  171           {
  172               repositoryFactory = getArtifactRepositoryFactory( repository );
  173   
  174               ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy( repository.getSnapshots() );
  175               ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy( repository.getReleases() );
  176   
  177               artifactRepository = repositoryFactory.createArtifactRepository( repository.getId(), repository.getUrl(),
  178                                                                                repositoryLayout, snapshots, releases );
  179           }
  180           finally
  181           {
  182               releaseArtifactRepositoryFactory( repositoryFactory );
  183           }
  184   
  185           return artifactRepository;
  186       }
  187   
  188       private static ArtifactRepositoryPolicy buildArtifactRepositoryPolicy( RepositoryPolicy policy )
  189       {
  190           boolean enabled = true;
  191           String updatePolicy = null;
  192           String checksumPolicy = null;
  193   
  194           if ( policy != null )
  195           {
  196               enabled = policy.isEnabled();
  197               if ( policy.getUpdatePolicy() != null )
  198               {
  199                   updatePolicy = policy.getUpdatePolicy();
  200               }
  201               if ( policy.getChecksumPolicy() != null )
  202               {
  203                   checksumPolicy = policy.getChecksumPolicy();
  204               }
  205           }
  206   
  207           return new ArtifactRepositoryPolicy( enabled, updatePolicy, checksumPolicy );
  208       }
  209   
  210       protected LocalRepository getDefaultLocalRepository()
  211       {
  212           Settings settings = getSettings();
  213           LocalRepository localRepository = new LocalRepository();
  214           localRepository.setId( "local" );
  215           localRepository.setPath( new File( settings.getLocalRepository() ) );
  216           return localRepository;
  217       }
  218   
  219       protected synchronized Settings getSettings()
  220       {
  221           if ( settings == null )
  222           {
  223               initSettings();
  224           }
  225           return settings;
  226       }
  227   
  228       private File newFile( String parent, String subdir, String filename )
  229       {
  230           return new File( new File( parent, subdir ), filename );
  231       }
  232   
  233       private void initSettings()
  234       {
  235           if ( userSettingsFile == null )
  236           {
  237               File tempSettingsFile = newFile( System.getProperty( "user.home" ), ".ant", "settings.xml" );
  238               if ( tempSettingsFile.exists() )
  239               {
  240                   userSettingsFile = tempSettingsFile;
  241               }
  242               else
  243               {
  244                   tempSettingsFile = newFile( System.getProperty( "user.home" ), ".m2", "settings.xml" );
  245                   if ( tempSettingsFile.exists() )
  246                   {
  247                       userSettingsFile = tempSettingsFile;
  248                   }
  249               }
  250           }
  251           if ( globalSettingsFile == null )
  252           {
  253               File tempSettingsFile = newFile( System.getProperty( "ant.home" ), "etc", "settings.xml" );
  254               if ( tempSettingsFile.exists() )
  255               {
  256                   globalSettingsFile = tempSettingsFile;
  257               }
  258               else
  259               {
  260                   // look in ${M2_HOME}/conf
  261                   List env = Execute.getProcEnvironment();
  262                   for ( Iterator iter = env.iterator(); iter.hasNext(); )
  263                   {
  264                       String var = (String) iter.next();
  265                       if ( var.startsWith( "M2_HOME=" ) )
  266                       {
  267                           String m2Home = var.substring( "M2_HOME=".length() );
  268                           tempSettingsFile = newFile( m2Home, "conf", "settings.xml" );
  269                           if ( tempSettingsFile.exists() )
  270                           {
  271                               globalSettingsFile = tempSettingsFile;
  272                           }
  273                           break;
  274                       }
  275                   }
  276               }
  277           }
  278   
  279           Settings userSettings = loadSettings( userSettingsFile );
  280           Settings globalSettings = loadSettings( globalSettingsFile );
  281   
  282           SettingsUtils.merge( userSettings, globalSettings, TrackableBase.GLOBAL_LEVEL );
  283           settings = userSettings;
  284   
  285           if ( StringUtils.isEmpty( settings.getLocalRepository() ) )
  286           {
  287               String location = newFile( System.getProperty( "user.home" ), ".m2", "repository" ).getAbsolutePath();
  288               settings.setLocalRepository( location );
  289           }
  290   
  291           WagonManager wagonManager = (WagonManager) lookup( WagonManager.ROLE );
  292           wagonManager.setDownloadMonitor( new AntDownloadMonitor() );
  293           if ( settings.isOffline() )
  294           {
  295               log( "You are working in offline mode.", Project.MSG_INFO );
  296               wagonManager.setOnline( false );
  297           }
  298           else
  299           {
  300               wagonManager.setOnline( true );
  301           }
  302       }
  303   
  304       private Settings loadSettings( File settingsFile )
  305       {
  306           Settings settings = null;
  307           try
  308           {
  309               if ( settingsFile != null )
  310               {
  311                   log( "Loading Maven settings file: " + settingsFile.getPath(), Project.MSG_VERBOSE );
  312                   settings = readSettings( settingsFile );
  313               }
  314           }
  315           catch ( IOException e )
  316           {
  317               log( "Error reading settings file '" + settingsFile + "' - ignoring. Error was: " + e.getMessage(),
  318                    Project.MSG_WARN );
  319           }
  320           catch ( XmlPullParserException e )
  321           {
  322               log( "Error parsing settings file '" + settingsFile + "' - ignoring. Error was: " + e.getMessage(),
  323                    Project.MSG_WARN );
  324           }
  325   
  326           if ( settings == null )
  327           {
  328               settings = new Settings();
  329               RuntimeInfo rtInfo = new RuntimeInfo( settings );
  330               settings.setRuntimeInfo( rtInfo );
  331           }
  332   
  333           return settings;
  334       }
  335   
  336       public void setSettingsFile( File settingsFile )
  337       {
  338           if ( !settingsFile.exists() )
  339           {
  340               throw new BuildException( "settingsFile does not exist: " + settingsFile.getAbsolutePath() );
  341           }
  342   
  343           userSettingsFile = settingsFile;
  344           settings = null;
  345       }
  346   
  347       /**
  348        * @see org.apache.maven.settings.DefaultMavenSettingsBuilder#readSettings
  349        */
  350       private Settings readSettings( File settingsFile )
  351           throws IOException, XmlPullParserException
  352       {
  353           Settings settings = null;
  354           Reader reader = null;
  355           try
  356           {
  357               reader = ReaderFactory.newXmlReader( settingsFile );
  358               StringWriter sWriter = new StringWriter();
  359   
  360               IOUtil.copy( reader, sWriter );
  361   
  362               String rawInput = sWriter.toString();
  363   
  364               try
  365               {
  366                   RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
  367                   interpolator.addValueSource( new EnvarBasedValueSource() );
  368   
  369                   rawInput = interpolator.interpolate( rawInput, "settings" );
  370               }
  371               catch ( Exception e )
  372               {
  373                   log( "Failed to initialize environment variable resolver. Skipping environment substitution in "
  374                        + "settings." );
  375               }
  376   
  377               StringReader sReader = new StringReader( rawInput );
  378   
  379               SettingsXpp3Reader modelReader = new SettingsXpp3Reader();
  380   
  381               settings = modelReader.read( sReader );
  382   
  383               RuntimeInfo rtInfo = new RuntimeInfo( settings );
  384   
  385               rtInfo.setFile( settingsFile );
  386   
  387               settings.setRuntimeInfo( rtInfo );
  388           }
  389           finally
  390           {
  391               IOUtil.close( reader );
  392           }
  393           return settings;
  394       }
  395   
  396       protected RemoteRepository createAntRemoteRepository( org.apache.maven.model.Repository pomRepository )
  397       {
  398           RemoteRepository r = createAntRemoteRepositoryBase( pomRepository );
  399   
  400           if ( pomRepository.getSnapshots() != null )
  401           {
  402               r.addSnapshots( convertRepositoryPolicy( pomRepository.getSnapshots() ) );
  403           }
  404           if ( pomRepository.getReleases() != null )
  405           {
  406               r.addReleases( convertRepositoryPolicy( pomRepository.getReleases() ) );
  407           }
  408   
  409           return r;
  410       }
  411   
  412       protected RemoteRepository createAntRemoteRepositoryBase( org.apache.maven.model.RepositoryBase pomRepository )
  413       {
  414           RemoteRepository r = new RemoteRepository();
  415           r.setId( pomRepository.getId() );
  416           r.setUrl( pomRepository.getUrl() );
  417           r.setLayout( pomRepository.getLayout() );
  418   
  419           return r;
  420       }
  421   
  422       protected void updateRepositoryWithSettings( RemoteRepository repository )
  423       {
  424           // TODO: actually, we need to not funnel this through the ant repository - we should pump settings into wagon
  425           // manager at the start like m2 does, and then match up by repository id
  426           // As is, this could potentially cause a problem with 2 remote repositories with different authentication info
  427   
  428           Mirror mirror = getMirror( getSettings().getMirrors(), repository );
  429           if ( mirror != null )
  430           {
  431               repository.setUrl( mirror.getUrl() );
  432               repository.setId( mirror.getId() );
  433           }
  434   
  435           if ( repository.getAuthentication() == null )
  436           {
  437               Server server = getSettings().getServer( repository.getId() );
  438               if ( server != null )
  439               {
  440                   repository.addAuthentication( new Authentication( server ) );
  441               }
  442           }
  443            
  444           if ( repository.getProxy() == null )
  445           {
  446               org.apache.maven.settings.Proxy proxy = getSettings().getActiveProxy();
  447               if ( proxy != null )
  448               {
  449                   repository.addProxy( new Proxy( proxy ) );
  450               }
  451           }
  452       }
  453   
  454       protected Object lookup( String role )
  455       {
  456           try
  457           {
  458               return getContainer().lookup( role );
  459           }
  460           catch ( ComponentLookupException e )
  461           {
  462               throw new BuildException( "Unable to find component: " + role, e );
  463           }
  464       }
  465   
  466       protected Object lookup( String role,
  467                                String roleHint )
  468       {
  469           try
  470           {
  471               return getContainer().lookup( role, roleHint );
  472           }
  473           catch ( ComponentLookupException e )
  474           {
  475               throw new BuildException( "Unable to find component: " + role + "[" + roleHint + "]", e );
  476           }
  477       }
  478   
  479       protected synchronized PlexusContainer getContainer()
  480       {
  481           if ( container == null )
  482           {
  483               container = (PlexusContainer) getProject().getReference( PlexusContainer.class.getName() );
  484   
  485               if ( container == null )
  486               {
  487                   try
  488                   {
  489                       ClassWorld classWorld = new ClassWorld();
  490   
  491                       classWorld.newRealm( "plexus.core", getClass().getClassLoader() );
  492   
  493                       Embedder embedder = new Embedder();
  494   
  495                       embedder.start( classWorld );
  496   
  497                       container = embedder.getContainer();
  498                   }
  499                   catch ( PlexusContainerException e )
  500                   {
  501                       throw new BuildException( "Unable to start embedder", e );
  502                   }
  503                   catch ( DuplicateRealmException e )
  504                   {
  505                       throw new BuildException( "Unable to create embedder ClassRealm", e );
  506                   }
  507   
  508                   getProject().addReference( PlexusContainer.class.getName(), container );
  509               }
  510           }
  511   
  512           return container;
  513       }
  514   
  515       /**
  516        * Tries to initialize the pom.  If no pom has been configured, returns null.
  517        * 
  518        * @param localArtifactRepository
  519        * @return An initialized pom or null.
  520        */
  521       public Pom initializePom( ArtifactRepository localArtifactRepository )
  522       {
  523   
  524           Pom pom = getPom();
  525           if ( pom != null )
  526           {
  527               MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
  528               pom.initialiseMavenProject( projectBuilder, localArtifactRepository );
  529           }
  530           
  531           return pom;
  532       }
  533   
  534       protected Pom createDummyPom( ArtifactRepository localRepository )
  535       {
  536           Pom pom = new Pom();
  537   
  538           pom.setMavenProject( createMinimalProject( localRepository ) );
  539   
  540           return pom;
  541       }
  542       
  543       /**
  544        * Create a minimal project when no POM is available.
  545        * 
  546        * @param localRepository
  547        * @return
  548        */
  549       protected MavenProject createMinimalProject( ArtifactRepository localRepository )
  550       {
  551           MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
  552           DefaultProjectBuilderConfiguration builderConfig = new DefaultProjectBuilderConfiguration( );
  553           builderConfig.setLocalRepository( localRepository );
  554           builderConfig.setGlobalProfileManager( getProfileManager() );
  555   
  556           try
  557           {
  558               return projectBuilder.buildStandaloneSuperProject( builderConfig );
  559           }
  560           catch ( ProjectBuildingException e )
  561           {
  562               throw new BuildException( "Unable to create dummy Pom", e );
  563           }
  564           
  565       }
  566       
  567       protected Artifact createDummyArtifact()
  568       {
  569           ArtifactFactory factory = (ArtifactFactory) lookup( ArtifactFactory.ROLE );
  570           // TODO: maybe not strictly correct, while we should enforce that packaging has a type handler of the same id, we don't
  571           return factory.createBuildArtifact( "unspecified", "unspecified", "0.0", "jar" );
  572       }
  573   
  574       public String[] getSupportedProtocols()
  575       {
  576           try
  577           {
  578               Map wagonMap = getContainer().lookupMap( Wagon.ROLE );
  579               List protocols = new ArrayList();
  580               for ( Iterator iter = wagonMap.entrySet().iterator(); iter.hasNext(); )
  581               {
  582                   Map.Entry entry = (Map.Entry) iter.next();
  583                   protocols.add( entry.getKey() );
  584               }
  585               return (String[]) protocols.toArray( new String[protocols.size()] );
  586           }
  587           catch ( ComponentLookupException e )
  588           {
  589               throw new BuildException( "Unable to lookup Wagon providers", e );
  590           }
  591       }
  592   
  593       public String getSupportedProtocolsAsString()
  594       {
  595           return StringUtils.join( getSupportedProtocols(), ", " );
  596       }
  597       
  598       public void diagnoseError( Throwable error )
  599       {
  600           try
  601           {
  602               ErrorDiagnostics diagnostics = (ErrorDiagnostics) container.lookup( ErrorDiagnostics.ROLE );
  603   
  604               StringBuffer message = new StringBuffer();
  605   
  606               message.append( "An error has occurred while processing the Maven artifact tasks.\n" );
  607               message.append( " Diagnosis:\n\n" );
  608   
  609               message.append( diagnostics.diagnose( error ) );
  610   
  611               message.append( "\n\n" );
  612   
  613               log( message.toString(), Project.MSG_INFO );
  614           }
  615           catch ( ComponentLookupException e )
  616           {
  617               log( "Failed to retrieve error diagnoser.", Project.MSG_DEBUG );
  618           }
  619       }
  620   
  621       public void addPom( Pom pom )
  622       {
  623           this.pom = pom;
  624       }
  625       
  626       /**
  627        * Try to get the POM from the nested pom element or a pomRefId
  628        * 
  629        * @return The pom object
  630        */
  631       public Pom getPom()
  632       {
  633           Pom thePom = this.pom;
  634           
  635           if ( thePom != null && getPomRefId() != null )
  636           {
  637               throw new BuildException( "You cannot specify both a nested \"pom\" element and a \"pomrefid\" attribute" );
  638           }
  639   
  640           if ( getPomRefId() != null )
  641           {
  642               Object pomRefObj = getProject().getReference( getPomRefId() );
  643               if ( pomRefObj instanceof Pom )
  644               {
  645                   thePom = (Pom) pomRefObj;
  646               }
  647               else
  648               {
  649                   throw new BuildException( "Reference '" + pomRefId + "' was not found." );
  650               }
  651           }
  652           
  653           return thePom;
  654       }
  655       
  656       public String getPomRefId()
  657       {
  658           return pomRefId;
  659       }
  660   
  661       public void setPomRefId( String pomRefId )
  662       {
  663           this.pomRefId = pomRefId;
  664       }
  665   
  666       public LocalRepository getLocalRepository()
  667       {
  668           if ( localRepository == null )
  669           {
  670               localRepository = getDefaultLocalRepository();
  671           }
  672           return localRepository;
  673       }
  674   
  675       protected ProfileManager getProfileManager()
  676       {
  677           if ( profileManager == null )
  678           {
  679               profileManager = new DefaultProfileManager( getContainer(), getSettings(), System.getProperties() );
  680           }
  681           return profileManager;
  682       }
  683   
  684       public void addLocalRepository( LocalRepository localRepository )
  685       {
  686           this.localRepository = localRepository;
  687       }
  688   
  689       public void setProfiles( String profiles )
  690       {
  691           if ( profiles != null )
  692           {
  693               // TODO: not sure this is the best way to do this...
  694               log( "Profiles not yet supported, ignoring profiles '" + profiles + "'", Project.MSG_WARN );
  695   //            System.setProperty( ProfileActivationUtils.ACTIVE_PROFILE_IDS, profiles );
  696           }
  697       }
  698   
  699       private static RepositoryPolicy convertRepositoryPolicy( org.apache.maven.model.RepositoryPolicy pomRepoPolicy )
  700       {
  701           RepositoryPolicy policy = new RepositoryPolicy();
  702           policy.setEnabled( pomRepoPolicy.isEnabled() );
  703           policy.setUpdatePolicy( pomRepoPolicy.getUpdatePolicy() );
  704           return policy;
  705       }
  706   
  707       /** @noinspection RefusedBequest */
  708       public void execute()
  709       {
  710           // Display the version if the log level is verbose
  711           showVersion();
  712           
  713           ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
  714           try
  715           {
  716               if ( plexusClassLoader != null )
  717               {
  718                   Thread.currentThread().setContextClassLoader( plexusClassLoader );
  719               }
  720               initSettings();
  721               doExecute();
  722           }
  723           catch ( BuildException e )
  724           {
  725               diagnoseError( e );
  726   
  727               throw e;
  728           }
  729           finally
  730           {
  731               plexusClassLoader = Thread.currentThread().getContextClassLoader();
  732               Thread.currentThread().setContextClassLoader( originalClassLoader );
  733           }
  734       }
  735       
  736       /**
  737        * The main entry point for the task.
  738        */
  739       protected abstract void doExecute();
  740   
  741       /**
  742        * This method finds a matching mirror for the selected repository. If there is an exact match,
  743        * this will be used. If there is no exact match, then the list of mirrors is examined to see if
  744        * a pattern applies.
  745        * 
  746        * @param mirrors The available mirrors.
  747        * @param repository See if there is a mirror for this repository.
  748        * @return the selected mirror or null if none is found.
  749        */
  750       private Mirror getMirror( List mirrors, RemoteRepository repository )
  751       {
  752           String repositoryId = repository.getId();
  753   
  754           if ( repositoryId != null )
  755           {
  756               for ( Iterator it = mirrors.iterator(); it.hasNext(); )
  757               {
  758                   Mirror mirror = (Mirror) it.next();
  759   
  760                   if ( repositoryId.equals( mirror.getMirrorOf() ) )
  761                   {
  762                       return mirror;
  763                   }
  764               }
  765   
  766               for ( Iterator it = mirrors.iterator(); it.hasNext(); )
  767               {
  768                   Mirror mirror = (Mirror) it.next();
  769   
  770                   if ( matchPattern( repository, mirror.getMirrorOf() ) )
  771                   {
  772                       return mirror;
  773                   }
  774               }
  775           }
  776   
  777           return null;
  778       }
  779   
  780       /**
  781        * This method checks if the pattern matches the originalRepository. Valid patterns: * =
  782        * everything external:* = everything not on the localhost and not file based. repo,repo1 = repo
  783        * or repo1 *,!repo1 = everything except repo1
  784        * 
  785        * @param originalRepository to compare for a match.
  786        * @param pattern used for match. Currently only '*' is supported.
  787        * @return true if the repository is a match to this pattern.
  788        */
  789       boolean matchPattern( RemoteRepository originalRepository, String pattern )
  790       {
  791           boolean result = false;
  792           String originalId = originalRepository.getId();
  793   
  794           // simple checks first to short circuit processing below.
  795           if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) )
  796           {
  797               result = true;
  798           }
  799           else
  800           {
  801               // process the list
  802               String[] repos = pattern.split( "," );
  803               
  804               for ( int i = 0; i < repos.length; i++ )
  805               {
  806                   String repo = repos[i];
  807                   
  808                   // see if this is a negative match
  809                   if ( repo.length() > 1 && repo.startsWith( "!" ) )
  810                   {
  811                       if ( originalId.equals( repo.substring( 1 ) ) )
  812                       {
  813                           // explicitly exclude. Set result and stop processing.
  814                           result = false;
  815                           break;
  816                       }
  817                   }
  818                   // check for exact match
  819                   else if ( originalId.equals( repo ) )
  820                   {
  821                       result = true;
  822                       break;
  823                   }
  824                   // check for external:*
  825                   else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( originalRepository ) )
  826                   {
  827                       result = true;
  828                       // don't stop processing in case a future segment explicitly excludes this repo
  829                   }
  830                   else if ( WILDCARD.equals( repo ) )
  831                   {
  832                       result = true;
  833                       // don't stop processing in case a future segment explicitly excludes this repo
  834                   }
  835               }
  836           }
  837           return result;
  838       }
  839   
  840       /**
  841        * Checks the URL to see if this repository refers to an external repository
  842        * 
  843        * @param originalRepository
  844        * @return true if external.
  845        */
  846       boolean isExternalRepo( RemoteRepository originalRepository )
  847       {
  848           try
  849           {
  850               URL url = new URL( originalRepository.getUrl() );
  851               return !( url.getHost().equals( "localhost" ) || url.getHost().equals( "127.0.0.1" ) || url.getProtocol().equals( "file" ) );
  852           }
  853           catch ( MalformedURLException e )
  854           {
  855               // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
  856               return false;
  857           }
  858       }
  859   
  860       /**
  861        * Log the current version of the ant-tasks to the verbose output.
  862        */
  863       protected void showVersion()
  864       {
  865           
  866           Properties properties = new Properties();
  867           final String antTasksPropertiesPath = "META-INF/maven/org.apache.maven/maven-ant-tasks/pom.properties";
  868           InputStream resourceAsStream = AbstractArtifactTask.class.getClassLoader().getResourceAsStream( antTasksPropertiesPath );
  869           
  870           try
  871           {
  872               if ( resourceAsStream != null )
  873               {
  874                   properties.load( resourceAsStream );
  875               }
  876   
  877               String version = properties.getProperty( "version", "unknown" );
  878               String builtOn = properties.getProperty( "builtOn" );
  879               if ( builtOn != null )
  880               {
  881                   log( "Maven Ant Tasks version: " + version + " built on " + builtOn, Project.MSG_VERBOSE );
  882               }
  883               else
  884               {
  885                   log( "Maven Ant Tasks version: " + version, Project.MSG_VERBOSE );
  886               }
  887           }
  888           catch ( IOException e )
  889           {
  890               log( "Unable to determine version from Maven Ant Tasks JAR file: " + e.getMessage(), Project.MSG_WARN );
  891           }
  892       }
  893   
  894   }

Save This Page
Home » maven-ant-tasks-2.1.0-src » org.apache » maven » artifact » ant » [javadoc | source]