We will see here how to use checkstyle plugin in gradle based project. Checkstyle is a static code quality tool used to find Fan-out complexity of a class, complexity of method, utility class, bugs due to not following coding standards etc. so that we can remove the complexity from our Java source code and make the code more readable and maintainable for future.

You may also like to read Code quality using SonarQube and Code quality using Jacoco on gradle based project

What is checkstyle?

Checkstyle is a static code analysis tool used in software development for checking if Java source code complies with coding rules.

The programming style adopted by a software development project can help to comply with good programming practices which improve the code quality, readability, re-usability, and reduce the cost of development. The performed checks mainly limit themselves to the presentation and don’t analyze content, and do not confirm the correctness or completeness of the program. In practice, it can be tedious to comply with all the style constraints, some of which could possibly harm the programming stages’ dynamic; so, it may be useful to determine which level of check is needed for a certain type of program.

Checkstyle defines a set of available modules, each of which provides rules checking with a configurable level of strictness (mandatory, optional…). Each rule can raise notifications, warnings, and errors.

For example, checkstyle can examine:

Javadoc comments for classes, attributes and methods;
Naming conventions of attributes and methods;
Limit of the number of function parameters, line lengths;
Presence of mandatory headers;
The use of packets imports, of classes, of scope modifiers and of instructions blocks;
The spaces between some characters;
The good practices of class construction;
Multiple complexity measurements, among which expressions.

What is checkstyle plugin?

The Checkstyle plugin performs quality checks on your project’s Java source files using Checkstyle and generates reports from these checks. Here we will see how to use checkstyle plugin in gradle based project.

The Checkstyle plugin adds the following tasks to the project:

To use checkstyle in gradle based Java project you need to use the checkstyle plugin in the following way:

apply plugin: 'checkstyle'

For checking such rules we first define such rules generally in checkstyle.xml file and if we want to suppress or avoid any defined rule in checkstyle.xml file as an exception for any class or module then we can define suppression rules in checkstyle-suppressions.xml file and include this file into checkstyle.xml file.

By default, the Checkstyle plugin expects configuration files to be placed in the root project, but this can be changed and you need to configure in the build.gradle script.

The default location of checkstyle.xml file is <root project directory>/config/checkstyle/checkstyle.xml. If you have checkstyle-suppressions.xml or suppression.xml file then you can also put this file under config/checkstyle directory.

If you do not want to use the default location of the checkstyle configuration file then you can create checkstyle configuration directory and put your checkstyle configuration files. Suppose you have created directories quality/checkstyle under project’s root directory you have put your checkstyle.xml and suppressions.xml files. In this case you need the following configurations in your build.gradle script:

def configDir = "${project.rootDir}/quality"

checkstyle {
    toolVersion '7.8.1'
    configFile file("$configDir/checkstyle/checkstyle.xml")
    configProperties.checkstyleSuppressionsPath = file("$configDir/checkstyle/suppressions.xml").absolutePath
}

checkstyleMain {
    source ='src/main/java'
}

checkstyleTest {
    source ='src/test/java'
}

In the above configurations we assume that you have not included suppressions.xml file into checkstyle.xml file. If you include suppressions.xml file into checkstyle.xml file then you don’t need to configure it separately in build.gradle script. Please find in below section how to include suppressions.xml or checkstyle-suppressions.xml file into checkstyle.xml file.

How to include other configuration file into checkstyle.xml file

We will use the Sun checkstyle file in this example. Add the following XML tag at the end of the content in checkstyle.xml file but before the last line(</module>), where suppressions.xml file is your suppression configuration file:

<module name="SuppressionFilter">
	<property name="file" value="quality/checkstyle/suppressions.xml" />
</module>

or if you have configuration files into default location then you can use below:

<module name="SuppressionFilter">
	<property name="file" value="${config_loc}/suppressions.xml" />
</module>

Where does error report get generated?

The error report gets generated at the location <roor project’s directory>/build/reports/checkstyle and you will find html and xml files generated where you will find all errors are listed. You can check one by one and solve those issues.

Let’s move on to the example…

Example Implementation

We will be creating a Java project to see how to use checkstyle plugin in gradle based project.

Setting up project

As a prerequisite we have to first setup the project environment so that we would be able to write the required code for using checkstyle in our application. Create below build.gradle script. We have also specified the JDK version we will be using for our application. Notice we have used checkstyle plugin and we are using the checkstyle file’s default location, so we don’t need to configure the checkstyle location in build file explicitly.

apply plugin: 'java'
apply plugin: 'checkstyle'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
    mavenLocal()
    mavenCentral()
}

Now you should be able to build the project.

Recommended reading: Utility classes should not have a public or default constructor

Creating a Java class

We have finished configuring checkstyle plugin and creating gradle based Java project. Now we need to create a Java class in order to check how checkstyle rules are applied to the Java class and what rules are getting violated and accordingly we need to fix those violation errors.

Create below Java class

package com.jeejava;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class TestCheckStyle {
    public static void main(String[] args) {
        int winner = joseph(5, 3);
        System.out.println("winner is " + winner);
        winner = joseph(10, 3);
        System.out.println("winner is " + winner);
        winner = joseph(5, 2);
        System.out.println("winner is " + winner);
        winner = joseph(7, 3);
        System.out.println("winner is " + winner);
    }
    public static int joseph(int noOfPeople, int remPosition) {
        int tempPos = remPosition - 1;
        int[] people = new int[noOfPeople];
        for (int i = 0; i < noOfPeople; i++) {
            people[i] = i + 1;
        }
        int iteration = noOfPeople - 1;
        List<Integer> list = IntStream.of(people).boxed().collect(Collectors.toList());
        while (iteration > 0) {
            list.remove(tempPos);
            tempPos += remPosition - 1;
            if (tempPos > list.size() - 1) {
                tempPos = tempPos % list.size();
            }
            iteration--;
        }
        return list.get(0);
    }
}

Testing the application

Now navigate to the project root directory using cmd prompt and execute the command gradle clean build. You should see the following error in cmd console:

> Task :checkstyleMain
[ant:checkstyle] [ERROR] <project root directory>srcmainjavacomjeejavapackage-info.java:0: File does not end with a newline. [NewlineAtEndOfFile]
[ant:checkstyle] [WARN] <project root directory>srcmainjavacomjeejavapackage-info.java:1: Missing a Javadoc comment. [JavadocStyle]
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':checkstyleMain'.
> Checkstyle rule violations were found. See the report at: file:///<project root directory>/build/reports/checkstyle/main.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 7s

You can open the error report file and check what are the errors you have encountered in your Java file. When you open the report file main.html then you see following errors:

How to use checkstyle plugin in gradle based project

Now it’s time to fix the issues.

First, add the documentation above the class as shown below:

...
import java.util.stream.IntStream;
/**
* 
 * @author Soumitra
*
*/
public class TestCheckStyle {
...

Next add the below package-info.java file in the same package of the project.

/**
* @author Soumitra
*/
package com.jeejava;

Now test the application from the cmd prompt by executing the same command gradle clean build. Now you should not see any error in cmd console or in the report file. The report file now looks similar to below:

How to use checkstyle plugin in gradle based project

That’s all. You can use the checkstyle plugin in the same way I have explained above for your any Java based application.

You may also like to read Code quality using SonarQube and Code quality using Jacoco on gradle based project

Recommended reading: Utility classes should not have a public or default constructor

Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *