# Chapter 27. The Sonar Plugin

The Sonar plugin provides integration with Sonar, a web-based platform for monitoring code quality. The plugin adds a `sonarAnalyze` task that analyzes the project to which the plugin is applied and its subprojects. The results are stored in the Sonar database. The plugin requires Sonar 2.9 or higher.

The `sonarAnalyze` task is a standalone task that needs to be executed explicitly and doesn't depend on any other tasks. Apart from source code, the task also analyzes class files and test result files (if available). For best results, it is therefore recommended to run a full build before the analysis. In a typical setup, analysis would be performed once per day on a build server.

## 27.1. Usage

At a minimum, the Sonar plugin has to be applied to the project.

Example 27.1. Applying the Sonar plugin

`build.gradle`

    apply plugin: "sonar"

Unless Sonar is run locally and with default settings, it is also necessary to configure connection settings for the Sonar server and database.

Example 27.2. Configuring Sonar connection settings

`build.gradle`

    sonar {
        server {
            url = "http://my.server.com"
        }
        database {
            url = "jdbc:mysql://my.server.com/sonar"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "Fred Flintstone"
            password = "very clever"
        }
    }

Project settings determine how the project is going to be analyzed. The default configuration works well for analyzing standard Java projects and can be customized in many ways.

Example 27.3. Configuring Sonar project settings

`build.gradle`

    sonar {
        project {
            coberturaReportPath = file("$buildDir/cobertura.xml")
        }
    }

The `sonar`, `server`, `database`, and `project` blocks in the examples above configure objects of type `SonarRootModel`, `SonarServer`, `SonarDatabase`, and `SonarProject`, respectively. See their API documentation for further information.

## 27.2. Analyzing Multi-Project Builds

The Sonar plugin is capable of analyzing a whole project hierarchy at once. This yields a hierarchical view in the Sonar web interface with aggregated metrics and the ability to drill down into subprojects. It is also faster and less likely to run into out-of-memory problems than analyzing each project separately.

To analyze a project hierarchy, the Sonar plugin needs to be applied to the top-most project of the hierarchy. Typically (but not necessarily) this will be the root project. The `sonar` block in that project configures an object of type `SonarRootModel`. It holds all global configuration, most importantly server and database connection settings.

Example 27.4. Global configuration in a multi-project build

`build.gradle`

    apply plugin: "sonar"

    sonar {
        server {
            url = "http://my.server.com"
        }
        database {
            url = "jdbc:mysql://my.server.com/sonar"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "Fred Flintstone"
            password = "very clever"
        }
    }

Each project in the hierarchy has its own project configuration. Common values can be set from a parent build script.

Example 27.5. Common project configuration in a multi-project build

`build.gradle`

    subprojects {
        sonar {
            project {
                sourceEncoding = "UTF-8"
            }
        }
    }

The `sonar` block in a subproject configures an object of type `SonarProjectModel`.

Projects can also be configured individually. For example, setting the `skip` property to `true` prevents a project (and its subprojects) from being analyzed. Skipped projects will not be displayed in the Sonar web interface.

Example 27.6. Individual project configuration in a multi-project build

`build.gradle`

    project(":project1") {
        sonar {
            project {
                skip = true
            }
        }
    }

Another typical per-project configuration is the programming language to be analyzed. Note that Sonar can only analyze one language per project.

Example 27.7. Configuring the language to be analyzed

`build.gradle`

    project(":project2") {
        sonar {
            project {
                language = "groovy"
            }
        }
    }

When setting only a single property at a time, the equivalent property syntax is more succinct:

Example 27.8. Using property syntax

`build.gradle`

    project(":project2").sonar.project.language = "groovy"

## 27.3. Analyzing Custom Source Sets

By default, the Sonar plugin will analyze the production sources in the `main` source set and the test sources in the `test` source set. This works independent of the project's source directory layout. Additional source sets can be added as needed.

Example 27.9. Analyzing custom source sets

`build.gradle`

    sonar.project {
        sourceDirs += sourceSets.custom.allSource.srcDirs
        testDirs += sourceSets.integTest.allSource.srcDirs
    }

## 27.4. Setting Custom Sonar Properties

Eventually, most configuration is passed to the Sonar code analyzer in the form of key-value pairs known as Sonar properties. The `SonarProperty` annotations in the API documentation show how properties of the plugin's object model get mapped to the corresponding Sonar properties. The Sonar plugin offers hooks to post-process Sonar properties before they get passed to the code analyzer. The same hooks can be used to add additional properties which aren't covered by the plugin's object model.

For global Sonar properties, use the `withGlobalProperties` hook on `SonarRootModel`:

Example 27.10. Setting custom global properties

`build.gradle`

    sonar.withGlobalProperties { props ->
        props["some.global.property"] = "some value"
    }

For per-project Sonar properties, use the `withProjectProperties` hook on `SonarProject`:

Example 27.11. Setting custom project properties

`build.gradle`

    sonar.project.withProjectProperties { props ->
        props["some.project.property"] = "some value"
    }

The Sonar documentation provides a complete list of Sonar properties. (Note that most of these properties are already covered by the plugin's object model.) For configuring third-party Sonar plugins, consult their documentation.

## 27.5. Tasks

The Sonar plugin adds the following tasks to the project.

Table 27.1. Sonar plugin - tasks

Task name | Depends on | Type | Description
`sonarAnalyze` | - | `SonarAnalyze` | Analyzes a project hierarchy and stores the results in the Sonar database.