# Chapter 35. The Sonar Plugin

You may wish to use the new Sonar Runner Plugin instead of this plugin. In particular, only the Sonar Runner plugin supports Sonar 3.4 and higher.

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, as well as its subprojects. The results are stored in the Sonar database. The plugin is based on the Sonar Runner and requires Sonar 2.11 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.

## 35.1. Usage

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

Example 35.1. Applying the Sonar plugin

`build.gradle`

    apply plugin: "sonar"

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

Example 35.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"
        }
    }

Alternatively, some or all connection settings can be set from the command line (see Section 35.6, “Configuring Sonar Settings from the Command Line”).

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

## 35.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 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 35.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 35.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 35.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 35.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 35.8. Using property syntax

`build.gradle`

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

## 35.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 35.9. Analyzing custom source sets

`build.gradle`

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

## 35.4. Analyzing languages other than Java

To analyze code written in a language other than Java, install the corresponding Sonar plugin, and set `sonar.project.language` accordingly:

Example 35.10. Analyzing languages other than Java

`build.gradle`

    sonar.project {
        language = "grvy" // set language to Groovy
    }

As of Sonar 3.4, only one language per project can be analyzed. You can, however, set a different language for each project in a multi-project build.

## 35.5. 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 35.11. Setting custom global properties

`build.gradle`

    sonar.withGlobalProperties { props ->
        props["some.global.property"] = "some value"
        // non-String values are automatically converted to Strings
        props["other.global.property"] = ["foo", "bar", "baz"]
    }

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

Example 35.12. Setting custom project properties

`build.gradle`

    sonar.project.withProjectProperties { props ->
        props["some.project.property"] = "some value"
        // non-String values are automatically converted to Strings
        props["other.project.property"] = ["foo", "bar", "baz"]
    }

A list of available Sonar properties can be found in the Sonar documentation. Note that for most of these properties, the Sonar plugin's object model has an equivalent property, and it isn't necessary to use a `withGlobalProperties` or `withProjectProperties` hook. For configuring a third-party Sonar plugin, consult the plugin's documentation.

## 35.6. Configuring Sonar Settings from the Command Line

The following properties can alternatively be set from the command line, as task parameters of the `sonarAnalyze` task. A task parameter will override any corresponding value set in the build script.

- `server.url`
- `database.url`
- `database.driverClassName`
- `database.username`
- `database.password`
- `showSql`
- `showSqlResults`
- `verbose`
- `forceAnalysis`

Here is a complete example:

`gradle sonarAnalyze --server.url=http://sonar.mycompany.com --database.password=myPassword --verbose`

If you need to set other properties from the command line, you can use system properties to do so:

Example 35.13. Implementing custom command line properties

`build.gradle`

    sonar.project {
        language = System.getProperty("sonar.language", "java")
    }

However, keep in mind that it is usually best to keep configuration in the build script and under source control.

## 35.7. Tasks

The Sonar plugin adds the following tasks to the project.

Table 35.1. Sonar plugin - tasks

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