Using the PMD Eclipse plugin on Android projects

This post will explain how to configure the Eclipse project of an Android application to use PMD and create a custom ruleset crafted for the Android platform used to detect violations automatically.

Starting with version 4.2.5, PMD has some rules specific for Android development, defined  in the android.xml ruleset included in the PMD distribution. The newest version of the PMD eclipse plugin, version 3.2.6,  includes some improvements so that the plugin can be used to check for violations on Android project.

First, you need to install the PMD Eclipse plugin by following the instructions on the plugin page.

Next, configure your project: in the project properties, select the PMD page. “Enable PMD” needs to be checked to run PMD automatically. Otherwise, you will need to manually start PMD each time you want to check your code using the PMD submenu and older violations will not be removed automatically once you fix your code, you will need to use the clear violations in the PMD submenu.

The “Handle high priority violations as errors” property needs to be unchecked. This is a new property in the 3.2.6 version of the PMD eclipse plugin. When that option is checked, the Android plugin will refuse to deploy your application if the project contains high level violations. So unless you have a development rule stating that there should be no high level violations in your project at any time, this option should be disabled.

With that setup, PMD will be enabled but it will be using the default ruleset shared by all projects in the workspace and that is not really adequate for Android development. To define a specific set of rules for your project, check the last box on the PMD page to create a file named “.ruleset” at the top level of your project. The configuration is now complete, press “OK” and then select “Yes” on the next popup.

A new “.pmd” file has now been created at the top level containing:

<?xml version="1.0" encoding="UTF-8"?>
<pmd>
  <useProjectRuleSet>true</useProjectRuleSet>
  <ruleSetFile>.ruleset</ruleSetFile>
  <includeDerivedFiles>false</includeDerivedFiles>
  <violationsAsErrors>false</violationsAsErrors>
</pmd>

The “.ruleset” file was also created and at this point references the workspace default rules. This file should be replaced to use rules more appropriate for Android development. For instance, you could replace its content with:

<?xml version="1.0"?>
<ruleset name="Android Application Rules"
    xmlns="http://pmd.sf.net/ruleset/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
    xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">

  <description>Ruleset for Android application</description>

  <exclude-pattern>.*/R.java</exclude-pattern>
  <exclude-pattern>.*/gen/.*</exclude-pattern>

  <rule ref="rulesets/android.xml"/>

  <rule name="DoNotHardCodeSDCard"
      message="Do not hardcode /sdcard."
      class="net.sourceforge.pmd.rules.XPathRule">
    <description>Use Environment.getExternalStorageDirectory() instead of "/sdcard"</description>
    <priority>3</priority>
    <properties>
      <property name="xpath">
        <value>//Literal[starts-with(@Image,'"/sdcard')]</value>
      </property>
    </properties>
  </rule>

  <rule ref="rulesets/clone.xml"/>
  <rule ref="rulesets/finalizers.xml"/>
  <rule ref="rulesets/imports.xml"/>
  <rule ref="rulesets/logging-java.xml"/>
  <rule ref="rulesets/naming.xml">
    <exclude name="AbstractNaming"/>
    <exclude name="LongVariable"/>
    <exclude name="LongMethodName"/>
    <exclude name="ShortMethodName"/>
    <exclude name="ShortVariable"/>
    <exclude name="VariableNamingConventions"/>
  </rule>

</ruleset>

The customization starts with ignoring R.java and the ‘gen’ directory introduced in the 1.5 SDK as it only contains automatically generated classes. Following that is the custom ruleset definition, starting with all the rules from the Android ruleset (android.xml), then a locally defined XPath based rule to check that “/sdcard” is not used (this rule will be part of the standard ruleset in future PMD versions) and finally some standard rulesets are included either entirely or as a subset of their rules.

Once you’ve modified “.ruleset” and refreshed the Eclipse workspace, the PMD plugin will use the new ruleset to flag violations and update the warnings on the fly in the Problems tab of the Java perspective. The PMD perspective can also be used to see an overview of the violations per package and to have access to detailed violation outlines for each warning.

Up to this point, the settings have only dealt with the Eclipse plugin but the same ruleset can also be used from the command line so that both Eclipse and ant will report the same violations. To do so, add the following target definition in the build.xml file:

    <target name="pmd">
        <fail unless="pmd.home" message="pmd.home must be defined" />
        <path id="pmd.path">
            <fileset dir="${pmd.home}/lib" includes="*.jar"/>
        </path>
        <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask" classpathref="pmd.path" />

        <pmd shortFilenames="true">
            <auxclasspath>
                <pathelement location="${android-jar}"/>
                <pathelement location="${out-classes}" />
                <fileset dir="libs">
                    <include name="*.jar" />
                </fileset>
            </auxclasspath>
            <formatter type="text" toConsole="true"/>
            <ruleset>.ruleset</ruleset>
            <fileset dir="${source-folder}" includes="**/*.java" />
        </pmd>
    </target>

The only additional ant configuration needed is to define pmd.home in build.properties to point to the PMD installation on your machine.

By following the steps above, you will be able to get started using PMD on Android projects. More ruleset customizations will be covered in a future post, based on the best practice documents on the Android site  (the design for performance and code style documents) and the feedback from users. Please forward suggestions on improvements and possible new PMD rules to be added to future versions.

Tags: ,

3 Responses to “Using the PMD Eclipse plugin on Android projects”

  1. [...] and the PMD Eclipse plugin have Android features. Xavier Le Vourch of XLV Labs was nice enough to wrtie up a basic blog post dettailing how to use the new features in PMD for Andrpoid. All, [...]

  2. Android says:

    Thank yo for sharing this info.

  3. JamesD says:

    Thanks for the useful info. It’s so interesting

Leave a Reply