June 14, 2024

Today, I tried using PMD with Eclipse. And it looks like PMD is a powerful error checking tool.

Here’s how I installed it. First, I downloaded PMD for Eclipse from SourceForge. Then I unzipped it into c:eclipseplugins and restarted Eclipse.

To use PMD, right click on a project in the navigator view. Then go to PMD/Check code with PMD. All the errors it finds will show up in the task list. To choose which rules it uses, right click on the project and go to properties. Then select PMD and check/uncheck the rules.

You can also have more flexibility by using it as an ant task. However, it doesn’t report the errors in the task list, but sends it to a file (and optionally to the console).

I created a file in my project ./rulesets/project_rules.xml:

<?xml version="1.0"?>
<ruleset name="Project Ruleset">

  <description>
  PMD project ruleset
  </description> 

  <rule ref="rulesets/basic.xml"/>
  <rule ref="rulesets/braces.xml"/>
  <rule ref="rulesets/codesize.xml"/>
  <rule ref="rulesets/controversial.xml"/>
  <rule ref="rulesets/design.xml"/>
  <rule ref="rulesets/favorites.xml"/>
  <rule ref="rulesets/imports.xml"/>
  <rule ref="rulesets/javabeans.xml"/>
  <rule ref="rulesets/junit.xml"/>
  <rule ref="rulesets/naming.xml"/>
  <rule ref="rulesets/newrules.xml"/>
  <rule ref="rulesets/scratchpad.xml"/>
  <rule ref="rulesets/strictexception.xml"/>
  <rule ref="rulesets/strings.xml"/>
  <rule ref="rulesets/unusedcode.xml"/>

<ruleset>

Then I added a task in my ant build.xml:

   <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>

	<target name="pmd">
	    <pmd rulesetfiles="${basedir}/rulesets/project_rules.xml"
	            printToConsole="true">
			<formatter type="text" toFile="pmd_report.txt"/>
	        <fileset dir="${src.dir}">
	            <include name="**/*.java"/>
	        </fileset>
	    </pmd>
	</target>

Finally, I added all the jar files in c:eclipsepluginsnet.sourceforge.pmd.eclipse_1.2.0lib into the ant runtime classpath.

Then I ran the pmd ant task and it reported a ton of errors.

Links:
PMD – SourceForge
Static Analysis with PMD – OnJava
Custom PMD Rules – OnJava
Detecting Duplicate Code with PMD’s CPD – OnJava