Code Quality Tool- PMD with Ant Integration Quick Guide

Value of code Reviews in brief

Code review is formal process for examining software source code to identify problems and improve software quality.

Types of  reviews

Automated tools :- PMD, FindBugs, CheckStyle ect.
Reduce the difficult and slow review of source code. Can Identify code issues quickly in early stage.

Lightweight code reviews (Peer Review)
Get the source code and log the findings of the Peer’s code.

Software inspections:
Product is selected for review and a team is gathered for an inspection meeting to review the work product.

PMD What does it mean?

Pretty Much Done
Project Mess Detector
Project Monitoring Directives
Project Meets Deadline
Programming Mistake Detector
Pounds Mistakes Dead

What is PMD?
PMD is a Automated Code Quality Review Tool. Rules can be configured easily. Tool helps to capture major programming defects in java.

PMD scans Java source code and looks for problems

Possible bugs – empty try/catch/finally/switch statements
Dead code – unused local variables, parameters and private methods
Suboptimal code – wasteful String/StringBuffer usage
Over complicated expressions – unnecessary if statements, for loops that could be while loops
Duplicate code – copied/pasted code means copied/pasted bugs

PMD Tool – Legal BackGround

PMD has “BSD” License.

What is BSD?
A BSD  (Berkeley Software Distribution) licence essentially says to other developers, “do what you like, so long as you retain my copyright note and disclaimer”.

The GPL and the BSD license are both “free”, and “open source”, as they are approved by both the FSF and the OSI


Configuring PMD with Source Code

PMD Jar file can be downloaded from http://pmd.sourceforge.net/

What is rules.xml ?

Contains the code quality rules. There are number of rule files in different categories. Rules files can be found in /rulesets folder inside pmd-x.x.jar.
Eg.
basic.xml, design.xml, import.xml

Rules can be easily customized by maintaining separate rule configuration file.

Priority levels can be set on those rules.

How to create RuleSet ?
Copy and use following lines to create rule.xml file.


<?xml version="1.0"?>
<ruleset name="Custom ruleset"
   xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
 <description>
 This ruleset checks my code for bad stuff
 </description>
</ruleset>




 

 

Add the rules one by one

<!-- Here's some rules we'll specify one at a time -->
 <rule ref="rulesets/java/unusedcode.xml/UnusedLocalVariable"/>
 <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateField"/>

You can select pre defined rules from /rulesets folder inside pmd-x.x.jar.
Eg.
basic.xml, design.xml, import.xml

Setting priority Levels and Customize messages for Rules.

Default error messages and priority levels can be overridden in custom ruleset.xml file.
eg :

 <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"
  message="Avoid unused private methods">
 <priority>3</priority>
 </rule>

User Defined Rules

New Rules can be defined base on specific project requirments.
There are two ways of defining customize rules.

Following two method can be use to create new rule.
Write a rule using Java
Write an XPath expression

Here I am not going to describe them in detail.

Integrating RuleSet with Busines Project.

Following are the steps of Integrating PMD custom ruleset with source code.

1.   Create ruleset.xml file.
2.   Integrate ruleset.xml file with build target.
3.   Generate PMD report

Following are most freequently using rules.

EmptyCatchBlock
AvoidUsingHardCodedIP
UseArraysAsList
AvoidArrayLoops
MethodArgumentCouldBeFinal
AvoidInstantiatingObjectsInLoops
SwitchStmtsShouldHaveDefault
CompareObjectsWithEquals
UnusedImports/MissingBreakInSwitch …. ect


Ant Targets to Generates PMD Report.

<target name="create-pmd-report">
<MACRO DEF TARGET NAME pmdmodule="sourcePackageNameOne" 
</target>

Macro def target is as follows.

	<!-- = = = = = = = = = = = = = = = = =
          macrodef: target        
         = = = = = = = = = = = = = = = = = -->
    <macrodef name="MACRO DEF TARGET NAME">
     <!--default package name can be set -->
        <attribute name="pmdmodule" default="common" />
 
        <sequential>
		<echo message="----Running pmd report from @{pmdmodule}"/>
		<taskdef name="pmd"   classpathref="pmd.taskdef.classpath" classname="net.sourceforge.pmd.ant.PMDTask"/>
		<fail unless="target.reports.pmd" message="@{pmdmodule} is not set"/>
			<delete dir="${target.reports.pmd}/@{pmdmodule}"/>
			<mkdir  dir="${target.reports.pmd}/@{pmdmodule}"/>

			 <pmd rulesetfiles="${basedir}/docs/pmdRules/pmdRules.xml">

				        <formatter type="xml" toFile="${target.reports.pmd}/@{pmdmodule}/@{pmdmodule}-pmd-report.xml" linkPrefix="${src.main}/"/>
						 <fileset dir="${basedir}/@{pmdmodule}">
				            <include name="**/*.java"/>
				        </fileset>

				    </pmd>

<xslt in="${target.reports.pmd}/@{pmdmodule}/@{pmdmodule}-pmd-report.xml" style="${basedir}/docs/pmdRules/ag-pmd-report.xslt" out="${target.reports.pmd}/@{pmdmodule}/@{pmdmodule}-pmd-report.html">
<param name="title" expression="Release branch details : ${release.branch} -@{pmdmodule}- Release Revision No: ${release.revision}" />
</xslt> 
  </sequential>
  </macrodef>

PMD Rule file (pmdRules.xml) is placed inside ${basedir}/docs/pmdRules/”

Here I have used ag-pmd-report.xslt to get look and feel of the generated report.

Following is Generated PMD Report.

Report displays number of violations in each file and their priority levels
Following is screen-shot of it.
eg :

PMD2

It displays the detailed violations of each file When you click on each file.

eg:
PMD111

Advertisements
Posted in Uncategorized
4 comments on “Code Quality Tool- PMD with Ant Integration Quick Guide
  1. kalhari says:

    Very useful and comprehensive post, good work Hasitha

  2. explains very well about using PMD. Thanks!!

  3. Asiri says:

    Nicely done article . Any one who know nothing about PMD , can easily configure PMD tool with their source following this steps. Helps me a lot .

  4. Dick Manning says:

    Great article, This saved my day. Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: