09. SonarQube with Maven Tutorial – Code Quality for Java developers

Industry strength code needs to statically & dynamically capture code quality. Also, more and more organizations are using “production quality” home assignments to shortlist candidates for job interviews. So, it really pays to set up code quality tools like SonarQube on your home development environment to get feedback on your code quality with the view to learm & improve.

This assumes that Java 8 and Maven 3 are set up.

Step 1: Download latest SonarQube from http://www.sonarqube.org/downloads/. This tutorial downloads SonarQube 5.3, which is a zip file, and unzip the file. The contents of unzipped sonarqube-5.3 folder:

sonarqube-5.3 folder Contents

sonarqube-5.3 folder Contents

This tutorial uses “macosx-universal-64” for mac OS.

Step 2: ./sonar.sh will start the sonar server on port number 9000. The usage is

SonarQube MAC OSX

SonarQube MAC OSX

for this tutorial start SonarQube in your local machine in console mode

Step 3: After starting the SonarQube server, you can access it on a web browser by typing “http://localhost:9000“.

SonarQube Web Interface where Code Quality metrics are published

SonarQube Web Interface where Code Quality metrics are published

Step 4: Your maven projects can connect to the server running on localhost:9000 by making the following changes to your project’s pom.xml file

Key Points

1) sonar.host.url = http://localhost:9000

Can also be configured via Maven settings.xml

2) Sonar & code quality hates System.out.println(…..) statements resulting as major code quality issue. So, use slf4j & logback in your code.

3) Latest “Maven sonar plugin” is used.

Step 5: You can publish the metrics with “mvn sonar:sonar”.

Step 6: SonarQube Code metrics summary

SonarQube Code Metrics Summary

SonarQube Code Metrics Summary

You can drill down into the metrics for blocker, critical, and major issues.

Code Quality Issues to fix

Code Quality Issues to fix

The above example has a major issue that requires attention:

Cause of major issue

Cause of major issue

You can drill down to code that has the issue:

Code with a major issue highlighted

Code with a major issue highlighted

So, get into the habit of passing your home assignments, self-taught projects, and pre-interview assignments via code quality tools like SonarQube. Every little thing matters to differentiate yourself from your competition.

You may also like: Jacoco for unit test coverage with SonarQube tutorial


300+ Java Interview FAQs

Tutorials on Java & Big Data