-
Notifications
You must be signed in to change notification settings - Fork 9
Code Inspection
- Use PMD as a code quality metric tool for preemptive defect detection.
- Obtain an html report with the different detected issues in the code using Maven.
- Eclipse IDE for Java Developers >= 2021‑03 Download from Eclipse || Get executable
- Git
PMD is a source code analyzer. It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth [1]. Like other tools, PMD can verify that coding conventions and standards are followed. PMD is more focused on preventive defect detection. It comes with a vast set of rules and is highly configurable. PMD can also configure - in a simple way - particular rules to use in a specific project [2].
PMD integrates well with IDEs such as Eclipse and NetBeans, and it also fits well into the build process thanks to its smooth integration with Ant and Maven [2].
For this lab, we will use Eclipse and Maven together with PMD to inspect the source code of a project.
Most Eclipse download include the maven tooling already. If it is missing in your installation, follow these steps, otherwise jump to part two:
- Open the plugin installation window by selecting the “help >> Install new software”.
- Click on add and type Maven for the name and http://download.eclipse.org/releases/neon for the location.
- Click “Add” again and wait until the process finishes.
- Check “Maven Integration for Eclipse” under “General Purpose Tools”.
- Download pmd-bin-6.35.0.zip
- Extract the zip-archive, e.g. to C:\pmd-bin-6.35.0
- Add folder C:\pmd-bin-6.35.0\bin to PATH, either
- Permanently: Using System Properties dialog > Environment variables > Append to PATH variable
- Temporarily, at command line: SET PATH=C:\pmd-bin-6.35.0\bin;%PATH%
- Execute at command line: pmd.bat -d c:\src -R rulesets/java/quickstart.xml -f text
or download it from the eclipse marketplace
- Fork the following repository: CodeInspection and open the project in eclipse.
- PMD will not be activated for the project by default. Open the project properties window by clicking in “Project >> Properties”.
- Select “PMD” on the side bar and check “Enabled PMD “.

- Look at all the rulesets that come with PMD, leave the default set of rules.
- Click “Apply and Close” and “Yes”.
Go to “Window >> Preferences”, select “PMD” and check “Check code after saving”

To run PMD, right click on the project and select “PMD >> Check code”
Two new windows are displayed with all violations. Each violation has its priority represented by a color and corresponding rule. The meaning of the colors is:
- Red is blocker >>> High priority.
- Cyan is critical >>> Medium priority.
- Green is urgent >>> Medium priority.
- Pink is Important >>> Medium priority.
- Blue is Warning >>> Low priority.

If you see that files are duplicated in the Violation Overview Window, check code again.
PMD shows the violations next to the lines that generate them.

We can filter violations using the color indicators on the top right of Violations Overview window.
For example, if we filter only by critical violations, Violations Overview window shows that Email.java and EmalApp.java have 2 and 3 violations respectively for the rule “SystemPrintln”. If we double-click on an element, the Violation Outline window will update showing all errors related to a file and some important data such as the violation line, the affected rule, and the error message.

We can right-click on a violation and select "Show details..." for more information and an example solution.

For more information about configurations, refer to section 2 and 3 from chapter 22 of the book [2] and PMD website [1].
A PMD ruleset is simply an XML file that lists a set of rules that fit the project. You can include entire rulesets, or selectively choose specific rules from within other rulesets. You can also provide extra parameters to certain rules to customize their behavior. To do so, follow these steps:
- Right click on the project, then “New >> Other >> XML >> XML File”.
- Select the project, enter a file name as “_ ruleset “
- Click “Source” in the bottom tab to change the view and edit the file directly.

- Here is a fragment of a typical configuration document, copy and paste into the file:
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="<your name> Rules"
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 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
Code Inspection Lab, <your full name>
</description>
</ruleset>
- Let’s reference a complete ruleset. Add the following line below the description tag:
<rule ref="category/java/performance.xml" />
This ruleset comes by default with PMD and it has rules that flag suboptimal code.
- Now, add another reference, but exclude some rules from the ruleset:
<rule ref="category/java/bestpractices.xml">
<exclude name="SystemPrintln" />
</rule>
This ruleset also comes by default with PMD and it has rules which enforce generally accepted best practices but excluding “SystemPrintln” rule.
- We can add rules from a specific ruleset as follow:
<rule ref="category/java/design.xml/ImmutableField" />
<rule ref="category/java/design.xml/UseUtilityClass">
<priority>1</priority>
</rule>
Here, we are adding “ImmutableField” rule and “UseUtilityClass” rule from the Design ruleset and changing its priority to 1. Priority is an integer ranging from 1 to 5, with 1 being the highest priority.
For more information about PMD rulesets, refer to PMD documentation [3]
- To use an external ruleset, we need to go to the PMD Configuration Window. Go to “Window >> Preferences PMD Rule Configurations”.
- Check “Use global rule management”, then group rules by “Rule Set”.
- Select all the rule sets and click in the “X” button to delete them.
- Click "Import rule set..." (under the "x"), browse your file and Click “Ok”.
- The rules we added are not listed yet, press "Apply and close", then "Yes".
- Return to PMD Configuration Window. Notice that the checkbox next to the rule names is unchecked.

- Press "Apply and close", then "Yes".
- Right click on the project and select “PMD >> Clear Violations”. Then “PMD Check Code.”
Note that it is possible to configure the properties for each rule we add. To learn more about rulesets and their properties, refer to PMD Java Rules [3]
- Open PMD configuration window, select Reports and check “html.”

- Right-click the project then click “PMD Generate Report.”
- A folder named reports is created in the tree project. Open it and double click the “pmd-report.html” to see the full report.

Sometimes you will have a legitimate reason for not respecting one of the PMD rules. PMD provides several methods by which Rule violations can be suppressed. We will be using comments and annotations.
- Go to Email.java. See that line 5 has a violation related to ImmutableField rule.
- Write “NOPMD” as a comment in the same line where the violation occurred.
- Optionally, add a message placed after the NOPMD marker. This will get placed in the report.

4. Go to EmailApp.java and check the violation. The rule violated is “UseUtilityClass”. 5. Write an annotation above the line as follow:

Please note that only that rule will be ignored.
6. Save the file and see the results.
For more information about suppressing rules, check the PMD website [4] and section 7 from chapter 22 of the book [2]
PMD comes with a useful tool for detecting cut-and-pasted code called CPD (Cut-and-Paste Detector). Follow these steps to use it and generate a report.
- Just for demonstration purpose, copy and paste the “randomPassword” method from Email.java to EmalApp.java.
- Right-click the project and select “PMD >> Find Suspect Cut and Paste” from menu options.
- Select “java” for Language, then click “Ok”.

- CPD View Window will open with the results. Also, a text file called cpd-report.txt will be generated in the /report directory.

- Revert the changes made in EmailApp.java.
- Open “pom.xml” file

- Add the following lines under project tag to install all the necessary plugins:
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.13.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<rulesets>
<ruleset><yourname>_ruleset.xml</ruleset>
</rulesets>
</configuration>
</plugin>
</plugins>
</reporting>
The ruleset tag is used to specify a file that contains rules to use in the checking process. In this case, we are telling the plugin to use our ruleset file. 3. Save the file, right Click on it, then “Run as >> Maven build…” 4. Type “site" for the Goals and Click Run.

- Wait for the process to finish.

- Go to your project directory, open “target>> site”. This folder is visible from the tree project in Eclipse too.
- Several html files are shown. Open “index.html".

- Click on “Project Reports PMD” to see a detailed PMD report of your project.

- Delete all comments and annotations from the code.
- Add the following ruleset and rules:
- Code Style Ruleset
- Rule “BeanMembersShouldSerialize” from Error Prone ruleset with a priority of 2
- Rule “UseLocaleWithCaseConvertion” from Error Prone ruleset
- Rule “CommentRequired” from Documentation ruleset with these properties set to “Ignored”:
- classCommentRequirement
- headerCommentRequirement
- fieldCommentRequirement
TIP: Refer to the PMD Java Rules [3].
The errors per class are show below:

- Generate an html report, make a copy and save it somewhere on your disk.
- Correct any violation in the code that have been generated in the report.
- Generate a new report (without violations).
- Lab report with screenshots of the process.
- Two PMD reports.
- Include in the report the url of the repository where you performed the lab.
╔════════════════════════════════════════════════════════════════════╦═══════╗
║ Description ║ Value ║
╠════════════════════════════════════════════════════════════════════╬═══════╣
║ Project code (in a repository) ║ 50 ║
╠════════════════════════════════════════════════════════════════════╬═══════╣
║ Lab report ║ 50 ║
╠════════════════════════════════════════════════════════════════════╬═══════╣
║ Penalty per hour or fraction of delay ║ -30 ║
╠════════════════════════════════════════════════════════════════════╬═══════╣
║ Penalty for not uploading required deliverables as specified ║ -30 ║
╚════════════════════════════════════════════════════════════════════╩═══════╝