See how maven works inside – remote debugging plugins

England Who uses maven as I do for a long time, knows that sometimes things does not go as expected. So it’s necessary to look at the ultimate documentation: the source code! In this post I’ll show how to debug a maven plugin using Eclipse’s remote debugger. I’ve chosen for this example the maven-clean-plugin.

Ok, let’s start. First create a simple sample project:

    mvn archetype:create -DgroupId=com.wordpress -DartifactId=maven-debug

In the folder maven-debug, edit the pom.xml and add the dependency of the plugin. This will serve as an “anchor” to bring all the sources needed to debug.

<dependency> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-clean-plugin</artifactId> 
       <version>2.1.1</version> 
       <scope>provided</scope> 
</dependency>

Note the scope “provided”, meaning that the dependency will be given to the project by someone and it should not make to the final package. It shouldn’t matter, anyway, since this is a dependency that will be removed later, it’s just for debug purposes.

It’s important to know what version of the plugin your project is using. When in doubt, run “mvn -X clean” and note lines like:

  [DEBUG] Retrieving parent-POM: org.apache.maven.plugins:maven-plugins::3 for project: 
           null:maven-clean-plugin:maven-plugin:2.1.1 from the repository.

Now generate the project in eclipse:

   mvn -Declipse.downloadSources=true eclipse:eclipse

Open eclipse, go to File -> Import -> Existing Projects into Workspace and select the root directory of the project. After that go to menu
“Run –> Open debug dialog” and under “Remote java application” create a new profile to debug our project:
debug.jpg

Using the eclipse search facilities, search for a class which name ends with “Mojo” (Maven Old Java Object) and place a breakpoint in the “execute” method. In the case of the clean plugin, this class is called CleanMojo

To debug, first enable debug on maven in the command line (linux shown here)

MAVEN_OPTS="-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"; 
export MAVEN_OPTS

and then do a “mvn clean”; the process will halt. Start the debugger in eclipse, it will hit the breakpoint.

breakpoint.jpg

Congratulations! Now you can know exactly what’s going on!