Sunday, 12 August 2012

How to Use Sonar from Maven for Code Quality?

Sonar is by far the best open source tool to perform code quality checks. Not only it is free, it is also very easy to learn and to use. A true blessing.

Installation & Start

  1. Download the .zip file.
  2. Unzip in a local directory (for example: C:\Temp\Sonar)
  3. Go in the \bin directory and select the subdirectory corresponding to your operating system (for example: C:\Temp\Sonar\bin\windows-x86-32)
  4. Double-click on StartSonar.


  1. Open http://localhost:9000
  2. Login as administrator (login: admin, password: admin)
  3. Click on Configuration
  4. Select Sonar way with Findbugs as default
Sonar Configuration


The following code sample is available on Github, in the Sonar-Example directory:
public class Sonar {

    public static class A {
        public void print() {
            System.out.println("Hello Word !");

    public static void main(String[] args) throws IOException {



    public static void printMessage(A a) {

        // Not testing for nullity


We explicity create some silly code not testing for nullity. To enable Sonar in Maven, we include the following pom.xml dependency:
  1. Run the sonar:sonar maven goal on the project.
  2. Go back to http://localhost:9000
  3. Click on Home.
  4. Select Sonar-Example. Notice the errors and warnings reported by Sonar.
  5. Click on Critical.
  6. Click on the Sonar link (with a text icon)

Sonar has detected the suspicious null method call. This is a tiny example of what Sonar can do for you. You can configure it to use FindBugs and PMD too. Sonar is also an excellent opportunity to learn about your coding errors. It improves your style.

No comments:

Post a comment