Calling a Maven plugin from another plugin

Last modified by Vincent Massol on 2019/06/11 10:11

Jan 27 2014

Normally you're not supposed to call a Maven plugin's mojo from another mojo but there are times when you may have this need. In my case I was developing a plugin and I needed to call the Maven License Plugin from within my mojo.

I succeeded in achieving this through the Maven Executor plugin.

Without further ado here's the code that worked for me:

[...]
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.element;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.goal;
import static org.twdata.maven.mojoexecutor.MojoExecutor.name;

[...]
* @requiresProject
* @requiresDependencyResolution compile
* @threadSafe
*/
public class FormatMojo extends AbstractVerifyMojo
{
   /**
     * The project currently being build.
     *
     * @parameter expression="${project}"
     * @required
     * @readonly
     */

   private MavenProject project;

   /**
     * The current Maven session.
     *
     * @parameter expression="${session}"
     * @required
     * @readonly
     */

   private MavenSession mavenSession;

   /**
     * The Maven BuildPluginManager component.
     *
     * @component
     * @required
     */

   private BuildPluginManager pluginManager;

[...]

   @Override
   public void execute() throws MojoExecutionException, MojoFailureException
   {
       [...]
       // Find the license plugin (it's project's responsibility to make sure the License plugin is properly setup in
       // its <pluginManagement>, for most XWiki projects it just mean inherits from xwiki-commons-pom)
       Plugin licensePlugin =
           this.project.getPluginManagement().getPluginsAsMap().get("com.mycila:license-maven-plugin");

       if (licensePlugin == null) {
           throw new MojoExecutionException("License plugin could not be found in <pluginManagement>");
       }

        executeMojo(
            licensePlugin,
            goal("format"),
            configuration(
                element(name("header"), "license.txt"),
                element(name("strictCheck"), "true"),
                element(name("headerDefinitions"),
                    element(name("headerDefinition"), "license-xml-definition.xml")),
                element(name("includes"),
                    element(name("include"), "src/main/resources/**/*.xml"))
           ),
            executionEnvironment(
               this.project,
               this.mavenSession,
               this.pluginManager
           )
       );
   }
[...]
}

And boom it worked! emoticon_smile

Hope this can be useful to someone.

Created by Vincent Massol on 2014/01/27 14:58