View Javadoc
1   package org.apache.maven.plugins.help;
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.Writer;
25  import java.util.List;
26  
27  import org.apache.maven.artifact.Artifact;
28  import org.apache.maven.artifact.repository.ArtifactRepository;
29  import org.apache.maven.execution.MavenSession;
30  import org.apache.maven.model.building.ModelBuildingRequest;
31  import org.apache.maven.plugin.AbstractMojo;
32  import org.apache.maven.plugin.MojoExecutionException;
33  import org.apache.maven.plugins.annotations.Component;
34  import org.apache.maven.plugins.annotations.Parameter;
35  import org.apache.maven.project.DefaultProjectBuildingRequest;
36  import org.apache.maven.project.MavenProject;
37  import org.apache.maven.project.ProjectBuilder;
38  import org.apache.maven.project.ProjectBuildingRequest;
39  import org.apache.maven.shared.transfer.artifact.ArtifactCoordinate;
40  import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate;
41  import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver;
42  import org.codehaus.plexus.util.IOUtil;
43  import org.codehaus.plexus.util.StringUtils;
44  import org.codehaus.plexus.util.WriterFactory;
45  
46  /**
47   * Base class with some Help Mojo functionalities.
48   *
49   * @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a>
50   * @since 2.1
51   */
52  public abstract class AbstractHelpMojo
53      extends AbstractMojo
54  {
55      /** The maximum length of a display line. */
56      protected static final int LINE_LENGTH = 79;
57      
58      /** The line separator for the current OS. */
59      protected static final String LS = System.getProperty( "line.separator" );
60      
61      /**
62       * Maven Project Builder component.
63       */
64      @Component
65      protected ProjectBuilder projectBuilder;
66      
67      /**
68       * Component used to resolve artifacts and download their files from remote repositories.
69       */
70      @Component
71      protected ArtifactResolver artifactResolver;
72      
73      /**
74       * Remote repositories used for the project.
75       */
76      @Parameter( defaultValue = "${project.remoteArtifactRepositories}", required = true, readonly = true )
77      protected List<ArtifactRepository> remoteRepositories;
78      
79      /**
80       * Local Repository.
81       */
82      @Parameter( defaultValue = "${localRepository}", required = true, readonly = true )
83      protected ArtifactRepository localRepository;
84      
85      /**
86       * The current build session instance. This is used for
87       * plugin manager API calls.
88       */
89      @Parameter( defaultValue = "${session}", readonly = true, required = true )
90      protected MavenSession session;
91  
92      /**
93       * Optional parameter to write the output of this help in a given file, instead of writing to the console.
94       * <br>
95       * <b>Note</b>: Could be a relative path.
96       */
97      @Parameter( property = "output" )
98      protected File output;
99  
100     /**
101      * Utility method to write a content in a given file.
102      *
103      * @param output is the wanted output file.
104      * @param content contains the content to be written to the file.
105      * @throws IOException if any
106      * @see #writeFile(File, String)
107      */
108     protected static void writeFile( File output, StringBuilder content )
109         throws IOException
110     {
111         writeFile( output, content.toString() );
112     }
113 
114     /**
115      * Utility method to write a content in a given file.
116      *
117      * @param output is the wanted output file.
118      * @param content contains the content to be written to the file.
119      * @throws IOException if any
120      */
121     protected static void writeFile( File output, String content )
122         throws IOException
123     {
124         if ( output == null )
125         {
126             return;
127         }
128 
129         Writer out = null;
130         try
131         {
132             output.getParentFile().mkdirs();
133 
134             out = WriterFactory.newPlatformWriter( output );
135 
136             out.write( content );
137 
138             out.close();
139             out = null;
140         }
141         finally
142         {
143             IOUtil.close( out );
144         }
145     }
146     
147     /**
148      * Parses the given String into GAV artifact coordinate information, adding the given type.
149      * 
150      * @param artifactString should respect the format <code>groupId:artifactId[:version]</code>
151      * @param type The extension for the artifact, must not be <code>null</code>.
152      * @return the <code>Artifact</code> object for the <code>artifactString</code> parameter.
153      * @throws MojoExecutionException if the <code>artifactString</code> doesn't respect the format.
154      */
155     protected ArtifactCoordinate getArtifactCoordinate( String artifactString, String type )
156         throws MojoExecutionException
157     {
158         if ( StringUtils.isEmpty( artifactString ) )
159         {
160             throw new IllegalArgumentException( "artifact parameter could not be empty" );
161         }
162 
163         String groupId; // required
164         String artifactId; // required
165         String version; // optional
166 
167         String[] artifactParts = artifactString.split( ":" );
168         switch ( artifactParts.length )
169         {
170             case 2:
171                 groupId = artifactParts[0];
172                 artifactId = artifactParts[1];
173                 version = Artifact.LATEST_VERSION;
174                 break;
175             case 3:
176                 groupId = artifactParts[0];
177                 artifactId = artifactParts[1];
178                 version = artifactParts[2];
179                 break;
180             default:
181                 throw new MojoExecutionException( "The artifact parameter '" + artifactString
182                     + "' should be conform to: " + "'groupId:artifactId[:version]'." );
183         }
184         return getArtifactCoordinate( groupId, artifactId, version, type );
185     }
186 
187     protected ArtifactCoordinate getArtifactCoordinate( String groupId, String artifactId, String version, String type )
188     {
189         DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate();
190         coordinate.setGroupId( groupId );
191         coordinate.setArtifactId( artifactId );
192         coordinate.setVersion( version );
193         coordinate.setExtension( type );
194         return coordinate;
195     }
196 
197     /**
198      * Retrieves the Maven Project associated with the given artifact String, in the form of
199      * <code>groupId:artifactId[:version]</code>. This resolves the POM artifact at those coordinates and then builds
200      * the Maven project from it.
201      * 
202      * @param artifactString Coordinates of the Maven project to get.
203      * @return New Maven project.
204      * @throws MojoExecutionException If there was an error while getting the Maven project.
205      */
206     protected MavenProject getMavenProject( String artifactString )
207         throws MojoExecutionException
208     {
209         ArtifactCoordinate coordinate = getArtifactCoordinate( artifactString, "pom" );
210         try
211         {
212             ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() );
213             pbr.setRemoteRepositories( remoteRepositories );
214             pbr.setProject( null );
215             pbr.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
216             pbr.setResolveDependencies( true );
217             Artifact artifact = artifactResolver.resolveArtifact( pbr, coordinate ).getArtifact();
218             return projectBuilder.build( artifact.getFile(), pbr ).getProject();
219         }
220         catch ( Exception e )
221         {
222             throw new MojoExecutionException( "Unable to get the POM for the artifact '" + artifactString
223                 + "'. Verify the artifact parameter.", e );
224         }
225     }
226 
227 }