Maven plugins with the archetype plugin

In Chapter 5, Maven Plugins, we discussed in detail how to develop Maven plugins. However, in all of those cases, we started from scratch, building everything from the project structure to everything by hand. Now, we will look at how to create a Maven plugin project with the archetype plugin. Here, we use the maven-archetype-plugin:

$ mvn archetype:generate 
                  -DgroupId=com.packt.samples
                  -DartifactId=com.packt.samples.plugins.myplugin
                  -DarchetypeGroupId=org.apache.maven.archetypes
                  -DarchetypeArtifactId=maven-archetype-plugin
                  -DinteractiveMode=false

The previous command will produce the following directory structure and the source code. If you look at the pom.xml file, you will notice that it contains all necessary instructions along with the required dependencies that are needed to build the Maven plugin project:

com.packt.samples.plugins.myplugin
                  |-pom.xml
                  |-src
                     |-main/java/com/packt/samples/MyMojo.java
                     |-it/settings.xml
                        |-simple-it/pom.xml
                        |-simple-it/verify.groovy

Let's have a look at the generated MyMojo.java file. This class is a template plugin class, which extends from org.apache.maven.plugin.AbstractMojo. This is a good example that demonstrates the capability of Maven archetypes to generate Java code templates and is also the most used use case of archetypes. Whenever your project has extension points (such as handlers), you can create an archetype to build them, and this will surely make the life of programmers extremely comfortable:

package com.packt.samples;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
  * Goal, which touches a timestamp file.
  *
  * @deprecated - Don't use!
*/
@Mojo(name="touch",defaultPhase =LifecyclePhase.PROCESS_SOURCES)
public class MyMojo extends AbstractMojo
{
  /**
    * Location of the file.
  */
  @Parameter(defaultValue="${project.build.directory}", property = "outputDir", required = true )
  private File outputDirectory;

  public void execute() throws MojoExecutionException
  {
    //add your code here.
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.54.245