View Javadoc

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 org.apache.maven.artifact.Artifact;
23  import org.apache.maven.artifact.repository.ArtifactRepository;
24  import org.apache.maven.model.Build;
25  import org.apache.maven.model.CiManagement;
26  import org.apache.maven.model.Contributor;
27  import org.apache.maven.model.Dependency;
28  import org.apache.maven.model.DependencyManagement;
29  import org.apache.maven.model.Developer;
30  import org.apache.maven.model.DistributionManagement;
31  import org.apache.maven.model.IssueManagement;
32  import org.apache.maven.model.License;
33  import org.apache.maven.model.MailingList;
34  import org.apache.maven.model.Model;
35  import org.apache.maven.model.Organization;
36  import org.apache.maven.model.Parent;
37  import org.apache.maven.model.Reporting;
38  import org.apache.maven.model.Repository;
39  import org.apache.maven.model.Scm;
40  import org.apache.maven.profiles.ProfileManager;
41  import org.apache.maven.project.DefaultProjectBuilderConfiguration;
42  import org.apache.maven.project.MavenProject;
43  import org.apache.maven.project.MavenProjectBuilder;
44  import org.apache.maven.project.MavenProjectHelper;
45  import org.apache.maven.project.ProjectBuilderConfiguration;
46  import org.apache.maven.project.ProjectBuildingException;
47  import org.apache.maven.project.inheritance.ModelInheritanceAssembler;
48  import org.apache.maven.project.injection.ModelDefaultsInjector;
49  import org.apache.maven.project.interpolation.ModelInterpolationException;
50  import org.apache.tools.ant.BuildException;
51  import org.apache.tools.ant.Project;
52  import org.apache.tools.ant.PropertyHelper;
53  import org.codehaus.plexus.util.StringUtils;
54  
55  import java.io.File;
56  import java.util.ArrayList;
57  import java.util.Hashtable;
58  import java.util.Iterator;
59  import java.util.List;
60  import java.util.Properties;
61  
62  /**
63   * A POM typedef. Also an Ant Task that registers a handler called POMPropertyHelper that intercepts all calls to
64   * property value resolution and replies instead of Ant to properties that start with the id of the pom. Example:
65   * ${maven.project.artifactId}
66   *
67   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
68   * @author <a href="mailto:nicolaken@apache.org">Nicola Ken Barozzi</a>
69   * @version $Id: Pom.html 806929 2012-03-01 18:57:40Z hboutemy $
70   */
71  public class Pom
72      extends AbstractArtifactWithRepositoryTask
73  {
74      /**
75       * The id referring to an existing pom object in the current Ant project.
76       */
77      private String refid;
78  
79      /**
80       * The id of this pom object to be stored in the current Ant project.
81       */
82      String antId;
83  
84      /**
85       * The maven project represented by this pom
86       */
87      private MavenProject mavenProject;
88  
89      /**
90       * The file from which the pom was loaded.
91       */
92      private File file;
93  
94      /**
95       * The list of profiles to either activate or deactivate for this pom.
96       */
97      private List<Profile> profiles = new ArrayList<Profile>();
98  
99      private boolean inheritAllProperties = true;
100 
101     /**
102      * The property intercepter.
103      */
104     private final POMPropertyHelper helper = new POMPropertyHelper( this );
105 
106     public String getRefid()
107     {
108         return refid;
109     }
110 
111     /**
112      * The ID used to retrieve this pom object from the Ant project.
113      *
114      * @param refid
115      */
116     public void setRefid( String refid )
117     {
118         this.refid = refid;
119     }
120 
121     /**
122      * The ID used to store this pom object in the Ant project.
123      *
124      * @param id
125      */
126     public void setId( String id )
127     {
128         this.antId = id;
129     }
130 
131     /**
132      * Retrieve the pom object from the current Ant project using the configured refid.
133      *
134      * @param refid
135      * @return
136      */
137     protected void getPomFromAntProject( String refid )
138     {
139         if ( refid == null )
140         {
141             throw new BuildException( "POM refid is null." );
142         }
143 
144         if ( getProject().getReference( refid ) == null )
145         {
146             throw new BuildException( "Unable to locate POM reference: '" + refid + "'" );
147         }
148 
149         Pom thePom = (Pom) getProject().getReference( refid );
150         mavenProject = thePom.getMavenProject();
151         file = thePom.getFile();
152     }
153 
154     public void setMavenProject( MavenProject mavenProject )
155     {
156         this.mavenProject = mavenProject;
157     }
158 
159     public File getFile()
160     {
161         return file;
162     }
163 
164     public void setFile( File file )
165     {
166         this.file = file;
167     }
168 
169     public List<Profile> getProfiles()
170     {
171         return profiles;
172     }
173 
174     public void addProfile( Profile activeProfile )
175     {
176         this.profiles.add( activeProfile );
177     }
178 
179     public Artifact getArtifact()
180     {
181         return getMavenProject().getArtifact();
182     }
183 
184     public void attach( AttachedArtifact attached )
185     {
186         MavenProjectHelper helper = (MavenProjectHelper) lookup( MavenProjectHelper.ROLE );
187         MavenProject project = getMavenProject();
188         if ( attached.getClassifier() != null )
189         {
190             helper.attachArtifact( project, attached.getType(), attached.getClassifier(), attached.getFile() );
191         }
192         else
193         {
194             helper.attachArtifact( project, attached.getType(), attached.getFile() );
195         }
196     }
197 
198     public List<Artifact> getAttachedArtifacts()
199     {
200         return getMavenProject().getAttachedArtifacts();
201     }
202 
203     public void initialiseMavenProject( MavenProjectBuilder builder, ArtifactRepository localRepository )
204     {
205         if ( file != null )
206         {
207             addAntRepositoriesToProfileManager();
208             ProjectBuilderConfiguration builderConfig = this.createProjectBuilderConfig( localRepository );
209             try
210             {
211                 mavenProject = builder.build( file, builderConfig );
212 
213                 builder.calculateConcreteState( mavenProject, builderConfig, false );
214             }
215             catch ( ProjectBuildingException pbe )
216             {
217                 throw new BuildException( "Unable to initialize POM " + file.getName() + ": " + pbe.getMessage(), pbe );
218             }
219             catch ( ModelInterpolationException mie )
220             {
221                 throw new BuildException( "Unable to interpolate POM " + file.getName() + ": " + mie.getMessage(), mie );
222             }
223         }
224         else if ( refid != null )
225         {
226             this.getPomFromAntProject( refid );
227         }
228         else if ( mavenProject != null )
229         {
230             addAntRepositoriesToProfileManager();
231             ProjectBuilderConfiguration builderConfig = this.createProjectBuilderConfig( localRepository );
232             try
233             {
234                 builder.calculateConcreteState( mavenProject, builderConfig, false );
235             }
236             catch ( ModelInterpolationException mie )
237             {
238                 throw new BuildException( "Unable to interpolate POM " + file.getName() + ": " + mie.getMessage(), mie );
239             }
240 
241         }
242         if ( mavenProject != null && mavenProject.getModel().getParent() != null )
243         {
244             String parentGroupId = mavenProject.getModel().getParent().getGroupId();
245             String parentArtifactId = mavenProject.getModel().getParent().getArtifactId();
246             String parentVersion = mavenProject.getModel().getParent().getVersion();
247             Iterator i = getAntReactorPoms().iterator();
248             while ( i.hasNext() )
249             {
250                 Pom pom = (Pom)i.next();
251                 if ( StringUtils.equals( parentGroupId, pom.getGroupId() )
252                         && StringUtils.equals( parentArtifactId, pom.getArtifactId() )
253                         && StringUtils.equals( parentVersion, pom.getVersion() ) )
254                 {
255                     pom.initialiseMavenProject( builder, localRepository );
256                     mavenProject.setParent( pom.getMavenProject() );
257                     ModelInheritanceAssembler modelInheritanceAssembler =
258                             (ModelInheritanceAssembler) lookup( ModelInheritanceAssembler. ROLE );
259                     modelInheritanceAssembler.assembleModelInheritance( mavenProject.getModel(), pom.getModel() );
260                     break;
261                 }
262             }
263         }
264         ModelDefaultsInjector modelDefaultsInjector = (ModelDefaultsInjector) lookup( ModelDefaultsInjector.ROLE );
265         modelDefaultsInjector.injectDefaults(mavenProject.getModel());
266     }
267 
268     protected MavenProject getMavenProject()
269     {
270         if ( mavenProject == null )
271         {
272             mavenProject = createMinimalProject( createLocalArtifactRepository() );
273         }
274         return mavenProject;
275     }
276 
277     public String getArtifactId()
278     {
279         return getMavenProject().getArtifactId();
280     }
281 
282     public Build getBuild()
283     {
284         return getMavenProject().getBuild();
285     }
286 
287     public CiManagement getCiManagement()
288     {
289         return getMavenProject().getCiManagement();
290     }
291 
292     public List getContributors()
293     {
294         return getMavenProject().getContributors();
295     }
296 
297     public List<Dependency> getDependencies()
298     {
299         return getMavenProject().getDependencies();
300     }
301 
302     public DependencyManagement getDependencyManagement()
303     {
304         return getMavenProject().getDependencyManagement();
305     }
306 
307     public String getDescription()
308     {
309         return getMavenProject().getDescription();
310     }
311 
312     public List getDevelopers()
313     {
314         return getMavenProject().getDevelopers();
315     }
316 
317     public DistributionManagement getDistributionManagement()
318     {
319         return getMavenProject().getDistributionManagement();
320     }
321 
322     public String getGroupId()
323     {
324         return getMavenProject().getGroupId();
325     }
326 
327     public String getInceptionYear()
328     {
329         return getMavenProject().getInceptionYear();
330     }
331 
332     public IssueManagement getIssueManagement()
333     {
334         return getMavenProject().getIssueManagement();
335     }
336 
337     public List getLicenses()
338     {
339         return getMavenProject().getLicenses();
340     }
341 
342     public List getMailingLists()
343     {
344         return getMavenProject().getMailingLists();
345     }
346 
347     public String getModelVersion()
348     {
349         return getMavenProject().getModelVersion();
350     }
351 
352     public List getModules()
353     {
354         return getMavenProject().getModules();
355     }
356 
357     public String getName()
358     {
359         return getMavenProject().getName();
360     }
361 
362     public Organization getOrganization()
363     {
364         return getMavenProject().getOrganization();
365     }
366 
367     public String getPackaging()
368     {
369         return getMavenProject().getPackaging();
370     }
371 
372     public List getPluginRepositories()
373     {
374         return getMavenProject().getPluginRepositories();
375     }
376 
377     public Reporting getReporting()
378     {
379         return getMavenProject().getReporting();
380     }
381 
382     public List<Repository> getRepositories()
383     {
384         return getMavenProject().getRepositories();
385     }
386 
387     public Scm getScm()
388     {
389         return getMavenProject().getScm();
390     }
391 
392     public String getUrl()
393     {
394         return getMavenProject().getUrl();
395     }
396 
397     public String getVersion()
398     {
399         return getMavenProject().getVersion();
400     }
401 
402     public String getId()
403     {
404         return getMavenProject().getId();
405     }
406 
407     /**
408      * Registers POMPropertyHelper as a property interceptor in Ant 1.6 - 1.7.1, or property delegate in Ant 1.8.0
409      */
410     protected void doExecute()
411     {
412         if ( getId() == null )
413         {
414             throw new BuildException( "id required for pom task" );
415         }
416         ArtifactRepository localRepo = createLocalArtifactRepository();
417         MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
418         initialiseMavenProject( projectBuilder, localRepo );
419 
420         Project antProject = getProject();
421 
422         // Add a reference to this task/type
423         antProject.addReference( antId, this );
424 
425         // Register the property intercepter or delegate
426         PropertyHelper phelper = PropertyHelper.getPropertyHelper( antProject );
427         try
428         {
429             // Ant 1.8.0 delegate
430             POMPropertyEvaluator.register( this, phelper );
431         }
432         catch ( LinkageError e )
433         {
434             // fallback to 1.6 - 1.7.1 intercepter chaining
435             helper.setNext( phelper.getNext() );
436             helper.setProject( antProject );
437             phelper.setNext( helper );
438         }
439     }
440 
441     /**
442      * The repositories defined in the ant "pom" task need to be added manually to the profile manager. Otherwise they
443      * won't be available when resolving the parent pom. MANTTASKS-87
444      */
445     private void addAntRepositoriesToProfileManager()
446     {
447         List<RemoteRepository> remoteRepositories = this.getRemoteRepositories();
448 
449         if ( remoteRepositories == null || remoteRepositories.isEmpty() )
450         {
451             return;
452         }
453         org.apache.maven.model.Profile repositoriesProfile = new org.apache.maven.model.Profile();
454         repositoriesProfile.setId( "maven-ant-tasks-repo-profile" );
455 
456         for ( RemoteRepository antRepo : remoteRepositories )
457         {
458             Repository mavenRepo = new Repository();
459             mavenRepo.setId( antRepo.getId() );
460             mavenRepo.setUrl( antRepo.getUrl() );
461             repositoriesProfile.addRepository( mavenRepo );
462         }
463 
464         getProfileManager().addProfile( repositoriesProfile );
465         getProfileManager().explicitlyActivate( repositoriesProfile.getId() );
466     }
467 
468     private ProfileManager getActivatedProfiles()
469     {
470         ProfileManager profileManager = getProfileManager();
471 
472         for ( Profile profile : getProfiles() )
473         {
474             if ( profile.getId() == null )
475             {
476                 throw new BuildException( "Attribute \"id\" is required for profile in pom type." );
477             }
478 
479             if ( profile.getActive() == null || Boolean.valueOf( profile.getActive() ).booleanValue() )
480             {
481                 profileManager.explicitlyActivate( profile.getId() );
482             }
483             else
484             {
485                 profileManager.explicitlyDeactivate( profile.getId() );
486             }
487 
488         }
489         return profileManager;
490     }
491 
492     /**
493      * Create a project builder configuration to be used when initializing the maven project.
494      *
495      * @return
496      */
497     private ProjectBuilderConfiguration createProjectBuilderConfig( ArtifactRepository localArtifactRepository )
498     {
499         ProjectBuilderConfiguration builderConfig = new DefaultProjectBuilderConfiguration();
500         builderConfig.setLocalRepository( localArtifactRepository );
501         builderConfig.setGlobalProfileManager( this.getActivatedProfiles() );
502         builderConfig.setUserProperties( getAntProjectProperties() );
503         builderConfig.setExecutionProperties( getAntProjectProperties() );
504 
505         return builderConfig;
506     }
507 
508     /**
509      * Convert the Hashtable of Ant project properties to a Properties object
510      *
511      * @return The Ant project properties
512      */
513     public Properties getAntProjectProperties()
514     {
515         Properties properties = new Properties();
516         Hashtable propsTable = null;
517         if ( this.isInheritAllProperties() )
518         {
519             propsTable = getProject().getProperties();
520         }
521         else
522         {
523             propsTable = getProject().getUserProperties();
524         }
525         Iterator propsIter = propsTable.keySet().iterator();
526 
527         while ( propsIter.hasNext() )
528         {
529             String key = (String) propsIter.next();
530             String value = (String) propsTable.get( key );
531             properties.setProperty( key, value );
532         }
533 
534         return properties;
535     }
536 
537     /**
538      * If set to true, all properties are passed to the maven pom. If set to false, only user properties are passed to
539      * the pom.
540      *
541      * @param inheritAllProperties
542      */
543     public void setInheritAllProperties( boolean inheritAllProperties )
544     {
545         this.inheritAllProperties = inheritAllProperties;
546     }
547 
548     public boolean isInheritAllProperties()
549     {
550         return inheritAllProperties;
551     }
552 
553     public Model getModel()
554     {
555         return getMavenProject().getModel();
556     }
557 
558     public void setGroupId( String groupId )
559     {
560         getMavenProject().setGroupId( groupId );
561     }
562 
563     public void setArtifactId( String artifactId )
564     {
565         getMavenProject().setArtifactId( artifactId );
566     }
567 
568     public void setVersion( String version )
569     {
570         getMavenProject().setVersion( version );
571     }
572 
573     public void addConfiguredParent( Parent parent )
574     {
575         getMavenProject().getModel().setParent( parent );
576     }
577 
578     public void addConfiguredCiManagement( CiManagement ciManagement )
579     {
580         getMavenProject().setCiManagement( ciManagement );
581     }
582 
583     public void addConfiguredContributor ( Contributor contributor )
584     {
585         getMavenProject().addContributor( contributor );
586     }
587 
588     public void addConfiguredDependency( Dependency dependency )
589     {
590         getMavenProject().getDependencies().add( dependency );
591     }
592 
593     public void addConfiguredDependencyManagement( DependencyManagement dependencyManagement )
594     {
595         if ( getMavenProject().getDependencyManagement() == null )
596         {
597             // is is a bit disappointing that we have to access the encapsulated model to fix the NPE
598             getMavenProject().getModel().setDependencyManagement(new DependencyManagement());
599         }
600         getMavenProject().getDependencyManagement().setDependencies( dependencyManagement.getDependencies() );
601     }
602 
603     public void setDescription( String description )
604     {
605         getMavenProject().setDescription( description );
606     }
607 
608     public void addConfiguredDeveloper( Developer developer )
609     {
610         getMavenProject().addDeveloper( developer );
611     }
612 
613     public void setInceptionYear( String inceptionYear )
614     {
615         getMavenProject().setInceptionYear( inceptionYear );
616     }
617 
618     public void addConfiguredIssueManagement( IssueManagement issueManagement )
619     {
620         getMavenProject().setIssueManagement( issueManagement );
621     }
622 
623     public void addConfiguredLicense ( License license )
624     {
625         getMavenProject().addLicense( license );
626     }
627 
628     public void addConfiguredMailingLists( MailingList mailingList )
629     {
630         getMavenProject().addMailingList( mailingList );
631     }
632 
633     public void setName( String name )
634     {
635         getMavenProject().setName( name );
636     }
637 
638     public void addConfiguredOrganization( Organization organization )
639     {
640         getMavenProject().setOrganization( organization );
641     }
642 
643     public void setPackaging( String packaging )
644     {
645         getMavenProject().setPackaging( packaging );
646     }
647 
648     public void addConfiguredScm( Scm scm )
649     {
650         getMavenProject().setScm( scm );
651     }
652 
653     public void setUrl( String url )
654     {
655         getMavenProject().setUrl( url );
656     }
657 
658 }