Code Inspection - leortyz/softwareEngineeringResources GitHub Wiki

Download spec file


Objectives

  • 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.

Requirements

Introduction

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.  

Activity

Part 1: Install Maven for Eclipse.

Most Eclipse download include the maven tooling already. If it is missing in your installation, follow these steps, otherwise jump to part two:

  1. Open the plugin installation window by selecting the β€œhelp >> Install new software”.
    Install new software
  2. Click on add and type Maven for the name and http://download.eclipse.org/releases/neon for the location.
    Maven neon
  3. Click β€œAdd” again and wait until the process finishes.
  4. Check β€œMaven Integration for Eclipse” under β€œGeneral Purpose Tools”.
    m2e

Part 2: Install the Eclipse PDM plug-in

  1. Download pmd-bin-6.35.0.zip
  2. Extract the zip-archive, e.g. to C:\pmd-bin-6.35.0
  3. 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%
  1. Execute at command line: pmd.bat -d c:\src -R rulesets/java/quickstart.xml -f text

or download it from the eclipse marketplace

_

Part 3: Download and configure the project.

  1. Fork the following repository: CodeInspection and open the project in eclipse.
  2. PMD will not be activated for the project by default. Open the project properties window by clicking in β€œProject >> Properties”.
  3. Select β€œPMD” on the side bar and check β€œEnabled PMD β€œ.

_

  1. Look at all the rulesets that come with PMD, leave the default set of rules.
  2. Click β€œApply and Close” and β€œYes”.

 

Part 4: Using PMD

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].

Part 5: Creating PMD rulesets

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:

  1. Right click on the project, then β€œNew >> Other >> XML >> XML File”.
  2. Select the project, enter a file name as β€œ_ ruleset β€œ
  3. Click β€œSource” in the bottom tab to change the view and edit the file directly.

_

  1. 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>
  1. 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.

  1. 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.

  1. 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]

  1. To use an external ruleset, we need to go to the PMD Configuration Window. Go to β€œWindow >> Preferences οƒ  PMD οƒ  Rule Configurations”.
  2. Check β€œUse global rule management”, then group rules by β€œRule Set”.
  3. Select all the rule sets and click in the β€œX” button to delete them.
  4. Click "Import rule set..." (under the "x"), browse your file and Click β€œOk”.
  5. The rules we added are not listed yet, press "Apply and close", then "Yes".
  6. Return to PMD Configuration Window. Notice that the checkbox next to the rule names is unchecked.

_

  1. Press "Apply and close", then "Yes".
  2. 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]

Part 6: Generating a PMD report

  1. Open PMD configuration window, select Reports and check β€œhtml.”

_

  1. Right-click the project then click β€œPMD οƒ  Generate Report.”
  2. A folder named reports is created in the tree project. Open it and double click the β€œpmd-report.html” to see the full report.

_

Part 7: Suppressing PMD Rules

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.

  1. Go to Email.java. See that line 5 has a violation related to ImmutableField rule.
  2. Write β€œNOPMD” as a comment in the same line where the violation occurred.
  3. 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]

Part 8: Detecting Cut-and-Paste with CPD

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.

  1. Just for demonstration purpose, copy and paste the β€œrandomPassword” method from Email.java to EmalApp.java.
  2. Right-click the project and select β€œPMD >> Find Suspect Cut and Paste” from menu options.
  3. Select β€œjava” for Language, then click β€œOk”.

_

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

_

  1. Revert the changes made in EmailApp.java.

Part 9: PMD and Maven

  1. Open β€œpom.xml” file

_

  1. 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.

_

  1. Wait for the process to finish.

_

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

_

  1. Click on β€œProject Reports οƒ  PMD” to see a detailed PMD report of your project.

_

 

Development

  1. Delete all comments and annotations from the code.
  2. 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:

_

  1. Generate an html report, make a copy and save it somewhere on your disk.
  2. Correct any violation in the code that have been generated in the report.
  3. Generate a new report (without violations).

Deliverables

  1. Lab report with screenshots of the process.
  2. Two PMD reports.
  3. Include in the report the url of the repository where you performed the lab.

Rubric

╔════════════════════════════════════════════════════════════════════╦═══════╗
β•‘ 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  β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•

References

  • 01 PMD Source Code Analyzer
  • 02 Java Power Tools
  • 03 Java Rules
  • 04 Suppressing warnings
⚠️ **GitHub.com Fallback** ⚠️